Decompiled source of Advanced Portal v1.0.3

AdvancedPortal.dll

Decompiled 2 weeks ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.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.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 AdvancedPortal
{
	internal static class Assets
	{
		internal static GameObject Storage;

		internal static readonly List<Object> Owned = new List<Object>();

		internal static void CreateStorage(ZNetScene scene)
		{
			//IL_000a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0014: Expected O, but got Unknown
			Release();
			Storage = new GameObject("Advanced Portal storage");
			Storage.SetActive(false);
			Storage.transform.SetParent(((Component)scene).transform, false);
		}

		internal static void Release()
		{
			foreach (Object item in Owned)
			{
				if (item != (Object)null)
				{
					Object.Destroy(item);
				}
			}
			Owned.Clear();
			if ((Object)(object)Storage != (Object)null)
			{
				Object.Destroy((Object)(object)Storage);
			}
			Storage = null;
		}

		internal static void RegisterScene(ZNetScene scene, GameObject prefab)
		{
			Prefabs.RegisterScene(scene, prefab);
		}

		internal static GameObject Need(ZNetScene scene, string name)
		{
			return scene.GetPrefab(name) ?? throw new InvalidOperationException("Prefab missing: " + name);
		}

		internal static IEnumerable<ZDO> AllZdos()
		{
			FieldInfo fieldInfo = AccessTools.Field(typeof(ZDOMan), "m_objectsByID");
			IDictionary dictionary = ((fieldInfo != null) ? (fieldInfo.GetValue(ZDOMan.instance) as IDictionary) : null);
			if (dictionary == null)
			{
				yield break;
			}
			foreach (object value in dictionary.Values)
			{
				ZDO val = (ZDO)((value is ZDO) ? value : null);
				if (val != null)
				{
					yield return val;
				}
			}
		}

		internal static Stream Resource(string name)
		{
			return Assembly.GetExecutingAssembly().GetManifestResourceStream("advancedportal." + name) ?? throw new FileNotFoundException("Embedded resource missing: " + name);
		}

		private static byte[] Bytes(string resource)
		{
			using Stream stream = 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 = "AP " + resource;
			((Texture)val).wrapMode = (TextureWrapMode)1;
			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 = "AP " + resource;
			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));
			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(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 = "AP " + 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 = "AP " + resource + " collider",
					vertices = func(arg2),
					triangles = func2(arg3)
				};
				collision.RecalculateBounds();
				collision.RecalculateNormals();
				Owned.Add((Object)(object)visual);
				Owned.Add((Object)(object)collision);
			}
			finally
			{
				if (reader != null)
				{
					((IDisposable)reader).Dispose();
				}
			}
		}

		private static void SetTexture(Material m, string name, Texture t)
		{
			if (m.HasProperty(name))
			{
				m.SetTexture(name, t);
			}
		}

		private static void SetFloat(Material m, string name, float v)
		{
			if (m.HasProperty(name))
			{
				m.SetFloat(name, v);
			}
		}

		internal static Material Surface(string colour, string normal, string glow, float glowStrength)
		{
			//IL_0224: Unknown result type (might be due to invalid IL or missing references)
			//IL_022b: Expected O, but got Unknown
			//IL_0278: Unknown result type (might be due to invalid IL or missing references)
			//IL_0378: Unknown result type (might be due to invalid IL or missing references)
			//IL_016e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0174: Expected O, but got Unknown
			//IL_0194: Unknown result type (might be due to invalid IL or missing references)
			//IL_019b: Expected O, but got Unknown
			//IL_0166: Unknown result type (might be due to invalid IL or missing references)
			//IL_03be: Unknown result type (might be due to invalid IL or missing references)
			ZNetScene instance = ZNetScene.instance;
			GameObject prefab = instance.GetPrefab("StoneGolem");
			GameObject val = Need(instance, "JotunWarrior");
			Material val2 = (from r in val.GetComponentsInChildren<SkinnedMeshRenderer>(true)
				where ((Object)r).name == "bodymale"
				select ((Renderer)r).sharedMaterial).FirstOrDefault((Func<Material, bool>)((Material m) => (Object)(object)m != (Object)null)) ?? (from r in val.GetComponentsInChildren<SkinnedMeshRenderer>(true)
				select ((Renderer)r).sharedMaterial).FirstOrDefault((Func<Material, bool>)((Material m) => (Object)(object)m != (Object)null));
			if ((Object)(object)val2 == (Object)null && (Object)(object)prefab != (Object)null)
			{
				val2 = (from r in prefab.GetComponentsInChildren<SkinnedMeshRenderer>(true)
					select ((Renderer)r).sharedMaterial).FirstOrDefault((Func<Material, bool>)((Material m) => (Object)(object)m != (Object)null));
			}
			Material val3 = (((Object)(object)val2 != (Object)null) ? new Material(val2) : new Material(Shader.Find("Standard") ?? Shader.Find("Diffuse")));
			((Object)val3).name = "AP " + colour;
			Owned.Add((Object)(object)val3);
			Texture2D val4 = new Texture2D(2, 2, (TextureFormat)4, true);
			if (!ImageConversion.LoadImage(val4, Bytes(colour)))
			{
				throw new InvalidDataException(colour);
			}
			((Object)val4).name = "AP " + colour;
			((Texture)val4).wrapMode = (TextureWrapMode)1;
			((Texture)val4).filterMode = (FilterMode)1;
			((Texture)val4).anisoLevel = 4;
			try
			{
				val4.Compress(false);
				val4.Apply(false, true);
			}
			catch (Exception ex)
			{
				AdvancedPortalPlugin.Log.LogWarning((object)("Texture compression skipped for " + colour + ": " + ex.Message));
			}
			Owned.Add((Object)(object)val4);
			Texture2D val5 = new Texture2D(2, 2, (TextureFormat)4, true, true);
			if (!ImageConversion.LoadImage(val5, Bytes(normal)))
			{
				throw new InvalidDataException(normal);
			}
			((Object)val5).name = "AP " + normal;
			((Texture)val5).wrapMode = (TextureWrapMode)1;
			((Texture)val5).anisoLevel = 4;
			Owned.Add((Object)(object)val5);
			val3.mainTexture = (Texture)(object)val4;
			val3.color = Color.white;
			if (val3.HasProperty("_BumpMap"))
			{
				val3.SetTexture("_BumpMap", (Texture)(object)val5);
				SetFloat(val3, "_BumpScale", 1f);
				val3.EnableKeyword("_NORMALMAP");
			}
			SetTexture(val3, "_MetallicGlossMap", null);
			SetTexture(val3, "_EmissionMap", null);
			val3.DisableKeyword("_METALLICGLOSSMAP");
			val3.DisableKeyword("_EMISSION");
			SetFloat(val3, "_Metallic", 0f);
			SetFloat(val3, "_MetalGloss", 0f);
			SetFloat(val3, "_Glossiness", 0.06f);
			SetFloat(val3, "_GlossMapScale", 0.06f);
			SetFloat(val3, "_UseGlossmap", 0f);
			SetFloat(val3, "_Hue", 0f);
			SetFloat(val3, "_Saturation", 0f);
			SetFloat(val3, "_Value", 0f);
			if (val3.HasProperty("_EmissionColor"))
			{
				val3.SetColor("_EmissionColor", Color.black);
			}
			if (glow != null && val3.HasProperty("_EmissionMap") && val3.HasProperty("_EmissionColor"))
			{
				val3.SetTexture("_EmissionMap", (Texture)(object)LoadTexture(glow));
				val3.SetColor("_EmissionColor", new Color(glowStrength, glowStrength, glowStrength, 1f));
				val3.EnableKeyword("_EMISSION");
			}
			return val3;
		}
	}
	internal static class CoahTakesOver
	{
		internal const string CoahId = "p0kahontazz.coah";

		private static bool told;

		internal static bool Active => Chainloader.PluginInfos.ContainsKey("p0kahontazz.coah");

		internal static void Announce()
		{
			AdvancedPortalPlugin.Log.LogWarning((object)"Children of the Ancient Heart is installed and has the same portal (the Heart Portal): the Advanced Portal is no longer in the hammer. Advanced Portals already standing keep working and can be taken down for their materials.");
		}

		internal static void Tick()
		{
			if (!told && Active && !((Object)(object)Player.m_localPlayer == (Object)null) && !((Object)(object)MessageHud.instance == (Object)null))
			{
				told = true;
				((Character)Player.m_localPlayer).Message((MessageType)2, "Advanced Portal: Children of the Ancient Heart has the same portal. Build its Heart Portal; your Advanced Portals keep working.", 0, (Sprite)null, false);
			}
		}
	}
	[BepInPlugin("p0kahontazz.advancedportal", "Advanced Portal", "1.0.3")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	public sealed class AdvancedPortalPlugin : BaseUnityPlugin
	{
		[HarmonyPatch(typeof(ZNetScene), "Awake")]
		private static class RegisterPatch
		{
			private static void Postfix(ZNetScene __instance)
			{
				try
				{
					Assets.CreateStorage(__instance);
					AdvancedPortals.Register(__instance);
				}
				catch (Exception ex)
				{
					Log.LogError((object)("Advanced Portal registration failed: " + ex));
				}
			}
		}

		[HarmonyPatch(typeof(ZNetScene), "OnDestroy")]
		private static class UnregisterPatch
		{
			private static void Prefix()
			{
				Assets.Release();
			}
		}

		public const string Id = "p0kahontazz.advancedportal";

		public const string Version = "1.0.3";

		internal static ManualLogSource Log;

		private Harmony harmony;

		private void Awake()
		{
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			//IL_0020: Expected O, but got Unknown
			Log = ((BaseUnityPlugin)this).Logger;
			ModReport.RegisterCommand();
			harmony = new Harmony("p0kahontazz.advancedportal");
			Type[] array = new Type[9]
			{
				typeof(RegisterPatch),
				typeof(UnregisterPatch),
				typeof(AdvancedPortals.UnlockPatch),
				typeof(AdvancedPortals.TakeInputPatch),
				typeof(AdvancedPortals.VisiblePatch),
				typeof(AdvancedPortals.MouseCapturePatch),
				typeof(AdvancedPortals.EscapePatch),
				typeof(AdvancedPortals.BeforeGamePairsPatch),
				typeof(AdvancedPortals.KeepOurPairPatch)
			};
			foreach (Type type in array)
			{
				try
				{
					harmony.CreateClassProcessor(type).Patch();
				}
				catch (Exception ex)
				{
					Log.LogError((object)("Patch " + type.Name + " failed: " + ex));
				}
			}
			Log.LogInfo((object)"Advanced Portal 1.0.3 loaded.");
			if (CoahTakesOver.Active)
			{
				CoahTakesOver.Announce();
			}
		}

		private void Start()
		{
			Compat.Report(Log, "AdvancedPortal");
		}

		private void OnDestroy()
		{
			Harmony obj = harmony;
			if (obj != null)
			{
				obj.UnpatchSelf();
			}
		}

		private void Update()
		{
			AdvancedPortals.Tick();
			CoahTakesOver.Tick();
		}
	}
	internal static class PortalBlue
	{
		private const float Hue = 0.58f;

		private static readonly Dictionary<Texture, Texture2D> shiftedTextures = new Dictionary<Texture, Texture2D>();

		private static int logged;

		internal static Color Shift(Color c)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_001e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			//IL_0026: 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_0014: Unknown result type (might be due to invalid IL or missing references)
			float num = default(float);
			float num2 = default(float);
			float num3 = default(float);
			Color.RGBToHSV(c, ref num, ref num2, ref num3);
			if (num2 < 0.2f)
			{
				return c;
			}
			Color result = Color.HSVToRGB(0.58f, num2, num3, true);
			result.a = c.a;
			return result;
		}

		private static Gradient Shift(Gradient g)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: Expected O, but got Unknown
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_0029: Unknown result type (might be due to invalid IL or missing references)
			//IL_0047: Unknown result type (might be due to invalid IL or missing references)
			Gradient val = new Gradient();
			GradientColorKey[] colorKeys = g.colorKeys;
			for (int i = 0; i < colorKeys.Length; i++)
			{
				colorKeys[i].color = Shift(colorKeys[i].color);
			}
			val.SetKeys(colorKeys, g.alphaKeys);
			val.mode = g.mode;
			return val;
		}

		private static MinMaxGradient Shift(MinMaxGradient m)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			//IL_001e: Expected I4, but got Unknown
			//IL_0022: Unknown result type (might be due to invalid IL or missing references)
			//IL_0027: 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_005c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0034: Unknown result type (might be due to invalid IL or missing references)
			//IL_0039: Unknown result type (might be due to invalid IL or missing references)
			//IL_0040: 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_004a: 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_009b: Unknown result type (might be due to invalid IL or missing references)
			ParticleSystemGradientMode mode = ((MinMaxGradient)(ref m)).mode;
			switch ((int)mode)
			{
			case 0:
				return new MinMaxGradient(Shift(((MinMaxGradient)(ref m)).color));
			case 2:
				return new MinMaxGradient(Shift(((MinMaxGradient)(ref m)).colorMin), Shift(((MinMaxGradient)(ref m)).colorMax));
			case 1:
				return new MinMaxGradient(Shift(((MinMaxGradient)(ref m)).gradient));
			case 3:
				return new MinMaxGradient(Shift(((MinMaxGradient)(ref m)).gradientMin), Shift(((MinMaxGradient)(ref m)).gradientMax));
			default:
			{
				MinMaxGradient result = default(MinMaxGradient);
				((MinMaxGradient)(ref result))..ctor(Shift(((MinMaxGradient)(ref m)).gradient));
				((MinMaxGradient)(ref result)).mode = (ParticleSystemGradientMode)4;
				return result;
			}
			}
		}

		private static Texture2D ShiftTexture(Texture source)
		{
			//IL_005e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0064: Expected O, but got Unknown
			//IL_008a: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ba: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bf: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f4: Unknown result type (might be due to invalid IL or missing references)
			if (shiftedTextures.TryGetValue(source, out var value) && (Object)(object)value != (Object)null)
			{
				return value;
			}
			if (source.width > 512 || source.height > 512)
			{
				return null;
			}
			RenderTexture temporary = RenderTexture.GetTemporary(source.width, source.height, 0, (RenderTextureFormat)0);
			RenderTexture active = RenderTexture.active;
			Texture2D val = new Texture2D(source.width, source.height, (TextureFormat)4, false);
			try
			{
				Graphics.Blit(source, temporary);
				RenderTexture.active = temporary;
				val.ReadPixels(new Rect(0f, 0f, (float)source.width, (float)source.height), 0, 0);
			}
			finally
			{
				RenderTexture.active = active;
				RenderTexture.ReleaseTemporary(temporary);
			}
			Color[] pixels = val.GetPixels();
			for (int i = 0; i < pixels.Length; i++)
			{
				pixels[i] = Shift(pixels[i]);
			}
			val.SetPixels(pixels);
			val.Apply(false);
			((Texture)val).wrapMode = source.wrapMode;
			((Texture)val).filterMode = source.filterMode;
			((Object)val).name = "AP blue " + ((Object)source).name;
			shiftedTextures[source] = val;
			return val;
		}

		private static void ShiftMaterial(Material material, StringBuilder report)
		{
			//IL_001a: Unknown result type (might be due to invalid IL or missing references)
			//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)
			//IL_0034: Unknown result type (might be due to invalid IL or missing references)
			//IL_0035: Unknown result type (might be due to invalid IL or missing references)
			//IL_003a: Unknown result type (might be due to invalid IL or missing references)
			//IL_003c: Unknown result type (might be due to invalid IL or missing references)
			//IL_003e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0048: 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_0141: 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_0150: Invalid comparison between Unknown and I4
			//IL_0209: Unknown result type (might be due to invalid IL or missing references)
			//IL_020c: Invalid comparison between Unknown and I4
			//IL_018e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0193: 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_019c: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a3: Unknown result type (might be due to invalid IL or missing references)
			//IL_01aa: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b1: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b6: Unknown result type (might be due to invalid IL or missing references)
			//IL_01bb: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c0: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c7: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ce: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d5: Unknown result type (might be due to invalid IL or missing references)
			//IL_01dc: Unknown result type (might be due to invalid IL or missing references)
			//IL_0307: Unknown result type (might be due to invalid IL or missing references)
			//IL_030c: Unknown result type (might be due to invalid IL or missing references)
			Shader shader = material.shader;
			if ((Object)(object)shader == (Object)null)
			{
				return;
			}
			for (int i = 0; i < shader.GetPropertyCount(); i++)
			{
				if ((int)shader.GetPropertyType(i) == 0)
				{
					string propertyName = shader.GetPropertyName(i);
					Color color = material.GetColor(propertyName);
					Color val = Shift(color);
					if (val != color)
					{
						material.SetColor(propertyName, val);
					}
					report?.Append(propertyName + " " + color.r.ToString("0.0") + "," + color.g.ToString("0.0") + "," + color.b.ToString("0.0") + ">" + val.r.ToString("0.0") + "," + val.g.ToString("0.0") + "," + val.b.ToString("0.0") + " ");
				}
			}
			for (int j = 0; j < shader.GetPropertyCount(); j++)
			{
				ShaderPropertyType propertyType = shader.GetPropertyType(j);
				string propertyName2 = shader.GetPropertyName(j);
				if ((int)propertyType == 1)
				{
					string text = propertyName2.ToLowerInvariant();
					if (text.Contains("color") || text.Contains("tint") || text.Contains("emis"))
					{
						Vector4 vector = material.GetVector(propertyName2);
						Color val2 = PortalBlue.Shift(new Color(vector.x, vector.y, vector.z, vector.w));
						material.SetVector(propertyName2, new Vector4(val2.r, val2.g, val2.b, val2.a));
						report?.Append("vec " + propertyName2 + " ");
					}
				}
				else
				{
					if ((int)propertyType != 4)
					{
						continue;
					}
					Texture texture = material.GetTexture(propertyName2);
					if (!((Object)(object)texture == (Object)null))
					{
						Texture2D val3 = ShiftTexture(texture);
						if ((Object)(object)val3 != (Object)null)
						{
							material.SetTexture(propertyName2, (Texture)(object)val3);
						}
						report?.Append("tex " + propertyName2 + " " + ((Object)texture).name + " " + texture.width + "x" + texture.height + (((Object)(object)val3 != (Object)null) ? " (shifted) " : " (kept) "));
					}
				}
			}
			report?.Append("| props: ");
			if (report != null)
			{
				for (int k = 0; k < shader.GetPropertyCount() && k < 24; k++)
				{
					report.Append(shader.GetPropertyName(k) + ":" + ((object)shader.GetPropertyType(k)/*cast due to .constrained prefix*/).ToString() + " ");
				}
			}
		}

		private static string Show(MinMaxGradient m)
		{
			//IL_0022: Unknown result type (might be due to invalid IL or missing references)
			//IL_0027: 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_0039: Unknown result type (might be due to invalid IL or missing references)
			//IL_002b: Unknown result type (might be due to invalid IL or missing references)
			//IL_002d: Invalid comparison between Unknown and I4
			//IL_0051: 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)
			//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)
			Func<Color, string> func = (Color k) => k.r.ToString("0.00") + "," + k.g.ToString("0.00") + "," + k.b.ToString("0.00");
			ParticleSystemGradientMode mode = ((MinMaxGradient)(ref m)).mode;
			if ((int)mode != 0)
			{
				if ((int)mode == 2)
				{
					return "two " + func(((MinMaxGradient)(ref m)).colorMin) + " / " + func(((MinMaxGradient)(ref m)).colorMax);
				}
				return ((object)((MinMaxGradient)(ref m)).mode/*cast due to .constrained prefix*/).ToString();
			}
			return "color " + func(((MinMaxGradient)(ref m)).color);
		}

		internal static void Apply(GameObject root)
		{
			//IL_001a: Unknown result type (might be due to invalid IL or missing references)
			//IL_001f: 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_0033: Unknown result type (might be due to invalid IL or missing references)
			//IL_0038: Unknown result type (might be due to invalid IL or missing references)
			//IL_009a: Unknown result type (might be due to invalid IL or missing references)
			//IL_009f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0072: Unknown result type (might be due to invalid IL or missing references)
			//IL_0077: Unknown result type (might be due to invalid IL or missing references)
			//IL_007b: Unknown result type (might be due to invalid IL or missing references)
			//IL_00be: 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_00ae: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d7: 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_00fb: Unknown result type (might be due to invalid IL or missing references)
			//IL_0109: Unknown result type (might be due to invalid IL or missing references)
			//IL_010e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0259: Unknown result type (might be due to invalid IL or missing references)
			//IL_025e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0221: Unknown result type (might be due to invalid IL or missing references)
			//IL_0228: Expected O, but got Unknown
			StringBuilder stringBuilder = new StringBuilder();
			ParticleSystem[] componentsInChildren = root.GetComponentsInChildren<ParticleSystem>(true);
			foreach (ParticleSystem val in componentsInChildren)
			{
				MainModule main = val.main;
				string text = Show(((MainModule)(ref main)).startColor);
				((MainModule)(ref main)).startColor = Shift(((MainModule)(ref main)).startColor);
				if (logged < 4)
				{
					string[] obj = new string[6]
					{
						((Object)val).name,
						" [",
						text,
						" -> ",
						null,
						null
					};
					MainModule main2 = val.main;
					obj[4] = Show(((MainModule)(ref main2)).startColor);
					obj[5] = "] ";
					stringBuilder.Append(string.Concat(obj));
				}
				ColorOverLifetimeModule colorOverLifetime = val.colorOverLifetime;
				if (((ColorOverLifetimeModule)(ref colorOverLifetime)).enabled)
				{
					((ColorOverLifetimeModule)(ref colorOverLifetime)).color = Shift(((ColorOverLifetimeModule)(ref colorOverLifetime)).c