Decompiled source of Content Ancient Cult v1.2.1

coah.dll

Decompiled a week ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Text;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using HypnoCode;
using Microsoft.CodeAnalysis;
using Splatform;
using TMPro;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.Networking;
using UnityEngine.Rendering;
using UnityEngine.UI;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: AssemblyVersion("0.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 HypnoCode
{
	internal static class Admin
	{
		private static readonly FieldInfo AdminListField = AccessTools.Field(typeof(ZNet), "m_adminList");

		private static string Bare(string value)
		{
			return value.Substring(value.LastIndexOf('_') + 1).Trim();
		}

		private static bool Listed(IEnumerable<string> admins, string id)
		{
			if (admins == null || string.IsNullOrEmpty(id))
			{
				return false;
			}
			string text = Bare(id);
			if (text.Length == 0)
			{
				return false;
			}
			foreach (string admin in admins)
			{
				if (admin != null && (string.Equals(admin.Trim(), id, StringComparison.OrdinalIgnoreCase) || string.Equals(Bare(admin), text, StringComparison.OrdinalIgnoreCase)))
				{
					return true;
				}
			}
			return false;
		}

		internal static bool IsPeer(long uid)
		{
			ZNet instance = ZNet.instance;
			if ((Object)(object)instance == (Object)null)
			{
				return false;
			}
			if (uid == ZNet.GetUID())
			{
				return true;
			}
			ZNetPeer peer = instance.GetPeer(uid);
			if (peer == null || peer.m_socket == null)
			{
				return false;
			}
			string hostName = peer.m_socket.GetHostName();
			if (string.IsNullOrEmpty(hostName))
			{
				return false;
			}
			if (instance.IsAdmin(hostName))
			{
				return true;
			}
			SyncedList val = (SyncedList)((AdminListField != null) ? /*isinst with value type is only supported in some contexts*/: null);
			return Listed((val != null) ? val.GetList() : instance.GetAdminList(), hostName);
		}

		internal static bool IsLocal(bool serverSays = false)
		{
			ZNet instance = ZNet.instance;
			if ((Object)(object)instance == (Object)null)
			{
				return false;
			}
			if (instance.LocalPlayerIsAdminOrHost() || serverSays)
			{
				return true;
			}
			string id;
			try
			{
				id = ((object)Unsafe.As<PlatformUserID, PlatformUserID>(ref UserInfo.GetLocalUser().UserId)/*cast due to .constrained prefix*/).ToString();
			}
			catch
			{
				return false;
			}
			return Listed(instance.GetAdminList(), id);
		}
	}
	internal static class Compat
	{
		internal enum Kind
		{
			CompatMode,
			Info,
			Option,
			Resolved
		}

		internal sealed class Known
		{
			public string Guid;

			public string TypeName;

			public string Name;

			public Kind Kind;

			public Dictionary<string, string> Does;

			public Dictionary<string, string> Toggle;
		}

		private const string Backpack = "the backpack's rows and its portal/ship dock follow SeneaL's layout, and the inventory is saved around SeneaL's own saving (no items lost at a save)";

		private const string BackpackSlots = "the backpack's rows go right after the player's own rows, before Extra Slots' special slots";

		private const string BackpackArchery = "the backpack's row goes above Better Archery's quiver rows, and the portal/ship dock leaves the quiver where it is";

		internal static readonly Known[] Table = new Known[7]
		{
			new Known
			{
				Guid = "seneaL.valheim.ui",
				Name = "SeneaL UI",
				Kind = Kind.CompatMode,
				Does = new Dictionary<string, string>
				{
					{ "COAH", "the backpack's rows and its portal/ship dock follow SeneaL's layout, and the inventory is saved around SeneaL's own saving (no items lost at a save)" },
					{ "AdvancedBackpacks", "the backpack's rows and its portal/ship dock follow SeneaL's layout, and the inventory is saved around SeneaL's own saving (no items lost at a save)" }
				},
				Toggle = new Dictionary<string, string>
				{
					{ "COAH", "SeneaLUI" },
					{ "AdvancedBackpacks", "SeneaLUI" }
				}
			},
			new Known
			{
				Guid = "seneaL.valheim.api",
				Name = "SeneaL API",
				Kind = Kind.Info,
				Does = new Dictionary<string, string> { { "ImmersiveTrader", "the Quest Log gets a tab in SeneaL's character window" } },
				Toggle = new Dictionary<string, string> { { "ImmersiveTrader", "SeneaLQuestLogTab" } }
			},
			new Known
			{
				Guid = "shudnal.ExtraSlots",
				Name = "Extra Slots",
				Kind = Kind.CompatMode,
				Does = new Dictionary<string, string>
				{
					{ "COAH", "the backpack's rows go right after the player's own rows, before Extra Slots' special slots" },
					{ "AdvancedBackpacks", "the backpack's rows go right after the player's own rows, before Extra Slots' special slots" }
				},
				Toggle = new Dictionary<string, string>
				{
					{ "COAH", "ExtraSlots" },
					{ "AdvancedBackpacks", "ExtraSlots" }
				}
			},
			new Known
			{
				Guid = "ishid4.mods.betterarchery",
				Name = "Better Archery",
				Kind = Kind.CompatMode,
				Does = new Dictionary<string, string>
				{
					{ "COAH", "the backpack's row goes above Better Archery's quiver rows, and the portal/ship dock leaves the quiver where it is" },
					{ "AdvancedBackpacks", "the backpack's row goes above Better Archery's quiver rows, and the portal/ship dock leaves the quiver where it is" }
				},
				Toggle = new Dictionary<string, string>
				{
					{ "COAH", "BetterArchery" },
					{ "AdvancedBackpacks", "BetterArchery" }
				}
			},
			new Known
			{
				TypeName = "ValheimProfessions.ProfessionManager",
				Name = "ValheimProfessions",
				Kind = Kind.Option,
				Does = new Dictionary<string, string> { { "ImmersiveTrader", "traders, boards and caravans turn away a player with a profession when [Compatibility] BlockPlayersWithProfession is on" } },
				Toggle = new Dictionary<string, string> { { "ImmersiveTrader", "BlockPlayersWithProfession" } }
			},
			new Known
			{
				Guid = "goldenrevolver.quick_stack_store",
				Name = "Quick Stack Store",
				Kind = Kind.Info,
				Does = new Dictionary<string, string> { { "SortByQoL", "works with it: when it refreshes the crafting list, the sorting and the filters are applied again" } }
			},
			new Known
			{
				Guid = "p0kahontazz.coah",
				Name = "Children of the Ancient Heart",
				Kind = Kind.Resolved,
				Does = new Dictionary<string, string>
				{
					{ "AdvancedBackpacks", "Advanced Backpacks is switched off (COAH has the same backpacks); the Advanced Backpacks a player carries become COAH backpacks with what they hold" },
					{ "AdvancedPortal", "the Advanced Portal is no longer in the hammer (COAH's Heart Portal is the same); the ones standing keep working" }
				}
			}
		};

		private static readonly Dictionary<string, string> OurGuids = new Dictionary<string, string>
		{
			{ "ImmersiveTrader", "p0kahontazz.immersivetrader" },
			{ "COAH", "p0kahontazz.coah" },
			{ "AdvancedBackpacks", "p0kahontazz.advancedbackpacks" },
			{ "AdvancedPortal", "p0kahontazz.advancedportal" },
			{ "SortByQoL", "p0kahontazz.sortbyqol" }
		};

		internal static Type FindType(string fullName)
		{
			Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();
			foreach (Assembly assembly in assemblies)
			{
				try
				{
					Type type = assembly.GetType(fullName, throwOnError: false);
					if (type != null)
					{
						return type;
					}
				}
				catch
				{
				}
			}
			return null;
		}

		internal static bool Installed(Known known, out string version)
		{
			version = "";
			try
			{
				if (known.Guid != null)
				{
					if (!Chainloader.PluginInfos.TryGetValue(known.Guid, out var value) || value == null)
					{
						return false;
					}
					version = ((value.Metadata != null && value.Metadata.Version != null) ? value.Metadata.Version.ToString() : "");
					return true;
				}
				return known.TypeName != null && FindType(known.TypeName) != null;
			}
			catch
			{
				return false;
			}
		}

		private static string Off(Known known, string ours)
		{
			//IL_006e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0075: Expected O, but got Unknown
			try
			{
				if (known.Toggle == null || !known.Toggle.TryGetValue(ours, out var value) || !OurGuids.TryGetValue(ours, out var value2))
				{
					return "";
				}
				if (!Chainloader.PluginInfos.TryGetValue(value2, out var value3) || value3 == null || (Object)(object)value3.Instance == (Object)null)
				{
					return "";
				}
				ConfigFile config = value3.Instance.Config;
				ConfigDefinition val = new ConfigDefinition("Compatibility", value);
				if (config == null || !config.ContainsKey(val) || !(config[val].BoxedValue is bool))
				{
					return "";
				}
				return ((bool)config[val].BoxedValue) ? "" : (" (off: [Compatibility] " + value + " = false)");
			}
			catch
			{
				return "";
			}
		}

		internal static void Report(ManualLogSource log, string ours)
		{
			if (log == null)
			{
				return;
			}
			Known[] table = Table;
			foreach (Known known in table)
			{
				if (known.Does != null && known.Does.TryGetValue(ours, out var value) && Installed(known, out var version))
				{
					log.LogInfo((object)("Detected " + known.Name + ((version.Length > 0) ? (" " + version) : "") + ": " + value + Off(known, ours) + "."));
				}
			}
		}

		internal static List<string> Lines()
		{
			List<string> list = new List<string>();
			Known[] table = Table;
			foreach (Known known in table)
			{
				if (Installed(known, out var version))
				{
					list.Add(known.Name + ((version.Length > 0) ? (" " + version) : "") + " (" + (known.Guid ?? known.TypeName) + ", " + known.Kind.ToString() + "): " + string.Join("; ", known.Does.Select((KeyValuePair<string, string> p) => p.Key + " - " + p.Value + Off(known, p.Key)).ToArray()));
				}
			}
			return list;
		}
	}
	internal static class LogLimit
	{
		private sealed class Seen
		{
			public float Next = float.MinValue;

			public int Skipped;
		}

		private const float Every = 10f;

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

		internal static void Warn(ManualLogSource log, string key, string message)
		{
			if (log != null)
			{
				float unscaledTime = Time.unscaledTime;
				if (!State.TryGetValue(key, out var value))
				{
					value = (State[key] = new Seen());
				}
				if (unscaledTime < value.Next)
				{
					value.Skipped++;
					return;
				}
				log.LogWarning((object)((value.Skipped > 0) ? (message + " (and " + value.Skipped + " more times in the last " + 10f.ToString("0") + " s)") : message));
				value.Next = unscaledTime + 10f;
				value.Skipped = 0;
			}
		}
	}
	internal static class ModReport
	{
		private sealed class Listener : ILogListener, IDisposable
		{
			public void LogEvent(object sender, LogEventArgs e)
			{
				//IL_0004: Unknown result type (might be due to invalid IL or missing references)
				//IL_000a: Unknown result type (might be due to invalid IL or missing references)
				//IL_006d: Unknown result type (might be due to invalid IL or missing references)
				//IL_0072: Unknown result type (might be due to invalid IL or missing references)
				if (e == null || (e.Level & 7) == 0)
				{
					return;
				}
				string text = Convert.ToString(e.Data) ?? "";
				if (text.Length > 800)
				{
					text = text.Substring(0, 800) + " ...";
				}
				string item = DateTime.Now.ToString("HH:mm:ss") + " [" + ((object)e.Level/*cast due to .constrained prefix*/).ToString() + ": " + ((e.Source != null) ? e.Source.SourceName : "?") + "] " + text.Replace("\r", "").Replace("\n", " | ");
				lock (recent)
				{
					recent.Enqueue(item);
					while (recent.Count > 200)
					{
						recent.Dequeue();
					}
				}
			}

			public void Dispose()
			{
			}
		}

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

			public static Func<PluginInfo, bool> <>9__8_0;

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

			public static Func<PluginInfo, bool> <>9__8_2;

			public static Func<KeyValuePair<ConfigDefinition, ConfigEntryBase>, string> <>9__9_0;

			public static Func<KeyValuePair<ConfigDefinition, ConfigEntryBase>, string> <>9__9_1;

			public static ConsoleEvent <>9__12_0;

			public static Func<PluginInfo, bool> <>9__14_0;

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

			internal bool <Plugins>b__8_0(PluginInfo p)
			{
				if (p != null)
				{
					return p.Metadata != null;
				}
				return false;
			}

			internal string <Plugins>b__8_1(PluginInfo p)
			{
				return p.Metadata.GUID;
			}

			internal bool <Plugins>b__8_2(PluginInfo p)
			{
				return IsHypnogoogic(p.Metadata.GUID);
			}

			internal string <ChangedSettings>b__9_0(KeyValuePair<ConfigDefinition, ConfigEntryBase> p)
			{
				return p.Key.Section;
			}

			internal string <ChangedSettings>b__9_1(KeyValuePair<ConfigDefinition, ConfigEntryBase> p)
			{
				return p.Key.Key;
			}

			internal void <RegisterCommand>b__12_0(ConsoleEventArgs args)
			{
				if (args.Length < 2 || !string.Equals(args[1], "report", StringComparison.OrdinalIgnoreCase))
				{
					if ((Object)(object)args.Context != (Object)null)
					{
						args.Context.AddString("Usage: hypno report");
					}
					return;
				}
				try
				{
					string text = WriteCommon();
					if ((Object)(object)args.Context != (Object)null)
					{
						args.Context.AddString("Report written: " + text + " - send this file with your bug report (it holds no account name or secrets).");
					}
				}
				catch (Exception ex)
				{
					if ((Object)(object)args.Context != (Object)null)
					{
						args.Context.AddString("The report could not be written: " + ex.Message);
					}
				}
			}

			internal bool <WriteCommon>b__14_0(PluginInfo p)
			{
				if (p != null && p.Metadata != null && (Object)(object)p.Instance != (Object)null)
				{
					return IsHypnogoogic(p.Metadata.GUID);
				}
				return false;
			}

			internal string <WriteCommon>b__14_1(PluginInfo p)
			{
				return p.Metadata.Name;
			}
		}

		private const int Keep = 200;

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

		private static Listener listener;

		internal const string CommonFile = "Hypnogoogic-report.txt";

		internal static readonly List<Action<StringBuilder>> Extra = new List<Action<StringBuilder>>();

		internal static void StartLog()
		{
			if (listener == null)
			{
				listener = new Listener();
				Logger.Listeners.Add((ILogListener)(object)listener);
			}
		}

		internal static bool IsHypnogoogic(string guid)
		{
			if (guid != null)
			{
				if (!guid.StartsWith("p0kahontazz.", StringComparison.OrdinalIgnoreCase))
				{
					return guid == "pl.rootsandremedies.foods";
				}
				return true;
			}
			return false;
		}

		internal static string GameType()
		{
			ZNet instance = ZNet.instance;
			if ((Object)(object)instance == (Object)null)
			{
				return "main menu (no world)";
			}
			if (!instance.IsServer())
			{
				return "client on a server";
			}
			if (instance.IsDedicated())
			{
				return "dedicated server";
			}
			bool flag = true;
			try
			{
				FieldInfo field = typeof(ZNet).GetField("m_openServer", BindingFlags.Static | BindingFlags.NonPublic);
				if (field != null)
				{
					flag = (bool)field.GetValue(null);
				}
			}
			catch
			{
			}
			if (!flag)
			{
				return "single player";
			}
			return "host (others can join)";
		}

		internal static void Head(StringBuilder sb, string title)
		{
			sb.AppendLine("=== " + title + " ===");
			sb.AppendLine("Written: " + DateTime.UtcNow.ToString("yyyy-MM-dd HH:mm:ss") + " UTC");
			try
			{
				sb.AppendLine("Valheim: " + Version.GetVersionString(false));
			}
			catch
			{
				sb.AppendLine("Valheim: ?");
			}
			sb.AppendLine("Game: " + GameType());
			try
			{
				if ((Object)(object)ZNet.instance != (Object)null && ZNet.instance.GetWorldName() != null)
				{
					sb.AppendLine("World: " + ZNet.instance.GetWorldName());
				}
			}
			catch
			{
			}
			Player localPlayer = Player.m_localPlayer;
			if ((Object)(object)localPlayer != (Object)null)
			{
				sb.AppendLine("Character: " + localPlayer.GetPlayerName() + " (player id " + localPlayer.GetPlayerID() + ")");
			}
			sb.AppendLine();
		}

		internal static void Plugins(StringBuilder sb)
		{
			List<PluginInfo> list = Chainloader.PluginInfos.Values.Where((PluginInfo p) => p != null && p.Metadata != null).OrderBy<PluginInfo, string>((PluginInfo p) => p.Metadata.GUID, StringComparer.OrdinalIgnoreCase).ToList();
			sb.AppendLine("--- Hypnogoogic mods ---");
			foreach (PluginInfo item in list.Where((PluginInfo p) => IsHypnogoogic(p.Metadata.GUID)))
			{
				sb.AppendLine(item.Metadata.Name + " " + item.Metadata.Version?.ToString() + "  (" + item.Metadata.GUID + ")");
			}
			sb.AppendLine();
			sb.AppendLine("--- Known mods (how ours work with them, see Compat) ---");
			List<string> list2 = Compat.Lines();
			if (list2.Count == 0)
			{
				sb.AppendLine("(none installed)");
			}
			foreach (string item2 in list2)
			{
				sb.AppendLine(item2);
			}
			sb.AppendLine();
			sb.AppendLine("--- All plugins (" + list.Count + ") ---");
			foreach (PluginInfo item3 in list)
			{
				sb.AppendLine(item3.Metadata.GUID + "  " + item3.Metadata.Version?.ToString() + "  " + item3.Metadata.Name);
			}
			sb.AppendLine();
		}

		internal static void ChangedSettings(StringBuilder sb, ConfigFile config, string title)
		{
			sb.AppendLine("--- " + title + ": settings changed from the default ---");
			int num = 0;
			if (config != null)
			{
				foreach (KeyValuePair<ConfigDefinition, ConfigEntryBase> item in from p in (IEnumerable<KeyValuePair<ConfigDefinition, ConfigEntryBase>>)config
					orderby p.Key.Section, p.Key.Key
					select p)
				{
					ConfigEntryBase value = item.Value;
					if (value != null && !object.Equals(value.BoxedValue, value.DefaultValue))
					{
						string text = item.Key.Section + "." + item.Key.Key;
						string text2 = item.Key.Key.ToLowerInvariant();
						bool flag = value.SettingType == typeof(string) && (text2.Contains("key") || text2.Contains("token") || text2.Contains("password") || text2.Contains("secret") || text2.Contains("webhook"));
						sb.AppendLine(text + " = " + (flag ? "(hidden)" : value.GetSerializedValue()) + "   (default " + (flag ? "(hidden)" : ((value.DefaultValue != null) ? Convert.ToString(value.DefaultValue) : "none")) + ")");
						num++;
					}
				}
			}
			if (num == 0)
			{
				sb.AppendLine("(none)");
			}
			sb.AppendLine();
		}

		internal static void RecentLog(StringBuilder sb)
		{
			string[] array;
			lock (recent)
			{
				array = recent.ToArray();
			}
			sb.AppendLine("--- Last " + array.Length + " warnings and errors of the log (all mods) ---");
			if (listener == null)
			{
				sb.AppendLine("(not kept: the log was not watched)");
			}
			string[] array2 = array;
			foreach (string value in array2)
			{
				sb.AppendLine(value);
			}
			sb.AppendLine();
		}

		internal static void RegisterCommand()
		{
			//IL_0038: Unknown result type (might be due to invalid IL or missing references)
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			//IL_0028: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Expected O, but got Unknown
			StartLog();
			object obj = <>c.<>9__12_0;
			if (obj == null)
			{
				ConsoleEvent val = delegate(ConsoleEventArgs args)
				{
					if (args.Length < 2 || !string.Equals(args[1], "report", StringComparison.OrdinalIgnoreCase))
					{
						if ((Object)(object)args.Context != (Object)null)
						{
							args.Context.AddString("Usage: hypno report");
						}
						return;
					}
					try
					{
						string text = WriteCommon();
						if ((Object)(object)args.Context != (Object)null)
						{
							args.Context.AddString("Report written: " + text + " - send this file with your bug report (it holds no account name or secrets).");
						}
					}
					catch (Exception ex)
					{
						if ((Object)(object)args.Context != (Object)null)
						{
							args.Context.AddString("The report could not be written: " + ex.Message);
						}
					}
				};
				<>c.<>9__12_0 = val;
				obj = (object)val;
			}
			new ConsoleCommand("hypno", "hypno report - writes BepInEx/Hypnogoogic-report.txt (game, mods, settings, last warnings) to send with a bug report", (ConsoleEvent)obj, false, false, false, false, false, false, (ConsoleOptionsFetcher)null, false, false, false);
		}

		internal static string WriteCommon()
		{
			StringBuilder stringBuilder = new StringBuilder();
			Head(stringBuilder, "Hypnogoogic mods report");
			Plugins(stringBuilder);
			foreach (PluginInfo item in Chainloader.PluginInfos.Values.Where((PluginInfo p) => p != null && p.Metadata != null && (Object)(object)p.Instance != (Object)null && IsHypnogoogic(p.Metadata.GUID)).OrderBy<PluginInfo, string>((PluginInfo p) => p.Metadata.Name, StringComparer.OrdinalIgnoreCase))
			{
				ChangedSettings(stringBuilder, item.Instance.Config, item.Metadata.Name + " " + item.Metadata.Version);
			}
			Action<StringBuilder>[] array = Extra.ToArray();
			foreach (Action<StringBuilder> action in array)
			{
				try
				{
					action(stringBuilder);
				}
				catch (Exception ex)
				{
					stringBuilder.AppendLine("(a report section failed: " + ex.Message + ")");
				}
			}
			RecentLog(stringBuilder);
			return Write("Hypnogoogic-report.txt", stringBuilder.ToString());
		}

		internal static string Write(string fileName, string text)
		{
			string text2 = Path.Combine(Paths.BepInExRootPath, fileName);
			File.WriteAllText(text2, text, new UTF8Encoding(encoderShouldEmitUTF8Identifier: false));
			return text2;
		}
	}
	internal static class Prefabs
	{
		private static Dictionary<int, GameObject> Named(ZNetScene scene)
		{
			return (Dictionary<int, GameObject>)AccessTools.Field(typeof(ZNetScene), "m_namedPrefabs").GetValue(scene);
		}

		internal static void RegisterScene(ZNetScene scene, GameObject prefab)
		{
			Dictionary<int, GameObject> dictionary = Named(scene);
			int stableHashCode = StringExtensionMethods.GetStableHashCode(((Object)prefab).name);
			if (dictionary.ContainsKey(stableHashCode))
			{
				throw new InvalidOperationException("Prefab name collision: " + ((Object)prefab).name);
			}
			dictionary.Add(stableHashCode, prefab);
			scene.m_prefabs.Add(prefab);
		}

		internal static void Replace(ZNetScene scene, GameObject prefab)
		{
			Named(scene)[StringExtensionMethods.GetStableHashCode(((Object)prefab).name)] = prefab;
			if (!scene.m_prefabs.Contains(prefab))
			{
				scene.m_prefabs.Add(prefab);
			}
		}

		internal static PieceTable Hammer(ZNetScene scene)
		{
			GameObject val = (((Object)(object)scene != (Object)null) ? scene.GetPrefab("Hammer") : null);
			ItemDrop val2 = (((Object)(object)val != (Object)null) ? val.GetComponent<ItemDrop>() : null);
			if (!((Object)(object)val2 != (Object)null))
			{
				return null;
			}
			return val2.m_itemData.m_shared.m_buildPieces;
		}

		internal static void AddToHammer(PieceTable table, GameObject prefab)
		{
			if (!((Object)(object)table == (Object)null) && !((Object)(object)prefab == (Object)null))
			{
				table.m_pieces.RemoveAll((GameObject p) => (Object)(object)p == (Object)null || ((Object)p).name == ((Object)prefab).name);
				table.m_pieces.Add(prefab);
			}
		}
	}
	internal static class StateFile
	{
		internal static class WorldCopy
		{
			internal static Func<bool> Applies = () => false;

			internal static Func<bool> Ready = () => false;

			internal static Func<string, string[]> Read = (string name) => (string[])null;

			internal static Func<string, DateTime> Stamp = (string name) => DateTime.MinValue;

			internal static Func<string, string[], bool> Write = (string name, string[] lines) => false;

			internal static Func<List<string>> Names = () => new List<string>();
		}

		internal sealed class Source
		{
			internal string Label;

			internal string[] Lines;

			internal DateTime Stamp;

			internal bool IsWorld;
		}

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

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

		private const int KeepBackups = 7;

		private const string MirrorFolder = "HypnoCode-state";

		private const string LatestName = "latest";

		private const double LatestEverySeconds = 60.0;

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

		private static readonly object Gate = new object();

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

		private static readonly HashSet<string> reconciled = new HashSet<string>(StringComparer.OrdinalIgnoreCase);

		private static readonly HashSet<string> warned = new HashSet<string>();

		internal static Func<string> SaveRoot = DefaultSaveRoot;

		internal static Func<string> GameRoot = DefaultGameRoot;

		internal const double WorldNewerBySeconds = 120.0;

		internal static string Folder(string mod)
		{
			string text = Path.Combine(Paths.BepInExRootPath, "data", mod);
			Directory.CreateDirectory(text);
			return text;
		}

		private static void WarnOnce(string key, string text)
		{
			if (warned.Add(key))
			{
				Warn(text);
			}
		}

		private static string DefaultSaveRoot()
		{
			try
			{
				string saveDataPath = Utils.GetSaveDataPath((FileSource)2);
				if (!string.IsNullOrEmpty(saveDataPath))
				{
					return saveDataPath;
				}
			}
			catch (Exception ex)
			{
				WarnOnce("saveroot", "State file copy beside the saves: the game's save path is not available (" + ex.Message + "); trying the default data path.");
			}
			try
			{
				string persistantDataPath = Utils.persistantDataPath;
				if (!string.IsNullOrEmpty(persistantDataPath))
				{
					return persistantDataPath;
				}
			}
			catch (Exception)
			{
			}
			return null;
		}

		private static string DefaultGameRoot()
		{
			try
			{
				string bepInExRootPath = Paths.BepInExRootPath;
				if (string.IsNullOrEmpty(bepInExRootPath))
				{
					return null;
				}
				string directoryName = Path.GetDirectoryName(bepInExRootPath.TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar));
				return string.IsNullOrEmpty(directoryName) ? null : directoryName;
			}
			catch (Exception ex)
			{
				WarnOnce("gameroot", "State file copy in the game folder: the folder is not known (" + ex.Message + ").");
				return null;
			}
		}

		private static List<string> MirrorRoots()
		{
			List<string> list = new List<string>();
			Func<string>[] array = new Func<string>[2] { SaveRoot, GameRoot };
			foreach (Func<string> func in array)
			{
				string text = null;
				try
				{
					text = func();
				}
				catch (Exception ex)
				{
					WarnOnce("root:" + ex.Message, "State file copy: a folder could not be resolved (" + ex.Message + ").");
				}
				if (!string.IsNullOrEmpty(text))
				{
					string root = Path.Combine(text, "HypnoCode-state");
					if (!list.Any((string r) => string.Equals(r, root, StringComparison.OrdinalIgnoreCase)))
					{
						list.Add(root);
					}
				}
			}
			if (list.Count == 0)
			{
				WarnOnce("noroots", "State files have NO copy outside BepInEx/data (neither the save folder nor the game folder could be resolved): the state is only as safe as BepInEx/data on this server.");
			}
			return list;
		}

		private static List<string> MirrorPaths(string path)
		{
			string mod = Path.GetFileName(Path.GetDirectoryName(path));
			string file = Path.GetFileName(path);
			return (from r in MirrorRoots()
				select Path.Combine(r, mod, file)).ToList();
		}

		internal static string PathOf(string mod, string file)
		{
			string text = Path.Combine(Folder(mod), file);
			MoveOld(Path.Combine(Paths.ConfigPath, file), text);
			MoveOld(Path.Combine(Paths.ConfigPath, file + ".bak"), text + ".bak");
			return text;
		}

		private static void MoveOld(string old, string path)
		{
			try
			{
				if (!File.Exists(path) && File.Exists(old))
				{
					File.Copy(old, path);
					string text = old + ".moved";
					if (File.Exists(text))
					{
						File.Delete(text);
					}
					File.Move(old, text);
					Info("State file moved out of BepInEx/config: " + Path.GetFileName(old) + " -> " + path + " (the old one is kept as " + Path.GetFileName(text) + ").");
				}
			}
			catch (Exception ex)
			{
				Warn("State file " + Path.GetFileName(old) + " could not be moved (" + ex.Message + "); it is read where it is next time.");
			}
		}

		private static string[] TryRead(string file)
		{
			try
			{
				if (File.Exists(file))
				{
					return File.ReadAllLines(file);
				}
			}
			catch (Exception ex)
			{
				Warn("State file " + file + " could not be read (" + ex.Message + ").");
			}
			return null;
		}

		internal static string[] ReadLines(string path)
		{
			lock (Gate)
			{
				DailyBackup(path);
				string fileName = Path.GetFileName(path);
				List<string> list = new List<string> { path };
				list.AddRange(MirrorPaths(path));
				Dictionary<string, string[]> found = new Dictionary<string, string[]>();
				foreach (string item in list)
				{
					found[item] = TryRead(item);
				}
				List<string> list2 = list.Where((string p) => found[p] != null && found[p].Length != 0).ToList();
				string[] array = null;
				DateTime dateTime = DateTime.MinValue;
				bool flag = false;
				bool flag2 = false;
				try
				{
					flag = WorldCopy.Applies();
					flag2 = flag && WorldCopy.Ready();
					if (flag2)
					{
						array = WorldCopy.Read(fileName);
						if (array != null)
						{
							dateTime = WorldCopy.Stamp(fileName);
						}
					}
				}
				catch (Exception ex)
				{
					flag2 = false;
					WarnOnce("worldread:" + fileName, "State file " + fileName + ": the world's copy could not be read (" + ex.Message + ").");
				}
				if (flag && !flag2)
				{
					WarnOnce("worldnotready:" + fileName, "State file " + fileName + " was read before the world was loaded: the world's copy is merged at the next read.");
				}
				DateTime dateTime2 = DateTime.MinValue;
				foreach (string item2 in list)
				{
					try
					{
						if (found[item2] != null)
						{
							DateTime lastWriteTimeUtc = File.GetLastWriteTimeUtc(item2);
							if (lastWriteTimeUtc > dateTime2)
							{
								dateTime2 = lastWriteTimeUtc;
							}
						}
					}
					catch (Exception)
					{
					}
				}
				bool flag3 = array != null && array.Length != 0 && (list.All((string p) => found[p] == null) || ((list2.Count == 0) ? (dateTime > dateTime2) : (dateTime > dateTime2.AddSeconds(120.0))));
				if (flag3)
				{
					if (list2.Count == 0)
					{
						Warn("State file " + fileName + " is gone from BepInEx/data and from its copies (wiped on this server?): " + array.Length + " lines taken from the world save.");
					}
					else
					{
						Info("State file " + fileName + ": the world's copy (" + array.Length + " lines, " + dateTime.ToString("yyyy-MM-dd HH:mm", CultureInfo.InvariantCulture) + " UTC) is newer than every file (" + dateTime2.ToString("yyyy-MM-dd HH:mm", CultureInfo.InvariantCulture) + " UTC): the files were behind, merged.");
					}
				}
				else if (array != null && array.Length != 0 && list2.Count > 0)
				{
					Info("State file " + fileName + ": the world's copy is not newer than the files, the files are used.");
				}
				List<string[]> list3 = list2.Select((string p) => found[p]).ToList();
				if (flag3)
				{
					list3.Add(array);
				}
				List<string> merged;
				if (list3.Count > 0)
				{
					merged = Merge(list3);
				}
				else if (list.All((string p) => found[p] == null))
				{
					merged = FromBackups(path);
				}
				else
				{
					merged = new List<string>();
					string text = path + ".bak";
					if (list.Count == 1)
					{
						string[] array2 = TryRead(text);
						if (array2 != null && array2.Length != 0)
						{
							Warn("State file " + fileName + " is empty: read from " + Path.GetFileName(text) + ".");
							merged = array2.ToList();
						}
					}
				}
				if (merged.Count > 0)
				{
					foreach (string place in list)
					{
						string[] array3 = found[place];
						if (array3 != null && array3.SequenceEqual(merged))
						{
							continue;
						}
						bool flag4 = place == path;
						try
						{
							RewriteFile(place, merged);
							if (array3 == null || array3.Length == 0)
							{
								if (flag4 && list2.Count > 0)
								{
									Warn("State file " + fileName + " was missing or empty in BepInEx/data (wiped on this server?): " + merged.Count + " lines put back from " + string.Join(", ", list2.Where((string p) => p != place)) + ".");
								}
								else
								{
									Info("State file " + fileName + ": copy made in " + place + " (" + merged.Count + " lines).");
								}
							}
							else
							{
								Warn("State file " + fileName + ": the copy in " + place + " was behind (" + array3.Length + " lines, the merge of all copies has " + merged.Count + "): updated, nothing was lost.");
							}
						}
						catch (Exception ex3)
						{
							WarnOnce("repair:" + place, "State file " + fileName + ": the copy in " + place + " could not be updated (" + ex3.Message + ").");
						}
					}
				}
				if (flag2 && ((array == null) ? (merged.Count > 0) : (!array.SequenceEqual(merged))))
				{
					try
					{
						if (WorldCopy.Write(fileName, merged.ToArray()))
						{
							Info("State file " + fileName + ": the world's copy " + ((array == null) ? "made" : "updated") + " (" + merged.Count + " lines).");
						}
					}
					catch (Exception ex4)
					{
						WarnOnce("worldwrite:" + fileName, "State file " + fileName + ": the world's copy could not be written (" + ex4.Message + ").");
					}
				}
				if (!flag || flag2)
				{
					reconciled.Add(path);
				}
				if (merged.Count > 0)
				{
					KeepLatest(path, found.Values.Any((string[] l) => l == null || l.Length != merged.Count));
				}
				return merged.ToArray();
			}
		}

		internal static List<Source> ReadSources(string path, out bool worldPending)
		{
			lock (Gate)
			{
				DailyBackup(path);
				string fileName = Path.GetFileName(path);
				List<string> list = new List<string>();
				list.Add(path);
				list.AddRange(MirrorPaths(path));
				List<Source> list2 = new List<Source>();
				foreach (string item in list)
				{
					DateTime stamp = DateTime.MinValue;
					string[] array = TryRead(item);
					if (array != null)
					{
						try
						{
							stamp = File.GetLastWriteTimeUtc(item);
						}
						catch (Exception)
						{
						}
					}
					list2.Add(new Source
					{
						Label = item,
						Lines = array,
						Stamp = stamp
					});
				}
				worldPending = false;
				try
				{
					if (WorldCopy.Applies())
					{
						if (WorldCopy.Ready())
						{
							string[] array2 = WorldCopy.Read(fileName);
							list2.Add(new Source
							{
								Label = "the world save",
								Lines = array2,
								Stamp = ((array2 == null) ? DateTime.MinValue : WorldCopy.Stamp(fileName)),
								IsWorld = true
							});
						}
						else
						{
							worldPending = true;
						}
					}
				}
				catch (Exception ex2)
				{
					worldPending = false;
					WarnOnce("worldread:" + fileName, "State file " + fileName + ": the world's copy could not be read (" + ex2.Message + ").");
				}
				return list2;
			}
		}

		internal static List<string> LinesFromBackups(string path)
		{
			lock (Gate)
			{
				return FromBackups(path);
			}
		}

		internal static bool WorldReady()
		{
			try
			{
				return WorldCopy.Applies() && WorldCopy.Ready();
			}
			catch (Exception)
			{
				return false;
			}
		}

		internal static bool WorldNotLoadedYet()
		{
			try
			{
				return WorldCopy.Applies() && !WorldCopy.Ready();
			}
			catch (Exception)
			{
				return false;
			}
		}

		internal static void MarkReconciled(string path)
		{
			lock (Gate)
			{
				reconciled.Add(path);
			}
		}

		private static List<string> Merge(List<string[]> sources)
		{
			int num = 0;
			for (int i = 1; i < sources.Count; i++)
			{
				if (sources[i].Length > sources[num].Length)
				{
					num = i;
				}
			}
			List<string> list = new List<string>(sources[num]);
			Dictionary<string, int> dictionary = new Dictionary<string, int>();
			foreach (string item in list)
			{
				dictionary.TryGetValue(item, out var value);
				dictionary[item] = value + 1;
			}
			for (int j = 0; j < sources.Count; j++)
			{
				if (j == num)
				{
					continue;
				}
				Dictionary<string, int> dictionary2 = new Dictionary<string, int>();
				string[] array = sources[j];
				foreach (string text in array)
				{
					dictionary2.TryGetValue(text, out var value2);
					value2 = (dictionary2[text] = value2 + 1);
					dictionary.TryGetValue(text, out var value3);
					if (value2 > value3)
					{
						list.Add(text);
						dictionary[text] = value3 + 1;
					}
				}
			}
			return list;
		}

		private static List<string> FromBackups(string path)
		{
			string fileName = Path.GetFileName(path);
			string text = path + ".bak";
			string[] array = TryRead(text);
			if (array != null && array.Length != 0)
			{
				Warn("State file " + fileName + " is gone: read from " + Path.GetFileName(text) + ".");
				return array.ToList();
			}
			try
			{
				string directoryName = Path.GetDirectoryName(path);
				List<KeyValuePair<string, string>> source = Backups(directoryName);
				foreach (KeyValuePair<string, string> item in source.Where((KeyValuePair<string, string> b) => b.Key == "latest").Concat(source.Where((KeyValuePair<string, string> b) => b.Key != "latest")).ToList())
				{
					string[] array2 = null;
					foreach (string item2 in BackupLocations(directoryName, item.Key))
					{
						string[] array3 = TryRead(Path.Combine(item2, fileName));
						if (array3 != null && array3.Length != 0 && (array2 == null || array3.Length > array2.Length))
						{
							array2 = array3;
						}
					}
					if (array2 != null)
					{
						Warn("State file " + fileName + " is gone from every place: restored from the backup copy '" + item.Key + "' (" + array2.Length + " lines). Anything newer than that copy is lost.");
						return array2.ToList();
					}
				}
			}
			catch (Exception ex)
			{
				Warn("State file " + fileName + ": the backup copies could not be searched (" + ex.Message + ").");
			}
			return new List<string>();
		}

		internal static void Append(string path, string line)
		{
			lock (Gate)
			{
				if (!reconciled.Contains(path))
				{
					ReadLines(path);
				}
				string fileName = Path.GetFileName(path);
				string contents = line + Environment.NewLine;
				bool flag = false;
				try
				{
					Directory.CreateDirectory(Path.GetDirectoryName(path));
					File.AppendAllText(path, contents);
					flag = true;
				}
				catch (Exception ex)
				{
					WarnOnce("append:" + path, "State file " + fileName + " could not be written in BepInEx/data (" + ex.Message + "); the other copies are written.");
				}
				foreach (string item in MirrorPaths(path))
				{
					try
					{
						Directory.CreateDirectory(Path.GetDirectoryName(item));
						if (File.Exists(item))
						{
							File.AppendAllText(item, contents);
						}
						else if (File.Exists(path))
						{
							File.Copy(path, item);
						}
						else
						{
							File.AppendAllText(item, contents);
						}
						flag = true;
					}
					catch (Exception ex2)
					{
						WarnOnce("append:" + item, "State file " + fileName + ": the copy in " + item + " could not be written (" + ex2.Message + ").");
					}
				}
				try
				{
					if (WorldCopy.Applies() && WorldCopy.Ready())
					{
						string[] array = WorldCopy.Read(fileName) ?? new string[0];
						string[] array2 = new string[array.Length + 1];
						Array.Copy(array, array2, array.Length);
						array2[array.Length] = line;
						if (WorldCopy.Write(fileName, array2))
						{
							flag = true;
						}
					}
				}
				catch (Exception ex3)
				{
					WarnOnce("worldappend:" + fileName, "State file " + fileName + ": the world's copy could not be written (" + ex3.Message + ").");
				}
				if (!flag)
				{
					throw new IOException("State file " + fileName + " could not be written in any place.");
				}
				DailyBackup(path);
				KeepLatest(path, force: false);
			}
		}

		internal static void Rewrite(string path, IEnumerable<string> lines)
		{
			lock (Gate)
			{
				List<string> list = lines.ToList();
				string fileName = Path.GetFileName(path);
				bool flag = false;
				Exception ex = null;
				try
				{
					RewriteFile(path, list);
					flag = true;
				}
				catch (Exception ex2)
				{
					ex = ex2;
					WarnOnce("rewrite:" + path, "State file " + fileName + " could not be rewritten in BepInEx/data (" + ex2.Message + "); the other copies are.");
				}
				foreach (string item in MirrorPaths(path))
				{
					try
					{
						RewriteFile(item, list);
						flag = true;
					}
					catch (Exception ex3)
					{
						WarnOnce("rewrite:" + item, "State file " + fileName + ": the copy in " + item + " could not be rewritten (" + ex3.Message + ").");
					}
				}
				try
				{
					if (WorldCopy.Applies() && WorldCopy.Ready() && WorldCopy.Write(fileName, list.ToArray()))
					{
						flag = true;
					}
				}
				catch (Exception ex4)
				{
					WarnOnce("worldrewrite:" + fileName, "State file " + fileName + ": the world's copy could not be rewritten (" + ex4.Message + ").");
				}
				reconciled.Add(path);
				if (!flag)
				{
					throw ex ?? new IOException("State file " + fileName + " could not be rewritten in any place.");
				}
				KeepLatest(path, force: true);
			}
		}

		private static void RewriteFile(string path, IEnumerable<string> lines)
		{
			Directory.CreateDirectory(Path.GetDirectoryName(path));
			string text = path + ".tmp";
			string text2 = path + ".bak";
			File.WriteAllLines(text, lines);
			try
			{
				if (File.Exists(path))
				{
					File.Replace(text, path, text2);
				}
				else
				{
					File.Move(text, path);
				}
			}
			catch (Exception ex)
			{
				Warn("State file " + Path.GetFileName(path) + ": atomic replace failed (" + ex.Message + "), copying instead.");
				if (File.Exists(path))
				{
					File.Copy(path, text2, overwrite: true);
				}
				File.Copy(text, path, overwrite: true);
				File.Delete(text);
			}
		}

		private static void KeepLatest(string path, bool force)
		{
			try
			{
				DateTime utcNow = DateTime.UtcNow;
				if (!force && latestAt.TryGetValue(path, out var value) && (utcNow - value).TotalSeconds < 60.0)
				{
					return;
				}
				latestAt[path] = utcNow;
				string fileName = Path.GetFileName(path);
				List<string> list = new List<string>();
				list.Add(path);
				list.AddRange(MirrorPaths(path));
				foreach (string item in list)
				{
					if (File.Exists(item))
					{
						string text = Path.Combine(Path.GetDirectoryName(item), "backups", "latest");
						Directory.CreateDirectory(text);
						File.Copy(item, Path.Combine(text, fileName), overwrite: true);
					}
				}
			}
			catch (Exception ex)
			{
				WarnOnce("latest", "State files: the rolling backup copy could not be written (" + ex.Message + ").");
			}
		}

		private static List<string> BackupRoots(string dir)
		{
			string mod = Path.GetFileName(dir);
			List<string> list = new List<string>();
			list.Add(Path.Combine(dir, "backups"));
			list.AddRange(from r in MirrorRoots()
				select Path.Combine(r, mod, "backups"));
			return list;
		}

		private static List<string> BackupLocations(string dir, string name)
		{
			return (from r in BackupRoots(dir)
				select Path.Combine(r, name)).Where(Directory.Exists).ToList();
		}

		private static long SizeOf(string folder)
		{
			try
			{
				return Directory.GetFiles(folder).Sum((string f) => new FileInfo(f).Length);
			}
			catch (Exception)
			{
				return 0L;
			}
		}

		internal static void DailyBackup(string path)
		{
			lock (Gate)
			{
				try
				{
					string directoryName = Path.GetDirectoryName(path);
					if (string.IsNullOrEmpty(directoryName))
					{
						return;
					}
					string text = DateTime.Now.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture);
					if (backedUpOn.TryGetValue(directoryName, out var value) && value == text)
					{
						return;
					}
					string fileName = Path.GetFileName(directoryName);
					bool flag = BackupInto(directoryName, text);
					foreach (string item in MirrorRoots())
					{
						BackupInto(Path.Combine(item, fileName), text);
					}
					if (flag)
					{
						backedUpOn[directoryName] = text;
					}
				}
				catch (Exception ex)
				{
					Warn("Daily backup of the state files failed (" + ex.Message + ").");
				}
			}
		}

		private static bool BackupInto(string folder, string name)
		{
			if (!Directory.Exists(folder))
			{
				return false;
			}
			string text = Path.Combine(folder, "backups");
			string text2 = Path.Combine(text, name);
			if (Directory.Exists(text2))
			{
				return true;
			}
			string[] array = (from f in Directory.GetFiles(folder)
				where !f.EndsWith(".tmp", StringComparison.OrdinalIgnoreCase)
				select f).ToArray();
			if (array.Length == 0)
			{
				return false;
			}
			Directory.CreateDirectory(text2);
			string[] array2 = array;
			foreach (string text3 in array2)
			{
				File.Copy(text3, Path.Combine(text2, Path.GetFileName(text3)), overwrite: true);
			}
			array2 = (from d in Directory.GetDirectories(text)
				where IsDaily(Path.GetFileName(d))
				select d).OrderByDescending<string, string>((string d) => Path.GetFileName(d), StringComparer.Ordinal).Skip(7).ToArray();
			for (int num = 0; num < array2.Length; num++)
			{
				Directory.Delete(array2[num], recursive: true);
			}
			Info("State files backed up to " + text2 + " (" + array.Length + " files, the " + 7 + " newest days are kept).");
			return true;
		}

		private static bool IsDaily(string name)
		{
			DateTime result;
			if (name.Length == 10)
			{
				return DateTime.TryParseExact(name, "yyyy-MM-dd", CultureInfo.InvariantCulture, DateTimeStyles.None, out result);
			}
			return false;
		}

		private static bool IsStateFile(string path)
		{
			string fileName = Path.GetFileName(path);
			if (!fileName.EndsWith(".bak", StringComparison.OrdinalIgnoreCase) && !fileName.EndsWith(".tmp", StringComparison.OrdinalIgnoreCase))
			{
				return !fileName.EndsWith(".moved", StringComparison.OrdinalIgnoreCase);
			}
			return false;
		}

		internal static string Snapshot(string dir, string label, out int count)
		{
			lock (Gate)
			{
				count = 0;
				string text = label + "-" + DateTime.Now.ToString("yyyy-MM-dd_HH-mm-ss", CultureInfo.InvariantCulture);
				string mod = Path.GetFileName(dir);
				List<string> list = new List<string>();
				list.Add(dir);
				list.AddRange(from r in MirrorRoots()
					select Path.Combine(r, mod));
				foreach (string item in list)
				{
					if (!Directory.Exists(item))
					{
						continue;
					}
					string[] array = (from f in Directory.GetFiles(item)
						where !f.EndsWith(".tmp", StringComparison.OrdinalIgnoreCase)
						select f).ToArray();
					if (array.Length != 0)
					{
						string text2 = Path.Combine(item, "backups", text);
						Directory.CreateDirectory(text2);
						string[] array2 = array;
						foreach (string text3 in array2)
						{
							File.Copy(text3, Path.Combine(text2, Path.GetFileName(text3)), overwrite: true);
						}
						count = Math.Max(count, array.Length);
						Info("State files copied to " + text2 + " (" + array.Length + " files).");
					}
				}
				return text;
			}
		}

		internal static List<KeyValuePair<string, string>> Backups(string dir)
		{
			List<KeyValuePair<string, string>> list = new List<KeyValuePair<string, string>>();
			Dictionary<string, DateTime> dictionary = new Dictionary<string, DateTime>();
			foreach (string item in BackupRoots(dir))
			{
				if (!Directory.Exists(item))
				{
					continue;
				}
				string[] directories = Directory.GetDirectories(item);
				foreach (string path in directories)
				{
					string fileName = Path.GetFileName(path);
					DateTime lastWriteTime = Directory.GetLastWriteTime(path);
					if (!dictionary.TryGetValue(fileName, out var value) || lastWriteTime > value)
					{
						dictionary[fileName] = lastWriteTime;
					}
				}
			}
			foreach (KeyValuePair<string, DateTime> item2 in dictionary.OrderByDescending((KeyValuePair<string, DateTime> p) => p.Value))
			{
				int num = (from l in BackupLocations(dir, item2.Key)
					select Directory.GetFiles(l).Count(IsStateFile)).DefaultIfEmpty(0).Max();
				list.Add(new KeyValuePair<string, string>(item2.Key, item2.Value.ToString("yyyy-MM-dd HH:mm", CultureInfo.InvariantCulture) + ", " + num + " state files"));
			}
			return list;
		}

		internal static int RestoreFrom(string dir, string backupName)
		{
			if (string.IsNullOrEmpty(backupName) || backupName.IndexOfAny(Path.GetInvalidFileNameChars()) >= 0 || backupName.Contains(".."))
			{
				return -1;
			}
			List<string> list = BackupLocations(dir, backupName);
			if (list.Count == 0)
			{
				return -1;
			}
			string text = list.OrderByDescending(SizeOf).First();
			int num = 0;
			foreach (string item in Directory.GetFiles(text).Where(IsStateFile))
			{
				Rewrite(Path.Combine(dir, Path.GetFileName(item)), File.ReadAllLines(item));
				num++;
			}
			Info("State files restored from " + text + " (" + num + " files).");
			return num;
		}

		private static string Brief(string file)
		{
			try
			{
				if (!File.Exists(file))
				{
					return "MISSING";
				}
				FileInfo fileInfo = new FileInfo(file);
				return File.ReadAllLines(file).Length + " lines, " + fileInfo.Length + " B, " + fileInfo.LastWriteTime.ToString("yyyy-MM-dd HH:mm", CultureInfo.InvariantCulture);
			}
			catch (Exception ex)
			{
				return "unreadable (" + ex.Message + ")";
			}
		}

		internal static List<string> Describe(string mod)
		{
			lock (Gate)
			{
				List<string> list = new List<string>();
				string text = Folder(mod);
				List<string> list2 = MirrorRoots();
				list.Add("Copies of the state files (reading merges all of them, every write goes to all):");
				list.Add("  data:   " + text);
				foreach (string item in list2)
				{
					list.Add("  copy:   " + Path.Combine(item, mod));
				}
				if (list2.Count == 0)
				{
					list.Add("  WARNING: no copy outside BepInEx/data (the save folder and the game folder could not be resolved).");
				}
				bool flag = false;
				bool flag2 = false;
				try
				{
					flag = WorldCopy.Applies();
					flag2 = flag && WorldCopy.Ready();
				}
				catch (Exception)
				{
				}
				list.Add("  world:  " + ((!flag) ? "not on this side (only a server or host keeps it)" : (flag2 ? "inside the world save (a persistent object far outside the map; saved with the world)" : "the world is not loaded yet")));
				List<string> list3 = new List<string>();
				list3.Add(text);
				list3.AddRange(list2.Select((string r) => Path.Combine(r, mod)));
				SortedSet<string> sortedSet = new SortedSet<string>(StringComparer.Ordinal);
				foreach (string item2 in list3)
				{
					if (!Directory.Exists(item2))
					{
						continue;
					}
					foreach (string item3 in Directory.GetFiles(item2).Where(IsStateFile))
					{
						sortedSet.Add(Path.GetFileName(item3));
					}
				}
				if (flag2)
				{
					try
					{
						foreach (string item4 in WorldCopy.Names())
						{
							sortedSet.Add(item4);
						}
					}
					catch (Exception ex2)
					{
						list.Add("  world copy: names could not be read (" + ex2.Message + ")");
					}
				}
				foreach (string item5 in sortedSet)
				{
					List<string> list4 = new List<string> { "data " + Brief(Path.Combine(text, item5)) };
					for (int num = 0; num < list2.Count; num++)
					{
						list4.Add("copy" + (num + 1) + " " + Brief(Path.Combine(list2[num], mod, item5)));
					}
					if (flag2)
					{
						try
						{
							string[] array = WorldCopy.Read(item5);
							list4.Add((array == null) ? "world MISSING" : ("world " + array.Length + " lines, " + WorldCopy.Stamp(item5).ToString("yyyy-MM-dd HH:mm", CultureInfo.InvariantCulture) + " UTC"));
						}
						catch (Exception ex3)
						{
							list4.Add("world unreadable (" + ex3.Message + ")");
						}
					}
					list.Add("  " + item5 + ": " + string.Join(" | ", list4));
				}
				List<KeyValuePair<string, string>> list5 = Backups(text);
				list.Add("  backups: " + list5.Count + ((list5.Count > 0) ? (" (newest " + list5[0].Key + ")") : "") + " - 'it backup list'");
				return list;
			}
		}

		internal static void ForgetReconciled()
		{
			lock (Gate)
			{
				reconciled.Clear();
			}
		}

		internal static void ForgetForTests()
		{
			lock (Gate)
			{
				backedUpOn.Clear();
				reconciled.Clear();
				warned.Clear();
				latestAt.Clear();
			}
		}
	}
	internal static class UiKit
	{
		internal static Action<string> Warn = delegate
		{
		};

		internal static readonly Dictionary<string, Sprite> sprites = new Dictionary<string, Sprite>();

		internal static Sprite panelSprite;

		internal static Type panelType;

		internal static Color panelColor = new Color(0.25f, 0.17f, 0.1f, 0.97f);

		internal static float panelPpu = 1f;

		internal static Material panelMaterial;

		internal static Button buttonTemplate;

		internal static TMP_FontAsset font;

		internal static TMP_FontAsset titleFont;

		internal static Color titleColor = new Color(1f, 0.63f, 0.235f);

		internal static Color bodyColor = new Color(0.98f, 0.95f, 0.9f);

		internal static bool skin;

		internal static Sprite flat;

		internal static TMP_FontAsset BodyFont()
		{
			if ((Object)(object)font == (Object)null)
			{
				Discover();
			}
			return font;
		}

		internal static RectTransform Rect(string name, Transform parent, Vector2 aMin, Vector2 aMax, Vector2 oMin, Vector2 oMax)
		{
			//IL_0014: Unknown result type (might be due to invalid IL or missing references)
			//IL_0019: 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_003e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0045: 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)
			RectTransform component = new GameObject(name, new Type[1] { typeof(RectTransform) })
			{
				layer = LayerMask.NameToLayer("UI")
			}.GetComponent<RectTransform>();
			((Transform)component).SetParent(parent, false);
			component.anchorMin = aMin;
			component.anchorMax = aMax;
			component.offsetMin = oMin;
			component.offsetMax = oMax;
			return component;
		}

		internal static Image Box(string name, Transform parent, Vector2 aMin, Vector2 aMax, Vector2 oMin, Vector2 oMax, Color color)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0003: Unknown result type (might be due to invalid IL or missing references)
			//IL_0004: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_0018: Unknown result type (might be due to invalid IL or missing references)
			Image obj = ((Component)Rect(name, parent, aMin, aMax, oMin, oMax)).gameObject.AddComponent<Image>();
			((Graphic)obj).color = color;
			return obj;
		}

		internal static Sprite FindSprite(string name)
		{
			if (sprites.TryGetValue(name, out var value) && (Object)(object)value != (Object)null)
			{
				return value;
			}
			value = null;
			Sprite[] array = Resources.FindObjectsOfTypeAll<Sprite>();
			foreach (Sprite val in array)
			{
				if ((Object)(object)val != (Object)null && ((Object)val).name == name)
				{
					value = val;
					break;
				}
			}
			sprites[name] = value;
			return value;
		}

		internal static bool Draws(TMP_FontAsset f)
		{
			if ((Object)(object)f == (Object)null)
			{
				return false;
			}
			try
			{
				return f.HasCharacter('A', true, true) && f.HasCharacter('g', true, true) && f.HasCharacter('7', true, true);
			}
			catch
			{
				return false;
			}
		}

		internal static void Discover()
		{
			//IL_005d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0062: Unknown result type (might be due to invalid IL or missing references)
			//IL_0272: Unknown result type (might be due to invalid IL or missing references)
			//IL_0277: Unknown result type (might be due to invalid IL or missing references)
			//IL_027e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0283: Unknown result type (might be due to invalid IL or missing references)
			skin = false;
			panelSprite = null;
			buttonTemplate = null;
			InventoryGui instance = InventoryGui.instance;
			TMP_FontAsset val = null;
			try
			{
				val = (((Object)(object)instance != (Object)null && (Object)(object)instance.m_recipeDecription != (Object)null) ? instance.m_recipeDecription.font : null);
				if ((Object)(object)instance != (Object)null && (Object)(object)instance.m_recipeDecription != (Object)null)
				{
					bodyColor = ((Graphic)instance.m_recipeDecription).color;
				}
			}
			catch
			{
			}
			try
			{
				titleFont = (((Object)(object)instance != (Object)null && (Object)(object)instance.m_recipeName != (Object)null && Draws(instance.m_recipeName.font)) ? instance.m_recipeName.font : null);
			}
			catch
			{
				titleFont = null;
			}
			TMP_FontAsset val2 = (Draws(val) ? val : null);
			if ((Object)(object)val2 == (Object)null)
			{
				TMP_FontAsset[] array = Resources.FindObjectsOfTypeAll<TMP_FontAsset>();
				foreach (TMP_FontAsset val3 in array)
				{
					if ((Object)(object)val3 != (Object)null && ((Object)val3).name.IndexOf("Averia", StringComparison.OrdinalIgnoreCase) >= 0 && Draws(val3))
					{
						val2 = val3;
						break;
					}
				}
			}
			if ((Object)(object)val2 == (Object)null)
			{
				try
				{
					TMP_FontAsset defaultFontAsset = TMP_Settings.defaultFontAsset;
					if (Draws(defaultFontAsset))
					{
						val2 = defaultFontAsset;
					}
				}
				catch
				{
				}
			}
			if ((Object)(object)val2 == (Object)null)
			{
				TMP_FontAsset[] array = Resources.FindObjectsOfTypeAll<TMP_FontAsset>();
				foreach (TMP_FontAsset val4 in array)
				{
					if (Draws(val4))
					{
						val2 = val4;
						break;
					}
				}
			}
			font = val2 ?? val;
			if ((Object)(object)instance == (Object)null || (Object)(object)instance.m_crafting == (Object)null)
			{
				return;
			}
			try
			{
				List<Image> list = ((Component)instance.m_crafting).GetComponentsInChildren<Image>(true).ToList();
				Transform parent = ((Transform)instance.m_crafting).parent;
				int num = 0;
				while (num < 3 && (Object)(object)parent != (Object)null)
				{
					Image component = ((Component)parent).GetComponent<Image>();
					if ((Object)(object)component != (Object)null)
					{
						list.Add(component);
					}
					num++;
					parent = parent.parent;
				}
				Func<Image, bool> bad = delegate(Image val6)
				{
					string text = (((Object)val6).name + " " + ((Object)val6.sprite).name).ToLowerInvariant();
					string[] array2 = new string[12]
					{
						"darken", "blob", "shadow", "glow", "select", "icon", "scroll", "handle", "bar", "highlight",
						"button", "tab"
					};
					foreach (string value in array2)
					{
						if (text.Contains(value))
						{
							return true;
						}
					}
					return false;
				};
				Image val5 = list.Where((Image val6) => (Object)(object)val6.sprite != (Object)null && !bad(val6) && ((Graphic)val6).color.a > 0.5f).OrderByDescending(delegate(Image val6)
				{
					//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_0019: Unknown result type (might be due to invalid IL or missing references)
					//IL_001e: Unknown result type (might be due to invalid IL or missing references)
					Rect rect = ((Graphic)val6).rectTransform.rect;
					float width = ((Rect)(ref rect)).width;
					rect = ((Graphic)val6).rectTransform.rect;
					return width * ((Rect)(ref rect)).height;
				}).FirstOrDefault();
				if ((Object)(object)val5 != (Object)null)
				{
					panelSprite = val5.sprite;
					panelType = val5.type;
					panelColor = ((Graphic)val5).color;
					panelPpu = val5.pixelsPerUnitMultiplier;
					panelMaterial = ((Graphic)val5).material;
				}
				buttonTemplate = instance.m_craftButton;
				skin = (Object)(object)val5 != (Object)null;
			}
			catch (Exception ex)
			{
				Warn("HypnoCode: the game's skin was not found (" + ex.Message + "), plain colours are used.");
			}
		}

		internal static TMP_Text Label(string name, Transform parent, Vector2 aMin, Vector2 aMax, Vector2 oMin, Vector2 oMax, string text, float size, Color color, TextAlignmentOptions align, bool ellipsis = false)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0003: Unknown result type (might be due to invalid IL or missing references)
			//IL_0004: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_0049: Unknown result type (might be due to invalid IL or missing references)
			//IL_0051: Unknown result type (might be due to invalid IL or missing references)
			GameObject gameObject = ((Component)Rect(name, parent, aMin, aMax, oMin, oMax)).gameObject;
			gameObject.SetActive(false);
			TextMeshProUGUI val = gameObject.AddComponent<TextMeshProUGUI>();
			if ((Object)(object)font != (Object)null)
			{
				((TMP_Text)val).font = font;
			}
			((TMP_Text)val).text = text;
			((TMP_Text)val).fontSize = size;
			((Graphic)val).color = color;
			((TMP_Text)val).alignment = align;
			((Graphic)val).raycastTarget = false;
			((TMP_Text)val).enableWordWrapping = false;
			((TMP_Text)val).overflowMode = (TextOverflowModes)(ellipsis ? 1 : 0);
			gameObject.SetActive(true);
			return (TMP_Text)(object)val;
		}

		internal static bool Keep(Component c)
		{
			if (!(c is Graphic) && !(c is Selectable) && !(c is Mask) && !(c is RectMask2D) && !(c is LayoutGroup) && !(c is ContentSizeFitter) && !(c is LayoutElement))
			{
				return c is BaseMeshEffect;
			}
			return true;
		}

		internal static Button MakeButton(string name, Transform parent, Vector2 aMin, Vector2 aMax, Vector2 oMin, Vector2 oMax, string text, Color colour, Action click, out TMP_Text labelOut, float size = 30f, bool edge = false)
		{
			//IL_0193: Unknown result type (might be due to invalid IL or missing references)
			//IL_0194: Unknown result type (might be due to invalid IL or missing references)
			//IL_0195: Unknown result type (might be due to invalid IL or missing references)
			//IL_0197: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ad: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d8: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e2: Expected O, but got Unknown
			//IL_01ed: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f2: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f7: 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_0205: Unknown result type (might be due to invalid IL or missing references)
			//IL_0050: Unknown result type (might be due to invalid IL or missing references)
			//IL_0055: 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_0061: Unknown result type (might be due to invalid IL or missing references)
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0368: Unknown result type (might be due to invalid IL or missing references)
			//IL_036a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0228: Unknown result type (might be due to invalid IL or missing references)
			//IL_022d: Unknown result type (might be due to invalid IL or missing references)
			//IL_023c: Unknown result type (might be due to invalid IL or missing references)
			//IL_024b: Unknown result type (might be due to invalid IL or missing references)
			//IL_02d5: Unknown result type (might be due to invalid IL or missing references)
			//IL_02dc: 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_02ef: Unknown result type (might be due to invalid IL or missing references)
			//IL_0306: Unknown result type (might be due to invalid IL or missing references)
			//IL_030d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0314: Unknown result type (might be due to invalid IL or missing references)
			//IL_0320: Unknown result type (might be due to invalid IL or missing references)
			//IL_0334: Unknown result type (might be due to invalid IL or missing references)
			//IL_0285: Unknown result type (might be due to invalid IL or missing references)
			//IL_028a: Unknown result type (might be due to invalid IL or missing references)
			//IL_02ad: 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_02bb: Unknown result type (might be due to invalid IL or missing references)
			//IL_02c7: Unknown result type (might be due to invalid IL or missing references)
			//IL_0122: Unknown result type (might be due to invalid IL or missing references)
			//IL_012a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0132: Unknown result type (might be due to invalid IL or missing references)
			//IL_016d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0172: Unknown result type (might be due to invalid IL or missing references)
			//IL_0173: Unknown result type (might be due to invalid IL or missing references)
			//IL_0179: Unknown result type (might be due to invalid IL or missing references)
			//IL_017a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0180: Unknown result type (might be due to invalid IL or missing references)
			//IL_0181: Unknown result type (might be due to invalid IL or missing references)
			//IL_0188: Unknown result type (might be due to invalid IL or missing references)
			Image val2;
			Button val3;
			if (skin && (Object)(object)buttonTemplate != (Object)null)
			{
				GameObject val = Object.Instantiate<GameObject>(((Component)buttonTemplate).gameObject, parent, false);
				((Object)val).name = name;
				val.SetActive(true);
				ColorBlock colors = ((Selectable)buttonTemplate).colors;
				Transition transition = ((Selectable)buttonTemplate).transition;
				SpriteState spriteState = ((Selectable)buttonTemplate).spriteState;
				foreach (MonoBehaviour item in val.GetComponentsInChildren<MonoBehaviour>(true).ToList())
				{
					if ((Object)(object)item != (Object)null && !Keep((Component)(object)item))
					{
						Object.DestroyImmediate((Object)(object)item);
					}
				}
				foreach (Selectable item2 in val.GetComponentsInChildren<Selectable>(true).ToList())
				{
					if ((Object)(object)item2 != (Object)null)
					{
						Object.DestroyImmediate((Object)(object)item2);
					}
				}
				val2 = val.GetComponent<Image>();
				val3 = val.AddComponent<Button>();
				((Selectable)val3).targetGraphic = (Graphic)(object)val2;
				((Selectable)val3).transition = transition;
				((Selectable)val3).colors = colors;
				((Selectable)val3).spriteState = spriteState;
				TMP_Text[] componentsInChildren = val.GetComponentsInChildren<TMP_Text>(true);
				for (int i = 0; i < componentsInChildren.Length; i++)
				{
					((Component)componentsInChildren[i]).gameObject.SetActive(false);
				}
				RectTransform val4 = (RectTransform)val.transform;
				val4.anchorMin = aMin;
				val4.anchorMax = aMax;
				val4.offsetMin = oMin;
				val4.offsetMax = oMax;
			}
			else
			{
				val2 = Box(name, parent, aMin, aMax, oMin, oMax, new Color(0.1f, 0.07f, 0.04f, 0.9f));
				val3 = ((Component)val2).gameObject.AddComponent<Button>();
				((Selectable)val3).targetGraphic = (Graphic)(object)val2;
			}
			((UnityEvent)val3.onClick).AddListener((UnityAction)delegate
			{
				ClickSound();
				click();
			});
			TMP_Text val5 = Label("text", ((Component)val2).transform, Vector2.zero, Vector2.one, Vector2.zero, Vector2.zero, text, size, colour, (TextAlignmentOptions)514);
			GameObject edge2 = null;
			RectTransform val6;
			if (edge)
			{
				val6 = Rect("edge", ((Component)val3).transform, Vector2.zero, Vector2.one, new Vector2(-1f, -1f), new Vector2(1f, 1f));
				Image val7 = ((Component)val6).gameObject.AddComponent<Image>();
				((Graphic)val7).raycastTarget = false;
				Sprite val8 = FindSprite("selection_frame");
				if ((Object)(object)val8 != (Object)null)
				{
					Vector4 border = val8.border;
					if (((Vector4)(ref border)).sqrMagnitude > 0f)
					{
						val7.sprite = val8;
						val7.type = (Type)1;
						((Graphic)val7).color = new Color(colour.r, colour.g, colour.b, 0.95f);
						goto IL_033e;
					}
				}
				((Graphic)val7).color = new Color(colour.r, colour.g, colour.b, 0f);
				Outline obj = ((Component)val6).gameObject.AddComponent<Outline>();
				((Shadow)obj).effectColor = new Color(colour.r, colour.g, colour.b, 0.9f);
				((Shadow)obj).effectDistance = new Vector2(2f, -2f);
				goto IL_033e;
			}
			goto IL_034e;
			IL_033e:
			((Transform)val6).SetAsFirstSibling();
			edge2 = ((Component)val6).gameObject;
			goto IL_034e;
			IL_034e:
			UiButtonTint uiButtonTint = ((Component)val3).gameObject.AddComponent<UiButtonTint>();
			uiButtonTint.Target = val3;
			uiButtonTint.Label = val5;
			uiButtonTint.Colour = colour;
			uiButtonTint.Edge = edge2;
			labelOut = val5;
			return val3;
		}

		internal static void ClickSound()
		{
			//IL_0041: Unknown result type (might be due to invalid IL or missing references)
			//IL_0046: Unknown result type (might be due to invalid IL or missing references)
			GameObject val = (((Object)(object)ZNetScene.instance != (Object)null) ? ZNetScene.instance.GetPrefab("sfx_gui_button") : null);
			if ((Object)(object)val != (Object)null && (Object)(object)Utils.GetMainCamera() != (Object)null)
			{
				Object.Instantiate<GameObject>(val, ((Component)Utils.GetMainCamera()).transform.position, Quaternion.identity);
			}
		}

		internal static Sprite FlatSprite()
		{
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			//IL_001c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0025: Expected O, but got Unknown
			//IL_0047: Unknown result type (might be due to invalid IL or missing references)
			//IL_004c: Unknown result type (might be due to invalid IL or missing references)
			//IL_007e: 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 ((Object)(object)flat != (Object)null)
			{
				return flat;
			}
			Texture2D val = new Texture2D(4, 4, (TextureFormat)4, false)
			{
				hideFlags = (HideFlags)61
			};
			Color32[] array = (Color32[])(object)new Color32[16];
			for (int i = 0; i < 16; i++)
			{
				array[i] = new Color32(byte.MaxValue, byte.MaxValue, byte.MaxValue, byte.MaxValue);
			}
			val.SetPixels32(array);
			val.Apply(false, true);
			flat = Sprite.Create(val, new Rect(0f, 0f, 4f, 4f), new Vector2(0.5f, 0.5f), 100f);
			((Object)flat).hideFlags = (HideFlags)61;
			return flat;
		}
	}
	public sealed class UiButtonTint : MonoBehaviour
	{
		public Button Target;

		public TMP_Text Label;

		public Color Colour;

		public GameObject Edge;

		private void Update()
		{
			//IL_004e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0046: Unknown result type (might be due to invalid IL or missing references)
			if (!((Object)(object)Target == (Object)null))
			{
				bool interactable = ((Selectable)Target).interactable;
				if ((Object)(object)Label != (Object)null)
				{
					((Graphic)Label).color = (Color)(interactable ? Colour : new Color(0.5f, 0.48f, 0.45f, 1f));
				}
				if ((Object)(object)Edge != (Object)null && Edge.activeSelf != interactable)
				{
					Edge.SetActive(interactable);
				}
			}
		}
	}
}
namespace ChildrenOfTheAncientHeart
{
	internal static class CoahAltars
	{
		private struct Kind
		{
			public string Key;

			public string Name;

			public Kind(string key, string name)
			{
				Key = key;
				Name = name;
			}
		}

		private static readonly Kind[] Kinds = new Kind[3]
		{
			new Kind("key", "Altar of the Key"),
			new Kind("gem", "Altar of the Crystal"),
			new Kind("shield", "Altar of the Aegis")
		};

		internal const string StatueName = "COAH_Statue_Sentinels";

		internal static string PrefabName(string key)
		{
			return "COAH_Altar_" + key;
		}

		internal static string Resolve(string key)
		{
			if (!Kinds.Any((Kind k) => k.Key == key))
			{
				return null;
			}
			return PrefabName(key);
		}

		internal static void Register(ZNetScene scene)
		{
			//IL_00a0: Unknown result type (might be due to invalid IL or missing references)
			GameObject storage = StoneSoldier.storage ?? throw new InvalidOperationException("COAH storage missing.");
			GameObject val = StoneSoldier.Need(scene, "stone_wall_1x1");
			Material val2 = StoneSoldier.CreateMaterial(scene.GetPrefab("StoneGolem"), StoneSoldier.Need(scene, "JotunWarrior"), "altars.jpg", "altars_n.jpg", compress: true);
			((Object)val2).name = "COAH altar";
			if (val2.HasProperty("_EmissionMap") && val2.HasProperty("_EmissionColor"))
			{
				Texture2D val3 = LoadTexture("altars_e.jpg");
				val2.SetTexture("_EmissionMap", (Texture)(object)val3);
				val2.SetColor("_EmissionColor", new Color(1.6f, 1.6f, 1.6f, 1f));
				val2.EnableKeyword("_EMISSION");
			}
			Collider componentInChildren = val.GetComponentInChildren<Collider>(true);
			int layer = (((Object)(object)componentInChildren != (Object)null) ? ((Component)componentInChildren).gameObject.layer : LayerMask.NameToLayer("piece"));
			GameObject prefab = scene.GetPrefab("Hammer");
			PieceTable val4 = (((Object)(object)prefab != (Object)null) ? prefab.GetComponent<ItemDrop>().m_itemData.m_shared.m_buildPieces : null);
			if ((Object)(object)val4 != (Object)null)
			{
				val4.m_pieces.RemoveAll((GameObject p) => (Object)(object)p == (Object)null || ((Object)p).name.StartsWith("COAH_Altar_") || ((Object)p).name == "COAH_Statue_Sentinels");
			}
			Kind[] kinds = Kinds;
			for (int num = 0; num < kinds.Length; num++)
			{
				Kind kind = kinds[num];
				AddPiece(scene, storage, val, layer, val4, PrefabName(kind.Key), kind.Name, "altar_" + kind.Key + ".bin", "altar_" + kind.Key + "_icon.png", val2, groundOnly: false, inMenu: false);
				GameObject prefab2 = scene.GetPrefab(PrefabName(kind.Key));
				CoahHeartChamber.Attach(prefab2, kind.Key, ((Component)prefab2.transform.Find("visual")).gameObject);
			}
			Material val5 = StoneSoldier.CreateMaterial(scene.GetPrefab("StoneGolem"), StoneSoldier.Need(scene, "JotunWarrior"), "prop_sentinels.jpg", "prop_sentinels_n.jpg", compress: true);
			((Object)val5).name = "COAH sentinels";
			AddPiece(scene, storage, val, layer, val4, "COAH_Statue_Sentinels", "Statue of True Love", "prop_sentinels.bin", "prop_sentinels_icon.png", val5, groundOnly: false, inMenu: false);
			scene.GetPrefab("COAH_Statue_Sentinels").AddComponent<CoahSentinels>();
			CoahPlugin.Log.LogInfo((object)("COAH decorations registered: " + string.Join(", ", Kinds.Select((Kind k) => PrefabName(k.Key)).ToArray()) + ", COAH_Statue_Sentinels (not in the hammer menu)."));
			CoahDecorations.Register(scene, storage, val, layer, val4);
		}

		internal static void AddPiece(ZNetScene scene, GameObject storage, GameObject source, int layer, PieceTable table, string prefabName, string displayName, string meshRes, string iconRes, Material material, bool groundOnly, bool inMenu)
		{
			//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_0124: 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)
			//IL_0148: Unknown result type (might be due to invalid IL or missing references)
			//IL_014d: Unknown result type (might be due to invalid IL or missing references)
			//IL_015f: 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_01fe: Unknown result type (might be due to invalid IL or missing references)
			ReadMeshes(meshRes, out var visual, out var collision);
			GameObject val = Object.Instantiate<GameObject>(source, storage.transform, false);
			((Object)val).name = prefabName;
			for (int num = val.transform.childCount - 1; num >= 0; num--)
			{
				Object.DestroyImmediate((Object)(object)((Component)val.transform.GetChild(num)).gameObject);
			}
			WearNTear[] components = val.GetComponents<WearNTear>();
			for (int i = 0; i < components.Length; i++)
			{
				Object.DestroyImmediate((Object)(object)components[i]);
			}
			Collider[] components2 = val.GetComponents<Collider>();
			for (int i = 0; i < components2.Length; i++)
			{
				Object.DestroyImmediate((Object)(object)components2[i]);
			}
			Renderer[] components3 = val.GetComponents<Renderer>();
			for (int i = 0; i < components3.Length; i++)
			{
				Object.DestroyImmediate((Object)(object)components3[i]);
			}
			MeshFilter[] components4 = val.GetComponents<MeshFilter>();
			for (int i = 0; i < components4.Length; i++)
			{
				Object.DestroyImmediate((Object)(object)components4[i]);
			}
			LODGroup[] components5 = val.GetComponents<LODGroup>();
			for (int i = 0; i < components5.Length; i++)
			{
				Object.DestroyImmediate((Object)(object)components5[i]);
			}
			GameObject val2 = new GameObject("visual");
			val2.transform.SetParent(val.transform, false);
			val2.layer = layer;
			val2.AddComponent<MeshFilter>().sharedMesh = visual;
			((Renderer)val2.AddComponent<MeshRenderer>()).sharedMaterial = material;
			GameObject val3 = new GameObject("collider");
			val3.transform.SetParent(val.transform, false);
			val3.layer = layer;
			val3.AddComponent<MeshCollider>().sharedMesh = collision;
			Piece component = val.GetComponent<Piece>();
			component.m_name = displayName;
			component.m_description = "Children of the Ancient Heart";
			component.m_icon = LoadIcon(iconRes);
			component.m_category = (PieceCategory)0;
			component.m_resources = (Requirement[])(object)new Requirement[0];
			component.m_craftingStation = null;
			component.m_allowedInDungeons = !groundOnly;
			component.m_groundOnly = groundOnly;
			component.m_groundPiece = false;
			component.m_cultivatedGroundOnly = false;
			component.m_waterPiece = false;
			component.m_notOnWood = false;
			component.m_notOnTiltingSurface = false;
			component.m_inCeilingOnly = false;
			component.m_notOnFloor = false;
			component.m_onlyInTeleportArea = false;
			component.m_onlyInBiome = (Biome)0;
			component.m_clipGround = true;
			component.m_clipEverything = true;
			component.m_noClipping = false;
			component.m_comfort = 0;
			component.m_enabled = true;
			component.m_canBeRemoved = true;
			StoneSoldier.RegisterScene(scene, val);
			if ((Object)(object)table != (Object)null && inMenu)
			{
				table.m_pieces.Add(val);
			}
		}

		private static byte[] Bytes(string resource)
		{
			using Stream stream = StoneSoldier.Resource(resource);
			using MemoryStream memoryStream = new MemoryStream();
			stream.CopyTo(memoryStream);
			return memoryStream.ToArray();
		}

		internal static Texture2D LoadTexture(string resource)
		{
			//IL_0004: Unknown result type (might be due to invalid IL or missing references)
			//IL_000a: Expected O, but got Unknown
			Texture2D val = new Texture2D(2, 2, (TextureFormat)4, true);
			if (!ImageConversion.LoadImage(val, Bytes(resource)))
			{
				throw new InvalidDataException(resource);
			}
			((Object)val).name = "COAH " + resource;
			((Texture)val).wrapMode = (TextureWrapMode)1;
			StoneSoldier.owned.Add((Object)(object)val);
			return val;
		}

		internal static Sprite LoadIcon(string resource)
		{
			//IL_0004: Unknown result type (might be due to invalid IL or missing references)
			//IL_000a: Expected O, but got Unknown
			//IL_0054: Unknown result type (might be due to invalid IL or missing references)
			//IL_0063: Unknown result type (might be due to invalid IL or missing references)
			Texture2D val = new Texture2D(2, 2, (TextureFormat)4, false);
			if (!ImageConversion.LoadImage(val, Bytes(resource)))
			{
				throw new InvalidDataException(resource);
			}
			((Object)val).name = "COAH " + resource;
			StoneSoldier.owned.Add((Object)(object)val);
			Sprite val2 = Sprite.Create(val, new Rect(0f, 0f, (float)((Texture)val).width, (float)((Texture)val).height), new Vector2(0.5f, 0.5f));
			StoneSoldier.owned.Add((Object)(object)val2);
			return val2;
		}

		internal static void ReadMeshes(string resource, out Mesh visual, out Mesh collision)
		{
			//IL_00d2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ed: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ff: Expected O, but got Unknown
			//IL_0148: Unknown result type (might be due to invalid IL or missing references)
			//IL_014d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0163: 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_0181: Expected O, but got Unknown
			BinaryReader reader = new BinaryReader(StoneSoldier.Resource(resource));
			try
			{
				if (Encoding.ASCII.GetString(reader.ReadBytes(8)) != "COAHS100")
				{
					throw new InvalidDataException(resource + ": bad header");
				}
				int num = reader.ReadInt32();
				int arg = reader.ReadInt32();
				int arg2 = reader.ReadInt32();
				int arg3 = reader.ReadInt32();
				Func<int, Vector3[]> func = delegate(int count)
				{
					//IL_002e: Unknown result type (might be due to invalid IL or missing references)
					//IL_0033: Unknown result type (might be due to invalid IL or missing references)
					Vector3[] array2 = (Vector3[])(object)new Vector3[count];
					for (int i = 0; i < count; i++)
					{
						array2[i] = new Vector3(reader.ReadSingle(), reader.ReadSingle(), reader.ReadSingle());
					}
					return array2;
				};
				Func<int, int[]> func2 = delegate(int count)
				{
					int[] array2 = new int[count];
					for (int i = 0; i < count; i++)
					{
						array2[i] = reader.ReadInt32();
					}
					return array2;
				};
				Vector3[] vertices = func(num);
				Vector3[] normals = func(num);
				Vector2[] array = (Vector2[])(object)new Vector2[num];
				for (int num2 = 0; num2 < num; num2++)
				{
					array[num2] = new Vector2(reader.ReadSingle(), reader.ReadSingle());
				}
				visual = new Mesh
				{
					name = "COAH " + resource
				};
				if (num > 65000)
				{
					visual.indexFormat = (IndexFormat)1;
				}
				visual.vertices = vertices;
				visual.normals = normals;
				visual.uv = array;
				visual.triangles = func2(arg);
				visual.RecalculateBounds();
				visual.RecalculateTangents();
				collision = new Mesh
				{
					name = "COAH " + resource + " collider",
					vertices = func(arg2),
					triangles = func2(arg3)
				};
				collision.RecalculateBounds();
				collision.RecalculateNormals();
				StoneSoldier.owned.Add((Object)(object)visual);
				StoneSoldier.owned.Add((Object)(object)collision);
			}
			finally
			{
				if (reader != null)
				{
					((IDisposable)reader).Dispose();
				}
			}
		}

		internal static void Command(ConsoleEventArgs args)
		{
			//IL_0099: Unknown result type (might be due to invalid IL or missing references)
			//IL_009e: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bd: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c8: 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_0100: Unknown result type (might be due to invalid IL or missing references)
			//IL_0102: Unknown result type (might be due to invalid IL or missing references)
			//IL_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_00e1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e8: Unknown result type (might be due to invalid IL or missing references)
			string text = ((args[1].ToLowerInvariant() == "statue") ? "COAH_Statue_Sentinels" : ((args.Length > 2) ? Resolve(args[2].ToLowerInvariant()) : null));
			Player localPlayer = Player.m_localPlayer;
			if (text == null || (Object)(object)localPlayer == (Object)null || (Object)(object)ZNetScene.instance == (Object)null)
			{
				args.Context.AddString("coah altar key|gem|shield  |  coah statue   (albo mlotek, zakladka Misc)");
				return;
			}
			GameObject prefab = ZNetScene.instance.GetPrefab(text);
			if ((Object)(object)prefab == (Object)null)
			{
				args.Context.AddString("COAH: that decoration is not available - see BepInEx/LogOutput.log.");
				return;
			}
			Vector3 forward = ((Component)localPlayer).transform.forward;
			forward.y = 0f;
			((Vector3)(ref forward)).Normalize();
			Vector3 val = ((Component)localPlayer).transform.position + forward * 3f;
			float y = default(float);
			if ((Object)(object)ZoneSystem.instance != (Object)null && ZoneSystem.instance.FindFloor(val + Vector3.up, ref y))
			{
				val.y = y;
			}
			Object.Instantiate<GameObject>(prefab, val, Quaternion.LookRotation(-forward));
			args.Context.AddString("COAH: placed " + prefab.GetComponent<Piece>().m_name + ".");
		}
	}
	internal static class CoahArena
	{
		private const string LocationName = "DN_Bossroom";

		internal const string SummonKey = "coah_arena_summon";

		private const float Above = 450f;

		private const float Scale = 3f;

		private const float Reach = 100f;

		private const float FloorGuess = -6f;

		private const float SummonDelay = 10f;

		private static readonly Vector3 ExitOffset = new Vector3(1f, 0.5f, -84f);

		private static readonly string[] Environments = new string[4] { "Crypt", "SunkenCrypt", "Caves", "Morkhalla" };

		private static readonly Color Tint = new Color(0.62f, 0.2f, 0.16f);

		private static readonly Color LakeTint = new Color(0.55f, 0.06f, 0.05f);

		private static readonly Color Glow = new Color(1f, 0.22f, 0.12f);

		private static GameObject root;

		private static GameObject growth;

		private static GameObject exit;

		private static int growthTries;

		private static float nextLook;

		private static float nextServer;

		private static float lastInside = -999f;

		private static bool visited;

		private static bool relocated;

		private static float nextSweep;

		private static long summonAt;

		private static long shownSummon;

		private static bool arrivalShown;

		private static Vector3 seaOffset;

		private static Vector3 seaFor = new Vector3(float.NaN, 0f, 0f);

		private const string OwnEnvironment = "COAH_AstronikusCave";

		internal static float Fps;

		private const string DefeatedKey = "defeated_coah_astronikus";

		private static Vector3 SeaOffset
		{
			get
			{
				//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_0010: Unknown result type (might be due to invalid IL or missing references)
				//IL_0036: Unknown result type (might be due to invalid IL or missing references)
				//IL_003b: 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_002a: Unknown result type (might be due to invalid IL or missing references)
				//IL_011b: Unknown result type (might be due to invalid IL or missing references)
				//IL_0122: Unknown result type (might be due to invalid IL or missing references)
				//IL_01be: Unknown result type (might be due to invalid IL or missing references)
				//IL_0175: Unknown result type (might be due to invalid IL or missing references)
				//IL_0176: Unknown result type (might be due to invalid IL or missing references)
				//IL_017b: Unknown result type (might be due to invalid IL or missing references)
				//IL_017c: Unknown result type (might be due to invalid IL or missing references)
				//IL_0145: Unknown result type (might be due to invalid IL or missing references)
				//IL_013c: Unknown result type (might be due to invalid IL or missing references)
				//IL_014a: Unknown result type (might be due to invalid IL or missing references)
				//IL_014e: Unknown result type (might be due to invalid IL or missing references)
				//IL_0160: 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_0098: 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_00d4: Unknown result type (might be due to invalid IL or missing references)
				//IL_00e2: Unknown result type (might be due to invalid IL or missing references)
				Vector3 sitePos = CoahCastle.SitePos;
				if (seaFor.x == sitePos.x && seaFor.z == sitePos.z)
				{
					return seaOffset;
				}
				WorldGenerator instance = WorldGenerator.instance;
				Vector3 zero = Vector3.zero;
				bool flag = false;
				if (instance != null)
				{
					float[] array = new float[5] { 1300f, 1600f, 2000f, 2500f, 3000f };
					foreach (float num in array)
					{
						for (int j = 0; j < 24; j++)
						{
							if (flag)
							{
								break;
							}
							float num2 = (float)j * (float)Math.PI * 2f / 24f;
							float num3 = sitePos.x + Mathf.Sin(num2) * num;
							float num4 = sitePos.z + Mathf.Cos(num2) * num;
							Vector2 val = new Vector2(num3, num4);
							if (!(((Vector2)(ref val)).magnitude > 9200f) && IsSea(instance, num3, num4))
							{
								((Vector3)(ref zero))..ctor(num3 - sitePos.x, 0f, num4 - sitePos.z);
								flag = true;
							}
						}
						if (flag)
						{
							break;
						}
					}
				}
				if (!flag)
				{
					Vector2 val2 = default(Vector2);
					((Vector2)(ref val2))..ctor(0f - sitePos.x, 0f - sitePos.z);
					val2 = ((((Vector2)(ref val2)).magnitude > 100f) ? ((Vector2)(ref val2)).normalized : Vector2.right);
					((Vector3)(ref zero))..ctor(val2.x * 1500f, 0f, val2.y * 1500f);
				}
				if (instance != null)
				{
					seaFor = sitePos;
					seaOffset = zero;
					CoahPlugin.Log.LogInfo((object)("COAH arena: Astronikus' cave stands " + ((Vector3)(ref zero)).magnitude.ToString("0") + " m from the castle's ground position" + (flag ? ", over open sea." : " (no open sea near; towards the middle of the map).")));
				}
				return zero;
			}
		}

		internal static Vector3 Centre => CoahDungeon.EntranceCentre + Vector3.up * 450f + SeaOffset;

		internal static string Environment
		{
			get
			{
				//IL_00cc: 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_00ce: Unknown result type (might be due to invalid IL or missing references)
				//IL_00cf: Unknown result type (might be due to invalid IL or missing references)
				//IL_00d4: 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_00d6: Unknown result type (might be due to invalid IL or missing references)
				//IL_00d7: 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_00dd: Unknown result type (might be due to invalid IL or missing references)
				//IL_00de: Unknown result type (might be due to invalid IL or missing references)
				//IL_00df: Unknown result type (might be due to invalid IL or missing references)
				//IL_00e4: Unknown result type (might be due to invalid IL or missing references)
				//IL_00e5: Unknown result type (might be due to invalid IL or missing references)
				//IL_00ee: 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_00f0: Unknown result type (might be due to invalid IL or missing references)
				//IL_00f1: Unknown result type (might be due to invalid IL or missing references)
				//IL_00f6: Unknown result type (might be due to invalid IL or missing references)
				//IL_00f7: Unknown result type (might be due to invalid IL or missing references)
				//IL_00f8: Unknown result type (might be due to invalid IL or missing references)
				//IL_00f9: 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_00ff: Unknown result type (might be due to invalid IL or missing references)
				//IL_0100: Unknown result type (might be due to invalid IL or missing references)
				//IL_0101: Unknown result type (might be due to invalid IL or missing references)
				//IL_0106: Unknown result type (might be due to invalid IL or missing references)
				//IL_0107: 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_014e: 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_0150: Unknown result type (might be due to invalid IL or missing references)
				//IL_0155: Unknown result type (might be due to invalid IL or missing references)
				//IL_0156: Unknown result type (might be due to invalid IL or missing references)
				EnvMan man = EnvMan.instance;
				if ((Object)(object)man == (Object)null)
				{
					return null;
				}
				if (man.m_environments.Any((EnvSetup e) => e.m_name == "COAH_AstronikusCave"))
				{
					return "COAH_AstronikusCave";
				}
				string from = Environments.FirstOrDefault((string n) => man.m_environments.Any((EnvSetup e) => e.m_name == n));
				if (from == null)
				{
					return null;
				}
				EnvSetup val = man.m_environments.First((EnvSetup e) => e.m_name == from).Clone();
				val.m_name = "COAH_AstronikusCave";
				val.m_default = false;
				Color val2 = default(Color);
				((Color)(ref val2))..ctor(0.2f, 0.02f, 0.02f);
				val.m_fogColorNight = (val.m_fogColorMorning = (val.m_fogColorDay = (val.m_fogColorEvening = val2)));
				val.m_fogColorSunNight = (val.m_fogColorSunMorning = (val.m_fogColorSunDay = (val.m_fogColorSunEvening = val2)));
				val.m_fogDensityNight = (val.m_fogDensityMorning = (val.m_fogDensityDay = (val.m_fogDensityEvening = 0.0018f)));
				val.m_ambColorNight = (val.m_ambColorDay = new Color(0.42f, 0.31f, 0.29f));
				man.AppendEnvironment(val);
				return "COAH_AstronikusCave";
			}
		}

		internal static Bounds Box => new Bounds(Centre + Vector3.up * 40f, new Vector3(260f, 190f, 260f));

		internal static Vector3 Entry
		{
			get
			{
				//IL_0000: 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_0019: Unknown result type (might be due to invalid IL or missing references)
				//IL_001e: Unknown result type (might be due to invalid IL or missing references)
				//IL_008f: Unknown result type (might be due to invalid IL or missing references)
				//IL_00a3: Unknown result type (might be due to invalid IL or missing references)
				//IL_00a8: Unknown result type (might be due to invalid IL or missing references)
				//IL_002c: Unknown result type (might be due to invalid IL or missing references)
				//IL_002d: Unknown result type (might be due to invalid IL or missing references)
				//IL_0075: 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)
				//IL_0084: Unknown result type (might be due to invalid IL or missing references)
				//IL_0089: Unknown result type (might be due to invalid IL or missing references)
				Vector3 val = Centre + new Vector3(0f, 6f, -57f);
				RaycastHit val2 = default(RaycastHit);
				if ((Object)(object)root != (Object)null && Physics.Raycast(val, Vector3.down, ref val2, 40f, LayerMask.GetMask(new string[5] { "Default", "static_solid", "Default_small", "piece", "terrain" })))
				{
					return ((RaycastHit)(ref val2)).point + Vector3.up * 0.3f;
				}
				return Centre + new Vector3(0f, -5f, -57f);
			}
		}

		private static Vector3 SpawnPoint => Centre + new Vector3(0f, -3f, 42f);

		private static bool Defeated
		{
			get
			{
				if ((Object)(object)ZoneSystem.instance != (Object)null)
				{
					return ZoneSystem.instance.GetGlobalKey("defeated_coah_astronikus");
				}
				return false;
			}
		}

		private static bool IsSea(WorldGenerator generator, float x, float z)
		{
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			//IL_002d: Invalid comparison between Unknown and I4
			for (int i = -1; i <= 1; i++)
			{
				for (int j = -1; j <= 1; j++)
				{
					if ((int)generator.GetBiome(x + (float)i * 200f, z + (float)j * 200f, 0.02f, false) != 256)
					{
						return false;
					}
				}
			}
			return true;
		}

		internal static bool Inside(Vector3 p)
		{
			//IL_0009: Unknown result type (might be due to invalid IL or missing references)
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_001d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			//IL_0031: 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)
			if (!CoahDungeon.Exists)
			{
				return false;
			}
			Vector3 centre = Centre;
			if (Utils.DistanceXZ(p, centre) < 120f && p.y > centre.y - 40f)
			{
				return p.y < centre.y + 130f;
			}
			return false;
		}

		internal static void Clear()
		{
			if ((Object)(object)root != (Object)null)
			{
				Object.Destroy((Object)(object)root);
			}
			if ((Object)(object)growth != (Object)null)
			{
				Object.Destroy((Object)(object)growth);
			}
			root = (growth = (exit = null));
			growthTries = 0;
			shownSummon = 0L;
			arrivalShown = false;
		}

		internal static bool Ensure()
		{
			if ((Object)(object)root != (Object)null)
			{
				return true;
			}
			if ((Object)(object)ZoneSystem.instance == (Object)null || (Object)(object)ZNetScene.instance == (Object)null)
			{
				return false;
			}
			try
			{
				Build();
			}
			catch (Exception ex)
			{
				CoahPlugin.Log.LogError((object)("COAH arena: " + ex));
				if ((Object)(object)root != (Object)null)
				{
					Object.Destroy((Object)(object)root);
				}
				root = null;
			}
			return (Object)(object)root != (Object)null;
		}

		private static void Build()
		{
			//IL_066c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0671: Unknown result type (might be due to invalid IL or missing references)
			//IL_0676: Unknown result type (might be due to invalid IL or missing references)
			//IL_067b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0713: Unknown result type (might be due to invalid IL or missing references)
			//IL_0718: Unknown result type (might be due to invalid IL or missing references)
			//IL_0042: Unknown result type (might be due to invalid IL or missing references)
			//IL_0263: Unknown result type (might be due to invalid IL or missing references)
			//IL_026d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0277: Unknown result type (might be due to invalid IL o