Decompiled source of ReplayTimerMod v1.0.0

ReplayTimerMod.SS.dll

Decompiled a month ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using System.Text;
using System.Text.RegularExpressions;
using BepInEx;
using BepInEx.Logging;
using GlobalEnums;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.Events;
using UnityEngine.Rendering;
using UnityEngine.UI;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("ReplayTimerMod.SS")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0+37522581096b36f96aa9c73a6982df73c4f373c0")]
[assembly: AssemblyProduct("ReplayTimerMod.SS")]
[assembly: AssemblyTitle("ReplayTimerMod")]
[assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/AdiPrk/ReplayTimerMod")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.0.0.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

		public NullableAttribute(byte P_0)
		{
			NullableFlags = new byte[1] { P_0 };
		}

		public NullableAttribute(byte[] P_0)
		{
			NullableFlags = P_0;
		}
	}
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableContextAttribute : Attribute
	{
		public readonly byte Flag;

		public NullableContextAttribute(byte P_0)
		{
			Flag = P_0;
		}
	}
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace BepInEx
{
	[AttributeUsage(AttributeTargets.Class, Inherited = false, AllowMultiple = false)]
	[Conditional("CodeGeneration")]
	internal sealed class BepInAutoPluginAttribute : Attribute
	{
		public BepInAutoPluginAttribute(string? id = null, string? name = null, string? version = null)
		{
		}
	}
}
namespace BepInEx.Preloader.Core.Patching
{
	[AttributeUsage(AttributeTargets.Class, Inherited = false, AllowMultiple = false)]
	[Conditional("CodeGeneration")]
	internal sealed class PatcherAutoPluginAttribute : Attribute
	{
		public PatcherAutoPluginAttribute(string? id = null, string? name = null, string? version = null)
		{
		}
	}
}
namespace ReplayTimerMod
{
	internal static class Compress
	{
		private const long MaxDecompressedBytes = 67108864L;

		internal static byte[] CompressData(byte[] data)
		{
			using MemoryStream memoryStream = new MemoryStream();
			using (DeflateStream deflateStream = new DeflateStream(memoryStream, CompressionLevel.Optimal))
			{
				deflateStream.Write(data, 0, data.Length);
			}
			return memoryStream.ToArray();
		}

		internal static byte[] DecompressData(byte[] data)
		{
			using MemoryStream stream = new MemoryStream(data);
			using MemoryStream memoryStream = new MemoryStream();
			using (DeflateStream deflateStream = new DeflateStream(stream, CompressionMode.Decompress))
			{
				byte[] array = new byte[8192];
				int num;
				while ((num = deflateStream.Read(array, 0, array.Length)) > 0)
				{
					if (memoryStream.Length + num > 67108864)
					{
						throw new InvalidDataException("Decompressed replay exceeds maximum allowed size");
					}
					memoryStream.Write(array, 0, num);
				}
			}
			return memoryStream.ToArray();
		}
	}
	public static class LoadRemover
	{
		private const BindingFlags AnyInstance = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;

		private static GameState prevGameState = (GameState)4;

		private static bool lookForTele = false;

		private static bool gameStateResolved;

		private static PropertyInfo? gameStateProp;

		private static FieldInfo? gameStateField;

		private static bool sceneLoadResolved;

		private static PropertyInfo? sceneLoadProp;

		private static FieldInfo? sceneLoadField;

		private static bool activationResolved;

		private static PropertyInfo? activationProp;

		private static FieldInfo? activationField;

		public static bool ShouldTick()
		{
			//IL_00dd: 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_00f0: Invalid comparison between Unknown and I4
			//IL_00f7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f9: Invalid comparison between Unknown and I4
			//IL_00f2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f5: Invalid comparison between Unknown and I4
			//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_0103: Unknown result type (might be due to invalid IL or missing references)
			//IL_0106: Invalid comparison between Unknown and I4
			//IL_0108: Unknown result type (might be due to invalid IL or missing references)
			//IL_010b: Invalid comparison between Unknown and I4
			//IL_0117: Unknown result type (might be due to invalid IL or missing references)
			//IL_011a: Invalid comparison between Unknown and I4
			//IL_008e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0093: Unknown result type (might be due to invalid IL or missing references)
			//IL_0095: Unknown result type (might be due to invalid IL or missing references)
			//IL_0098: Invalid comparison between Unknown and I4
			//IL_0121: Unknown result type (might be due to invalid IL or missing references)
			//IL_0124: Invalid comparison between Unknown and I4
			//IL_009a: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a0: Invalid comparison between Unknown and I4
			//IL_012b: Unknown result type (might be due to invalid IL or missing references)
			//IL_012e: Invalid comparison between Unknown and I4
			//IL_0132: Unknown result type (might be due to invalid IL or missing references)
			//IL_0134: Invalid comparison between Unknown and I4
			//IL_00af: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b2: Invalid comparison between Unknown and I4
			//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_00b4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b7: Invalid comparison between Unknown and I4
			//IL_016a: Unknown result type (might be due to invalid IL or missing references)
			//IL_016c: Unknown result type (might be due to invalid IL or missing references)
			//IL_013a: Unknown result type (might be due to invalid IL or missing references)
			//IL_013c: Invalid comparison between Unknown and I4
			//IL_013e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0140: Invalid comparison between Unknown and I4
			GameManager instance = GameManager.instance;
			if ((Object)(object)instance == (Object)null || (Object)(object)instance.ui == (Object)null || (Object)(object)instance.inputHandler == (Object)null)
			{
				return false;
			}
			UIState uiState = instance.ui.uiState;
			string sceneNameString = instance.GetSceneNameString();
			string nextSceneName = instance.nextSceneName;
			bool flag = (sceneNameString != "Menu_Title" && nextSceneName == "") || (sceneNameString != "Menu_Title" && nextSceneName == "Menu_Title") || sceneNameString == "Quit_To_Menu";
			GameState val = ReadGameState();
			if ((int)val == 4 && (int)prevGameState == 1)
			{
				lookForTele = true;
			}
			if (lookForTele && (int)val != 4 && (int)val != 3)
			{
				lookForTele = false;
			}
			bool acceptingInput = instance.inputHandler.acceptingInput;
			HeroTransitionState val2;
			try
			{
				val2 = instance.hero_ctrl.transitionState;
			}
			catch
			{
				val2 = (HeroTransitionState)0;
			}
			bool flag2 = ReadSceneLoadActivationAllowed();
			bool num = lookForTele;
			bool flag3 = ((int)val == 4 || (int)val == 3) && (int)uiState != 4;
			bool flag4 = (int)val != 4 && (int)val != 7 && !acceptingInput;
			bool flag5 = ((int)val == 6 && flag2) || (int)val == 2;
			bool flag6 = (int)val2 == 2;
			bool flag7 = (int)uiState != 4 && (flag || ((int)uiState != 5 && (int)uiState != 3 && !(nextSceneName == ""))) && nextSceneName != sceneNameString;
			bool num2 = num || flag3 || flag4 || flag5 || flag6 || flag7;
			prevGameState = val;
			return !num2;
		}

		private static GameState ReadGameState()
		{
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0014: Unknown result type (might be due to invalid IL or missing references)
			//IL_0126: Unknown result type (might be due to invalid IL or missing references)
			//IL_012c: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fe: Unknown result type (might be due to invalid IL or missing references)
			//IL_0119: Unknown result type (might be due to invalid IL or missing references)
			//IL_011e: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				GameManager instance = GameManager.instance;
				if ((Object)(object)instance == (Object)null)
				{
					return prevGameState;
				}
				if (!gameStateResolved)
				{
					gameStateResolved = true;
					Type type = ((object)instance).GetType();
					string[] array = new string[2] { "GameState", "gameState" };
					foreach (string name in array)
					{
						gameStateProp = type.GetProperty(name, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
						if (gameStateProp != null && gameStateProp.PropertyType == typeof(GameState))
						{
							break;
						}
						gameStateProp = null;
						gameStateField = type.GetField(name, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
						if (gameStateField != null && gameStateField.FieldType == typeof(GameState))
						{
							break;
						}
						gameStateField = null;
					}
				}
				if (gameStateProp != null)
				{
					return (GameState)gameStateProp.GetValue(instance, null);
				}
				if (gameStateField != null)
				{
					return (GameState)gameStateField.GetValue(instance);
				}
			}
			catch
			{
			}
			return prevGameState;
		}

		private static bool ReadSceneLoadActivationAllowed()
		{
			try
			{
				GameManager instance = GameManager.instance;
				if ((Object)(object)instance == (Object)null)
				{
					return false;
				}
				if (!sceneLoadResolved)
				{
					sceneLoadResolved = true;
					Type type = ((object)instance).GetType();
					string[] array = new string[2] { "sceneLoad", "SceneLoad" };
					foreach (string name in array)
					{
						sceneLoadProp = type.GetProperty(name, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
						if (sceneLoadProp != null)
						{
							break;
						}
						sceneLoadField = type.GetField(name, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
						if (sceneLoadField != null)
						{
							break;
						}
					}
				}
				object obj = ((sceneLoadProp != null) ? sceneLoadProp.GetValue(instance, null) : sceneLoadField?.GetValue(instance));
				if (obj == null)
				{
					return false;
				}
				if (!activationResolved)
				{
					activationResolved = true;
					Type type2 = obj.GetType();
					string[] array = new string[2] { "IsActivationAllowed", "isActivationAllowed" };
					foreach (string name2 in array)
					{
						activationProp = type2.GetProperty(name2, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
						if (activationProp != null && activationProp.PropertyType == typeof(bool))
						{
							break;
						}
						activationProp = null;
						activationField = type2.GetField(name2, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
						if (activationField != null && activationField.FieldType == typeof(bool))
						{
							break;
						}
						activationField = null;
					}
				}
				if (activationProp != null)
				{
					return (bool)activationProp.GetValue(obj, null);
				}
				if (activationField != null)
				{
					return (bool)activationField.GetValue(obj);
				}
			}
			catch
			{
			}
			return false;
		}
	}
	internal static class ManualInstallImport
	{
		private static readonly ManualLogSource Log = Logger.CreateLogSource("ManualInstallImport");

		private const string DataFolder = "ReplayMod";

		private const string PluginDll = "ReplayTimerMod.SS.dll";

		public static void Run(string pluginDirectory)
		{
			string text = Path.Combine(pluginDirectory, "ReplayMod");
			if (Directory.Exists(text))
			{
				return;
			}
			string text2 = text + ".importing";
			try
			{
				if (Directory.Exists(text2))
				{
					Directory.Delete(text2, recursive: true);
				}
				string text3 = FindManualInstall();
				if (text3 != null)
				{
					CopyDirectory(text3, text2);
					Directory.Move(text2, text);
					Log.LogInfo((object)("[ManualInstallImport] Imported runs and settings from " + text3));
				}
			}
			catch (Exception ex)
			{
				Log.LogWarning((object)("[ManualInstallImport] Import skipped: " + ex.Message));
				try
				{
					if (Directory.Exists(text2))
					{
						Directory.Delete(text2, recursive: true);
					}
				}
				catch (IOException)
				{
				}
			}
		}

		private static string? FindManualInstall()
		{
			string text = null;
			string[] directories = Directory.GetDirectories(Paths.PluginPath, "ReplayMod", SearchOption.AllDirectories);
			foreach (string text2 in directories)
			{
				string path = Path.Combine(text2, "data");
				if (File.Exists(Path.Combine(Path.GetDirectoryName(text2) ?? "", "ReplayTimerMod.SS.dll")) && Directory.Exists(path) && Directory.GetFiles(path, "*.json").Length != 0)
				{
					if (text != null)
					{
						Log.LogInfo((object)"[ManualInstallImport] Several manual installs found - not importing");
						return null;
					}
					text = text2;
				}
			}
			return text;
		}

		private static void CopyDirectory(string source, string destination)
		{
			Directory.CreateDirectory(destination);
			string[] files = Directory.GetFiles(source);
			foreach (string text in files)
			{
				File.Copy(text, Path.Combine(destination, Path.GetFileName(text)));
			}
			files = Directory.GetDirectories(source);
			foreach (string text2 in files)
			{
				CopyDirectory(text2, Path.Combine(destination, Path.GetFileName(text2)));
			}
		}
	}
	public static class QuickWarp
	{
		private static readonly ManualLogSource Log = Logger.CreateLogSource("QuickWarp");

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

		private static readonly bool Enabled = false;

		private static bool _loaded;

		private const float WarpWatchdogSeconds = 15f;

		public static bool IsWarping { get; private set; }

		public static void Init()
		{
			if (_loaded || !Enabled)
			{
				return;
			}
			_loaded = true;
			try
			{
				Assembly executingAssembly = Assembly.GetExecutingAssembly();
				string text = null;
				string[] manifestResourceNames = executingAssembly.GetManifestResourceNames();
				foreach (string text2 in manifestResourceNames)
				{
					if (text2.EndsWith("transitions.json", StringComparison.OrdinalIgnoreCase))
					{
						text = text2;
						break;
					}
				}
				if (text == null)
				{
					Log.LogError((object)"[QuickWarp] Transition resource not found in assembly");
					return;
				}
				string json;
				using (Stream stream = executingAssembly.GetManifestResourceStream(text))
				{
					using StreamReader streamReader = new StreamReader(stream);
					json = streamReader.ReadToEnd();
				}
				ParseFlatStringMap(json, _map);
				Log.LogInfo((object)$"[QuickWarp] Loaded {_map.Count} transitions from {text}");
			}
			catch (Exception ex)
			{
				Log.LogError((object)("[QuickWarp] Failed to load transition map: " + ex.Message));
			}
		}

		public static string? ResolveExitGate(string sourceScene, string destScene)
		{
			if (string.IsNullOrEmpty(sourceScene) || string.IsNullOrEmpty(destScene))
			{
				return null;
			}
			if (_map.TryGetValue(sourceScene + "|" + destScene, out string value))
			{
				return value;
			}
			return null;
		}

		public static string? ResolveExitGate(RoomKey routeKey)
		{
			return ResolveExitGate(routeKey.EntryFromScene, routeKey.SceneName);
		}

		public static bool CanWarp(RoomKey routeKey)
		{
			if (string.IsNullOrEmpty(routeKey.EntryFromScene))
			{
				return false;
			}
			return ResolveExitGate(routeKey) != null;
		}

		public static bool WarpToRoute(RoomKey routeKey)
		{
			string text = ResolveExitGate(routeKey);
			if (text == null)
			{
				Log.LogWarning((object)$"[QuickWarp] No known gate for {routeKey}");
				return false;
			}
			WarpToTransition(routeKey.EntryFromScene, text);
			return true;
		}

		public static void WarpToTransition(string sceneName, string gateName)
		{
			if (string.IsNullOrEmpty(sceneName) || string.IsNullOrEmpty(gateName))
			{
				Log.LogWarning((object)"[QuickWarp] WarpToTransition: empty scene/gate");
				return;
			}
			if (IsWarping)
			{
				Log.LogInfo((object)"[QuickWarp] Warp already in progress - ignoring");
				return;
			}
			Log.LogInfo((object)("[QuickWarp] Warping to " + sceneName + " via '" + gateName + "'"));
			try
			{
				GameManager instance = GameManager.instance;
				if ((Object)(object)instance == (Object)null)
				{
					Log.LogWarning((object)"[QuickWarp] GameManager not available");
					return;
				}
				IsWarping = true;
				((MonoBehaviour)instance).StartCoroutine(WarpCoroutine(instance, sceneName, gateName));
			}
			catch (Exception ex)
			{
				IsWarping = false;
				Log.LogError((object)("[QuickWarp] Warp failed: " + ex.Message));
			}
		}

		public static void NotifyArrival()
		{
			if (IsWarping)
			{
				IsWarping = false;
				Log.LogDebug((object)"[QuickWarp] Warp arrival consumed");
			}
		}

		private static IEnumerator WarpCoroutine(GameManager gm, string sceneName, string gateName)
		{
			if (IsGamePaused(gm))
			{
				IEnumerator unpause = GetUnpauseIterator(gm);
				if (unpause != null)
				{
					while (unpause.MoveNext())
					{
						yield return unpause.Current;
					}
				}
			}
			yield return null;
			DoWarp(gm, sceneName, gateName);
			float deadline = Time.unscaledTime + 15f;
			while (IsWarping && Time.unscaledTime < deadline)
			{
				yield return null;
			}
			if (IsWarping)
			{
				Log.LogWarning((object)"[QuickWarp] Warp watchdog timeout - clearing flag");
				IsWarping = false;
			}
		}

		private static IEnumerator? GetUnpauseIterator(GameManager gm)
		{
			try
			{
				return gm.PauseGameToggleByMenu();
			}
			catch (Exception ex)
			{
				Log.LogWarning((object)("[QuickWarp] Unpause failed: " + ex.Message));
				return null;
			}
		}

		private static void DoWarp(GameManager gm, string sceneName, string gateName)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			//IL_001a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0021: Unknown result type (might be due to invalid IL or missing references)
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			//IL_0028: Unknown result type (might be due to invalid IL or missing references)
			//IL_002f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0037: Expected O, but got Unknown
			SceneLoadInfo val = new SceneLoadInfo
			{
				SceneName = sceneName,
				EntryGateName = gateName,
				PreventCameraFadeOut = true,
				WaitForSceneTransitionCameraFade = false,
				Visualization = (SceneLoadVisualizations)0,
				AlwaysUnloadUnusedAssets = true,
				IsFirstLevelForPlayer = false
			};
			GameManager.UnsafeInstance.BeginSceneTransition(val);
		}

		private static bool IsGamePaused(GameManager gm)
		{
			//IL_001e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0024: Invalid comparison between Unknown and I4
			try
			{
				return gm.IsGamePaused();
			}
			catch
			{
				try
				{
					return (Object)(object)gm.ui != (Object)null && (int)gm.ui.uiState == 5;
				}
				catch
				{
					return false;
				}
			}
		}

		private static void ParseFlatStringMap(string json, Dictionary<string, string> into)
		{
			if (string.IsNullOrEmpty(json))
			{
				return;
			}
			int i = 0;
			int length = json.Length;
			SkipWs(json, ref i);
			if (i >= length || json[i] != '{')
			{
				return;
			}
			i++;
			while (i < length)
			{
				SkipWs(json, ref i);
				if (i < length && json[i] == '}')
				{
					i++;
					break;
				}
				string text = ParseString(json, ref i);
				if (text == null)
				{
					break;
				}
				SkipWs(json, ref i);
				if (i >= length || json[i] != ':')
				{
					break;
				}
				i++;
				SkipWs(json, ref i);
				string text2 = ParseString(json, ref i);
				if (text2 == null)
				{
					break;
				}
				into[text] = text2;
				SkipWs(json, ref i);
				if (i < length && json[i] == ',')
				{
					i++;
				}
				else if (i < length && json[i] == '}')
				{
					i++;
					break;
				}
			}
		}

		private static void SkipWs(string s, ref int i)
		{
			while (i < s.Length)
			{
				char c = s[i];
				if (c == ' ' || c == '\t' || c == '\n' || c == '\r')
				{
					i++;
					continue;
				}
				break;
			}
		}

		private static string? ParseString(string s, ref int i)
		{
			if (i >= s.Length || s[i] != '"')
			{
				return null;
			}
			i++;
			StringBuilder stringBuilder = new StringBuilder();
			while (i < s.Length)
			{
				char c = s[i++];
				switch (c)
				{
				case '"':
					return stringBuilder.ToString();
				case '\\':
					if (i < s.Length)
					{
						char c2 = s[i++];
						switch (c2)
						{
						case '"':
							stringBuilder.Append('"');
							break;
						case '\\':
							stringBuilder.Append('\\');
							break;
						case '/':
							stringBuilder.Append('/');
							break;
						case 'n':
							stringBuilder.Append('\n');
							break;
						case 't':
							stringBuilder.Append('\t');
							break;
						case 'r':
							stringBuilder.Append('\r');
							break;
						default:
							stringBuilder.Append(c2);
							break;
						}
						continue;
					}
					break;
				}
				stringBuilder.Append(c);
			}
			return null;
		}
	}
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInPlugin("io.github.adiprk.replaytimermod", "ReplayTimerMod", "1.0.0")]
	public class ReplayTimerModSS : BaseUnityPlugin
	{
		private static GameManager? cachedGameManager;

		private FrameRecorder frameRecorder;

		private GhostPlayback ghostPlayback;

		private ReplayUI replayUI;

		private RoomTimerHUD roomTimerHUD;

		private ReplaySelectionState replaySelectionState;

		private RoomLifecycle roomLifecycle;

		private bool lateInitDone;

		private readonly Dictionary<string, float> _lastTickErrorLog = new Dictionary<string, float>();

		public const string Id = "io.github.adiprk.replaytimermod";

		public static string Name => "ReplayTimerMod";

		public static string Version => "1.0.0";

		private void Awake()
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			((BaseUnityPlugin)this).Logger.LogInfo((object)("Plugin " + Name + " (io.github.adiprk.replaytimermod) has loaded!"));
			new Harmony("io.github.adiprk.replaytimermod").PatchAll(Assembly.GetExecutingAssembly());
			string? obj = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) ?? ".";
			ManualInstallImport.Run(obj);
			GhostSettings.Init(obj);
			QuickWarp.Init();
			DataStore.Init(Path.Combine(obj, "ReplayMod", "data"));
			replaySelectionState = new ReplaySelectionState();
			PBManager.SetSelectionState(replaySelectionState);
			PBManager.Init();
			frameRecorder = new FrameRecorder();
			ghostPlayback = new GhostPlayback();
			ghostPlayback.SetSelectionState(replaySelectionState);
			replayUI = new ReplayUI();
			roomTimerHUD = new RoomTimerHUD();
			replayUI.SetTimerHUD(roomTimerHUD);
			roomLifecycle = new RoomLifecycle(frameRecorder, ghostPlayback, replayUI);
			RoomTracker.Init();
			RoomTracker.OnRoomEnter += roomLifecycle.HandleRoomEnter;
			RoomTracker.OnRoomExit += roomLifecycle.HandleRoomExit;
			RoomTracker.OnRecordingDiscarded += roomLifecycle.HandleRecordingDiscarded;
		}

		private void LateUpdate()
		{
			TryLateInit();
			if (!TryGetGameManager(out GameManager _))
			{
				return;
			}
			bool shouldTick = false;
			try
			{
				shouldTick = LoadRemover.ShouldTick();
			}
			catch (Exception ex)
			{
				LogTickError("LoadRemover", ex);
			}
			try
			{
				RoomTracker.Tick(shouldTick);
			}
			catch (Exception ex2)
			{
				LogTickError("RoomTracker", ex2);
			}
			try
			{
				frameRecorder.Tick(shouldTick);
			}
			catch (Exception ex3)
			{
				LogTickError("FrameRecorder", ex3);
			}
			try
			{
				ghostPlayback.Tick(shouldTick);
			}
			catch (Exception ex4)
			{
				LogTickError("GhostPlayback", ex4);
			}
			try
			{
				replayUI.Tick();
			}
			catch (Exception ex5)
			{
				LogTickError("ReplayUI", ex5);
			}
			try
			{
				roomTimerHUD.Tick(shouldTick);
			}
			catch (Exception ex6)
			{
				LogTickError("RoomTimerHUD", ex6);
			}
		}

		private void LogTickError(string subsystem, Exception ex)
		{
			float realtimeSinceStartup = Time.realtimeSinceStartup;
			if (!_lastTickErrorLog.TryGetValue(subsystem, out var value) || !(realtimeSinceStartup - value < 5f))
			{
				_lastTickErrorLog[subsystem] = realtimeSinceStartup;
				((BaseUnityPlugin)this).Logger.LogError((object)("[Tick] " + subsystem + " failed: " + ex));
			}
		}

		private void TryLateInit()
		{
			if (!lateInitDone && !((Object)(object)HeroController.instance == (Object)null))
			{
				lateInitDone = true;
				((BaseUnityPlugin)this).Logger.LogInfo((object)"Hero ready - setting up UI and ghost");
				replayUI.Setup();
				roomTimerHUD.Setup();
			}
		}

		private void OnDestroy()
		{
			roomTimerHUD.Teardown();
			GhostSettings.Flush();
		}

		private static bool TryGetGameManager(out GameManager? gm)
		{
			if ((Object)(object)cachedGameManager != (Object)null)
			{
				gm = cachedGameManager;
				return true;
			}
			gm = Object.FindFirstObjectByType<GameManager>();
			if ((Object)(object)gm == (Object)null)
			{
				return false;
			}
			cachedGameManager = gm;
			return true;
		}
	}
	public static class CameraFollow
	{
		private static readonly ManualLogSource Log = Logger.CreateLogSource("CameraFollow");

		private static FieldInfo? _heroTransformField;

		private static bool _fieldLookupDone;

		private static Transform? _currentTarget;

		private static readonly List<CameraLockArea> _zones = new List<CameraLockArea>();

		private static readonly List<Collider2D> _zoneColliders = new List<Collider2D>();

		private static CameraLockArea? _currentZone;

		public static void SetTarget(Transform? target, bool facingRight = true)
		{
			//IL_00a7: Unknown result type (might be due to invalid IL or missing references)
			//IL_0118: Unknown result type (might be due to invalid IL or missing references)
			//IL_0120: Unknown result type (might be due to invalid IL or missing references)
			//IL_0126: Invalid comparison between Unknown and I4
			//IL_014c: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)target == (Object)null && (Object)(object)_currentTarget == (Object)null)
			{
				return;
			}
			FieldInfo fieldInfo = HeroTransformField();
			if (fieldInfo == null)
			{
				_currentTarget = null;
				return;
			}
			GameCameras instance = GameCameras.instance;
			CameraTarget val = (((Object)(object)instance != (Object)null) ? instance.cameraTarget : null);
			if ((Object)(object)val == (Object)null)
			{
				ClearZones();
				_currentTarget = null;
				return;
			}
			CameraController cameraCtrl = val.cameraCtrl;
			if ((Object)(object)target != (Object)null)
			{
				if ((Object)(object)_currentTarget == (Object)null)
				{
					Log.LogInfo((object)("[CameraFollow] Following '" + ((Object)target).name + "'"));
					GatherZones();
				}
				fieldInfo.SetValue(val, target);
				ApplyGhostLockZone(val, cameraCtrl, target.position);
				ApplyGhostLookAhead(val, facingRight);
				_currentTarget = target;
				return;
			}
			HeroController instance2 = HeroController.instance;
			if ((Object)(object)instance2 != (Object)null)
			{
				fieldInfo.SetValue(val, instance2.transform);
			}
			if ((Object)(object)cameraCtrl != (Object)null)
			{
				val.xLockMin = cameraCtrl.xLockMin;
				val.xLockMax = cameraCtrl.xLockMax;
				val.yLockMin = cameraCtrl.yLockMin;
				val.yLockMax = cameraCtrl.yLockMax;
				if ((int)val.mode == 0 || (int)val.mode == 1)
				{
					bool flag = cameraCtrl.lockZoneList != null && cameraCtrl.lockZoneList.Count > 0;
					val.mode = (TargetMode)(flag ? 1 : 0);
				}
			}
			ClearZones();
			Log.LogInfo((object)"[CameraFollow] Released - camera back on the player");
			_currentTarget = null;
		}

		private static void ApplyGhostLockZone(CameraTarget camTarget, CameraController? ctrl, Vector3 ghostPos)
		{
			//IL_000b: 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_0013: Unknown result type (might be due to invalid IL or missing references)
			//IL_0019: Invalid comparison between Unknown and I4
			//IL_0034: 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)
			if ((Object)(object)ctrl == (Object)null || ((int)camTarget.mode != 0 && (int)camTarget.mode != 1))
			{
				return;
			}
			CameraLockArea val = (_currentZone = FindZoneAt(ghostPos));
			if ((Object)(object)val == (Object)null)
			{
				camTarget.mode = (TargetMode)0;
				camTarget.xLockMin = 0f;
				camTarget.xLockMax = ctrl.xLimit;
				camTarget.yLockMin = 0f;
				camTarget.yLockMax = ctrl.yLimit;
				return;
			}
			float num = val.cameraXMin;
			float num2 = val.cameraXMax;
			float num3 = val.cameraYMin;
			float num4 = val.cameraYMax;
			if (num < 0f)
			{
				num = 14.6f;
			}
			if (num2 < 0f)
			{
				num2 = ctrl.xLimit;
			}
			if (num3 < 0f)
			{
				num3 = 8.3f;
			}
			if (num4 < 0f)
			{
				num4 = ctrl.yLimit;
			}
			camTarget.mode = (TargetMode)1;
			camTarget.xLockMin = num;
			camTarget.xLockMax = num2;
			camTarget.yLockMin = num3;
			camTarget.yLockMax = num4;
		}

		private static void ApplyGhostLookAhead(CameraTarget camTarget, bool facingRight)
		{
			//IL_0029: Unknown result type (might be due to invalid IL or missing references)
			//IL_002f: Invalid comparison between Unknown and I4
			//IL_0037: Unknown result type (might be due to invalid IL or missing references)
			float xLookAhead = camTarget.xLookAhead;
			float num = (facingRight ? xLookAhead : (0f - xLookAhead));
			float num2 = Mathf.MoveTowards(camTarget.xOffset, num, Time.deltaTime * 6f);
			if ((int)camTarget.mode == 1)
			{
				float x = ((Component)camTarget).transform.position.x;
				if (x + num2 > camTarget.xLockMax)
				{
					num2 = camTarget.xLockMax - x;
				}
				if (x + num2 < camTarget.xLockMin)
				{
					num2 = camTarget.xLockMin - x;
				}
			}
			camTarget.xOffset = num2;
		}

		private static CameraLockArea? FindZoneAt(Vector3 point)
		{
			//IL_003e: Unknown result type (might be due to invalid IL or missing references)
			//IL_003f: Unknown result type (might be due to invalid IL or missing references)
			CameraLockArea val = null;
			bool flag = false;
			for (int i = 0; i < _zones.Count; i++)
			{
				CameraLockArea val2 = _zones[i];
				Collider2D val3 = _zoneColliders[i];
				if (!((Object)(object)val2 == (Object)null) && !((Object)(object)val3 == (Object)null) && ((Behaviour)val2).isActiveAndEnabled && val3.OverlapPoint(Vector2.op_Implicit(point)))
				{
					if ((Object)(object)val2 == (Object)(object)_currentZone)
					{
						flag = true;
					}
					if ((Object)(object)val == (Object)null || HigherPriority(val2, val))
					{
						val = val2;
					}
				}
			}
			if (flag && (Object)(object)val != (Object)null && (Object)(object)_currentZone != (Object)null && !HigherPriority(val, _currentZone))
			{
				return _currentZone;
			}
			return val;
		}

		private static bool HigherPriority(CameraLockArea a, CameraLockArea b)
		{
			return a.priority > b.priority;
		}

		private static void GatherZones()
		{
			ClearZones();
			CameraLockArea[] array = Object.FindObjectsByType<CameraLockArea>((FindObjectsSortMode)0);
			foreach (CameraLockArea val in array)
			{
				Collider2D component = ((Component)val).GetComponent<Collider2D>();
				if (!((Object)(object)component == (Object)null))
				{
					_zones.Add(val);
					_zoneColliders.Add(component);
				}
			}
			Log.LogInfo((object)$"[CameraFollow] {_zones.Count} lock zone(s) in room");
		}

		private static void ClearZones()
		{
			_zones.Clear();
			_zoneColliders.Clear();
			_currentZone = null;
		}

		private static FieldInfo? HeroTransformField()
		{
			if (_fieldLookupDone)
			{
				return _heroTransformField;
			}
			_fieldLookupDone = true;
			_heroTransformField = typeof(CameraTarget).GetField("heroTransform", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
			if (_heroTransformField == null)
			{
				Log.LogWarning((object)"[CameraFollow] CameraTarget.heroTransform not found - camera follow unavailable");
			}
			else if (_heroTransformField.FieldType != typeof(Transform))
			{
				Log.LogWarning((object)"[CameraFollow] CameraTarget.heroTransform has unexpected type - camera follow unavailable");
				_heroTransformField = null;
			}
			return _heroTransformField;
		}
	}
	public static class CheatMessages
	{
		public const string Default = "Run cancelled - debug tools detected";

		public static readonly Dictionary<DebugAbilityKind, string> ByKind = new Dictionary<DebugAbilityKind, string>
		{
			{
				DebugAbilityKind.Noclip,
				"Run cancelled (noclip)"
			},
			{
				DebugAbilityKind.Invincible,
				"Run cancelled (invincibility)"
			},
			{
				DebugAbilityKind.InfiniteSilk,
				"Run cancelled (inf silk)"
			},
			{
				DebugAbilityKind.InfiniteJump,
				"Run cancelled (inf jump)"
			},
			{
				DebugAbilityKind.HeroColliderDisabled,
				"Run cancelled (collider disabled)"
			},
			{
				DebugAbilityKind.TimeFrozen,
				"Run cancelled (timescale)"
			},
			{
				DebugAbilityKind.TimeScale,
				"Run cancelled (timescale)"
			}
		};

		public static string For(DebugAbilityKind kind)
		{
			if (!ByKind.TryGetValue(kind, out string value))
			{
				return "Run cancelled - debug tools detected";
			}
			return value;
		}
	}
	[Serializable]
	internal class SceneIndex
	{
		public List<EntryIndex> entries = new List<EntryIndex>();
	}
	[Serializable]
	internal class EntryIndex
	{
		public string snapshotId = "";

		public long capturedAtUtcTicks;

		public string sceneName = "";

		public string entryFromScene = "";

		public string exitToScene = "";

		public float totalTime;

		public string data = "";

		public bool hasVisualOverride;

		public float colorR = 1f;

		public float colorG = 1f;

		public float colorB = 1f;

		public float alpha = 0.4f;

		public bool usedCheats;
	}
	public static class DataStore
	{
		private static readonly ManualLogSource Log = Logger.CreateLogSource("DataStore");

		private static string _dataDirectory = "";

		public static void Init(string baseDirectory)
		{
			_dataDirectory = baseDirectory;
			Directory.CreateDirectory(_dataDirectory);
			Log.LogInfo((object)("[DataStore] Directory: " + _dataDirectory));
			MigrateFromLegacy();
		}

		private static void MigrateFromLegacy()
		{
			try
			{
				string fullPath = Path.GetFullPath(LegacyDataDirectory(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)));
				if (!Directory.Exists(fullPath) || fullPath == Path.GetFullPath(_dataDirectory))
				{
					return;
				}
				string[] files = Directory.GetFiles(fullPath, "*.json");
				if (files.Length == 0)
				{
					return;
				}
				int num = 0;
				string[] array = files;
				foreach (string text in array)
				{
					string text2 = Path.Combine(_dataDirectory, Path.GetFileName(text));
					if (!File.Exists(text2))
					{
						File.Move(text, text2);
						num++;
					}
				}
				if (num > 0)
				{
					Log.LogInfo((object)$"[DataStore] Migrated {num} file(s) from legacy path: {fullPath}");
				}
			}
			catch (Exception ex)
			{
				Log.LogWarning((object)("[DataStore] Legacy migration failed: " + ex.Message));
			}
		}

		private static string LegacyDataDirectory(string assemblyDir)
		{
			return Path.Combine(assemblyDir, "..", "..", "data", "ReplayMod");
		}

		private static string FilePath(string sceneName)
		{
			return Path.Combine(_dataDirectory, sceneName + ".json");
		}

		private static SceneIndex LoadIndex(string path)
		{
			if (!File.Exists(path))
			{
				return new SceneIndex();
			}
			try
			{
				SceneIndex sceneIndex;
				SceneIndex result = (sceneIndex = MiniJson.Deserialize(File.ReadAllText(path)));
				if (sceneIndex.entries == null)
				{
					sceneIndex.entries = new List<EntryIndex>();
				}
				return result;
			}
			catch (Exception ex)
			{
				Log.LogError((object)("[DataStore] Index read failed " + path + ": " + ex.Message));
				return new SceneIndex();
			}
		}

		private static SceneIndex LoadIndexAndUpgrade(string path)
		{
			SceneIndex sceneIndex = LoadIndex(path);
			bool flag = false;
			foreach (EntryIndex entry in sceneIndex.entries)
			{
				flag |= NormalizeMetadata(entry);
			}
			if (flag)
			{
				WriteIndex(path, sceneIndex);
			}
			return sceneIndex;
		}

		private static void WriteIndex(string path, SceneIndex idx)
		{
			try
			{
				if (idx.entries == null)
				{
					idx.entries = new List<EntryIndex>();
				}
				if (idx.entries.Count == 0)
				{
					if (File.Exists(path))
					{
						File.Delete(path);
					}
					return;
				}
				foreach (EntryIndex entry in idx.entries)
				{
					NormalizeMetadata(entry);
				}
				File.WriteAllText(path, MiniJson.Serialize(idx));
			}
			catch (Exception ex)
			{
				Log.LogError((object)("[DataStore] Index write failed " + path + ": " + ex.Message));
			}
		}

		private static bool NormalizeMetadata(EntryIndex entry)
		{
			bool result = false;
			if (string.IsNullOrEmpty(entry.snapshotId))
			{
				entry.snapshotId = Guid.NewGuid().ToString("N");
				result = true;
			}
			float num = Clamp01(entry.colorR);
			float num2 = Clamp01(entry.colorG);
			float num3 = Clamp01(entry.colorB);
			float num4 = Clamp01(entry.alpha);
			if (entry.colorR != num)
			{
				entry.colorR = num;
				result = true;
			}
			if (entry.colorG != num2)
			{
				entry.colorG = num2;
				result = true;
			}
			if (entry.colorB != num3)
			{
				entry.colorB = num3;
				result = true;
			}
			if (entry.alpha != num4)
			{
				entry.alpha = num4;
				result = true;
			}
			return result;
		}

		private static float Clamp01(float value)
		{
			return Math.Max(0f, Math.Min(1f, value));
		}

		private static bool MatchesRoute(EntryIndex entry, RoomKey key)
		{
			if (entry.sceneName == key.SceneName && entry.entryFromScene == key.EntryFromScene)
			{
				return entry.exitToScene == key.ExitToScene;
			}
			return false;
		}

		private static EntryIndex ToEntryIndex(ReplaySnapshot snapshot)
		{
			return new EntryIndex
			{
				snapshotId = snapshot.SnapshotId,
				capturedAtUtcTicks = snapshot.CapturedAtUtcTicks,
				sceneName = snapshot.Key.SceneName,
				entryFromScene = snapshot.Key.EntryFromScene,
				exitToScene = snapshot.Key.ExitToScene,
				totalTime = snapshot.TotalTime,
				data = snapshot.EncodedData,
				hasVisualOverride = snapshot.HasVisualOverride,
				colorR = snapshot.ColorR,
				colorG = snapshot.ColorG,
				colorB = snapshot.ColorB,
				alpha = snapshot.Alpha,
				usedCheats = snapshot.UsedCheats
			};
		}

		public static void SaveSnapshot(ReplaySnapshot snapshot)
		{
			string path = FilePath(snapshot.Key.SceneName);
			try
			{
				SceneIndex sceneIndex = LoadIndexAndUpgrade(path);
				sceneIndex.entries.Add(ToEntryIndex(snapshot));
				WriteIndex(path, sceneIndex);
				Log.LogInfo((object)$"[DataStore] Saved {snapshot.Key}#{snapshot.SnapshotId} ({snapshot.Room.FrameCount} frames, {snapshot.EncodedData.Length} chars)");
			}
			catch (Exception ex)
			{
				Log.LogError((object)$"[DataStore] Save failed {snapshot.Key}#{snapshot.SnapshotId}: {ex.Message}");
			}
		}

		public static void DeleteSnapshot(RoomKey key, string snapshotId)
		{
			string path = FilePath(key.SceneName);
			try
			{
				SceneIndex sceneIndex = LoadIndexAndUpgrade(path);
				sceneIndex.entries.RemoveAll((EntryIndex e) => MatchesRoute(e, key) && e.snapshotId == snapshotId);
				WriteIndex(path, sceneIndex);
				Log.LogInfo((object)$"[DataStore] Deleted snapshot {key}#{snapshotId}");
			}
			catch (Exception ex)
			{
				Log.LogError((object)$"[DataStore] DeleteSnapshot failed {key}#{snapshotId}: {ex.Message}");
			}
		}

		public static void UpdateSnapshotVisuals(RoomKey key, string snapshotId, bool hasVisualOverride, float colorR, float colorG, float colorB, float alpha)
		{
			string path = FilePath(key.SceneName);
			try
			{
				SceneIndex sceneIndex = LoadIndexAndUpgrade(path);
				EntryIndex entryIndex = sceneIndex.entries.Find((EntryIndex e) => MatchesRoute(e, key) && e.snapshotId == snapshotId);
				if (entryIndex == null)
				{
					Log.LogWarning((object)$"[DataStore] UpdateSnapshotVisuals missing {key}#{snapshotId}");
					return;
				}
				entryIndex.hasVisualOverride = hasVisualOverride;
				entryIndex.colorR = Clamp01(colorR);
				entryIndex.colorG = Clamp01(colorG);
				entryIndex.colorB = Clamp01(colorB);
				entryIndex.alpha = Clamp01(alpha);
				WriteIndex(path, sceneIndex);
				Log.LogInfo((object)$"[DataStore] Updated snapshot visuals {key}#{snapshotId}");
			}
			catch (Exception ex)
			{
				Log.LogError((object)$"[DataStore] UpdateSnapshotVisuals failed {key}#{snapshotId}: {ex.Message}");
			}
		}

		public static void ReplaceRouteSnapshots(RoomKey key, ICollection<ReplaySnapshot> retainedSnapshots)
		{
			string path = FilePath(key.SceneName);
			try
			{
				SceneIndex sceneIndex = LoadIndexAndUpgrade(path);
				sceneIndex.entries.RemoveAll((EntryIndex e) => MatchesRoute(e, key));
				int num = 0;
				foreach (ReplaySnapshot retainedSnapshot in retainedSnapshots)
				{
					if (!retainedSnapshot.Key.Equals(key))
					{
						Log.LogWarning((object)$"[DataStore] Skipping mismatched route snapshot during replace: expected {key}, got {retainedSnapshot.Key}#{retainedSnapshot.SnapshotId}");
						continue;
					}
					sceneIndex.entries.Add(ToEntryIndex(retainedSnapshot));
					num++;
				}
				WriteIndex(path, sceneIndex);
				Log.LogInfo((object)$"[DataStore] Replaced route {key} with {num} snapshots");
			}
			catch (Exception ex)
			{
				Log.LogError((object)$"[DataStore] ReplaceRouteSnapshots failed {key}: {ex.Message}");
			}
		}

		public static void DeleteRoute(RoomKey key)
		{
			string path = FilePath(key.SceneName);
			try
			{
				SceneIndex sceneIndex = LoadIndexAndUpgrade(path);
				sceneIndex.entries.RemoveAll((EntryIndex e) => MatchesRoute(e, key));
				WriteIndex(path, sceneIndex);
				Log.LogInfo((object)$"[DataStore] Deleted route {key}");
			}
			catch (Exception ex)
			{
				Log.LogError((object)$"[DataStore] DeleteRoute failed {key}: {ex.Message}");
			}
		}

		public static void DeleteScene(string sceneName)
		{
			string path = FilePath(sceneName);
			try
			{
				if (File.Exists(path))
				{
					File.Delete(path);
					Log.LogInfo((object)("[DataStore] Deleted scene file " + sceneName));
				}
			}
			catch (Exception ex)
			{
				Log.LogError((object)("[DataStore] DeleteScene failed " + sceneName + ": " + ex.Message));
			}
		}

		public static List<ReplaySnapshot> LoadAll()
		{
			List<ReplaySnapshot> list = new List<ReplaySnapshot>();
			if (!Directory.Exists(_dataDirectory))
			{
				return list;
			}
			string[] files = Directory.GetFiles(_dataDirectory, "*.json");
			foreach (string path in files)
			{
				string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(path);
				foreach (EntryIndex entry in LoadIndexAndUpgrade(path).entries)
				{
					try
					{
						if (string.IsNullOrEmpty(entry.data))
						{
							Log.LogWarning((object)("[DataStore] Skipping empty entry in " + fileNameWithoutExtension));
							continue;
						}
						RecordedRoom recordedRoom = ReplayShareEncoder.Decode(entry.data);
						if (recordedRoom == null)
						{
							Log.LogWarning((object)("[DataStore] Skipping corrupt entry in " + fileNameWithoutExtension));
						}
						else
						{
							list.Add(new ReplaySnapshot(entry.snapshotId, entry.capturedAtUtcTicks, recordedRoom, entry.data, entry.hasVisualOverride, entry.colorR, entry.colorG, entry.colorB, entry.alpha, entry.usedCheats));
						}
					}
					catch (Exception ex)
					{
						Log.LogWarning((object)("[DataStore] Skipping corrupt entry in " + fileNameWithoutExtension + ": " + ex.Message));
					}
				}
			}
			Log.LogInfo((object)$"[DataStore] Loaded {list.Count} total snapshots");
			return list;
		}
	}
	public enum DebugAbilityKind
	{
		Noclip,
		Invincible,
		InfiniteSilk,
		InfiniteJump,
		HeroColliderDisabled,
		TimeFrozen,
		TimeScale
	}
	public static class DebugModBridge
	{
		private static readonly ManualLogSource Log = Logger.CreateLogSource("DebugModBridge");

		private const string AssemblyName = "DebugMod";

		private const BindingFlags StaticAny = BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic;

		private static bool _hooked;

		private static bool _giveUp;

		private const int HookRetryIntervalMs = 1000;

		private static int _nextHookAttemptTick;

		private static PropertyInfo? _loadingSavestateProp;

		private static FieldInfo? _noclipField;

		private static FieldInfo? _invincibleField;

		private static FieldInfo? _infiniteSilkField;

		private static FieldInfo? _heroColliderDisabledField;

		private static PropertyInfo? _customTimeScaleProp;

		private static PropertyInfo? _frozenProp;

		private static FieldInfo? _hkFrozenField;

		private static FieldInfo? _hkTimeScaleActiveField;

		private static FieldInfo? _hkCurrentTimeScaleField;

		public static bool IsAvailable => _hooked;

		public static bool IsLoadingSavestate
		{
			get
			{
				TryHook();
				try
				{
					object obj = _loadingSavestateProp?.GetValue(null, null);
					if (obj == null)
					{
						return false;
					}
					if (obj is bool result)
					{
						return result;
					}
					return true;
				}
				catch (Exception ex)
				{
					Log.LogWarning((object)("[DebugModBridge] IsLoadingSavestate check failed: " + ex.Message));
					return false;
				}
			}
		}

		public static void TryHook()
		{
			if (_hooked || _giveUp)
			{
				return;
			}
			int tickCount = Environment.TickCount;
			if (tickCount - _nextHookAttemptTick < 0)
			{
				return;
			}
			_nextHookAttemptTick = tickCount + 1000;
			Assembly assembly = FindAssembly("DebugMod");
			if (assembly == null)
			{
				return;
			}
			try
			{
				Type type = FindType(assembly, "DebugMod.SaveStates.SaveState", "DebugMod.SaveState", "SaveState");
				Type type2 = FindType(assembly, "DebugMod.DebugMod", "DebugMod");
				Type type3 = FindType(assembly, "DebugMod.MonoBehaviours.TimeScale", "TimeScale");
				if (type != null)
				{
					try
					{
						_loadingSavestateProp = type.GetProperty("loadingSavestate", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
						if (_loadingSavestateProp == null)
						{
							Log.LogWarning((object)("[DebugModBridge] 'loadingSavestate' not found on " + type.FullName));
						}
					}
					catch (Exception ex)
					{
						Log.LogWarning((object)("[DebugModBridge] Failed resolving SaveState members: " + ex.Message));
					}
				}
				else
				{
					Log.LogWarning((object)"[DebugModBridge] SaveState type not found - savestate-load detection unavailable");
				}
				if (type2 != null)
				{
					try
					{
						_noclipField = GetField(type2, "noclip");
						_invincibleField = GetField(type2, "playerInvincible");
						_infiniteSilkField = GetField(type2, "infiniteSilk", "infiniteSoul");
						_heroColliderDisabledField = GetField(type2, "heroColliderDisabled");
						_hkFrozenField = GetField(type2, "PauseGameNoUIActive");
						_hkTimeScaleActiveField = GetField(type2, "TimeScaleActive");
						_hkCurrentTimeScaleField = GetField(type2, "CurrentTimeScale");
					}
					catch (Exception ex2)
					{
						Log.LogWarning((object)("[DebugModBridge] Failed resolving DebugMod cheat fields: " + ex2.Message));
					}
				}
				else
				{
					Log.LogWarning((object)"[DebugModBridge] DebugMod type not found - cheat-flag checks unavailable");
				}
				if (type3 != null)
				{
					try
					{
						_customTimeScaleProp = GetProperty(type3, "CustomTimeScale");
						_frozenProp = GetProperty(type3, "Frozen");
					}
					catch (Exception ex3)
					{
						Log.LogWarning((object)("[DebugModBridge] Failed resolving TimeScale members: " + ex3.Message));
					}
				}
				_hooked = true;
				Log.LogInfo((object)"[DebugModBridge] Hooked into DebugMod");
			}
			catch (Exception arg)
			{
				_giveUp = true;
				Log.LogWarning((object)$"[DebugModBridge] Failed to hook DebugMod, disabling integration: {arg}");
			}
		}

		private static Assembly? FindAssembly(string name)
		{
			Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();
			foreach (Assembly assembly in assemblies)
			{
				if (assembly.GetName().Name == name)
				{
					return assembly;
				}
			}
			return null;
		}

		private static Type? FindType(Assembly asm, params string[] candidates)
		{
			foreach (string name in candidates)
			{
				Type type = asm.GetType(name);
				if (type != null)
				{
					return type;
				}
			}
			return null;
		}

		private static FieldInfo? GetField(Type type, params string[] names)
		{
			foreach (string name in names)
			{
				FieldInfo field = type.GetField(name, BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
				if (field != null)
				{
					return field;
				}
			}
			return null;
		}

		private static PropertyInfo? GetProperty(Type type, params string[] names)
		{
			foreach (string name in names)
			{
				PropertyInfo property = type.GetProperty(name, BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
				if (property != null)
				{
					return property;
				}
			}
			return null;
		}

		public static DebugAbilityKind? GetActiveDebugAbility()
		{
			if (IsInfiniteJumpActive())
			{
				return DebugAbilityKind.InfiniteJump;
			}
			TryHook();
			if (!_hooked)
			{
				return null;
			}
			try
			{
				if (GetBool(_noclipField))
				{
					return DebugAbilityKind.Noclip;
				}
				if (GetBool(_invincibleField))
				{
					return DebugAbilityKind.Invincible;
				}
				if (GetBool(_infiniteSilkField))
				{
					return DebugAbilityKind.InfiniteSilk;
				}
				if (GetBool(_heroColliderDisabledField))
				{
					return DebugAbilityKind.HeroColliderDisabled;
				}
				if (IsTimeFrozen())
				{
					return DebugAbilityKind.TimeFrozen;
				}
				if (IsTimeScaleChanged())
				{
					return DebugAbilityKind.TimeScale;
				}
			}
			catch (Exception ex)
			{
				Log.LogWarning((object)("[DebugModBridge] GetActiveDebugAbility check failed: " + ex.Message));
			}
			return null;
		}

		private static bool IsInfiniteJumpActive()
		{
			try
			{
				return PlayerData.instance != null && PlayerData.instance.infiniteAirJump;
			}
			catch (Exception ex)
			{
				Log.LogWarning((object)("[DebugModBridge] IsInfiniteJumpActive check failed: " + ex.Message));
				return false;
			}
		}

		private static bool IsTimeFrozen()
		{
			bool flag = default(bool);
			int num;
			if (_frozenProp != null)
			{
				object value = _frozenProp.GetValue(null, null);
				if (value is bool)
				{
					flag = (bool)value;
					num = 1;
				}
				else
				{
					num = 0;
				}
			}
			else
			{
				num = 0;
			}
			if (((uint)num & (flag ? 1u : 0u)) != 0)
			{
				return true;
			}
			if (GetBool(_hkFrozenField))
			{
				return true;
			}
			return false;
		}

		private static bool IsTimeScaleChanged()
		{
			if (_customTimeScaleProp != null && _customTimeScaleProp.GetValue(null, null) is float num && Mathf.Abs(num - 1f) > 0.001f)
			{
				return true;
			}
			if (GetBool(_hkTimeScaleActiveField))
			{
				return true;
			}
			if (_hkCurrentTimeScaleField != null && _hkCurrentTimeScaleField.GetValue(null) is float num2 && Mathf.Abs(num2 - 1f) > 0.001f)
			{
				return true;
			}
			return false;
		}

		public static bool AnyDebugAbilityActive()
		{
			return GetActiveDebugAbility().HasValue;
		}

		private static bool GetBool(FieldInfo? field)
		{
			if (field == null)
			{
				return false;
			}
			object value = field.GetValue(null);
			bool flag = default(bool);
			int num;
			if (value is bool)
			{
				flag = (bool)value;
				num = 1;
			}
			else
			{
				num = 0;
			}
			return (byte)((uint)num & (flag ? 1u : 0u)) != 0;
		}
	}
	internal static class FrameCodec
	{
		public const float PosScale = 100f;

		public static byte[] Encode2ndOrder(FrameData[] frames, bool getX)
		{
			int num = frames.Length;
			if (num == 0)
			{
				return new byte[0];
			}
			using MemoryStream memoryStream = new MemoryStream(2 + num * 3);
			using BinaryWriter binaryWriter = new BinaryWriter(memoryStream, Encoding.UTF8);
			short num2 = ToShort(getX ? frames[0].x : frames[0].y);
			binaryWriter.Write(num2);
			if (num == 1)
			{
				return memoryStream.ToArray();
			}
			short num3 = ToShort(getX ? frames[1].x : frames[1].y);
			WriteSVLQ(binaryWriter, num3 - num2);
			short num4 = num2;
			short num5 = num3;
			for (int i = 2; i < num; i++)
			{
				short num6 = ToShort(getX ? frames[i].x : frames[i].y);
				WriteSVLQ(binaryWriter, num6 - 2 * num5 + num4);
				num4 = num5;
				num5 = num6;
			}
			return memoryStream.ToArray();
		}

		public static short[] Decode2ndOrder(byte[] stream, int n)
		{
			if (n == 0)
			{
				return new short[0];
			}
			using MemoryStream input = new MemoryStream(stream);
			using BinaryReader binaryReader = new BinaryReader(input, Encoding.UTF8);
			short[] array = new short[n];
			array[0] = binaryReader.ReadInt16();
			if (n == 1)
			{
				return array;
			}
			array[1] = (short)(array[0] + ReadSVLQ(binaryReader));
			for (int i = 2; i < n; i++)
			{
				array[i] = (short)(ReadSVLQ(binaryReader) + 2 * array[i - 1] - array[i - 2]);
			}
			return array;
		}

		public static void WriteSVLQ(BinaryWriter w, int v)
		{
			uint num = (uint)((v >= 0) ? (v << 1) : ((-v << 1) - 1));
			do
			{
				byte b = (byte)(num & 0x7F);
				num >>= 7;
				if (num != 0)
				{
					b |= 0x80;
				}
				w.Write(b);
			}
			while (num != 0);
		}

		public static int ReadSVLQ(BinaryReader r)
		{
			uint num = 0u;
			int num2 = 0;
			byte b;
			do
			{
				b = r.ReadByte();
				num |= (uint)((b & 0x7F) << num2);
				num2 += 7;
			}
			while ((b & 0x80) != 0);
			if ((num & 1) != 0)
			{
				return (int)(0 - (num >> 1) - 1);
			}
			return (int)(num >> 1);
		}

		public static void WriteString(BinaryWriter w, string s)
		{
			byte[] bytes = Encoding.UTF8.GetBytes(s);
			w.Write((ushort)bytes.Length);
			w.Write(bytes);
		}

		public static string ReadString(BinaryReader r)
		{
			return Encoding.UTF8.GetString(r.ReadBytes(r.ReadUInt16()));
		}

		public static short ToShort(float world)
		{
			float num = world * 100f;
			if (num >= 32767f)
			{
				return short.MaxValue;
			}
			if (num <= -32768f)
			{
				return short.MinValue;
			}
			return (short)Math.Round(num);
		}
	}
	public class FrameRecorder
	{
		public const float RECORD_FPS = 30f;

		public const float RECORD_INTERVAL = 1f / 30f;

		private readonly List<FrameData> _frames = new List<FrameData>();

		private bool _recording;

		private float _accumulatedTime;

		private tk2dSpriteAnimator? _cachedAnim;

		public bool IsRecording => _recording;

		public int FrameCount => _frames.Count;

		public void StartRecording()
		{
			_frames.Clear();
			_recording = true;
			_cachedAnim = null;
			_accumulatedTime = 1f / 30f;
		}

		public void DiscardRecording()
		{
			_frames.Clear();
			_recording = false;
			_accumulatedTime = 0f;
			_cachedAnim = null;
		}

		public RecordedRoom? FinishRecording(RoomKey key, float totalLRTime)
		{
			if (!_recording || _frames.Count == 0)
			{
				_frames.Clear();
				_recording = false;
				_cachedAnim = null;
				return null;
			}
			_recording = false;
			_cachedAnim = null;
			RecordedRoom result = new RecordedRoom(key, totalLRTime, _frames.ToArray());
			_frames.Clear();
			return result;
		}

		public void Tick(bool shouldTick)
		{
			//IL_0125: 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_0045: 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_0066: Unknown result type (might be due to invalid IL or missing references)
			if (!_recording || (Object)(object)HeroController.instance == (Object)null || !shouldTick)
			{
				return;
			}
			_accumulatedTime += Time.deltaTime;
			if (_accumulatedTime < 1f / 30f)
			{
				return;
			}
			bool facingRight = HeroController.instance.transform.localScale.x > 0f;
			Vector3 position = HeroController.instance.transform.position;
			if ((Object)(object)_cachedAnim == (Object)null)
			{
				_cachedAnim = ResolveHeroAnimator();
			}
			string animClip = "";
			int animFrame = 0;
			try
			{
				tk2dSpriteAnimator? cachedAnim = _cachedAnim;
				if (((cachedAnim != null) ? cachedAnim.CurrentClip : null) != null)
				{
					animClip = _cachedAnim.CurrentClip.name;
					animFrame = _cachedAnim.CurrentFrame;
				}
				else
				{
					_cachedAnim = ResolveHeroAnimator();
					tk2dSpriteAnimator? cachedAnim2 = _cachedAnim;
					if (((cachedAnim2 != null) ? cachedAnim2.CurrentClip : null) != null)
					{
						animClip = _cachedAnim.CurrentClip.name;
						animFrame = _cachedAnim.CurrentFrame;
					}
				}
			}
			catch
			{
				_cachedAnim = null;
			}
			while (_accumulatedTime >= 1f / 30f)
			{
				_accumulatedTime -= 1f / 30f;
				_frames.Add(new FrameData
				{
					x = position.x,
					y = position.y,
					facingRight = facingRight,
					animClip = animClip,
					animFrame = animFrame
				});
			}
		}

		private static tk2dSpriteAnimator? ResolveHeroAnimator()
		{
			HeroController instance = HeroController.instance;
			if ((Object)(object)instance == (Object)null)
			{
				return null;
			}
			tk2dSprite val = ((Component)instance).GetComponent<tk2dSprite>() ?? ((Component)instance).GetComponentInChildren<tk2dSprite>();
			if ((Object)(object)val != (Object)null)
			{
				tk2dSpriteAnimator val2 = ((Component)val).GetComponent<tk2dSpriteAnimator>() ?? ((Component)val).GetComponentInParent<tk2dSpriteAnimator>() ?? ((Component)val).GetComponentInChildren<tk2dSpriteAnimator>();
				if ((Object)(object)val2 != (Object)null)
				{
					return val2;
				}
			}
			return ((Component)instance).GetComponent<tk2dSpriteAnimator>() ?? ((Component)instance).GetComponentInChildren<tk2dSpriteAnimator>();
		}
	}
	[HarmonyPatch]
	public static class GameHooks
	{
		private static readonly ManualLogSource Log = Logger.CreateLogSource("GameHooks");

		private static bool _pendingDeath = false;

		public static event Action? OnPlayerDead;

		public static event Action<string, string>? OnGateTransitionBegin;

		[HarmonyPatch(typeof(GameManager), "PlayerDead")]
		[HarmonyPrefix]
		private static void GameManager_PlayerDead()
		{
			Log.LogInfo((object)"[GameHooks] PlayerDead fired");
			_pendingDeath = true;
			GameHooks.OnPlayerDead?.Invoke();
		}

		[HarmonyPatch(typeof(GameManager), "BeginSceneTransition")]
		[HarmonyPrefix]
		private static void GameManager_BeginSceneTransition(object __0)
		{
			if (__0 != null)
			{
				if (_pendingDeath)
				{
					Log.LogInfo((object)"[GameHooks] BeginSceneTransition - death respawn, skipping");
					_pendingDeath = false;
					return;
				}
				string text = ReflectionStringMemberReader.TryReadStringMember(__0, "SceneName", "sceneName", "ToScene", "Scene");
				string text2 = ReflectionStringMemberReader.TryReadStringMember(__0, "EntryGateName", "EntryGate", "entryGateName", "GateName");
				Log.LogInfo((object)("[GameHooks] BeginSceneTransition -> '" + text + "' via '" + text2 + "' (type=" + __0.GetType().Name + ")"));
				GameHooks.OnGateTransitionBegin?.Invoke(text, text2);
			}
		}
	}
	internal static class ReflectionStringMemberReader
	{
		internal static string TryReadStringMember(object instance, params string[] names)
		{
			if (instance == null)
			{
				return "";
			}
			Type type = instance.GetType();
			foreach (string name in names)
			{
				try
				{
					PropertyInfo property = type.GetProperty(name, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
					if (property != null && property.PropertyType == typeof(string))
					{
						return (property.GetValue(instance, null) as string) ?? "";
					}
					FieldInfo field = type.GetField(name, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
					if (field != null && field.FieldType == typeof(string))
					{
						return (field.GetValue(instance) as string) ?? "";
					}
				}
				catch
				{
				}
			}
			return "";
		}
	}
	internal static class GameUiState
	{
		public static bool IsPaused()
		{
			//IL_0029: Unknown result type (might be due to invalid IL or missing references)
			//IL_002f: Invalid comparison between Unknown and I4
			try
			{
				return (Object)(object)GameManager.instance != (Object)null && (Object)(object)GameManager.instance.ui != (Object)null && (int)GameManager.instance.ui.uiState == 5;
			}
			catch
			{
				return false;
			}
		}
	}
	public class GhostPlayback
	{
		private sealed class PlaybackInstance
		{
			public ReplaySnapshot Snapshot { get; }

			public float PlaybackTime { get; set; }

			public GameObject? SpriteGo { get; set; }

			public tk2dSprite? Sprite { get; set; }

			public GameObject? DiamondGo { get; set; }

			public LineRenderer? DiamondLine { get; set; }

			public Material? DiamondMat { get; set; }

			public GameObject? AnchorGo { get; set; }

			public GameObject? ReeseGo { get; set; }

			public SpriteRenderer? Reese { get; set; }

			public bool FacingRight { get; set; } = true;

			public RecordedRoom Room => Snapshot.Room;

			public PlaybackInstance(ReplaySnapshot snapshot)
			{
				Snapshot = snapshot;
			}
		}

		private static readonly ManualLogSource Log = Logger.CreateLogSource("GhostPlayback");

		private readonly List<PlaybackInstance> _activeInstances = new List<PlaybackInstance>();

		private Dictionary<string, tk2dSpriteAnimationClip>? _clipCache;

		private tk2dSpriteCollectionData? _spriteCollection;

		private int _defaultSpriteId = -1;

		private bool _spriteInitDone;

		private ReplaySelectionState? _selectionState;

		private bool _playing;

		public void SetSelectionState(ReplaySelectionState? state)
		{
			_selectionState = state;
		}

		public void StartPlayback(string sceneName, string entryFromScene)
		{
			StopPlayback();
			if (!GhostSettings.GhostEnabled)
			{
				return;
			}
			List<ReplaySnapshot> list = SelectSnapshots(sceneName, entryFromScene);
			if (list.Count == 0)
			{
				Log.LogInfo((object)("[GhostPlayback] No playback candidates for " + sceneName + " <- " + entryFromScene));
				return;
			}
			EnsureSpriteResources();
			foreach (ReplaySnapshot item in list)
			{
				PlaybackInstance playbackInstance = new PlaybackInstance(item);
				CreateVisuals(playbackInstance);
				_activeInstances.Add(playbackInstance);
			}
			_playing = _activeInstances.Count > 0;
			if (_playing)
			{
				Log.LogInfo((object)$"[GhostPlayback] Playing {_activeInstances.Count} snapshot(s) for {sceneName} <- {entryFromScene}");
			}
		}

		public void StopPlayback()
		{
			_playing = false;
			CameraFollow.SetTarget(null);
			foreach (PlaybackInstance activeInstance in _activeInstances)
			{
				DestroyVisuals(activeInstance);
			}
			_activeInstances.Clear();
		}

		public void Tick(bool shouldTick)
		{
			//IL_0052: Unknown result type (might be due to invalid IL or missing references)
			//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_0089: Unknown result type (might be due to invalid IL or missing references)
			if (!_playing || _activeInstances.Count == 0)
			{
				return;
			}
			if (!GhostSettings.GhostEnabled)
			{
				StopPlayback();
			}
			else
			{
				if (!shouldTick)
				{
					return;
				}
				float interval = 1f / 30f;
				float deltaTime = Time.deltaTime;
				float z = (((Object)(object)HeroController.instance != (Object)null) ? HeroController.instance.transform.position.z : 0f);
				Color ghostColor = GhostSettings.GhostColor;
				for (int num = _activeInstances.Count - 1; num >= 0; num--)
				{
					PlaybackInstance instance = _activeInstances[num];
					if (!TickInstance(instance, deltaTime, interval, z, ghostColor))
					{
						DestroyVisuals(instance);
						_activeInstances.RemoveAt(num);
					}
				}
				if (_activeInstances.Count == 0)
				{
					_playing = false;
				}
				UpdateCameraFollow();
			}
		}

		private void UpdateCameraFollow()
		{
			Transform target = null;
			bool facingRight = true;
			string text = _selectionState?.CameraFollowSnapshotId;
			if (!string.IsNullOrEmpty(text))
			{
				foreach (PlaybackInstance activeInstance in _activeInstances)
				{
					if (!(activeInstance.Snapshot.SnapshotId != text))
					{
						target = (((Object)(object)activeInstance.AnchorGo != (Object)null) ? activeInstance.AnchorGo.transform : null);
						facingRight = activeInstance.FacingRight;
						break;
					}
				}
			}
			CameraFollow.SetTarget(target, facingRight);
		}

		private List<ReplaySnapshot> SelectSnapshots(string sceneName, string entryFromScene)
		{
			IList<ReplaySnapshot> playbackCandidates = PBManager.GetPlaybackCandidates(sceneName, entryFromScene);
			if (playbackCandidates.Count == 0)
			{
				return new List<ReplaySnapshot>();
			}
			List<ReplaySnapshot> list = playbackCandidates.Where((ReplaySnapshot snapshot) => _selectionState?.IsPlaybackSelected(snapshot.SnapshotId) ?? false).ToList();
			if (list.Count > 0)
			{
				Log.LogInfo((object)$"[GhostPlayback] Using selected playback subset ({list.Count}/{playbackCandidates.Count}) for {sceneName} <- {entryFromScene}");
				return list;
			}
			ReplaySnapshot replaySnapshot = playbackCandidates.FirstOrDefault((ReplaySnapshot s) => (!GhostSettings.SkipCheatedRuns || !s.UsedCheats) && (!GhostSettings.SkipBacktrackPlayback || !s.Key.IsReentry));
			if (replaySnapshot == null)
			{
				Log.LogInfo((object)("[GhostPlayback] No eligible runs for " + sceneName + " <- " + entryFromScene + " - skipping"));
				return new List<ReplaySnapshot>();
			}
			Log.LogInfo((object)$"[GhostPlayback] Using fallback best PB {replaySnapshot.Key}#{replaySnapshot.SnapshotId} for {sceneName} <- {entryFromScene}");
			return new List<ReplaySnapshot> { replaySnapshot };
		}

		private bool TickInstance(PlaybackInstance instance, float deltaTime, float interval, float z, Color globalColor)
		{
			//IL_0062: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b7: Unknown result type (might be due to invalid IL or missing references)
			RecordedRoom room = instance.Room;
			if (room.FrameCount == 0)
			{
				return false;
			}
			instance.PlaybackTime += deltaTime;
			int num = Mathf.FloorToInt(instance.PlaybackTime / interval);
			if (num >= room.FrameCount)
			{
				return false;
			}
			if (room.FrameCount == 1)
			{
				RenderFrame(instance, room.Frames[0], room.Frames[0], 0f, z, globalColor);
				return true;
			}
			if (num >= room.FrameCount - 1)
			{
				num = room.FrameCount - 2;
			}
			FrameData a = room.Frames[num];
			FrameData b = room.Frames[num + 1];
			float t = Mathf.Clamp01((instance.PlaybackTime - (float)num * interval) / interval);
			RenderFrame(instance, a, b, t, z, globalColor);
			return true;
		}

		private void RenderFrame(PlaybackInstance instance, FrameData a, FrameData b, float t, float z, Color globalColor)
		{
			//IL_0047: 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_004e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0069: Unknown result type (might be due to invalid IL or missing references)
			//IL_0083: Unknown result type (might be due to invalid IL or missing references)
			//IL_008a: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cb: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cd: Unknown result type (might be due to invalid IL or missing references)
			float num = Mathf.LerpUnclamped(a.x, b.x, t);
			float num2 = Mathf.LerpUnclamped(a.y, b.y, t);
			FrameData fd = ((t < 0.5f) ? a : b);
			Vector3 val = default(Vector3);
			((Vector3)(ref val))..ctor(num, num2, z);
			Color color = instance.Snapshot.ResolveGhostColor(globalColor);
			if ((Object)(object)instance.AnchorGo != (Object)null)
			{
				instance.AnchorGo.transform.position = val;
			}
			instance.FacingRight = fd.facingRight;
			if (!GhostSettings.ReeseEnabled || !RenderReese(instance, val, fd.facingRight, color))
			{
				if ((Object)(object)instance.ReeseGo != (Object)null)
				{
					instance.ReeseGo.SetActive(false);
				}
				if (!string.IsNullOrEmpty(fd.animClip) && (Object)(object)instance.Sprite != (Object)null)
				{
					RenderSprite(instance, val, fd, color);
				}
				else
				{
					RenderDiamond(instance, val, color);
				}
			}
		}

		private void EnsureSpriteResources()
		{
			if (_spriteInitDone)
			{
				return;
			}
			try
			{
				if ((Object)(object)HeroController.instance == (Object)null)
				{
					Log.LogWarning((object)"[GhostPlayback] HeroController null - using diamond for now");
					return;
				}
				_spriteInitDone = true;
				tk2dSprite val = ((Component)HeroController.instance).GetComponent<tk2dSprite>() ?? ((Component)HeroController.instance).GetComponentInChildren<tk2dSprite>();
				if ((Object)(object)((val != null) ? ((tk2dBaseSprite)val).Collection : null) == (Object)null)
				{
					Log.LogWarning((object)"[GhostPlayback] No tk2dSprite/Collection on hero - using diamond");
					return;
				}
				_spriteCollection = ((tk2dBaseSprite)val).Collection;
				_defaultSpriteId = ((tk2dBaseSprite)val).spriteId;
				Log.LogInfo((object)("[GhostPlayback] Sprite ready - collection='" + ((Object)((tk2dBaseSprite)val).Collection).name + "'"));
				tk2dSpriteAnimator val2 = ((Component)val).GetComponent<tk2dSpriteAnimator>() ?? ((Component)val).GetComponentInParent<tk2dSpriteAnimator>() ?? ((Component)val).GetComponentInChildren<tk2dSpriteAnimator>() ?? ((Component)HeroController.instance).GetComponent<tk2dSpriteAnimator>() ?? ((Component)HeroController.instance).GetComponentInChildren<tk2dSpriteAnimator>();
				if ((Object)(object)((val2 != null) ? val2.Library : null) != (Object)null)
				{
					_clipCache = new Dictionary<string, tk2dSpriteAnimationClip>(val2.Library.clips.Length);
					tk2dSpriteAnimationClip[] clips = val2.Library.clips;
					foreach (tk2dSpriteAnimationClip val3 in clips)
					{
						if (!string.IsNullOrEmpty(val3.name))
						{
							_clipCache[val3.name] = val3;
						}
					}
					Log.LogInfo((object)$"[GhostPlayback] Clip cache: {_clipCache.Count} clips");
				}
				else
				{
					Log.LogWarning((object)"[GhostPlayback] No animator library - sprite will show default frame");
				}
			}
			catch (Exception ex)
			{
				Log.LogWarning((object)("[GhostPlayback] Sprite init failed: " + ex.Message + " - using diamond"));
				_spriteCollection = null;
				_clipCache = null;
				_defaultSpriteId = -1;
			}
		}

		private void CreateVisuals(PlaybackInstance instance)
		{
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			//IL_0020: Expected O, but got Unknown
			//IL_0041: Unknown result type (might be due to invalid IL or missing references)
			//IL_004b: Expected O, but got Unknown
			//IL_00aa: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b0: Expected O, but got Unknown
			//IL_00f4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fe: Expected O, but got Unknown
			instance.AnchorGo = new GameObject("ReplayGhost_Anchor_" + instance.Snapshot.SnapshotId);
			ScenePersistence.Apply(instance.AnchorGo);
			instance.DiamondGo = new GameObject("ReplayGhost_Diamond_" + instance.Snapshot.SnapshotId);
			ScenePersistence.Apply(instance.DiamondGo);
			instance.DiamondGo.SetActive(false);
			LineRenderer val = instance.DiamondGo.AddComponent<LineRenderer>();
			val.useWorldSpace = true;
			val.positionCount = 5;
			val.startWidth = 0.06f;
			val.endWidth = 0.06f;
			((Renderer)val).shadowCastingMode = (ShadowCastingMode)0;
			((Renderer)val).receiveShadows = false;
			Material diamondMat = (((Renderer)val).material = new Material(Shader.Find("Sprites/Default")));
			instance.DiamondLine = val;
			instance.DiamondMat = diamondMat;
			if ((Object)(object)_spriteCollection == (Object)null || _defaultSpriteId < 0)
			{
				return;
			}
			try
			{
				instance.SpriteGo = new GameObject("ReplayGhost_Sprite_" + instance.Snapshot.SnapshotId);
				instance.SpriteGo.SetActive(false);
				ScenePersistence.Apply(instance.SpriteGo);
				tk2dSprite val3 = instance.SpriteGo.AddComponent<tk2dSprite>();
				((tk2dBaseSprite)val3).Collection = _spriteCollection;
				((tk2dBaseSprite)val3).spriteId = _defaultSpriteId;
				instance.Sprite = val3;
				instance.SpriteGo.SetActive(true);
			}
			catch (Exception ex)
			{
				Log.LogWarning((object)("[GhostPlayback] Sprite instance init failed: " + ex.Message + " - using diamond"));
				if ((Object)(object)instance.SpriteGo != (Object)null)
				{
					Object.Destroy((Object)(object)instance.SpriteGo);
					instance.SpriteGo = null;
				}
				instance.Sprite = null;
			}
		}

		private void DestroyVisuals(PlaybackInstance instance)
		{
			if ((Object)(object)instance.SpriteGo != (Object)null)
			{
				Object.Destroy((Object)(object)instance.SpriteGo);
			}
			if ((Object)(object)instance.DiamondGo != (Object)null)
			{
				Object.Destroy((Object)(object)instance.DiamondGo);
			}
			if ((Object)(object)instance.DiamondMat != (Object)null)
			{
				Object.Destroy((Object)(object)instance.DiamondMat);
			}
			if ((Object)(object)instance.AnchorGo != (Object)null)
			{
				Object.Destroy((Object)(object)instance.AnchorGo);
			}
			if ((Object)(object)instance.ReeseGo != (Object)null)
			{
				Object.Destroy((Object)(object)instance.ReeseGo);
			}
			instance.SpriteGo = null;
			instance.Sprite = null;
			instance.DiamondGo = null;
			instance.DiamondLine = null;
			instance.DiamondMat = null;
			instance.AnchorGo = null;
			instance.ReeseGo = null;
			instance.Reese = null;
		}

		private static bool RenderReese(PlaybackInstance instance, Vector3 pos, bool facingRight, Color color)
		{
			//IL_006d: 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_0035: Unknown result type (might be due to invalid IL or missing references)
			//IL_003f: Expected O, but got Unknown
			//IL_00a8: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)instance.Reese == (Object)null)
			{
				Sprite val = ReeseImages.Random();
				if ((Object)(object)val == (Object)null)
				{
					return false;
				}
				instance.ReeseGo = new GameObject("ReplayGhost_Reese_" + instance.Snapshot.SnapshotId);
				ScenePersistence.Apply(instance.ReeseGo);
				instance.Reese = instance.ReeseGo.AddComponent<SpriteRenderer>();
				instance.Reese.sprite = val;
			}
			instance.Reese.color = color;
			instance.ReeseGo.transform.position = pos;
			instance.ReeseGo.transform.localScale = new Vector3(facingRight ? 1f : (-1f), 1f, 1f);
			instance.ReeseGo.SetActive(true);
			if ((Object)(object)instance.SpriteGo != (Object)null)
			{
				instance.SpriteGo.SetActive(false);
			}
			GameObject? diamondGo = instance.DiamondGo;
			if (diamondGo != null)
			{
				diamondGo.SetActive(false);
			}
			return true;
		}

		private void RenderSprite(PlaybackInstance instance, Vector3 pos, FrameData fd, Color color)
		{
			//IL_006f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0081: Unknown result type (might be due to invalid IL or missing references)
			//IL_0092: Unknown result type (might be due to invalid IL or missing references)
			//IL_0097: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ab: 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_00ca: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d0: Unknown result type (might be due to invalid IL or missing references)
			if (!((Object)(object)instance.Sprite == (Object)null) && !((Object)(object)instance.SpriteGo == (Object)null))
			{
				if (_clipCache != null && _clipCache.TryGetValue(fd.animClip, out tk2dSpriteAnimationClip value) && value.frames.Length != 0)
				{
					((tk2dBaseSprite)instance.Sprite).spriteId = value.frames[fd.animFrame % value.frames.Length].spriteId;
				}
				((tk2dBaseSprite)instance.Sprite).color = color;
				instance.SpriteGo.transform.position = pos;
				Vector3 localScale = instance.SpriteGo.transform.localScale;
				instance.SpriteGo.transform.localScale = new Vector3(fd.facingRight ? Mathf.Abs(localScale.x) : (0f - Mathf.Abs(localScale.x)), localScale.y, localScale.z);
				instance.SpriteGo.SetActive(true);
				GameObject? diamondGo = instance.DiamondGo;
				if (diamondGo != null)
				{
					diamondGo.SetActive(false);
				}
			}
		}

		private static void RenderDiamond(PlaybackInstance instance, Vector3 center, Color color)
		{
			//IL_0064: Unknown result type (might be due to invalid IL or missing references)
			//IL_0074: Unknown result type (might be due to invalid IL or missing references)
			//IL_0079: Unknown result type (might be due to invalid IL or missing references)
			//IL_008a: 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_00b0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00eb: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fc: Unknown result type (might be due to invalid IL or missing references)
			//IL_010c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0111: Unknown result type (might be due to invalid IL or missing references)
			//IL_004b: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)instance.SpriteGo != (Object)null)
			{
				instance.SpriteGo.SetActive(false);
			}
			if (!((Object)(object)instance.DiamondGo == (Object)null) && !((Object)(object)instance.DiamondLine == (Object)null))
			{
				if ((Object)(object)instance.DiamondMat != (Object)null)
				{
					instance.DiamondMat.color = color;
				}
				instance.DiamondGo.SetActive(true);
				instance.DiamondLine.SetPosition(0, center + new Vector3(0f, 0.25f, 0f));
				instance.DiamondLine.SetPosition(1, center + new Vector3(0.25f, 0f, 0f));
				instance.DiamondLine.SetPosition(2, center + new Vector3(0f, -0.25f, 0f));
				instance.DiamondLine.SetPosition(3, center + new Vector3(-0.25f, 0f, 0f));
				instance.DiamondLine.SetPosition(4, center + new Vector3(0f, 0.25f, 0f));
			}
		}
	}
	public sealed class GhostSettingsData
	{
		public bool TrackingEnabled = true;

		public bool GhostEnabled = true;

		public float ColorR = 1f;

		public float ColorG = 1f;

		public float ColorB = 1f;

		public float Alpha = 0.4f;

		public bool MultiReplayEnabled;

		public bool SaveAllRunsEnabled;

		public int MaxSavedReplaysPerRoute = 5;

		public bool TimerHudEnabled = true;

		public bool ChainRoomTimers = true;

		public bool SkipBacktrackRuns;

		public bool SkipBacktrackTimer;

		public bool CancelRunOnCheats = true;

		public bool SkipCheatedRuns;

		public bool ReeseEnabled;
	}
	public static class GhostSettings
	{
		private static readonly ManualLogSource Log = Logger.CreateLogSource("GhostSettings");

		private static string _filePath = "";

		private static readonly GhostSettingsData _d = new GhostSettingsData();

		private const float MinSaveIntervalSec = 0.5f;

		private static bool _dirty;

		private static float _lastSaveRealtime = float.NegativeInfinity;

		public static bool TrackingEnabled
		{
			get
			{
				return _d.TrackingEnabled;
			}
			set
			{
				_d.TrackingEnabled = value;
				Save();
			}
		}

		public static bool GhostEnabled
		{
			get
			{
				return _d.GhostEnabled;
			}
			set
			{
				_d.GhostEnabled = value;
				Save();
			}
		}

		public static bool ReeseEnabled
		{
			get
			{
				return _d.ReeseEnabled;
			}
			set
			{
				_d.ReeseEnabled = value;
				Save();
			}
		}

		public static bool MultiReplayEnabled
		{
			get
			{
				return _d.MultiReplayEnabled;
			}
			set
			{
				_d.MultiReplayEnabled = value;
				Save();
			}
		}

		public static bool SaveAllRunsEnabled
		{
			get
			{
				return _d.SaveAllRunsEnabled;
			}
			set
			{
				_d.SaveAllRunsEnabled = value;
				Save();
			}
		}

		public static int MaxSavedReplaysPerRoute
		{
			get
			{
				return Mathf.Max(1, _d.MaxSavedReplaysPerRoute);
			}
			set
			{
				_d.MaxSavedReplaysPerRoute = Mathf.Max(1, value);
				Save();
			}
		}

		public static Color GhostColor
		{
			get
			{
				//IL_0028: Unknown result type (might be due to invalid IL or missing references)
				return new Color(_d.ColorR, _d.ColorG, _d.ColorB, _d.Alpha);
			}
			set
			{
				//IL_0005: Unknown result type (might be due to invalid IL or missing references)
				//IL_0015: Unknown result type (might be due to invalid IL or missing references)
				//IL_0025: 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)
				_d.ColorR = value.r;
				_d.ColorG = value.g;
				_d.ColorB = value.b;
				_d.Alpha = value.a;
				SaveThrottled();
			}
		}

		public static float GhostAlpha
		{
			get
			{
				return _d.Alpha;
			}
			set
			{
				_d.Alpha = Mathf.Clamp01(value);
				SaveThrottled();
			}
		}

		public static bool TimerHudEnabled
		{
			get
			{
				return _d.TimerHudEnabled;
			}
			set
			{
				_d.TimerHudEnabled = value;
				Save();
			}
		}

		public static bool ChainRoomTimers
		{
			get
			{
				return _d.ChainRoomTimers;
			}
			set
			{
				_d.ChainRoomTimers = value;
				Save();
			}
		}

		public static bool SkipBacktrackRuns
		{
			get
			{
				return _d.SkipBacktrackRuns;
			}
			set
			{
				_d.SkipBacktrackRuns = value;
				Save();
			}
		}

		public static bool SkipBacktrackPlayback
		{
			get
			{
				return _d.SkipBacktrackTimer;
			}
			set
			{
				_d.SkipBacktrackTimer = value;
				Save();
			}
		}

		public static bool CancelRunOnCheats
		{
			get
			{
				return _d.CancelRunOnCheats;
			}
			set
			{
				_d.CancelRunOnCheats = value;
				Save();
			}
		}

		public static bool SkipCheatedRuns
		{
			get
			{
				return _d.SkipCheatedRuns;
			}
			set
			{
				_d.SkipCheatedRuns = value;
				Save();
			}
		}

		public static void Init(string baseDirectory)
		{
			_filePath = Path.Combine(Path.Combine(baseDirectory, "ReplayMod"), "settings.txt");
			Load();
		}

		public static void Save()
		{
			if (string.IsNullOrEmpty(_filePath))
			{
				return;
			}
			try
			{
				List<string> list = new List<string>();
				FieldInfo[] fields = typeof(GhostSettingsData).GetFields(BindingFlags.Instance | BindingFlags.Public);
				foreach (FieldInfo fieldInfo in fields)
				{
					list.Add(fieldInfo.Name + "=" + Convert.ToString(fieldInfo.GetValue(_d), CultureInfo.InvariantCulture));
				}
				File.WriteAllLines(_filePath, list.ToArray());
				_dirty = false;
				_lastSaveRealtime = Time.realtimeSinceStartup;
			}
			catch (Exception ex)
			{
				Log.LogError((object)("[GhostSettings] Save failed: " + ex.Message));
			}
		}

		private static void SaveThrottled()
		{
			if (Time.realtimeSinceStartup - _lastSaveRealtime >= 0.5f)
			{
				Save();
			}
			else
			{
				_dirty = true;
			}
		}

		public static void Flush()
		{
			if (_dirty)
			{
				Save();
			}
		}

		private static void Load()
		{
			if (!File.Exists(_filePath))
			{
				return;
			}
			try
			{
				GhostSettingsData obj = new GhostSettingsData();
				string[] array = File.ReadAllLines(_filePath);
				foreach (string text in array)
				{
					int num = text.IndexOf('=');
					if (num < 0)
					{
						continue;
					}
					string name = text.Substring(0, num).Trim();
					string val = text.Substring(num + 1).Trim();
					FieldInfo field = typeof(GhostSettingsData).GetField(name, BindingFlags.Instance | BindingFlags.Public);
					if (!(field == null))
					{
						try
						{
							field.SetValue(_d, ParseField(field.FieldType, val, field.GetValue(obj)));
						}
						catch
						{
						}
					}
				}
			}
			catch (Exception ex)
			{
				Log.LogError((object)("[GhostSettings] Load failed: " + ex.Message));
			}
		}

		private static object ParseField(Type t, string val, object fallback)
		{
			try
			{
				if (t == typeof(bool))
				{
					return bool.Parse(val);
				}
				if (t == typeof(int))
				{
					return int.Parse(val, CultureInfo.InvariantCulture);
				}
				if (t == typeof(float))
				{
					return float.Parse(val, NumberStyles.Float, CultureInfo.InvariantCulture);
				}
				if (t == typeof(string))
				{
					return val;
				}
			}
			catch
			{
			}
			return fallback;
		}
	}
	internal static class JsonText
	{
		public static void AppendQuoted(StringBuilder sb, string? s)
		{
			if (s == null)
			{
				sb.Append("null");
				return;
			}
			sb.Append('"');
			AppendEscaped(sb, s);
			sb.Append('"');
		}

		public static string Escape(string? s)
		{
			if (string.IsNullOrEmpty(s))
			{
				return s ?? "";
			}
			StringBuilder stringBuilder = new StringBuilder(s.Length);
			AppendEscaped(stringBuilder, s);
			return stringBuilder.ToString();
		}

		public static string ReadString(string json, ref int i)
		{
			if (i >= json.Length || json[i] != '"')
			{
				return "";
			}
			i++;
			int num = i;
			for (; i < json.Length; i++)
			{
				switch (json[i])
				{
				case '"':
				{
					string result = json.Substring(num, i - num);
					i++;
					return result;
				}
				default:
					continue;
				case '\\':
					break;
				}
				break;
			}
			if (i >= json.Length)
			{
				return json.Substring(num, i - num);
			}
			StringBuilder stringBuilder = new StringBuilder(json, num, i - num, i - num + 16);
			while (i < json.Length)
			{
				char c = json[i];
				if (c == '"')
				{
					i++;
					break;
				}
				if (c == '\\' && i + 1 < json.Length)
				{
					i++;
					switch (json[i])
					{
					case '"':
						stringBuilder.Append('"');
						break;
					case '\\':
						stringBuilder.Append('\\');
						break;
					case '/':
						stringBuilder.Append('/');
						break;
					case 'n':
						stringBuilder.Append('\n');
						break;
					case 'r':
						stringBuilder.Append('\r');
						break;
					case 't':
						stringBuilder.Append('\t');
						break;
					case 'u':
						if (i + 4 < json.Length)
						{
							string value = json.Substring(i + 1, 4);
							stringBuilder.Append((char)Convert.ToInt32(value, 16));
							i += 4;
						}
						break;
					default:
						stringBuilder.Append(json[i]);
						break;
					}
				}
				else
				{
					stringBuilder.Append(c);
				}
				i++;
			}
			return stringBuilder.ToString();
		}

		public static void SkipWs(string json, ref int i)
		{
			while (i < json.Length && (json[i] == ' ' || json[i] == '\t' || json[i] == '\n' || json[i] == '\r'))
			{
				i++;
			}
		}

		private static void AppendEscaped(StringBuilder sb, string s)
		{
			foreach (char c in s)
			{
				switch (c)
				{
				case '"':
					sb.Append("\\\"");
					continue;
				case '\\':
					sb.Append("\\\\");
					continue;
				case '\n':
					sb.Append("\\n");
					continue;
				case '\r':
					sb.Append("\\r");
					continue;
				case '\t':
					sb.Append("\\t");
					continue;
				}
				if (c < ' ')
				{
					StringBuilder stringBuilder = sb.Append("\\u");
					int num = c;
					stringBuilder.Append(num.ToString("x4"));
				}
				else
				{
					sb.Append(c);
				}
			}
		}
	}
	internal static class KnownScenes
	{
		public const string MenuTitle = "Menu_Title";

		public const string QuitToMenu = "Quit_To_Menu";
	}
	internal static class MiniJson
	{
		private sealed class Parser
		{
			private readonly string _s;

			private int _pos;

			public Parser(string s)
			{
				_s = s;
			}

			public char Peek()
			{
				if (_pos >= _s.Length)
				{
					return '\0';
				}
				return _s[_pos];
			}

			public void Advance()
			{
				_pos++;
			}

			public void SkipWs()
			{
				while (_pos < _s.Length && _s[_pos] <= ' ')
				{
					_pos++;
				}
			}

			public void Expect(char c)
			{
				SkipWs();
				if (_pos >= _s.Length || _s[_pos] != c)
				{
					throw new Exception($"MiniJson: expected '{c}' at pos {_pos}, got '{Peek()}'");
				}
				_pos++;
			}

			public string ReadString()
			{
				SkipWs();
				Expect('"');
				StringBuilder stringBuilder = new StringBuilder();
				while (_pos < _s.Length)
				{
					char c = _s[_pos++];
					switch (c)
					{
					case '"':
						return stringBuilder.ToString();
					default:
						stringBuilder.Append(c);
						break;
					case '\\':
					{
						char c2 = _s[_pos++];
						switch (c2)
						{
						case '"':
							stringBuilder.Append('"');
							break;
						case '\\':
							stringBuilder.Append('\\');
							break;
						case '/':
							stringBuilder.Append('/');
							break;
						case 'n':
							stringBuilder.Append('\n');
							break;
						case 'r':
							stringBuilder.Append('\r');
							break;
						case 't':
							stringBuilder.Append('\t');
							break;
						case 'u':
							stringBuilder.Append((char)Convert.ToInt32(_s.Substring(_pos, 4), 16));
							_pos += 4;
							break;
						default:
							stringBuilder.Append(c2);
							break;
						}
						break;
					}
					}
				}
				throw new Exception("MiniJson: unterminated string");
			}

			public float ReadFloat()
			{
				int pos = _pos;
				while (_pos < _s.Length)
				{
					char c = _s[_pos];
					if (c == ',' || c == '}' || c == ']' || c <= ' ')
					{
						break;
					}
					_pos++;
				}
				return float.Parse(_s.Substring(pos, _pos - pos), CultureInfo.InvariantCulture);
			}

			public long ReadLong()
			{
				int pos = _pos;
				while (_pos < _s.Length)
				{
					char c = _s[_pos];
					if (c == ',' || c == '}' || c == ']' || c <= ' ')
					{
						break;
					}
					_pos++;
				}
				return long.Parse(_s.Substring(pos, _pos - pos), CultureInfo.InvariantCulture);
			}

			public bool ReadBool()
			{
				SkipWs();
				bool result = Peek() == 't';
				SkipValue();
				return result;
			}

			public void SkipValue()
			{
				SkipWs();
				char c = Peek();
				switch (c)
				{
				case '"':
					ReadString();
					return;
				case '[':
				case '{':
				{
					char c2 = ((c == '{') ? '}' : ']');
					Advance();
					int num = 1;
					while (_pos < _s.Length && num > 0)
					{
						char c3 = _s[_pos++];
						if (c3 == '"')
						{
							while (_pos < _s.Length)
							{
								switch (_s[_pos++])
								{
								case '\\':
									_pos++;
									continue;
								default:
									continue;
								case '"':
									break;
								}
								break;
							}
						}
						else if (c3 == c)
						{
							num++;
						}
						else if (c3 == c2)
						{
							num--;
						}
					}
					return;
				}
				}
				while (_pos < _s.Length)
				{
					char c4 = _s[_pos];
					if (c4 != ',' && c4 != '}' && c4 != ']' && c4 > ' ')
					{
						_pos++;
						continue;
					}
					break;
				}
			}
		}

		public static string Serialize(SceneIndex idx)
		{
			StringBuilder stringBuilder = new StringBuilder();
			stringBuilder.Append("{\"entries\":[");
			for (int i = 0; i < idx.entries.Count; i++)
			{
				if (i > 0)
				{
					stringBuilder.Append(',');
				}
				SerializeEntry(stringBuilder, idx.entries[i]);
			}
			stringBuilder.Append("]}");
			return stringBuilder.ToString();
		}

		public static SceneIndex Deserialize(string json)
		{
			Parser parser = new Parser(json);
			parser.SkipWs();
			parser.Expect('{');
			SceneIndex sceneIndex = new SceneIndex();
			while (true)
			{
				parser.SkipWs();
				if (parser.Peek() == '}')
				{
					break;
				}
				if (parser.Peek() == ',')
				{
					parser.Advance();
					continue;
				}
				string text = parser.ReadString();
				parser.SkipWs();
				parser.Expect(':');
				parser.SkipWs();
				if (text == "entries")
				{
					parser.Expect('[');
					while (true)
					{
						parser.SkipWs();
						if (parser.Peek() == ']')
						{
							break;
						}
						if (parser.Peek() == ',')
						{
							parser.Advance();
						}
						else
						{
							sceneIndex.entries.Add(DeserializeEntry(parser));
						}
					}
					parser.Advance();
				}
				else
				{
					parser.SkipValue();
				}
			}
			parser.Advance();
			return sceneIndex;
		}

		private static void SerializeEntry(StringBuilder sb, EntryIndex e)
		{
			sb.Append("{\"snapshotId\":");
			AppendString(sb, e.snapshotId);
			sb.Append(",\"capturedAtUtcTicks\":");
			sb.Append(e.capturedAtUtcTicks.ToString(CultureInfo.InvariantCulture));
			sb.Append(",\"sceneName\":");
			AppendString(sb, e.sceneName);
			sb.Append(",\"entryFromScene\":");
			AppendString(sb, e.entryFromScene);
			sb.Append(",\"exitToScene\":");
			AppendString(sb, e.exitToScene);
			sb.Append(",\"totalTime\":");
			sb.Append(e.totalTime.ToString("R", CultureInfo.InvariantCulture));
			sb.Append(",\"hasVisualOverride\":");
			sb.Append(e.hasVisualOverride ? "true" : "false");
			sb.Append(",\"colorR\":");
			sb.Append(e.colorR.ToString("R", CultureInfo.InvariantCulture));
			sb.Append(",\"colorG\":");
			sb.Append(e.colorG.ToString("R", CultureInfo.InvariantCulture));
			sb.Append(",\"colorB\":");
			sb.Append(e.colorB.ToString("R", CultureInfo.InvariantCulture));
			sb.Append(",\"alpha\":");
			sb.Append(e.alpha.ToString("R", CultureInfo.InvariantCulture));
			sb.Append(",\"usedCheats\":");
			sb.Append(e.usedCheats ? "true" : "false");
			sb.Append(",\"data\":");
			AppendString(sb, e.data);
			sb.Append('}');
		}

		private static void AppendString(StringBuilder sb, string s)
		{
			JsonText.AppendQuoted(sb, s);
		}

		private static EntryIndex DeserializeEntry(Parser p)
		{
			p.Expect('{');
			EntryIndex entryIndex = new EntryIndex();
			while (true)
			{
				p.SkipWs();
				if (p.Peek() == '}')
				{
					break;
				}
				if (p.Peek() == ',')
				{
					p.Advance();
					continue;
				}
				string text = p.ReadString();
				p.SkipWs();
				p.Expect(':');
				p.SkipWs();
				switch (text)
				{
				case "snapshotId":
					entryIndex.snapshotId = p.ReadString();
					break;
				case "capturedAtUtcTicks":
					entryIndex.capturedAtUtcTicks = p.ReadLong();
					break;
				case "sceneName":
					entryIndex.sceneName = p.ReadString();
					break;
				case "entryFromScene":
					entryIndex.entryFromScene = p.ReadString();
					break;
				case "exitToScene":
					entryIndex.exitToScene = p.ReadString();
					break;
				case "totalTime":
					entryIndex.totalTime = p.ReadFloat();
					break;
				case "hasVisualOverride":
					entryIndex.hasVisualOverride = p.ReadBool();
					break;
				case "colorR":
					entryIndex.colorR = p.ReadFloat();
					break;
				case "colorG":
					entryIndex.colorG = p.ReadFloat();
					break;
				case "colorB":
					entryIndex.colorB = p.ReadFloat();
					break;
				case "alpha":
					entryIndex.alpha = p.ReadFloat();
					break;
				case "usedCheats":
					entryIndex.usedCheats = p.ReadBool();
					break;
				case "data":
					entryIndex.data = p.ReadString();
					break;
				default:
					p.SkipValue();
					break;
				}
			}
			p.Advance();
			return entryIndex;
		}
	}
	public static class PBManager
	{
		public enum ImportOutcome
		{
			Imported,
			Duplicate,
			RouteFull
		}

		private static readonly ManualLogSource Log = Logger.CreateLogSource("PBManager");

		private static readonly Dictionary<RoomKey, List<ReplaySnapshot>> _histories = new Dictionary<RoomKey, List<ReplaySnapshot>>();

		private static readonly Dictionary<RoomKey, ReplaySnapshot> _currentPbs = new Dictionary<RoomKey, ReplaySnapshot>();

		private static ReplaySelectionState? _selectionState;

		public static ReplaySnapshot? LatestSaved { get; private set; }

		public static ReplaySelectionState? SelectionState => _selectionState;

		public static IEnumerable<KeyValuePair<RoomKey, RecordedRoom>> AllPBs()
		{
			return _currentPbs.Select<KeyValuePair<RoomKey, ReplaySnapshot>, KeyValuePair<RoomKey, RecordedRoom>>((KeyValuePair<RoomKey, ReplaySnapshot> kvp) => new KeyValuePair<RoomKey, RecordedRoom>(kvp.Key, kvp.Value.Room));
		}

		public static IEnumerable<RouteReplayHistory> AllHistories()
		{
			return (from kvp in _histories
				orderby kvp.Key.SceneName, kvp.Key.EntryFromScene, kvp.Key.ExitToScene
				select kvp).Select(delegate(KeyValuePair<RoomKey, List<ReplaySnapshot>> kvp)
			{
				ReplaySnapshot[] array = OrderSnapshots(kvp.Value);
				return new RouteReplayHistory(kvp.Key, array, array[0]);
			});
		}

		public static void Init()
		{
			_histories.Clear();
			_currentPbs.Clear();
			_selectionState?.ClearAll();
			foreach (ReplaySnapshot item in DataStore.LoadAll())
			{
				AddSnapshot(item, persist: false, allowDuplicate: false, enforceLimit: false);
			}
			int num = PruneAllHistories(GhostSettings.MaxSavedReplaysPerRoute, persist: true);
			Log.LogInfo((object)($"[PBManager] Loaded {_currentPbs.Count} active PBs from disk ({_histories.Values.Sum((List<ReplaySnapshot> list) => list.Count)} snapshots)" + ((num > 0) ? $", pruned {num} overflow snapshots" : string.Empty)));
		}

		public static void SetSelectionState(ReplaySelectionState? state)
		{
			_selectionState = state;
			_selectionState?.PruneToExisting(_histories.Values.SelectMany((List<ReplaySnapshot> list) => list));
		}

		public static RecordedRoom? GetPB(RoomKey key)
		{
			_currentPbs.TryGetValue(key, out ReplaySnapshot value);
			return value?.Room;
		}

		public static ReplaySnapshot? GetPBSnapshot(RoomKey key)
		{
			if (!_currentPbs.TryGetValue(key, out ReplaySnapshot value))
			{
				return null;
			}
			return value;
		}

		public static IList<ReplaySnapshot> GetHistory(RoomKey key)
		{
			if (!_histories.TryGetValue(key, out List<ReplaySnapshot> value))
			{
				return new ReplaySnapshot[0];
			}
			return OrderSnapshots(value);
		}

		public static RouteReplayHistory? GetRouteHistory(RoomKey key)
		{
			if (!_histories.TryGetValue(key, out List<ReplaySnapshot> value) || value.Count == 0)
			{
				return null;
			}
			ReplaySnapshot[] array = OrderSnapshots(value);
			return new RouteReplayHistory(key, array, array[0]);
		}

		public static ReplaySnapshot? GetSnapshot(RoomKey key, string snapshotId)
		{
			if (!_histories.TryGetValue(key, out List<ReplaySnapshot> value))
			{
				return null;
			}
			return value.FirstOrDefault((ReplaySnapshot snapshot) => snapshot.SnapshotId == snapshotId);
		}

		public static IList<ReplaySnapshot> GetPlaybackCandidates(string sceneName, string entryFromScene)
		{
			return OrderSnapshots(_histories.Where<KeyValuePair<RoomKey, List<R