Decompiled source of Mist Practice v1.4.2

BepInEx/plugins/MistPractice/MistPractice.dll

Decompiled 2 weeks ago
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Text;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Configuration;
using DebugMod.SaveStates;
using HarmonyLib;
using HutongGames.PlayMaker;
using HutongGames.PlayMaker.Actions;
using Newtonsoft.Json;
using UnityEngine;
using UnityEngine.SceneManagement;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: AssemblyVersion("0.0.0.0")]
namespace MistPractice;

internal sealed class ConfigurationManagerAttributes
{
	public bool? Browsable;

	public bool? HideDefaultButton;

	public string DispName;

	public string Description;

	public int? Order;

	public Action<ConfigEntryBase> CustomDrawer;
}
public enum InterfaceLanguage
{
	Auto,
	English,
	SimplifiedChinese
}
[BepInDependency(/*Could not decode attribute arguments.*/)]
[BepInPlugin("local.silksong.mistpractice", "Mist Practice", "1.4.2")]
[BepInDependency(/*Could not decode attribute arguments.*/)]
public sealed class Plugin : BaseUnityPlugin
{
	private sealed class RoomSection
	{
		internal readonly string Title;

		internal readonly List<string> Lines;

		internal RoomSection(string title, params string[] lines)
		{
			Title = title;
			Lines = new List<string>(lines);
		}
	}

	private sealed class DebugArrival
	{
		internal readonly object Load;

		internal readonly string Room;

		internal readonly Layout Replay;

		internal bool AllowOverrides;

		internal bool TargetStarted;

		internal bool Finished;

		internal bool Consumed;

		internal int PreviousHandle;

		internal DebugArrival(object load, string room, Layout replay)
		{
			Load = load;
			Room = room;
			Replay = replay;
			AllowOverrides = Training;
		}

		internal bool IsTarget(Scene scene)
		{
			if (TargetStarted && !Consumed && ((Scene)(ref scene)).name == Room)
			{
				return ((Scene)(ref scene)).handle != PreviousHandle;
			}
			return false;
		}
	}

	private const string ManagerId = "com.bepis.bepinex.configurationmanager";

	public const string Id = "local.silksong.mistpractice";

	public const string DebugId = "io.github.hk-speedrunning.debugmod";

	public const string WarpId = "io.github.hk-speedrunning.quickwarp";

	internal const string OriginalGameVersion = "1.0.28324";

	private ConfigEntry<InterfaceLanguage> language;

	private readonly List<Action> settingLabels = new List<Action>();

	private bool openFromManager;

	private bool refreshManager;

	private Vector2 currentRoomScroll;

	private List<RoomSection> currentRoomSections;

	private int inspectedScene = -1;

	private int inspectedLiveScene = -1;

	private float refreshLiveObjects;

	private GameObject[] liveFlies = (GameObject[])(object)new GameObject[0];

	private HealthManager[] liveWraiths = (HealthManager[])(object)new HealthManager[0];

	private Breakable[] liveSpools = (Breakable[])(object)new Breakable[0];

	private Rect window = new Rect(32f, 28f, 750f, 586f);

	private Vector2 scroll;

	private int editRoom;

	private int tab;

	private int page;

	private Font font;

	private bool triedFont;

	private bool cursorOwned;

	private bool previousCursor;

	private CursorLockMode previousLock;

	private static readonly string[] RoomNames = (from i in Enumerable.Range(1, 8)
		select "M" + i).ToArray();

	private static readonly Dictionary<string, string> TrapNames = new Dictionary<string, string>(StringComparer.Ordinal)
	{
		{ "Dust Trap Spike Plate", "踏板尖刺" },
		{ "Dust Trap Spike Dropper", "落刺" },
		{ "Mite Trap", "捕兽夹" },
		{ "greymoor_flip_bridge", "翻转桥板" },
		{ "Spike Pendulum", "钉刺摆锤" },
		{ "Spike Pendulum Hanging", "悬挂钉刺摆锤" },
		{ "Spike Pendulum Upright (1) fix", "直立钉刺摆锤 (1)" },
		{ "Drop Cage", "坠落吊笼" },
		{ "Safe Cage", "固定吊笼" },
		{ "cage_mid_small_long_sway", "摆动吊笼" },
		{ "cage_mid_small_long_sway drop", "坠落吊笼" },
		{ "cage_mid_small_longer_sway", "长摆吊笼" },
		{ "break_spool_side", "横放线轴" },
		{ "break_spool_upright", "直立线轴" }
	};

	internal static Plugin Instance;

	private static DebugArrival debugArrival;

	private static string messageEnglish = "";

	private static string messageChinese = "";

	private static readonly Dictionary<int, Visit> visits = new Dictionary<int, Visit>();

	private static readonly HashSet<int> passiveRooms = new HashSet<int>();

	private static readonly HashSet<int> debugRooms = new HashSet<int>();

	private static readonly Random random = new Random();

	internal readonly Dictionary<string, Plan> Plans = new Dictionary<string, Plan>();

	private ConfigEntry<bool> enabledPractice;

	private ConfigEntry<bool> restoreSave;

	private ConfigEntry<KeyboardShortcut> menuKey;

	private ConfigEntry<KeyboardShortcut> warpKey;

	private ConfigEntry<string> savedPlans;

	private Harmony harmony;

	private MethodInfo warpMethod;

	private bool debugAttached;

	private bool ready;

	private bool open;

	private static bool UseChinese
	{
		get
		{
			//IL_0040: Unknown result type (might be due to invalid IL or missing references)
			//IL_0045: Unknown result type (might be due to invalid IL or missing references)
			//IL_0046: Unknown result type (might be due to invalid IL or missing references)
			//IL_0048: Invalid comparison between Unknown and I4
			//IL_004a: Unknown result type (might be due to invalid IL or missing references)
			//IL_004d: Invalid comparison between Unknown and I4
			//IL_004f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0052: Invalid comparison between Unknown and I4
			if (!Object.op_Implicit((Object)(object)Instance) || Instance.language == null)
			{
				return false;
			}
			switch (Instance.language.Value)
			{
			case InterfaceLanguage.English:
				return false;
			case InterfaceLanguage.SimplifiedChinese:
				return true;
			default:
			{
				SystemLanguage systemLanguage = Application.systemLanguage;
				if ((int)systemLanguage != 6 && (int)systemLanguage != 40)
				{
					return (int)systemLanguage == 41;
				}
				return true;
			}
			}
		}
	}

	internal static bool LoadingDebug
	{
		get
		{
			if (debugArrival != null)
			{
				return !debugArrival.Finished;
			}
			return false;
		}
	}

	internal static string Message => T(messageEnglish, messageChinese);

	internal static string GameVersion { get; private set; }

	internal static bool AllowsJuggling { get; private set; }

	internal static string ModeLabel
	{
		get
		{
			if (!AllowsJuggling)
			{
				return T("No room juggling", "不支持切房技巧");
			}
			return T("Room juggling", "支持切房技巧");
		}
	}

	internal static bool MayRun
	{
		get
		{
			if ((Object)(object)Instance != (Object)null && Instance.ready)
			{
				if (!Instance.enabledPractice.Value)
				{
					return visits.Count != 0;
				}
				return true;
			}
			return false;
		}
	}

	internal static bool Training
	{
		get
		{
			if (Object.op_Implicit((Object)(object)Instance) && Instance.ready)
			{
				return Instance.enabledPractice.Value;
			}
			return false;
		}
	}

	internal static string T(string en, string zh)
	{
		if (!UseChinese)
		{
			return en;
		}
		return zh;
	}

	private ConfigDescription Setting(string en, string zh, string enDescription, string zhDescription, int order, Action<ConfigEntryBase> drawer = null)
	{
		//IL_0087: Unknown result type (might be due to invalid IL or missing references)
		//IL_008d: Expected O, but got Unknown
		ConfigurationManagerAttributes tags = new ConfigurationManagerAttributes
		{
			Order = order,
			HideDefaultButton = (drawer != null),
			CustomDrawer = drawer
		};
		settingLabels.Add(delegate
		{
			tags.DispName = T(en, zh);
			tags.Description = T(enDescription, zhDescription);
		});
		return new ConfigDescription(enDescription, (AcceptableValueBase)null, new object[1] { tags });
	}

	private void LocalizeSettings()
	{
		foreach (Action settingLabel in settingLabels)
		{
			settingLabel();
		}
	}

	private void LanguageChanged(object sender, EventArgs args)
	{
		LocalizeSettings();
		refreshManager = true;
	}

	private static bool ConfigurationManagerIsOpen()
	{
		if (!Chainloader.PluginInfos.TryGetValue("com.bepis.bepinex.configurationmanager", out var value))
		{
			return false;
		}
		PropertyInfo propertyInfo = AccessTools.Property(((object)value.Instance).GetType(), "DisplayingWindow");
		if (propertyInfo != null)
		{
			return object.Equals(propertyInfo.GetValue(value.Instance, null), true);
		}
		return false;
	}

	private void UpdateManager()
	{
		if (!openFromManager && !refreshManager)
		{
			return;
		}
		if (Chainloader.PluginInfos.TryGetValue("com.bepis.bepinex.configurationmanager", out var value))
		{
			BaseUnityPlugin instance = value.Instance;
			if (refreshManager)
			{
				MethodInfo methodInfo = AccessTools.Method(((object)instance).GetType(), "BuildSettingList", (Type[])null, (Type[])null);
				if (methodInfo != null)
				{
					methodInfo.Invoke(instance, null);
				}
			}
			if (openFromManager)
			{
				PropertyInfo propertyInfo = AccessTools.Property(((object)instance).GetType(), "DisplayingWindow");
				if (propertyInfo != null && propertyInfo.CanWrite)
				{
					propertyInfo.SetValue(instance, false, null);
				}
			}
		}
		refreshManager = false;
		if (openFromManager)
		{
			open = true;
		}
		openFromManager = false;
	}

	private void DrawLanguage()
	{
		language.Value = (InterfaceLanguage)GUILayout.Toolbar((int)language.Value, new string[3]
		{
			T("Auto", "自动"),
			"English",
			"简体中文"
		}, (GUILayoutOption[])(object)new GUILayoutOption[0]);
	}

	private void DrawLanguageSetting(ConfigEntryBase _)
	{
		WithInterfaceFont(DrawLanguage);
	}

	private void DrawEditorButton(ConfigEntryBase _)
	{
		WithInterfaceFont(delegate
		{
			if (GUILayout.Button(T("Open editor", "打开迷瘴编辑器"), (GUILayoutOption[])(object)new GUILayoutOption[0]))
			{
				openFromManager = true;
			}
		});
	}

	private void DrawCurrentRoom()
	{
		//IL_0005: Unknown result type (might be due to invalid IL or missing references)
		//IL_000b: Invalid comparison between Unknown and I4
		//IL_002b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0032: Expected O, but got Unknown
		//IL_003e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0045: Expected O, but got Unknown
		//IL_0052: Unknown result type (might be due to invalid IL or missing references)
		//IL_006f: 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)
		if ((int)Event.current.type == 8 || currentRoomSections == null)
		{
			currentRoomSections = ReadCurrentRoom();
		}
		GUIStyle val = new GUIStyle(GUI.skin.label);
		val.wordWrap = true;
		GUIStyle val2 = val;
		GUIStyle val3 = new GUIStyle(val2);
		val3.fontStyle = (FontStyle)1;
		GUIStyle val4 = val3;
		currentRoomScroll = GUILayout.BeginScrollView(currentRoomScroll, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Height(482f) });
		foreach (RoomSection currentRoomSection in currentRoomSections)
		{
			GUILayout.BeginVertical(GUI.skin.box, (GUILayoutOption[])(object)new GUILayoutOption[0]);
			GUILayout.Label(currentRoomSection.Title, val4, (GUILayoutOption[])(object)new GUILayoutOption[0]);
			foreach (string line in currentRoomSection.Lines)
			{
				GUILayout.Label(line, val2, (GUILayoutOption[])(object)new GUILayoutOption[0]);
			}
			GUILayout.EndVertical();
		}
		GUILayout.EndScrollView();
	}

	private List<RoomSection> ReadCurrentRoom()
	{
		//IL_0006: Unknown result type (might be due to invalid IL or missing references)
		//IL_000b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0029: Unknown result type (might be due to invalid IL or missing references)
		//IL_002e: Unknown result type (might be due to invalid IL or missing references)
		//IL_006b: 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_00ca: Unknown result type (might be due to invalid IL or missing references)
		//IL_037f: Unknown result type (might be due to invalid IL or missing references)
		//IL_038f: Unknown result type (might be due to invalid IL or missing references)
		List<RoomSection> list = new List<RoomSection>();
		Scene activeScene = SceneManager.GetActiveScene();
		if (inspectedScene != ((Scene)(ref activeScene)).handle)
		{
			inspectedScene = ((Scene)(ref activeScene)).handle;
			currentRoomScroll = Vector2.zero;
		}
		GameManager unsafeInstance = GameManager.UnsafeInstance;
		if (Object.op_Implicit((Object)(object)unsafeInstance) && unsafeInstance.IsInSceneTransition)
		{
			list.Add(new RoomSection(T("Room transition in progress", "正在切换房间")));
			return list;
		}
		RoomObservation roomObservation = RoomObservation.For(activeScene);
		if (roomObservation == null)
		{
			list.Add(new RoomSection(T("Outside The Mist", "当前不在迷瘴"), T("Enter a Mist room to inspect its live state.", "进入迷瘴房间后可查看实时状态。")));
			return list;
		}
		MazeController val = MazeController.NewestInstance;
		if (Object.op_Implicit((Object)(object)val) && ((Component)val).gameObject.scene != activeScene)
		{
			val = null;
		}
		PlayerData instance = PlayerData.instance;
		Visit visit = (Object.op_Implicit((Object)(object)val) ? Current() : null);
		RoomSection roomSection = new RoomSection(SceneLabel(((Scene)(ref activeScene)).name) + "  ·  " + ((Scene)(ref activeScene)).name);
		if (roomObservation.Populated || ((Scene)(ref activeScene)).name == "Dust_Maze_08_completed")
		{
			roomSection.Lines.Add((visit == null) ? T("Vanilla visit", "原版布置") : ((visit.Replay != null) ? T("Restored DebugMod layout", "已恢复 DebugMod 布置") : T("Practice visit", "练习房间布置")));
		}
		else
		{
			roomSection.Lines.Add(T("Waiting for room generation", "等待房间生成完成"));
		}
		list.Add(roomSection);
		if (instance != null && ((Scene)(ref activeScene)).name != "Dust_Maze_08_completed")
		{
			RoomSection roomSection2 = new RoomSection(T("Progress", "计分与进度"));
			roomSection2.Lines.Add(T("Score ", "当前分数 ") + instance.CorrectMazeDoorsEntered + (Object.op_Implicit((Object)(object)val) ? (T("   ·   Correct exits left ", "   ·   剩余分数 ") + val.CorrectDoorsLeft) : ""));
			roomSection2.Lines.Add(T("Wrong exits ", "连续错门 ") + instance.IncorrectMazeDoorsEntered + (Object.op_Implicit((Object)(object)val) ? (T("   ·   Wrong-exit allowance left ", "   ·   距错门阈值 ") + val.IncorrectDoorsLeft) : ""));
			roomSection2.Lines.Add(T("Crossing entered ", "已进中途长廊 ") + YesNo(instance.EnteredMazeRestScene) + T("   ·   Needolin obtained ", "   ·   已取得织忆弦针 ") + YesNo(instance.hasNeedolin));
			if (Catalog.Find(((Scene)(ref activeScene)).name) != null && roomObservation.TrapMultiplier.HasValue && roomObservation.WraithMultiplier.HasValue)
			{
				roomSection2.Lines.Add(T("Native trap multiplier ", "原版陷阱生成系数 ") + DecimalValue(roomObservation.TrapMultiplier.Value) + T("   ·   Native wraith multiplier ", "   ·   原版丝魂生成系数 ") + DecimalValue(roomObservation.WraithMultiplier.Value));
			}
			if (Doors.IsRecovering(instance))
			{
				roomSection2.Lines.Add(T("A return exit is required to regain the lost point.", "当前需走指定回走门补回扣除的一分。"));
			}
			list.Add(roomSection2);
		}
		list.Add(InspectDoors(activeScene, val, instance));
		RefreshRoomObjects(activeScene, roomObservation.Populated);
		list.Add(InspectActors(T("Lightmoths", "丝蝇"), roomObservation.Spawns[0], liveFlies));
		list.Add(InspectActors(T("Wraiths", "丝魂"), roomObservation.Spawns[1], from w in liveWraiths
			where Object.op_Implicit((Object)(object)w)
			select ((Component)w).gameObject));
		list.Add(InspectTraps(roomObservation));
		list.Add(InspectExtraGroups(roomObservation));
		list.Add(InspectSpools());
		return list;
	}

	private static RoomSection InspectDoors(Scene scene, MazeController controller, PlayerData player)
	{
		//IL_0009: Unknown result type (might be due to invalid IL or missing references)
		//IL_000a: Unknown result type (might be due to invalid IL or missing references)
		RoomSection roomSection = new RoomSection(T("Exits and destinations", "出入口与目的地"));
		if (Object.op_Implicit((Object)(object)controller) && !controller.IsDoorLinkComplete)
		{
			roomSection.Lines.Add(T("Waiting for door connections", "等待游戏连门"));
			return roomSection;
		}
		TransitionPoint[] array = (TransitionPoint[])(Object.op_Implicit((Object)(object)controller) ? ((Array)(from g in controller.EnumerateCorrectDoors()
			where Object.op_Implicit((Object)(object)g)
			select g).ToArray()) : ((Array)new TransitionPoint[0]));
		TransitionPoint[] array2 = TransitionPoint.TransitionPoints.Where((TransitionPoint g) => Object.op_Implicit((Object)(object)g) && ((Component)g).gameObject.scene == scene).OrderBy<TransitionPoint, string>((TransitionPoint g) => ((Object)g).name, StringComparer.Ordinal).ToArray();
		string arrival = player?.PreviousMazeTargetDoor;
		if (array2.Any((TransitionPoint g) => ((Object)g).name == arrival))
		{
			roomSection.Lines.Add(T("Arrival gate ", "来时门 ") + arrival);
		}
		if (array.Length == 0 && Object.op_Implicit((Object)(object)controller))
		{
			roomSection.Lines.Add(T("No gate marked correct", "本房无计分正确门"));
		}
		TransitionPoint[] array3 = array2;
		foreach (TransitionPoint val in array3)
		{
			int num2 = Array.IndexOf(array, val);
			string text = ((num2 >= 0) ? (T("Correct #", "正确 #") + (num2 + 1) + "   ") : "");
			if (((Object)val).name == arrival)
			{
				text += T("Arrival   ", "来时门   ");
			}
			string text2 = ((string.IsNullOrEmpty(val.targetScene) || val.targetScene == "[dynamic]") ? T("No destination", "无连接目的地") : (SceneLabel(val.targetScene) + (string.IsNullOrEmpty(val.entryPoint) ? "" : (" / " + val.entryPoint))));
			roomSection.Lines.Add(text + ((Object)val).name + "   →   " + text2);
		}
		if (array2.Length == 0)
		{
			roomSection.Lines.Add(T("No exits found", "未读到房间出口"));
		}
		return roomSection;
	}

	private void RefreshRoomObjects(Scene scene, bool populated)
	{
		if (inspectedLiveScene != ((Scene)(ref scene)).handle || !(Time.unscaledTime < refreshLiveObjects))
		{
			inspectedLiveScene = ((Scene)(ref scene)).handle;
			refreshLiveObjects = Time.unscaledTime + (populated ? 0.65f : 0.2f);
			GameObject[] rootGameObjects = ((Scene)(ref scene)).GetRootGameObjects();
			liveFlies = rootGameObjects.Where((GameObject root) => RoomObservation.IsInstanceOf(root, "Silkfly Mistmaze")).ToArray();
			liveWraiths = (from w in rootGameObjects.SelectMany((GameObject root) => root.GetComponentsInChildren<HealthManager>(true))
				where RoomObservation.IsInstanceOf(((Component)w).gameObject, "Wraith")
				select w).ToArray();
			liveSpools = (from s in rootGameObjects.SelectMany((GameObject root) => root.GetComponentsInChildren<Breakable>(true))
				where SilkSpoolControl.IsSpool(((Object)s).name)
				select s).ToArray();
		}
	}

	private static RoomSection InspectActors(string title, IList<Spot> spawns, IEnumerable<GameObject> actors)
	{
		RoomSection roomSection = new RoomSection(title + T("   ·   Spawn points ", "   ·   生成点 ") + spawns.Count);
		for (int i = 0; i < spawns.Count; i++)
		{
			Spot spot = spawns[i];
			roomSection.Lines.Add(i + 1 + ". " + spot.Name + " " + Coordinates(spot.X, spot.Y));
		}
		string[] array = (from obj in actors
			where Object.op_Implicit((Object)(object)obj) && obj.activeInHierarchy
			select WorldPosition(obj.transform) + (((Object)obj).name.EndsWith("(Clone)", StringComparison.Ordinal) ? "" : T(" [scene object]", "[场景预置]"))).ToArray();
		roomSection.Lines.Add(T("Current positions", "当前坐标") + " (" + array.Length + ")" + ((array.Length == 0) ? "" : ("   " + string.Join("   ", array))));
		return roomSection;
	}

	private static RoomSection InspectTraps(RoomObservation observation)
	{
		RoomSection roomSection = new RoomSection(T("Selected trap pool entries", "入选的普通陷阱") + " (" + observation.TrapPicks.Count + ")");
		foreach (RoomObservation.TrapPick trapPick in observation.TrapPicks)
		{
			if (observation.Groups.TryGetValue(trapPick.Id, out var value))
			{
				AddGroup(roomSection, value);
			}
			else
			{
				roomSection.Lines.Add(TrapLabel(ShortName(trapPick.Path)) + T("   ·   Individual trap   ·   ", "   ·   单独陷阱   ·   ") + ActiveLabel(trapPick.Object));
			}
		}
		if (observation.TrapPicks.Count == 0)
		{
			roomSection.Lines.Add(T("No trap pool entries selected", "本次未抽中普通陷阱"));
		}
		return roomSection;
	}

	private static RoomSection InspectExtraGroups(RoomObservation observation)
	{
		RoomObservation.GroupPick[] array = observation.Groups.Values.Where((RoomObservation.GroupPick group) => group.Extra).OrderBy<RoomObservation.GroupPick, string>((RoomObservation.GroupPick group) => group.Path, StringComparer.Ordinal).ToArray();
		RoomSection roomSection = new RoomSection(T("Extra groups", "额外组") + " (" + array.Length + ")");
		RoomObservation.GroupPick[] array2 = array;
		foreach (RoomObservation.GroupPick groupPick in array2)
		{
			AddGroup(roomSection, groupPick);
		}
		if (array.Length == 0)
		{
			roomSection.Lines.Add(T("No extra groups activated", "本次未启用额外组"));
		}
		return roomSection;
	}

	private static void AddGroup(RoomSection section, RoomObservation.GroupPick group)
	{
		section.Lines.Add(ShortName(group.Path) + "   ·   " + ActiveLabel(group.Object));
		if (group.Choices.Length == 0)
		{
			section.Lines.Add(T("    No active variant", "    未启用变体"));
		}
		RoomObservation.VariantPick[] choices = group.Choices;
		foreach (RoomObservation.VariantPick variantPick in choices)
		{
			string text = T("    Variant #", "    变体 #") + (variantPick.Index + 1) + "  " + TrapLabel(variantPick.Name);
			if (variantPick.Empty)
			{
				text += T("   ·   Empty branch", "   ·   空分支");
			}
			else if (Object.op_Implicit((Object)(object)variantPick.Object))
			{
				text = text + "   " + WorldPosition(variantPick.Object.transform);
			}
			if (!Object.op_Implicit((Object)(object)variantPick.Object) || !variantPick.Object.activeInHierarchy)
			{
				text = text + "   ·   " + ActiveLabel(variantPick.Object);
			}
			if (!variantPick.Empty && Object.op_Implicit((Object)(object)variantPick.Object) && ((Object)variantPick.Object).name.StartsWith("GameObject", StringComparison.Ordinal))
			{
				Transform transform = variantPick.Object.transform;
				List<string> list = new List<string>();
				for (int j = 0; j < transform.childCount; j++)
				{
					list.Add(TrapLabel(((Object)transform.GetChild(j)).name));
				}
				if (list.Count > 0)
				{
					text = text + "   ·   " + string.Join(T(", ", "、"), list.ToArray());
				}
			}
			section.Lines.Add(text);
		}
	}

	private RoomSection InspectSpools()
	{
		Breakable[] array = liveSpools.Where((Breakable s) => Object.op_Implicit((Object)(object)s) && ((Component)s).gameObject.activeInHierarchy && !s.IsBroken).ToArray();
		RoomSection roomSection = new RoomSection(T("Intact silk spools", "当前完好线轴") + " (" + array.Length + ")");
		Breakable[] array2 = array;
		foreach (Breakable val in array2)
		{
			int num2 = SilkSpoolControl.RemainingSilk(val);
			roomSection.Lines.Add(TrapLabel(((Object)val).name) + "  " + WorldPosition(((Component)val).transform) + "  ·  " + ((num2 < 0) ? T("Silk amount unavailable", "读不到丝量") : (T("Silk left ", "剩余灵丝 ") + num2)));
		}
		return roomSection;
	}

	private static string SceneLabel(string name)
	{
		int num = Array.FindIndex(Catalog.Rooms, (Room r) => r.Name == name);
		if (num >= 0)
		{
			return RoomNames[num];
		}
		return name switch
		{
			"Dust_Maze_09_entrance" => T("Mist Entrance", "入口长廊"), 
			"Dust_Maze_crossing" => T("Crossing", "中途长廊"), 
			"Dust_Maze_Last_Hall" => T("Last Hall", "出口长廊"), 
			"Dust_Maze_08_completed" => T("Cleared Mist", "迷瘴消散后的房间"), 
			"Dust_09" => T("Exhaust Organ", "废鸣管风琴"), 
			_ => name, 
		};
	}

	private static string ActiveLabel(GameObject obj)
	{
		if (!Object.op_Implicit((Object)(object)obj) || !obj.activeInHierarchy)
		{
			return T("Inactive now", "当前不活动");
		}
		return T("Active", "已激活");
	}

	private static string YesNo(bool yes)
	{
		if (!yes)
		{
			return T("No", "否");
		}
		return T("Yes", "是");
	}

	private static string ShortName(string path)
	{
		return path.Substring(path.LastIndexOf('/') + 1);
	}

	private static string WorldPosition(Transform t)
	{
		//IL_0001: Unknown result type (might be due to invalid IL or missing references)
		//IL_0006: Unknown result type (might be due to invalid IL or missing references)
		Vector3 position = t.position;
		return Coordinates(position.x, position.y);
	}

	private static string Coordinates(float x, float y)
	{
		return "(" + DecimalValue(x) + ", " + DecimalValue(y) + ")";
	}

	private static string DecimalValue(float value)
	{
		return value.ToString("0.##", CultureInfo.InvariantCulture);
	}

	private void LateUpdate()
	{
		//IL_0019: Unknown result type (might be due to invalid IL or missing references)
		//IL_001e: Unknown result type (might be due to invalid IL or missing references)
		if (open && ready)
		{
			if (!cursorOwned)
			{
				previousLock = Cursor.lockState;
				previousCursor = Cursor.visible;
				cursorOwned = true;
			}
			Cursor.lockState = (CursorLockMode)0;
			Cursor.visible = true;
		}
		else
		{
			ReleaseCursor();
		}
	}

	private void ReleaseCursor()
	{
		//IL_000a: Unknown result type (might be due to invalid IL or missing references)
		if (cursorOwned)
		{
			Cursor.lockState = previousLock;
			Cursor.visible = previousCursor;
			cursorOwned = false;
		}
	}

	private void WithInterfaceFont(Action draw)
	{
		Font val = GUI.skin.font;
		try
		{
			if (!triedFont)
			{
				triedFont = true;
				font = Font.CreateDynamicFontFromOSFont(new string[3] { "Microsoft YaHei", "SimHei", "Arial" }, 15);
			}
			if (Object.op_Implicit((Object)(object)font))
			{
				GUI.skin.font = font;
			}
			draw();
		}
		finally
		{
			GUI.skin.font = val;
		}
	}

	private void OnGUI()
	{
		//IL_00f9: 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_0018: Unknown result type (might be due to invalid IL or missing references)
		//IL_0055: Unknown result type (might be due to invalid IL or missing references)
		//IL_005a: Unknown result type (might be due to invalid IL or missing references)
		if (!ready || !open)
		{
			return;
		}
		Matrix4x4 matrix = GUI.matrix;
		try
		{
			float num = Mathf.Min(1.35f, Mathf.Min((float)Screen.width / 800f, (float)Screen.height / 650f));
			if (!(num <= 0f))
			{
				GUI.matrix = Matrix4x4.Scale(new Vector3(num, num, 1f));
				((Rect)(ref window)).x = Mathf.Clamp(((Rect)(ref window)).x, 0f, Mathf.Max(0f, (float)Screen.width / num - ((Rect)(ref window)).width));
				((Rect)(ref window)).y = Mathf.Clamp(((Rect)(ref window)).y, 0f, Mathf.Max(0f, (float)Screen.height / num - ((Rect)(ref window)).height));
				WithInterfaceFont(delegate
				{
					//IL_0007: 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_004e: Expected O, but got Unknown
					//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)
					window = GUILayout.Window(1296651092, window, new WindowFunction(Draw), T("Mist Practice", "迷瘴练习"), (GUILayoutOption[])(object)new GUILayoutOption[2]
					{
						GUILayout.Width(750f),
						GUILayout.Height(586f)
					});
				});
			}
		}
		finally
		{
			GUI.matrix = matrix;
		}
	}

	private void Draw(int id)
	{
		//IL_012e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0160: Unknown result type (might be due to invalid IL or missing references)
		//IL_0165: Unknown result type (might be due to invalid IL or missing references)
		//IL_02a1: Unknown result type (might be due to invalid IL or missing references)
		//IL_02a6: Unknown result type (might be due to invalid IL or missing references)
		//IL_0368: Unknown result type (might be due to invalid IL or missing references)
		//IL_0385: Unknown result type (might be due to invalid IL or missing references)
		//IL_038a: Unknown result type (might be due to invalid IL or missing references)
		//IL_035c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0361: Unknown result type (might be due to invalid IL or missing references)
		//IL_0531: Unknown result type (might be due to invalid IL or missing references)
		GUILayout.BeginHorizontal((GUILayoutOption[])(object)new GUILayoutOption[0]);
		SetTraining(GUILayout.Toggle(enabledPractice.Value, T("Enable practice", "启用练习"), (GUILayoutOption[])(object)new GUILayoutOption[0]));
		restoreSave.Value = GUILayout.Toggle(restoreSave.Value, T("Restore saved layout", "读档时恢复房间布局"), (GUILayoutOption[])(object)new GUILayoutOption[0]);
		GUILayout.FlexibleSpace();
		GUILayout.Label(GameVersion + " · " + ModeLabel, (GUILayoutOption[])(object)new GUILayoutOption[0]);
		if (GUILayout.Button(T("Close", "关闭"), (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(80f) }))
		{
			open = false;
		}
		GUILayout.EndHorizontal();
		page = GUILayout.Toolbar(page, new string[2]
		{
			T("Room presets", "房间方案"),
			T("Current room", "当前房间")
		}, (GUILayoutOption[])(object)new GUILayoutOption[0]);
		if (page == 1)
		{
			DrawCurrentRoom();
			GUI.DragWindow(new Rect(0f, 0f, 650f, 22f));
			return;
		}
		MazeController newestInstance = MazeController.NewestInstance;
		string text = T("Outside the editable maze rooms", "当前未进入可编辑的迷瘴房间");
		object obj;
		if (!Object.op_Implicit((Object)(object)newestInstance))
		{
			obj = null;
		}
		else
		{
			Scene scene = ((Component)newestInstance).gameObject.scene;
			obj = Catalog.Find(((Scene)(ref scene)).name);
		}
		Room room = (Room)obj;
		if (room != null && newestInstance.IsDoorLinkComplete)
		{
			PlayerData instance = PlayerData.instance;
			text = RoomNames[Array.IndexOf(Catalog.Rooms, room)] + T("   Entry ", "   入口 ") + instance.PreviousMazeTargetDoor + T("   Score ", "   当前分数 ") + instance.CorrectMazeDoorsEntered + T("   Left ", "   剩余分数 ") + newestInstance.CorrectDoorsLeft + T("   Correct exits ", "   正确出口 ") + string.Join(T(", ", "、"), (from g in newestInstance.EnumerateCorrectDoors()
				select ((Object)g).name).ToArray());
		}
		GUILayout.Label(text, (GUILayoutOption[])(object)new GUILayoutOption[0]);
		int num = GUILayout.Toolbar(editRoom, RoomNames, (GUILayoutOption[])(object)new GUILayoutOption[0]);
		if (num != editRoom)
		{
			editRoom = num;
			scroll = Vector2.zero;
		}
		Room room2 = Catalog.Rooms[editRoom];
		Plan plan = Plans[room2.Name];
		int num2 = GUILayout.Toolbar(tab, new string[5]
		{
			T("Progress & Exits", "进度与出口"),
			T("Lightmoths", "丝蝇"),
			T("Wraiths", "丝魂"),
			T("Traps", "陷阱"),
			T("Silk spools", "线轴")
		}, (GUILayoutOption[])(object)new GUILayoutOption[0]);
		if (num2 != tab)
		{
			tab = num2;
			scroll = Vector2.zero;
		}
		scroll = GUILayout.BeginScrollView(scroll, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Height(345f) });
		if (tab == 0)
		{
			DoorPanel(room2, plan);
		}
		else if (tab == 4)
		{
			SpoolPanel(room2, plan);
		}
		else
		{
			SpawnPanel(room2, plan, tab - 1);
		}
		GUILayout.EndScrollView();
		GUILayout.FlexibleSpace();
		GUILayout.Label(string.IsNullOrEmpty(Message) ? T("Presets apply on room entry. Warp below to start a new attempt.", "再次进入房间时应用方案。可选下方入口开始练习。") : Message, (GUILayoutOption[])(object)new GUILayoutOption[0]);
		GUILayout.BeginHorizontal((GUILayoutOption[])(object)new GUILayoutOption[0]);
		GUILayout.Label(T("Warp entrance", "传送入口"), (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(115f) });
		plan.WarpGate = GateSelect(plan.WarpGate, room2.Gates);
		GUILayout.EndHorizontal();
		GUILayout.BeginHorizontal((GUILayoutOption[])(object)new GUILayoutOption[0]);
		if (GUILayout.Button(T("Save presets", "保存全部方案"), (GUILayoutOption[])(object)new GUILayoutOption[0]))
		{
			Persist();
			Note("Presets saved. They apply on room entry.", "方案已保存,再次进入对应房间时生效。");
		}
		if (GUILayout.Button(T("Enable & warp to ", "启用并传送到 ") + RoomNames[editRoom], (GUILayoutOption[])(object)new GUILayoutOption[0]))
		{
			WarpSelectedRoom();
		}
		if (GUILayout.Button(string.Format(T("Reset {0} preset", "重置 {0} 方案"), RoomNames[editRoom]), (GUILayoutOption[])(object)new GUILayoutOption[0]))
		{
			Plans[room2.Name] = new Plan();
			Note("Reset the room preset.", "本房方案已重置。");
		}
		GUILayout.EndHorizontal();
		GUI.DragWindow(new Rect(0f, 0f, 650f, 22f));
	}

	private static string GateSelect(string current, string[] gates)
	{
		int val = Array.IndexOf(gates, current);
		return gates[GUILayout.Toolbar(Math.Max(0, val), gates, (GUILayoutOption[])(object)new GUILayoutOption[0])];
	}

	private static int Step(string label, int val, int min, int max, string defaultLabel = null, float labelWidth = 146f)
	{
		defaultLabel = defaultLabel ?? T("Vanilla", "沿用");
		GUILayout.BeginHorizontal((GUILayoutOption[])(object)new GUILayoutOption[0]);
		GUILayout.Label(label, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(labelWidth) });
		if (GUILayout.Button("−", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(35f) }))
		{
			val = Math.Max(min, val - 1);
		}
		GUILayout.Label((val < 0) ? defaultLabel : val.ToString(), (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(112f) });
		if (GUILayout.Button("+", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(35f) }))
		{
			val = Math.Min(max, val + 1);
		}
		if (min < 0 && GUILayout.Button(defaultLabel, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(112f) }))
		{
			val = -1;
		}
		GUILayout.EndHorizontal();
		return val;
	}

	private void DoorPanel(Room r, Plan p)
	{
		p.Score = Step(T("Entry score", "进房分数"), p.Score, -1, 8);
		p.Wrong = Step(T("Wrong exits", "连续走错次数"), p.Wrong, -1, 9);
		GUILayout.BeginHorizontal((GUILayoutOption[])(object)new GUILayoutOption[0]);
		GUILayout.Label(T("Crossing entered", "已进中途长廊"), (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(146f) });
		p.Rest = GUILayout.Toolbar(p.Rest + 1, new string[3]
		{
			T("Vanilla", "沿用"),
			T("No", "否"),
			T("Yes", "是")
		}, (GUILayoutOption[])(object)new GUILayoutOption[0]) - 1;
		GUILayout.EndHorizontal();
		p.ApplyProgressOnTraversal = GUILayout.Toggle(p.ApplyProgressOnTraversal, T("Also reset progress when entering through a gate", "从游戏内走门进入时也重设进度"), (GUILayoutOption[])(object)new GUILayoutOption[0]);
		if (p.ApplyProgressOnTraversal && (p.Score >= 0 || p.Wrong >= 0 || p.Rest >= 0))
		{
			GUILayout.Label(T("The values above can replace progress gained on the previous transition.", "上方指定的值会覆盖刚才过门产生的进度。"), (GUILayoutOption[])(object)new GUILayoutOption[0]);
		}
		p.FixedDoors = GUILayout.Toggle(p.FixedDoors, AllowsJuggling ? T("Set correct exits (lightmoths follow the first valid choice)", "指定正确出口(可多选,丝蝇指向首个有效出口)") : T("Set the correct exit (one choice)", "指定正确出口(单选,丝蝇指向该出口)"), (GUILayoutOption[])(object)new GUILayoutOption[0]);
		if (p.FixedDoors)
		{
			GUILayout.BeginHorizontal((GUILayoutOption[])(object)new GUILayoutOption[0]);
			string text = p.Correct.FirstOrDefault((string g) => r.Gates.Contains(g) && g != p.WarpGate) ?? p.Correct.FirstOrDefault(((IEnumerable<string>)r.Gates).Contains<string>);
			string[] gates = r.Gates;
			foreach (string text2 in gates)
			{
				bool flag = (AllowsJuggling ? p.Correct.Contains(text2) : (text2 == text));
				bool flag2 = GUILayout.Toggle(flag, ((AllowsJuggling && flag) ? (p.Correct.IndexOf(text2) + 1 + ". ") : "") + text2, GUIStyle.op_Implicit("button"), (GUILayoutOption[])(object)new GUILayoutOption[0]);
				if (flag2 != flag)
				{
					if (!AllowsJuggling)
					{
						p.Correct.Clear();
					}
					if (flag2)
					{
						p.Correct.Add(text2);
					}
					else
					{
						p.Correct.Remove(text2);
					}
				}
			}
			GUILayout.EndHorizontal();
			GUILayout.Label(T("Correct exit destination (must have a matching entrance)", "正确出口通往(目标房间须有方向相接的入口)"), (GUILayoutOption[])(object)new GUILayoutOption[0]);
			string[] array = new string[3] { "", "Dust_Maze_crossing", "Dust_Maze_Last_Hall" }.Concat(Catalog.Rooms.Select((Room x) => x.Name)).ToArray();
			string[] array2 = new string[3]
			{
				T("By progress", "按进度"),
				T("Crossing", "中途长廊"),
				T("Last Hall", "出口长廊")
			}.Concat(RoomNames).ToArray();
			int num2 = GUILayout.SelectionGrid(Math.Max(0, Array.IndexOf(array, p.Destination)), array2, 6, (GUILayoutOption[])(object)new GUILayoutOption[0]);
			p.Destination = array[num2];
		}
		if (!AllowsJuggling)
		{
			GUILayout.Label(T("Backtracking uses the game's penalty. Each normal room has one correct exit.", "折返按游戏规则扣分。普通进房时只有一个正确出口。"), (GUILayoutOption[])(object)new GUILayoutOption[0]);
			return;
		}
		GUILayout.Label(T("Room to return to after a direct warp", "直接传送后可折返到的房间"), (GUILayoutOption[])(object)new GUILayoutOption[0]);
		string[] array3 = new string[1] { "" }.Concat(from x in Catalog.Rooms
			where x != r
			select x.Name).ToArray();
		string[] array4 = array3.Select((string s) => (!(s == "")) ? ("M" + int.Parse(s.Substring(s.Length - 2))) : T("Auto", "自动")).ToArray();
		p.BackRoom = array3[GUILayout.Toolbar(Math.Max(0, Array.IndexOf(array3, p.BackRoom)), array4, (GUILayoutOption[])(object)new GUILayoutOption[0])];
		Room room = Catalog.Find(p.BackRoom);
		if (room != null)
		{
			string side = Catalog.Opposite(r.Gates.Contains(p.WarpGate) ? p.WarpGate : r.Gates[0]);
			string[] array5 = room.Gates.Where((string g) => g.StartsWith(side, StringComparison.Ordinal)).ToArray();
			if (array5.Length > 0)
			{
				p.BackGate = GateSelect(p.BackGate, array5);
			}
			else
			{
				GUILayout.Label(T("No matching gate. A compatible return room will be picked on warp.", "所选房间没有相接的门。传送时将自动选择可折返的房间。"), (GUILayoutOption[])(object)new GUILayoutOption[0]);
			}
		}
	}

	private void SpawnPanel(Room room, Plan p, int cat)
	{
		Choice choice = p.Spawn[cat];
		Spot[] array = room.Nodes[cat];
		PickControls(choice, array.Length, cat == 2);
		if (choice.Mode == PickMode.Fixed)
		{
			if (cat < 2)
			{
				PointMap(room, choice, array);
			}
			for (int i = 0; i < array.Length; i++)
			{
				bool flag = choice.Points.Contains(i);
				string text = i + 1 + ". " + ((cat == 2) ? TrapLabel(array[i].Name) : Position(array[i]));
				bool flag2 = GUILayout.Toggle(flag, text, (GUILayoutOption[])(object)new GUILayoutOption[0]);
				if (flag2 != flag)
				{
					Toggle(choice, i);
				}
			}
		}
		if (cat != 2)
		{
			return;
		}
		if (GUILayout.Button(T("Disable regular trap selection", "关闭普通陷阱抽选"), (GUILayoutOption[])(object)new GUILayoutOption[0]))
		{
			choice.Mode = PickMode.Fixed;
			choice.Points.Clear();
		}
		GUILayout.Label(T("Variants  ·  Extra groups are independent of trap count", "各组变体(额外组独立于抽选组数)"), (GUILayoutOption[])(object)new GUILayoutOption[0]);
		Group[] groups = room.Groups;
		foreach (Group obj in groups)
		{
			if (!p.Variants.TryGetValue(obj.Path, out var value))
			{
				value = -1;
			}
			GUILayout.Label((obj.Extra ? T("Extra group  ", "额外组  ") : T("Trap set  ", "抽选组  ")) + obj.Path.Split('/').Last(), (GUILayoutOption[])(object)new GUILayoutOption[0]);
			bool flag3 = Generation.CanDisableGroup(room, obj);
			int num = ((!flag3) ? 1 : 2);
			string[] first = (flag3 ? new string[2]
			{
				T("Off", "关闭"),
				T("Vanilla", "原版随机")
			} : new string[1] { T("Vanilla (keeps room geometry)", "原版随机(保留场景结构)") });
			string[] array2 = first.Concat(obj.Children.Select((Spot x) => TrapLabel(x.Name) + "  " + Position(x))).ToArray();
			int num2 = ((value >= -num && value < obj.Children.Length) ? (value + num) : (num - 1));
			int num3 = GUILayout.SelectionGrid(num2, array2, 2, (GUILayoutOption[])(object)new GUILayoutOption[0]) - num;
			if (num3 == -1)
			{
				p.Variants.Remove(obj.Path);
			}
			else
			{
				p.Variants[obj.Path] = num3;
			}
			if (num3 == -2 && !obj.Extra && obj.Children.Any((Spot x) => x.Name.StartsWith("greymoor_flip_bridge", StringComparison.Ordinal)))
			{
				GUILayout.Label(T("Off also removes this group's flip bridges.", "关闭后,这个组的翻转桥板也不会出现。"), (GUILayoutOption[])(object)new GUILayoutOption[0]);
			}
		}
	}

	private static void PickControls(Choice choice, int count, bool traps)
	{
		choice.Mode = (PickMode)GUILayout.Toolbar((int)choice.Mode, new string[3]
		{
			T("Vanilla", "原版生成"),
			traps ? T("Choose trap sets", "指定陷阱组") : T("Choose positions", "指定点位"),
			T("Random by count", "按数量随机")
		}, (GUILayoutOption[])(object)new GUILayoutOption[0]);
		if (choice.Mode == PickMode.Count)
		{
			choice.Count = Step(traps ? T("Trap set count", "抽选组数") : T("Spawn count", "生成数量"), choice.Count, 0, count);
		}
		if (choice.Mode == PickMode.Fixed)
		{
			GUILayout.BeginHorizontal((GUILayoutOption[])(object)new GUILayoutOption[0]);
			GUILayout.Label(T("Selected ", "已选 ") + choice.Points.Count + " / " + count, (GUILayoutOption[])(object)new GUILayoutOption[0]);
			if (GUILayout.Button(T("Select all", "全选"), (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(85f) }))
			{
				choice.Points = Enumerable.Range(0, count).ToList();
			}
			if (GUILayout.Button(T("Clear", "清空"), (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(70f) }))
			{
				choice.Points.Clear();
			}
			GUILayout.EndHorizontal();
		}
	}

	private static void SpoolPanel(Room room, Plan plan)
	{
		Spot[] silkSpools = room.SilkSpools;
		if (!SilkSpoolControl.Supported)
		{
			GUILayout.Label(T("Silk spool controls are unavailable in this game build.", "当前游戏版本无法控制线轴。"), (GUILayoutOption[])(object)new GUILayoutOption[0]);
			return;
		}
		if (silkSpools.Length == 0)
		{
			GUILayout.Label(T("This room has no silk spool positions.", "本房间没有线轴点位。"), (GUILayoutOption[])(object)new GUILayoutOption[0]);
			return;
		}
		PickControls(plan.SilkSpools, silkSpools.Length, traps: false);
		if (plan.SilkSpools.Mode == PickMode.Fixed)
		{
			PointMap(room, plan.SilkSpools, silkSpools);
		}
		plan.SpoolSilk = Step(T("Silk per spool", "每根线轴丝量"), plan.SpoolSilk, -1, 2);
		GUILayout.Label(T("Each valid needle hit grants one Silk. A spool set to 0 is empty.", "每次有效的织针命中补一格灵丝。丝量为 0 时是空线轴。"), (GUILayoutOption[])(object)new GUILayoutOption[0]);
		for (int i = 0; i < silkSpools.Length; i++)
		{
			string name = silkSpools[i].Name.Split('/').Last();
			string text = i + 1 + ". " + TrapLabel(name) + " " + Position(silkSpools[i]);
			if (plan.SilkSpools.Mode == PickMode.Fixed)
			{
				bool flag = plan.SilkSpools.Points.Contains(i);
				if (GUILayout.Toggle(flag, text, (GUILayoutOption[])(object)new GUILayoutOption[0]) != flag)
				{
					Toggle(plan.SilkSpools, i);
				}
			}
			else
			{
				GUILayout.Label(text, (GUILayoutOption[])(object)new GUILayoutOption[0]);
			}
			if (!plan.SpoolSilkByPoint.TryGetValue(i, out var value))
			{
				value = -1;
			}
			value = Step(T("Silk at point ", "点位丝量 ") + (i + 1), value, -1, 2, T("Use room value", "随房间设置"));
			if (value < 0)
			{
				plan.SpoolSilkByPoint.Remove(i);
			}
			else
			{
				plan.SpoolSilkByPoint[i] = value;
			}
		}
	}

	private static string TrapLabel(string name)
	{
		if (!UseChinese)
		{
			if (name.StartsWith("break_spool_side", StringComparison.Ordinal))
			{
				return "Sideways silk spool" + name.Substring("break_spool_side".Length);
			}
			if (name.StartsWith("break_spool_upright", StringComparison.Ordinal))
			{
				return "Upright silk spool" + name.Substring("break_spool_upright".Length);
			}
			return name;
		}
		if (TrapNames.TryGetValue(name, out var value))
		{
			return value;
		}
		int num = name.LastIndexOf(" (", StringComparison.Ordinal);
		if (num < 0 || !name.EndsWith(")", StringComparison.Ordinal) || !TrapNames.TryGetValue(name.Substring(0, num), out value))
		{
			return name;
		}
		return value + name.Substring(num);
	}

	private static string Position(Spot spot)
	{
		return "(" + spot.X.ToString("0.#") + ", " + spot.Y.ToString("0.#") + ")";
	}

	private static void Toggle(Choice c, int i)
	{
		if (!c.Points.Remove(i))
		{
			c.Points.Add(i);
		}
	}

	private static void PointMap(Room room, Choice c, Spot[] nodes)
	{
		//IL_001e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0023: Unknown result type (might be due to invalid IL or missing references)
		//IL_0024: Unknown result type (might be due to invalid IL or missing references)
		//IL_015b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0160: Unknown result type (might be due to invalid IL or missing references)
		//IL_0198: Unknown result type (might be due to invalid IL or missing references)
		//IL_0180: Unknown result type (might be due to invalid IL or missing references)
		//IL_01b9: Unknown result type (might be due to invalid IL or missing references)
		Rect rect = GUILayoutUtility.GetRect(400f, 142f, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.ExpandWidth(true) });
		GUI.Box(rect, "");
		Spot[] source = room.Nodes[0].Concat(room.Nodes[1]).Concat(nodes).ToArray();
		float num = source.Min((Spot p) => p.X);
		float num2 = source.Max((Spot p) => p.X);
		float num3 = source.Min((Spot p) => p.Y);
		float num4 = source.Max((Spot p) => p.Y);
		for (int num5 = 0; num5 < nodes.Length; num5++)
		{
			float num6 = ((Rect)(ref rect)).x + 5f + (((Rect)(ref rect)).width - 43f) * (nodes[num5].X - num) / Mathf.Max(1f, num2 - num);
			float num7 = ((Rect)(ref rect)).y + 4f + (((Rect)(ref rect)).height - 32f) * (num4 - nodes[num5].Y) / Mathf.Max(1f, num4 - num3);
			Color backgroundColor = GUI.backgroundColor;
			if (c.Points.Contains(num5))
			{
				GUI.backgroundColor = new Color(0.35f, 0.9f, 0.65f);
			}
			if (GUI.Button(new Rect(num6, num7, 34f, 24f), (num5 + 1).ToString()))
			{
				Toggle(c, num5);
			}
			GUI.backgroundColor = backgroundColor;
		}
	}

	internal static void Note(string en, string zh)
	{
		messageEnglish = en;
		messageChinese = zh;
		if (Object.op_Implicit((Object)(object)Instance))
		{
			((BaseUnityPlugin)Instance).Logger.LogInfo((object)Message);
		}
	}

	private static MethodInfo Require(Type t, string method)
	{
		MethodInfo methodInfo = AccessTools.DeclaredMethod(t, method, (Type[])null, (Type[])null);
		if (methodInfo == null)
		{
			throw new MissingMethodException(t.FullName, method);
		}
		return methodInfo;
	}

	private void Hook(Type t, string m, Type target, string pre, string post)
	{
		//IL_0019: Unknown result type (might be due to invalid IL or missing references)
		//IL_002d: Unknown result type (might be due to invalid IL or missing references)
		harmony.Patch((MethodBase)Require(t, m), (pre == null) ? ((HarmonyMethod)null) : new HarmonyMethod(Require(target, pre)), (post == null) ? ((HarmonyMethod)null) : new HarmonyMethod(Require(target, post)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
	}

	private void Awake()
	{
		//IL_02b7: Expected O, but got Unknown
		//IL_0188: Unknown result type (might be due to invalid IL or missing references)
		//IL_01cc: Unknown result type (might be due to invalid IL or missing references)
		//IL_0277: Unknown result type (might be due to invalid IL or missing references)
		//IL_0281: Expected O, but got Unknown
		//IL_0333: Unknown result type (might be due to invalid IL or missing references)
		//IL_033d: Expected O, but got Unknown
		//IL_05e4: Unknown result type (might be due to invalid IL or missing references)
		Instance = this;
		try
		{
			language = ((BaseUnityPlugin)this).Config.Bind<InterfaceLanguage>("Interface", "Language", InterfaceLanguage.Auto, Setting("Language", "界面语言", "Auto follows the system language.", "自动模式跟随系统语言。", 60, DrawLanguageSetting));
			LocalizeSettings();
			FieldInfo field = typeof(MazeController).Assembly.GetType("Constants").GetField("GAME_VERSION", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
			GameVersion = (string)field.GetRawConstantValue();
			AllowsJuggling = SelectJugglingMode(GameVersion);
			if (!AllowsJuggling && !Doors.HasReturnFlag)
			{
				throw new NotSupportedException(T("The Mist return state is unavailable in game version " + GameVersion + ".", "无法读取游戏版本 " + GameVersion + " 的迷瘴折返状态。"));
			}
			enabledPractice = ((BaseUnityPlugin)this).Config.Bind<bool>("Practice", "Enabled", false, Setting("Enable Mist practice", "启用迷瘴练习", "Apply presets on entry to M1 through M8.", "再次进入 M1 至 M8 时应用设置。", 40));
			enabledPractice.SettingChanged += TrainingChanged;
			restoreSave = ((BaseUnityPlugin)this).Config.Bind<bool>("Practice", "RestoreDebugLayout", true, Setting("Restore saved layout", "读档时恢复房间布局", "Restore the layout from a DebugMod savestate made on this game version. Turn off to use the current preset.", "读取同版本的 DebugMod 存档时恢复保存的布局。关闭后使用当前房间方案。", 30));
			menuKey = ((BaseUnityPlugin)this).Config.Bind<KeyboardShortcut>("Practice", "Menu", new KeyboardShortcut((KeyCode)288, (KeyCode[])(object)new KeyCode[1] { (KeyCode)306 }), Setting("Editor shortcut", "编辑器快捷键", "Open or close the Mist Practice editor.", "打开或收起迷瘴编辑器。", 20));
			warpKey = ((BaseUnityPlugin)this).Config.Bind<KeyboardShortcut>("Practice", "WarpShortcut", new KeyboardShortcut((KeyCode)0, (KeyCode[])(object)new KeyCode[0]), Setting("Enable & warp shortcut", "启用并传送快捷键", "Enable practice and warp to the selected room preset and entrance, even with the editor closed.", "启用练习并传送到编辑器所选房间的指定入口,收起编辑器后也可使用。", 19));
			((BaseUnityPlugin)this).Config.Bind<bool>("Practice", "Editor", false, Setting("Room editor", "房间编辑器", "Inspect the current room, edit presets, or warp to an entrance.", "查看当前房间、编辑方案或传送。", 50, DrawEditorButton));
			savedPlans = ((BaseUnityPlugin)this).Config.Bind<string>("Practice", "RoomPlans", "{}", new ConfigDescription("Presets saved in the room editor.", (AcceptableValueBase)null, new object[1]
			{
				new ConfigurationManagerAttributes
				{
					Browsable = false
				}
			}));
			LocalizeSettings();
			language.SettingChanged += LanguageChanged;
			Dictionary<string, Plan> dictionary;
			try
			{
				dictionary = JsonConvert.DeserializeObject<Dictionary<string, Plan>>(savedPlans.Value);
			}
			catch (JsonException ex)
			{
				JsonException ex2 = ex;
				((BaseUnityPlugin)this).Logger.LogWarning((object)ex2);
				Note("Room presets could not be read. Using defaults until you save again.", "无法读取房间方案。重新保存方案前使用默认设置。");
				dictionary = null;
			}
			Room[] rooms = Catalog.Rooms;
			foreach (Room room in rooms)
			{
				if (dictionary == null || !dictionary.TryGetValue(room.Name, out var value) || !ValidPlan(value, room))
				{
					value = new Plan();
				}
				Plans[room.Name] = value;
			}
			harmony = new Harmony("local.silksong.mistpractice");
			Hook(typeof(MazeController), "Activate", typeof(Doors), "BeforeActivate", null);
			Hook(typeof(GameManager), "BeginSceneTransition", typeof(Plugin), null, "TransitionStarted");
			Hook(typeof(MazeController), "LinkDoors", typeof(Doors), null, "AfterLink");
			Hook(typeof(GameObjectIsNull), "DoIsGameObjectNull", typeof(Generation), "BeforeNull", null);
			Hook(typeof(MultiplyIntByFloat), "DoMultiply", typeof(Generation), null, "AfterCount");
			Hook(typeof(GetRandomChildSceneSeed), "DoGetRandomChild", typeof(Generation), null, "AfterPick");
			Hook(typeof(ActivateAllChildren), "OnEnter", typeof(Generation), "AtMusic", null);
			Hook(typeof(ActivateRandomChildren), "OnEnable", typeof(Generation), "BeforeVariant", "AfterVariant");
			if (SilkSpoolControl.Supported)
			{
				Hook(typeof(PersistentBoolItem), "TryGetValue", typeof(SilkSpoolControl), "BeforeLoadSilk", null);
				Hook(typeof(PersistentBoolItem), "SaveValue", typeof(SilkSpoolControl), "BeforeSaveSilk", null);
			}
			if (Chainloader.PluginInfos.ContainsKey("io.github.hk-speedrunning.quickwarp"))
			{
				Type type = ((object)Chainloader.PluginInfos["io.github.hk-speedrunning.quickwarp"].Instance).GetType().Assembly.GetType("QuickWarp.Warp", throwOnError: true);
				warpMethod = Require(type, "TryWarp");
				if (!Doors.PatchQuickWarp(harmony, AccessTools.DeclaredMethod(type, "TryWarpCoroutine", (Type[])null, (Type[])null)))
				{
					((BaseUnityPlugin)this).Logger.LogWarning((object)"QuickWarp arrival detection is unavailable. Normal room transitions still use the game’s progress.");
				}
			}
			if (Chainloader.PluginInfos.ContainsKey("io.github.hk-speedrunning.debugmod"))
			{
				DebugBridge.Attach();
				debugAttached = true;
			}
			SceneManager.sceneUnloaded += Unload;
			ready = true;
			((BaseUnityPlugin)this).Logger.LogInfo((object)("Mist Practice ready | game " + GameVersion + " | " + ModeLabel + " | QuickWarp=" + (warpMethod != null) + " | DebugMod=" + debugAttached + " | " + menuKey.Value));
		}
		catch (Exception ex3)
		{
			if (harmony != null)
			{
				harmony.UnpatchSelf();
			}
			((BaseUnityPlugin)this).Logger.LogError((object)ex3);
		}
	}

	internal static bool SelectJugglingMode(string gameVersion)
	{
		if (!Version.TryParse(gameVersion, out Version result) || result < new Version(1, 0, 28324))
		{
			throw new NotSupportedException(T("Could not determine the Mist rules for game version " + gameVersion + ".", "无法识别游戏版本 " + gameVersion + " 的迷瘴规则。"));
		}
		return result < new Version(1, 0, 29139);
	}

	private static bool ValidPlan(Plan p, Room room)
	{
		if (p != null && p.Spawn != null && p.Spawn.Length == 3 && p.Spawn.All((Choice s) => s != null && s.Points != null && Enum.IsDefined(typeof(PickMode), s.Mode)) && p.Variants != null && p.Correct != null && p.Score >= -1 && p.Score <= 8 && p.Wrong >= -1 && p.Rest >= -1 && p.Rest <= 1 && p.SilkSpools != null && p.SilkSpools.Points != null && Enum.IsDefined(typeof(PickMode), p.SilkSpools.Mode) && p.SpoolSilk >= -1 && p.SpoolSilk <= 2 && p.SpoolSilkByPoint != null)
		{
			return p.SpoolSilkByPoint.All((KeyValuePair<int, int> v) => v.Key >= 0 && v.Key < room.SilkSpools.Length && v.Value >= 0 && v.Value <= 2);
		}
		return false;
	}

	private void OnDestroy()
	{
		ReleaseCursor();
		if (language != null)
		{
			language.SettingChanged -= LanguageChanged;
		}
		if (enabledPractice != null)
		{
			enabledPractice.SettingChanged -= TrainingChanged;
		}
		if (debugAttached)
		{
			DebugBridge.Detach();
		}
		SceneManager.sceneUnloaded -= Unload;
		if (harmony != null)
		{
			harmony.UnpatchSelf();
		}
		visits.Clear();
		passiveRooms.Clear();
		debugRooms.Clear();
		RoomObservation.Clear();
		debugArrival = null;
		Doors.ClearWarp();
		Instance = null;
	}

	private static void Unload(Scene scene)
	{
		//IL_0036: Unknown result type (might be due to invalid IL or missing references)
		visits.Remove(((Scene)(ref scene)).handle);
		passiveRooms.Remove(((Scene)(ref scene)).handle);
		debugRooms.Remove(((Scene)(ref scene)).handle);
		RoomObservation.Unload(scene);
	}

	private static void TransitionStarted(GameManager __instance, SceneLoadInfo __0)
	{
		//IL_0085: 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)
		Doors.OnTransition(__instance, __0);
		DebugArrival debugArrival = Plugin.debugArrival;
		SceneLoad lastSceneLoad = __instance.LastSceneLoad;
		if (debugArrival == null || lastSceneLoad == null || __0 == null || !object.ReferenceEquals(lastSceneLoad.SceneLoadInfo, __0))
		{
			return;
		}
		if (debugArrival.Finished || !DebugBridge.IsLoading(debugArrival.Load) || !DebugBridge.IsDebugTransition(__0))
		{
			Plugin.debugArrival = null;
			return;
		}
		debugArrival.TargetStarted = __0.SceneName == debugArrival.Room && __0.EntryGateName == "dreamGate";
		if (debugArrival.TargetStarted)
		{
			Scene activeScene = SceneManager.GetActiveScene();
			debugArrival.PreviousHandle = ((Scene)(ref activeScene)).handle;
		}
	}

	internal static bool IsDebugVisit(Scene scene)
	{
		return debugRooms.Contains(((Scene)(ref scene)).handle);
	}

	internal static void BeginDebugLoad(object load, string room, Layout replay)
	{
		Doors.ClearWarp();
		debugArrival = new DebugArrival(load, room, replay);
	}

	internal static void EndDebugLoad(object load)
	{
		DebugArrival debugArrival = Plugin.debugArrival;
		if (debugArrival != null && object.ReferenceEquals(debugArrival.Load, load))
		{
			debugArrival.Finished = true;
			if (!debugArrival.TargetStarted || debugArrival.Consumed)
			{
				Plugin.debugArrival = null;
			}
		}
	}

	private static void ClearFinishedDebugLoad()
	{
		//IL_002e: Unknown result type (might be due to invalid IL or missing references)
		DebugArrival debugArrival = Plugin.debugArrival;
		if (debugArrival != null && !DebugBridge.IsLoading(debugArrival.Load))
		{
			GameManager unsafeInstance = GameManager.UnsafeInstance;
			if (!debugArrival.Finished || debugArrival.Consumed || (!debugArrival.IsTarget(SceneManager.GetActiveScene()) && (!Object.op_Implicit((Object)(object)unsafeInstance) || !unsafeInstance.IsInSceneTransition)))
			{
				Plugin.debugArrival = null;
			}
		}
	}

	internal static Visit For(Scene scene)
	{
		//IL_0070: Unknown result type (might be due to invalid IL or missing references)
		if (!Object.op_Implicit((Object)(object)Instance) || !Instance.ready || !((Scene)(ref scene)).IsValid())
		{
			return null;
		}
		if (visits.TryGetValue(((Scene)(ref scene)).handle, out var value))
		{
			return value;
		}
		if (passiveRooms.Contains(((Scene)(ref scene)).handle))
		{
			return null;
		}
		Room room = Catalog.Find(((Scene)(ref scene)).name);
		if (room == null)
		{
			return null;
		}
		ClearFinishedDebugLoad();
		DebugArrival debugArrival = Plugin.debugArrival;
		bool flag = debugArrival?.IsTarget(scene) ?? false;
		if (!Training || (debugArrival != null && (!flag || !debugArrival.AllowOverrides)))
		{
			passiveRooms.Add(((Scene)(ref scene)).handle);
			return null;
		}
		Layout layout = ((flag && Instance.restoreSave.Value) ? debugArrival.Replay : null);
		value = new Visit(room, Instance.Plans[room.Name].Copy(), layout, random);
		visits[((Scene)(ref scene)).handle] = value;
		if (flag)
		{
			debugRooms.Add(((Scene)(ref scene)).handle);
			debugArrival.Consumed = true;
			if (layout != null)
			{
				Note("Restored the room layout from the DebugMod savestate.", "已恢复 DebugMod 存档中的房间布局。");
			}
		}
		return value;
	}

	internal static Visit Current()
	{
		//IL_0019: Unknown result type (might be due to invalid IL or missing references)
		//IL_001e: Unknown result type (might be due to invalid IL or missing references)
		MazeController newestInstance = MazeController.NewestInstance;
		if (Object.op_Implicit((Object)(object)newestInstance))
		{
			Dictionary<int, Visit> dictionary = visits;
			Scene scene = ((Component)newestInstance).gameObject.scene;
			if (dictionary.TryGetValue(((Scene)(ref scene)).handle, out var value))
			{
				return value;
			}
		}
		return null;
	}

	internal static bool IsProtectedSpool(Scene scene, int stateId)
	{
		if (visits.TryGetValue(((Scene)(ref scene)).handle, out var value))
		{
			return value.ProtectedSpools.Contains(stateId);
		}
		return false;
	}

	internal void Persist()
	{
		savedPlans.Value = JsonConvert.SerializeObject((object)Plans);
		((BaseUnityPlugin)this).Config.Save();
	}

	private void SetTraining(bool value)
	{
		if (value != enabledPractice.Value)
		{
			enabledPractice.Value = value;
		}
	}

	private void TrainingChanged(object sender, EventArgs args)
	{
		//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)
		bool value = enabledPractice.Value;
		if (value)
		{
			Scene activeScene = SceneManager.GetActiveScene();
			if (Catalog.Find(((Scene)(ref activeScene)).name) != null && !visits.ContainsKey(((Scene)(ref activeScene)).handle))
			{
				passiveRooms.Add(((Scene)(ref activeScene)).handle);
			}
		}
		else
		{
			if (debugArrival != null)
			{
				debugArrival.AllowOverrides = false;
			}
			Doors.ClearWarp();
		}
		if (value)
		{
			Note("Practice enabled. Presets apply on room entry.", "练习已开启。再次进入房间时应用方案。");
		}
		else
		{
			Note("Practice disabled. The next room uses the game's layout.", "练习已关闭。再次进入房间时恢复原版规则。");
		}
	}

	private void Update()
	{
		//IL_001a: Unknown result type (might be due to invalid IL or missing references)
		//IL_001f: Unknown result type (might be due to invalid IL or missing references)
		//IL_003f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0044: Unknown result type (might be due to invalid IL or missing references)
		//IL_0047: Unknown result type (might be due to invalid IL or missing references)
		//IL_0054: Unknown result type (might be due to invalid IL or missing references)
		//IL_0059: Unknown result type (might be due to invalid IL or missing references)
		ClearFinishedDebugLoad();
		UpdateManager();
		if (!ready)
		{
			return;
		}
		KeyboardShortcut value = menuKey.Value;
		if (((KeyboardShortcut)(ref value)).IsDown())
		{
			open = !open;
			return;
		}
		KeyboardShortcut value2 = warpKey.Value;
		if ((int)((KeyboardShortcut)(ref value2)).MainKey != 0)
		{
			KeyboardShortcut value3 = warpKey.Value;
			if (((KeyboardShortcut)(ref value3)).IsDown() && !ConfigurationManagerIsOpen())
			{
				WarpSelectedRoom();
			}
		}
	}

	private void WarpSelectedRoom()
	{
		Room room = Catalog.Rooms[editRoom];
		Warp(room, Plans[room.Name]);
	}

	private void Warp(Room room, Plan plan)
	{
		GameManager instance = GameManager.instance;
		if (!Object.op_Implicit((Object)(object)instance) || !Object.op_Implicit((Object)(object)HeroController.instance) || instance.IsInSceneTransition)
		{
			Note("Load a game save and wait for the room transition to finish.", "请载入游戏存档,等转场结束后再传送。");
			return;
		}
		if (warpMethod == null)
		{
			Note("QuickWarp is unavailable. Enable practice and enter through an in-game gate.", "QuickWarp 未加载。可开启练习,再从游戏内进入目标房间。");
			return;
		}
		if (!room.Gates.Contains(plan.WarpGate))
		{
			plan.WarpGate = room.Gates[0];
		}
		Persist();
		SetTraining(value: true);
		try
		{
			warpMethod.Invoke(null, new object[2] { room.Name, plan.WarpGate });
			open = false;
		}
		catch (Exception ex)
		{
			Note("Warp failed. " + ex.GetBaseException().Message, "传送失败。" + ex.GetBaseException().Message);
		}
	}
}
internal static class Doors
{
	internal const string Cross = "Dust_Maze_crossing";

	internal const string Hall = "Dust_Maze_Last_Hall";

	private const string Entrance = "Dust_Maze_09_entrance";

	private static readonly FieldInfo ReturnFlag = AccessTools.Field(typeof(PlayerData), "DidEnterPreviousMazeDoor");

	private static int quickWarpDepth;

	private static SceneLoadInfo warpLoad;

	private static readonly string[] CorridorGates = new string[2] { "left1", "right1" };

	internal static bool HasReturnFlag => ReturnFlag != null;

	internal static bool IsRecovering(PlayerData player)
	{
		if (!Plugin.AllowsJuggling && ReturnFlag != null)
		{
			return (bool)ReturnFlag.GetValue(player);
		}
		return false;
	}

	internal static bool PatchQuickWarp(Harmony harmony, MethodInfo coroutineFactory)
	{
		//IL_0061: 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_0089: Expected O, but got Unknown
		//IL_0089: Expected O, but got Unknown
		if (coroutineFactory == null)
		{
			return false;
		}
		MethodInfo methodInfo;
		try
		{
			methodInfo = AccessTools.EnumeratorMoveNext((MethodBase)coroutineFactory);
		}
		catch (Exception ex)
		{
			Plugin.Note("Could not track QuickWarp's scene transition. " + ex.Message, "无法跟踪 QuickWarp 的转场。" + ex.Message);
			return false;
		}
		if (methodInfo == null)
		{
			return false;
		}
		harmony.Patch((MethodBase)methodInfo, new HarmonyMethod(AccessTools.DeclaredMethod(typeof(Doors), "BeginWarpStep", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, new HarmonyMethod(AccessTools.DeclaredMethod(typeof(Doors), "EndWarpStep", (Type[])null, (Type[])null)), (HarmonyMethod)null);
		return true;
	}

	private static void BeginWarpStep()
	{
		quickWarpDepth++;
	}

	private static void EndWarpStep()
	{
		quickWarpDepth--;
	}

	internal static void ClearWarp()
	{
		warpLoad = null;
	}

	internal static void OnTransition(GameManager game, SceneLoadInfo info)
	{
		if (info == null || game.LastSceneLoad == null || !object.ReferenceEquals(game.LastSceneLoad.SceneLoadInfo, info))
		{
			return;
		}
		ClearWarp();
		if (quickWarpDepth != 0 && Plugin.Training)
		{
			Room room = Catalog.Find(info.SceneName);
			if (room != null && room.Gates.Contains(info.EntryGateName))
			{
				warpLoad = info;
			}
		}
	}

	private static bool ConsumeWarp(GameManager game, string room, string gate)
	{
		if (warpLoad == null || warpLoad.SceneName != room || warpLoad.EntryGateName != gate || game.LastSceneLoad == null || !object.ReferenceEquals(game.LastSceneLoad.SceneLoadInfo, warpLoad))
		{
			return false;
		}
		ClearWarp();
		return true;
	}

	internal static void BeforeActivate(MazeController __instance, bool ___isActive)
	{
		//IL_000a: Unknown result type (might be due to invalid IL or missing references)
		//IL_000f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0042: 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 (___isActive)
		{
			return;
		}
		Scene scene = ((Component)__instance).gameObject.scene;
		GameManager unsafeInstance = GameManager.UnsafeInstance;
		string text = (Object.op_Implicit((Object)(object)unsafeInstance) ? unsafeInstance.GetEntryGateName() : null);
		bool flag = Object.op_Implicit((Object)(object)unsafeInstance) && ConsumeWarp(unsafeInstance, ((Scene)(ref scene)).name, text);
		Visit visit = Plugin.For(scene);
		if (visit == null)
		{
			return;
		}
		PlayerData instance = PlayerData.instance;
		Plan plan = visit.Plan;
		EnsureOrigin(instance);
		bool flag2 = Plugin.IsDebugVisit(scene);
		bool flag3 = visit.Room.Gates.Contains(instance.PreviousMazeTargetDoor) && !string.IsNullOrEmpty(instance.PreviousMazeScene) && !string.IsNullOrEmpty(instance.PreviousMazeDoor);
		bool flag4 = flag3 && IsRecovering(instance);
		if (!flag2 && visit.Room.Gates.Contains(text) && (flag || (!flag4 && (!flag3 || instance.PreviousMazeTargetDoor != text))))
		{
			DoorLink doorLink = (Plugin.AllowsJuggling ? BackLink(visit.Room, plan, text) : Ordinary(visit.Room, text));
			if (doorLink != null)
			{
				instance.PreviousMazeScene = doorLink.Scene;
				instance.PreviousMazeDoor = doorLink.Gate;
				instance.PreviousMazeTargetDoor = text;
				if (!Plugin.AllowsJuggling)
				{
					ReturnFlag.SetValue(instance, false);
				}
				flag4 = false;
			}
		}
		if (visit.Replay == null && !flag4 && (flag || flag2 || plan.ApplyProgressOnTraversal))
		{
			int correctMazeDoorsEntered = instance.CorrectMazeDoorsEntered;
			if (plan.Score >= 0)
			{
				instance.CorrectMazeDoorsEntered = plan.Score;
			}
			if (plan.Wrong >= 0)
			{
				instance.IncorrectMazeDoorsEntered = plan.Wrong;
			}
			if (plan.Rest >= 0)
			{
				instance.EnteredMazeRestScene = plan.Rest == 1;
			}
			if (correctMazeDoorsEntered != instance.CorrectMazeDoorsEntered)
			{
				Plugin.Note(visit.Room.Name + " entry preset: score " + correctMazeDoorsEntered + " → " + instance.CorrectMazeDoorsEntered, visit.Room.Name + " 进房方案将分数由 " + correctMazeDoorsEntered + " 设为 " + instance.CorrectMazeDoorsEntered + "。");
			}
		}
	}

	private static void EnsureOrigin(PlayerData player)
	{
		if (HallSide(player.MazeEntranceScene, player.MazeEntranceDoor) == null)
		{
			if (HallSide(player.MazeEntranceInitialScene, player.MazeEntranceInitialDoor) == null)
			{
				player.MazeEntranceInitialScene = "Dust_05";
				player.MazeEntranceInitialDoor = "left1";
			}
			player.MazeEntranceScene = player.MazeEntranceInitialScene;
			player.MazeEntranceDoor = player.MazeEntranceInitialDoor;
		}
	}

	private static string HallSide(string scene, string door)
	{
		if (scene == "Dust_05" && Starts(door, "left"))
		{
			return "left";
		}
		if (scene == "Shadow_04" && Starts(door, "left"))
		{
			return "right";
		}
		if (scene == "Dust_09")
		{
			if (Starts(door, "left"))
			{
				return "right";
			}
			if (Starts(door, "right"))
			{
				return "left";
			}
		}
		return null;
	}

	private static bool Starts(string s, string prefix)
	{
		return s?.StartsWith(prefix, StringComparison.Ordinal) ?? false;
	}

	internal static DoorLink BackLink(Room room, Plan plan, string arrival)
	{
		Room room2 = Catalog.Find(plan.BackRoom);
		if (room2 != null && room2 != room)
		{
			if (room2.Gates.Contains(plan.BackGate) && Starts(plan.BackGate, Catalog.Opposite(arrival)))
			{
				return new DoorLink(room2.Name, plan.BackGate);
			}
			string text = Catalog.Match(room2.Gates, arrival);
			if (text != null)
			{
				return new DoorLink(room2.Name, text);
			}
		}
		return Ordinary(room, arrival);
	}

	private static DoorLink Ordinary(Room room, string gate)
	{
		Room[] rooms = Catalog.Rooms;
		foreach (Room room2 in rooms)
		{
			if (room2 != room)
			{
				string text = Catalog.Match(room2.Gates, gate);
				if (text != null)
				{
					return new DoorLink(room2.Name, text);
				}
			}
		}
		return null;
	}

	private static bool Special(string scene)
	{
		if (!(scene == "Dust_Maze_crossing"))
		{
			return scene == "Dust_Maze_Last_Hall";
		}
		return true;
	}

	private static string[] DestinationGates(string scene)
	{
		if (Special(scene) || scene == "Dust_Maze_09_entrance")
		{
			return CorridorGates;
		}
		return Catalog.Find(scene)?.Gates;
	}

	private static DoorLink To(string scene, string from)
	{
		if (scene == "Dust_Maze_09_entrance")
		{
			return null;
		}
		string[] array = DestinationGates(scene);
		if (array == null)
		{
			return null;
		}
		string text = Catalog.Match(array, from);
		if (text != null)
		{
			return new DoorLink(scene, text);
		}
		return null;
	}

	private static bool SameLink(DoorLink a, DoorLink b)
	{
		if (a.Scene == b.Scene)
		{
			return a.Gate == b.Gate;
		}
		return false;
	}

	private static bool ReplayDoorsValid(Room room, Layout replay, Dictionary<string, DoorLink> native, List<string> nativeCorrect, string arrival)
	{
		if ((replay.Correct.Contains(arrival) && !nativeCorrect.Contains(arrival)) || replay.Correct.Count != replay.Correct.Distinct().Count())
		{
			return false;
		}
		foreach (KeyValuePair<string, DoorLink> link in replay.Links)
		{
			DoorLink value = link.Value;
			if (value == null || !native.TryGetValue(link.Key, out var value2))
			{
				return false;
			}
			if (link.Key != arrival && Special(value.Scene) && !replay.Correct.Contains(link.Key))
			{
				return false;
			}
			if (!SameLink(value2, value))
			{
				if (link.Key == arrival || value.Scene == room.Name)
				{
					return false;
				}
				string[] array = DestinationGates(value.Scene);
				if (array == null || !array.Contains(value.Gate) || !Starts(value.Gate, Catalog.Opposite(link.Key)))
				{
					return false;
				}
			}
		}
		return true;
	}

	internal static void AfterLink(MazeController __instance, IReadOnlyList<TransitionPoint> __0, List<TransitionPoint> ___correctDoors)
	{
		//IL_0012: Unknown result type (might be due to invalid IL or missing references)
		Visit v = Plugin.For(((Component)__instance).gameObject.scene);
		if (v == null)
		{
			return;
		}
		TransitionPoint[] array = __0.Where((TransitionPoint g) => Object.op_Implicit((Object)(object)g) && v.Room.Gates.Contains(((Object)g).name)).ToArray();
		if (array.Length != v.Room.Gates.Length || array.Select((TransitionPoint g) => ((Object)g).name).Distinct().Count() != array.Length || ___correctDoors.Any((TransitionPoint g) => Object.op_Implicit((Object)(object)g) && !v.Room.Gates.Contains(((Object)g).name)))
		{
			v.CaptureFailed = true;
			return;
		}
		Dictionary<string, TransitionPoint> map = array.ToDictionary((TransitionPoint g) => ((Object)g).name);
		Dictionary<string, DoorLink> dictionary = map.ToDictionary((KeyValuePair<string, TransitionPoint> k) => k.Key, (KeyValuePair<string, TransitionPoint> k) => new DoorLink(k.Value.targetScene, k.Value.entryPoint));
		List<string> list = (from g in ___correctDoors
			where Object.op_Implicit((Object)(object)g)
			select ((Object)g).name).ToList();
		string arrival = PlayerData.instance.PreviousMazeTargetDoor;
		bool flag = !Plugin.AllowsJuggling && list.Count == 1 && list[0] == arrival;
		bool flag2 = false;
		if (!flag && v.Replay != null)
		{
			if (ReplayDoorsValid(v.Room, v.Replay, dictionary, list, arrival))
			{
				dictionary = new Dictionary<string, DoorLink>(v.Replay.Links);
				list = new List<string>(v.Replay.Correct);
				flag2 = true;
			}
			else
			{
				Plugin.Note("Saved door links do not match the room or arrival gate. The game's door links were kept.", "存档中的门连接与房间或来时门不符。本次沿用游戏生成的连接。");
			}
		}
		else if (!flag && v.Plan.FixedDoors)
		{
			List<string> list2 = v.Plan.Correct.Where((string g) => g != null && map.ContainsKey(g) && g != arrival).Distinct().ToList();
			if (!Plugin.AllowsJuggling && list2.Count > 1)
			{
				list2.RemoveRange(1, list2.Count - 1);
			}
			if (list2.Count == 0)
			{
				Plugin.Note("Choose a correct exit other than the arrival gate. The game chose the answer for this visit.", "请指定一个不同于来时入口的出口。本次采用游戏选出的正确出口。");
			}
			else
			{
				Dictionary<string, DoorLink> dictionary2 = new Dictionary<string, DoorLink>(dictionary);
				if (Configure(v, list2, dictionary2))
				{
					dictionary = dictionary2;
					list = list2;
					flag2 = true;
				}
			}
		}
		if (flag2)
		{
			foreach (KeyValuePair<string, TransitionPoint> item in map)
			{
				DoorLink doorLink = dictionary[item.Key];
				if (item.Value.targetScene != doorLink.Scene)
				{
					item.Value.SetTargetScene(doorLink.Scene);
				}
				item.Value.entryPoint = doorLink.Gate;
			}
			___correctDoors.Clear();
			foreach (string item2 in list)
			{
				___correctDoors.Add(map[item2]);
			}
		}
		v.Seen.Correct = list;
		v.Seen.Links = dictionary;
		v.Linked = true;
	}

	private static bool Configure(Visit v, List<string> selected, Dictionary<string, DoorLink> links)
	{
		PlayerData instance = PlayerData.instance;
		string destination = v.Plan.Destination;
		string[] gates = v.Room.Gates;
		foreach (string text in gates)
		{
			if (text == instance.PreviousMazeTargetDoor)
			{
				continue;
			}
			bool flag = selected.Contains(text);
			DoorLink doorLink = links[text];
			if (flag && !string.IsNullOrEmpty(destination))
			{
				DoorLink doorLink2 = To(destination, text);
				if (doorLink2 == null || doorLink2.Scene == v.Room.Name)
				{
					Plugin.Note("Choose another room with a matching entrance. Using the game's door links.", "请选有相接入口的其他房间。本次采用游戏生成的出入口连接。");
					return false;
				}
				links[text] = doorLink2;
			}
			else if (flag)
			{
				string text2 = Catalog.Opposite(text);
				string text3 = HallSide(instance.MazeEntranceScene, instance.MazeEntranceDoor);
				if (instance.CorrectMazeDoorsEntered >= 6 && text2 == text3)
				{
					links[text] = To("Dust_Maze_Last_Hall", text);
				}
				else if (instance.CorrectMazeDoorsEntered >= 2 && instance.CorrectMazeDoorsEntered < 6 && !instance.EnteredMazeRestScene && (text2 == "left" || text2 == "right"))
				{
					links[text] = To("Dust_Maze_crossing", text);
				}
				else if (Special(doorLink.Scene))
				{
					links[text] = Ordinary(v.Room, text);
				}
			}
			else if (Special(doorLink.Scene))
			{
				links[text] = Ordinary(v.Room, text);
			}
		}
		return true;
	}
}
internal sealed class Visit
{
	internal readonly Room Room;

	internal readonly Plan Plan;

	internal readonly Layout Replay;

	internal readonly Layout Seen;

	internal readonly int[][] Desired;

	internal readonly GameObject[][] Pools = new GameObject[3][];

	internal readonly Dictionary<int, Group> Groups = new Dictionary<int, Group>();

	internal readonly int[] PlannedSpools;

	internal Breakable[] SilkSpools;

	internal readonly HashSet<int> ProtectedSpools = new HashSet<int>();

	internal float? NativeWraithMultiplier;

	internal bool InitializedMoths;

	internal bool Populated;

	internal bool Linked;

	internal bool CaptureFailed;

	internal Visit(Room room, Plan plan, Layout replay, Random random)
	{
		Room = room;
		Plan = plan;
		Replay = replay;
		Seen = new Layout
		{
			Room = room.Name,
			GameVersion = Plugin.GameVersion
		};
		IEnumerable<int> source = Enumerable.Range(0, 3);
		Func<int, int[]> selector = (int i) => (replay != null) ? replay.Spawn[i].ToArray() : plan.Spawn[i].Resolve(room.Nodes[i].Length, random);
		Desired = source.Select(selector).ToArray();
		PlannedSpools = ((replay != null && replay.SpoolSilk != null) ? replay.SpoolSilk.Keys.ToArray() : plan.SilkSpools.Resolve(room.SilkSpools.Length, random));
	}

	internal static int Category(string state)
	{
		switch (state)
		{
		case "Set Silkflies":
			return 0;
		case "Set Wraiths":
		case "Get Wraith Count":
			return 1;
		case "Set Traps":
		case "Get Trap Count":
			return 2;
		default:
			return -1;
		}
	}

	internal void BindPool(int cat, Transform parent)
	{
		if (Pools[cat] == null && !((Object)(object)parent == (Object)null))
		{
			GameObject[] array = (GameObject[])(object)new GameObject[parent.childCount];
			for (int i = 0; i < array.Length; i++)
			{
				array[i] = ((Component)parent.GetChild(i)).gameObject;
			}
			Spot[] expected = Room.Nodes[cat];
			if (array.Length != expected.Length || array.Where((GameObject o, int num) => ((Object)o).name != expected[num].Name).Any())
			{
				Desired[cat] = null;
				CaptureFailed = true;
				string text = Room.Name + "/" + ((Object)parent).name;
				Plugin.Note("Spawn points differ from the bundled room data. Using vanilla generation. " + text, "生成点位与内置房间数据不符。该类对象沿用原版生成。 " + text);
			}
			Pools[cat] = array;
		}
	}

	internal Group ResolveGroup(Transform t)
	{
		if (Groups.TryGetValue(((Object)t).GetInstanceID(), out var value))
		{
			return value;
		}
		string path = Catalog.PathOf(t);
		value = Array.Find(Room.Groups, (Group x) => x.Path == path);
		if (value != null)
		{
			Groups[((Object)t).GetInstanceID()] = value;
		}
		return value;
	}

	internal int Variant(string path)
	{
		Dictionary<string, int> dictionary = ((Replay == null) ? Plan.Variants : Replay.Variants);
		if (!dictionary.TryGetValue(path, out var value))
		{
			return -1;
		}
		return value;
	}
}
internal static class Generation
{
	internal sealed class VariantState
	{
		internal Visit Run;

		internal Group Group;

		internal RoomObservation Observation;

		internal string Path;

		internal bool Extra;

		internal GameObject[] Children;
	}

	private static readonly HashSet<string> RemovableExtraGroups = new HashSet<string>(StringComparer.Ordinal) { "Dust_Maze_04/Level Set (15)", "Dust_Maze_04/Level Set (16)", "Dust_Maze_05/Level Set (7)", "Dust_Maze_05/Level Set (15)", "Dust_Maze_05/Level Set (17)", "Dust_Maze_05/Level Set (18)", "Dust_Maze_06/Level Set (9)", "Dust_Maze_06/Level Set (14)", "Dust_Maze_07/Level Set (14)", "Dust_Maze_07/Level Set (15)" };

	internal static bool CanDisableGroup(Room room, Group group)
	{
		if (!group.Extra)
		{
			return true;
		}
		string text = group.Path.Substring(group.Path.LastIndexOf('/') + 1);
		return RemovableExtraGroups.Contains(room.Name + "/" + text);
	}

	internal static bool ContainsSolidTerrain(GameObject root)
	{
		int terrain = LayerMask.NameToLayer("Terrain");
		if (terrain >= 0)
		{
			return root.GetComponentsInChildren<Collider2D>(true).Any((Collider2D collider) => !collider.isTrigger && ((Component)collider).gameObject.layer == terrain);
		}
		return false;
	}

	private static Visit For(FsmStateAction a)
	{
		//IL_0026: Unknown result type (might be due to invalid IL or missing references)
		if (!Plugin.MayRun || !(a.Fsm.Name == "mist_maze_controller"))
		{
			return null;
		}
		return Plugin.For(a.Owner.scene);
	}

	internal static bool BeforeNull(GameObjectIsNull __instance)
	{
		Visit visit = For((FsmStateAction)(object)__instance);
		if (visit == null)
		{
			return true;
		}
		string name = ((FsmStateAction)__instance).State.Name;
		int num = Visit.Category(name);
		if (num < 0)
		{
			return true;
		}
		GameObject value = __instance.gameObject.Value;
		if (!Object.op_Implicit((Object)(object)value))
		{
			return true;
		}
		visit.BindPool(num, value.transform);
		int[] array = visit.Desired[num];
		if (array == null)
		{
			return true;
		}
		if (array.Length == 0)
		{
			((FsmStateAction)__instance).Fsm.Event(__instance.isNull);
			return false;
		}
		if (num == 0 && !visit.InitializedMoths)
		{
			visit.InitializedMoths = true;
			((FsmStateAction)__instance).Fsm.Variables.FindFsmInt("Silkflies").Value = array.Length;
		}
		if (num == 1)
		{
			FsmFloat val = ((FsmStateAction)__instance).Fsm.Variables.FindFsmFloat("Wraith Multiplier");
			if (val.Value <= 0f)
			{
				visit.NativeWraithMultiplier = val.Value;
				val.Value = 1f;
			}
		}
		return true;
	}

	internal static void AfterCount(MultiplyIntByFloat __instance)
	{
		Visit visit = For((FsmStateAction)(object)__instance);
		if (visit != null)
		{
			int num = Visit.Category(((FsmStateAction)__instance).State.Name);
			if (num > 0 && visit.Desired[num] != null)
			{
				__instance.storeResult.Value = visit.Desired[num].Length;
			}
			if (num == 1 && visit.NativeWraithMultiplier.HasValue)
			{
				((FsmStateAction)__instance).Fsm.Variables.FindFsmFloat("Wraith Multiplier").Value = visit.NativeWraithMultiplier.Value;
				visit.NativeWraithMultiplier = null;
			}
		}
	}

	internal static void AfterPick(GetRandomChildSceneSeed __instance)
	{
		//IL_0034: Unknown result type (might be due to invalid IL or missing references)
		//IL_0039: Unknown result type (might be due to invalid IL or missing references)
		//IL_003a: 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)
		if (((FsmStateAction)__instance).Fsm.Name != "mist_maze_controller")
		{
			return;
		}
		int num = Visit.Category(((FsmStateAction)__instance).State.Name);
		if (num < 0)
		{
			return;
		}
		Scene scene = ((FsmStateAction)__instance).Owner.scene;
		RoomObservation roomObservation = RoomObservation.For(scene);
		if (roomObservation != null)
		{
			Visit visit = Plugin.For(scene);
			if (visit != null)
			{
				ApplyPick(__instance, visit, num);
			}
			GameObject value = __instance.StoreResult.Value;
			if (Object.op_Implicit((Object)(object)value))
			{
				roomObservation.RecordPick(num, value);
			}
		}
	}

	private static void ApplyPick(GetRandomChildSceneSeed action, Visit v, int c)
	{
		GameObject value = action.StoreResult.Value;
		if (!Object.op_Implicit((Object)(object)value))
		{
			v.CaptureFailed = true;
			return;
		}
		v.BindPool(c, value.transform.parent);
		GameObject[] array = v.Pools[c];
		if (array == null)
		{
			v.CaptureFailed = true;
			return;
		}
		int count = v.Seen.Spawn[c].Count;
		if (v.Desired[c] != null && count < v.Desired[c].Length)
		{
			GameObject val = array[v.Desired[c][count]];
			if (Object.op_Implicit((Object)(object)val) && (Object)(object)val.transform.parent == (Object)(object)value.transform.parent)
			{
				action.StoreResult.Value = val;
			}
			else
			{
				v.CaptureFailed = true;
				Plugin.Note("The selected spawn point is unavailable. Using the game's choice.", "所选点位不可用。本次沿用游戏抽到的点位。");
			}
		}
		int num = Array.IndexOf(array, action.StoreResult.Value);
		if (num < 0 || v.Seen.Spawn[c].Contains(num))
		{
			v.CaptureFailed = true;
		}
		else
		{
			v.Seen.Spawn[c].Add(num);
		}
	}

	internal static void AtMusic(ActivateAllChildren __instance)
	{
		//IL_0035: Unknown result type (might be due to invalid IL or missing references)
		//IL_003a: Unknown result type (might be due to invalid IL or missing references)
		//IL_003b: Unknown result type (might be due to invalid IL or missing references)
		//IL_005b: 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)
		if (((FsmStateAction)__instance).Fsm.Name != "mist_maze_controller" || ((FsmStateAction)__instance).State.Name != "Check Music Level")
		{
			return;
		}
		Scene scene = ((FsmStateAction)__instance).Owner.scene;
		Visit visit = Plugin.For(scene);
		if (visit != null && !visit.Populated)
		{
			SilkSpoolControl.Apply(visit, scene);
			visit.Populated = true;
		}
		RoomObservation roomObservation = RoomObservation.For(scene);
		if (roomObservation == null)
		{
			return;
		}
		FsmFloat[] floatVariables = ((FsmStateAction)__instance).Fsm.Variables.FloatVariables;
		foreach (FsmFloat val in floatVariables)
		{
			if (((NamedVariable)val).Name == "Trap Multiplier")
			{
				roomObservation.TrapMultiplier = val.Value;
			}
			else if (((NamedVariable)val).Name == "Wraith Multiplier")
			{
				roomObservation.WraithMultiplier = val.Value;
			}
		}
		roomObservation.Populated = true;
	}

	internal static bool BeforeVariant(ActivateRandomChildren __instance, int ___amountMin, int ___amountMax, bool ___deparentAfterActivated, out VariantState __state)
	{
		//IL_001f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0024: Unknown result type (might be due to invalid IL or missing references)
		//IL_0025: Unknown result type (might be due to invalid IL or missing references)
		//IL_010b: Unknown result type (might be due to invalid IL or missing references)
		__state = null;
		Transform transform = ((Component)__instance).transform;
		Transform parent = transform.parent;
		Scene scene = ((Component)transform).gameObject.scene;
		RoomObservation roomObservation = RoomObservation.For(scene);
		if (roomObservation == null)
		{
			return true;
		}
		roomObservation.Groups.TryGetValue(((Object)((Component)transform).gameObject).GetInstanceID(), out var value);
		bool flag = value?.Extra ?? (Object.op_Implicit((Object)(object)parent) && ((Object)parent).name.StartsWith("Mist Maze Controller", StringComparison.Ordinal));
		if (value == null && !flag && (!Object.op_Implicit((Object)(object)parent) || ((Object)parent).name != "Trap Sets"))
		{
			return true;
		}
		GameObject[] array = (GameObject[])(object)new GameObject[transform.childCount];
		for (int i = 0; i < array.Length; i++)
		{
			array[i] = ((Component)transform.GetChild(i)).gameObject;
		}
		__state = new VariantState
		{
			Observation = roomObservation,
			Path = ((value == null) ? Catalog.PathOf(transform) : value.Path),
			Extra = flag,
			Children = array
		};
		Visit visit = Plugin.For(scene);
		Group group = visit?.ResolveGroup(transform);
		if (group == null)
		{
			return true;
		}
		if (array.Length != group.Children.Length || array.Where((GameObject o, int num3) => ((Object)o).name != group.Children[num3].Name).Any())
		{
			visit.CaptureFailed = true;
			return true;
		}
		__state.Run = visit;
		__state.Group = group;
		int num = visit.Variant(group.Path);
		if (num == -1 || num >= array.Length || num < -2 || array.Length == 0 || ___amountMin != 1 || ___amountMax != 1)
		{
			return true;
		}
		if (num == -2 && (!CanDisableGroup(visit.Room, group) || (group.Extra && array.Any(ContainsSolidTerrain))))
		{
			return true;
		}
		GameManager unsafeInstance = GameManager.UnsafeInstance;
		Random random = (Object.op_Implicit((Object)(object)unsafeInstance) ? unsafeInstance.SceneSeededRandom : null);
		GameObject[] array2 = array;
		foreach (GameObject val in array2)
		{
			val.SetActive(false);
		}
		if (random != null)
		{
			random.Next(___amountMin, ___amountMax);
			random.Next(0, transform.childCount);
		}
		if (num >= 0)
		{
			array[num].SetActive(true);
			if (___deparentAfterActivated)
			{
				array[num].transform.SetParent((Transform)null, true);
			}
		}
		return false;
	}

	internal static void AfterVariant(ActivateRandomChildren __instance, VariantState __state)
	{
		if (__state == null)
		{
			return;
		}
		__state.Observation.RecordGroup(((Component)__instance).gameObject, __state.Path, __state.Extra, __state.Children);
		if (__state.Run != null)
		{
			int num = Array.FindIndex(__state.Children, (GameObject c) => Object.op_Implicit((Object)(object)c) && c.activeSelf);
			__state.Run.Seen.Variants[__state.Group.Path] = ((num < 0) ? (-2) : num);
		}
	}
}
public sealed class Spot
{
	public string Name;

	public float X;

	public float Y;

	public string Label => Name + "  (" + X.ToString("0.#") + ", " + Y.ToString("0.#") + ")";
}
public sealed class Group
{
	public string Path;

	public Spot[] Children;

	public bool Extra;
}
public sealed class Room
{
	public string Name;

	public string[] Gates;

	public Spot[][] Nodes;

	public Group[] Groups;

	public Spot[] SilkSpools = new Spot[0];
}
public static class Catalog
{
	public static readonly Room[] Rooms = Read();

	private static Room[] Read()
	{
		using StreamReader streamReader = new StreamReader(typeof(Catalog).Assembly.GetManifestResourceStream("rooms.json"));
		return JsonConvert.DeserializeObject<Room[]>(streamReader.ReadToEnd());
	}

	public static Room Find(string name)
	{
		return Array.Find(Rooms, (Room r) => r.Name == name);
	}

	internal static string PathOf(Transform transform)
	{
		string text = ((Object)transform).name;
		Transform parent = transform.parent;
		while ((Object)(object)parent != (Object)null)
		{
			text = ((Object)parent).name + "/" + text;
			parent = parent.parent;
		}
		return text;
	}

	public static string Opposite(string door)
	{
		if (door == null)
		{
			return null;
		}
		string[] array = new string[4] { "left:right", "right:left", "top:bot", "bot:top" };
		foreach (string text in array)
		{
			string[] array2 = text.Split(':');
			if (door.StartsWith(array2[0], StringComparison.Ordinal))
			{
				return array2[1];
			}
		}
		return null;
	}

	public static string Match(string[] gates, string from)
	{
		string prefix = Opposite(from);
		if (prefix != null)
		{
			return Array.Find(gates, (string g) => g.StartsWith(prefix, StringComparison.Ordinal));
		}
		return null;
	}
}
public enum PickMode
{
	Native,
	Fixed,
	Count
}
public sealed class Choice
{
	public PickMode Mode;

	public int Count;

	public List<int> Points = new List<int>();

	public int[] Resolve(int length, Random rng)
	{
		if (Mode == PickMode.Native)
		{
			return null;
		}
		if (Mode == PickMode.Fixed)
		{
			return Points.Where((int n) => n >= 0 && n < length).Distinct().ToArray();
		}
		int[] array = Enumerable.Range(0, length).ToArray();
		int num = Math.Max(0, Math.Min(length, Count));
		for (int num2 = 0; num2 < num; num2++)
		{
			int num3 = rng.Next(num2, length);
			int num4 = array[num2];
			array[num2] = array[num3];
			array[num3] = num4;
		}
		return array.Take(num).ToArray();
	}
}
public sealed class Plan
{
	public int Score = -1;

	public int Wrong = -1;

	public int Rest = -1;

	public bool ApplyProgressOnTraversal;

	public Choice[] Spawn = new Choice[3]
	{
		new Choice(),
		new Choice(),
		new Choice()
	};

	public Choice SilkSpools = new Choice();

	public int SpoolSilk = -1;

	public Dictionary<int, int> SpoolSilkByPoint = new Dictionary<int, int>();

	public Dictionary<string, int> Variants = new Dictionary<string, int>();

	public bool FixedDoors;

	public List<string> Correct = new List<string>();

	public string Destination = "";

	public string WarpGate = "";

	public string BackRoom = "";

	public string BackGate = "";

	public Plan Copy()
	{
		return JsonConvert.DeserializeObject<Plan>(JsonConvert.SerializeObject((object)this));
	}
}
public sealed class DoorLink
{
	public string Scene;

	public string Gate;

	public DoorLink()
	{
	}

	public DoorLink(string scene, string gate)
	{
		Scene = scene;
		Gate = gate;
	}
}
public sealed class Layout
{
	public int Version = 1;

	public string GameVersion = "1.0.28324";

	public string Room;

	public List<int>[] Spawn = new List<int>[3]
	{
		new List<int>(),
		new List<int>(),
		new List<int>()
	};

	public Dictionary<string, int> Variants = new Dictionary<string, int>();

	public Dictionary<string, DoorLink> Links = new Dictionary<string, DoorLink>();

	public List<string> Correct = new List<string>();

	public Dictionary<int, int> SpoolSilk;

	public bool Valid(Room r)
	{
		if (r != null && Room == r.Name && Version == 1 && Spawn != null && Spawn.Length == 3 && Spawn.Select((List<int> s, int i) => s != null && s.All((int v) => v >= 0 && v < r.Nodes[i].Length) && s.Distinct().Count() == s.Count).All((bool v) => v) && Links != null && Links.Count == r.Gates.Length && r.Gates.All((string g) => Links.ContainsKey(g) && Links[g] != null && !string.IsNullOrEmpty(Links[g].Scene) && !string.IsNullOrEmpty(Links[g].Gate)) && Correct != null && Correct.All(((IEnumerable<string>)r.Gates).Contains<string>) && Variants != null && Variants.All((KeyValuePair<string, int> v) => r.Groups.Any((Group g) => g.Path == v.Key && (v.Value == -2 || (v.Value >= 0 && v.Value < g.Children.Length)))))
		{
			if (SpoolSilk != null)
			{
				return SpoolSilk.All((KeyValuePair<int, int> v) => v.Key >= 0 && v.Key < r.SilkSpools.Length && v.Value >= 0 && v.Value <= 2);
			}
			return true;
		}
		return false;
	}
}
internal static class DebugBridge
{
	private const string Key = "MistPractice_layout_v1";

	[MethodImpl(MethodImplOptions.NoInlining)]
	internal static void Attach()
	{
		SaveState.OnSave += Save;
		SaveState.BeforeLoad += Before;
		SaveState.AfterLoad += After;
	}

	[MethodImpl(MethodImplOptions.NoInlining)]
	internal static void Detach()
	{
		SaveState.OnSave -= Save;
		SaveState.BeforeLoad -= Before;
		SaveState.AfterLoad -= After;
	}

	[MethodImpl(MethodImplOptions.NoInlining)]
	internal static bool IsLoading(object load)
	{
		return object.ReferenceEquals(SaveState.loadingSavestate, load);
	}

	[MethodImpl(MethodImplOptions.NoInlining)]
	internal static bool IsDebugTransition(SceneLoadInfo info)
	{
		Type type = ((object)info).GetType();
		if (type.DeclaringType == typeof(SaveState))
		{
			return type.Name == "DebugModSaveStateSceneLoadInfo";
		}
		return false;
	}

	private static void Save(SaveState s)
	{
		//IL_004d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0052: Unknown result type (might be due to invalid IL or missing references)
		if (!Plugin.Training)
		{
			return;
		}
		try
		{
			Visit visit = Plugin.Current();
			if (visit == null || visit.Room.Name != s.data.saveScene)
			{
				return;
			}
			MazeController newestInstance = MazeController.NewestInstance;
			GameManager unsafeInstance = GameManager.UnsafeInstance;
			if (Object.op_Implicit((Object)(object)newestInstance) && !(((Component)newestInstance).gameObject.scene != SceneManager.GetActiveScene()) && (!Object.op_Implicit((Object)(object)unsafeInstance) || !unsafeInstance.IsInSceneTransition))
			{
				visit.Seen.SpoolSilk = SilkSpoolControl.Snapshot(visit);
				if (!visit.Linked || !visit.Populated || visit.CaptureFailed || !visit.Seen.Valid(visit.Room))
				{
					Plugin.Note("Room setup is incomplete. DebugMod saved the baseline state.", "房间布局尚未完整记录。已由 DebugMod 保存基本状态。");
					return;
				}
				s.data.customData["MistPractice_layout_v1"] = Convert.ToBase64String(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject((object)visit.Seen)));
				Plugin.Note("Saved the room layout and door links with the DebugMod savestate.", "房间布局和出入口连接已写入 DebugMod 存档。");
			}
		}
		catch (Exception ex)
		{
			Plugin.Note("Could not save the room layout. " + ex.Message, "保存房间布局失败。" + ex.Message);
		}
	}

	private static void Before(SaveState s)
	{
		Layout replay = null;
		try
		{
			if (Plugin.Training && s.data != null && s.data.customData != null && s.data.customData.TryGetValue("MistPractice_layout_v1", out var value))
			{
				Layout layout = JsonConvert.DeserializeObject<Layout>(Encoding.UTF8.GetString(Convert.FromBase64String(value)));
				if (layout != null && layout.GameVersion != Plugin.GameVersion)
				{
					Plugin.Note("This layout was saved on game version " + layout.GameVersion + ". Using the current preset.", "存档中的布局来自游戏版本 " + layout.GameVersion + "。本次读档使用当前房间方案。");
				}
				else if (layout != null && layout.Valid(Catalog.Find(s.data.saveScene)))
				{
					replay = layout;
					Plugin.Note("Read the saved room layout.", "已读取存档中的房间布局。");
				}
				else
				{
					Plugin.Note("The saved layout does not match this room. Using the current preset.", "存档布局与目标房间不匹配。本次读档使用当前房间方案。");
				}
			}
		}
		catch (Exception ex)
		{
			Plugin.Note("Could not read the saved room layout. " + ex.Message, "读取房间布局失败。" + ex.Message);
		}
		finally
		{
			Plugin.BeginDebugLoad(s, (s.data == null) ? null : s.data.saveScene, replay);
		}
	}

	private static void After(SaveState s)
	{
		Plugin.EndDebugLoad(s);
	}
}
internal sealed class RoomObservation
{
	internal sealed class TrapPick
	{
		internal int Id;

		internal string Path;

		internal GameObject Object;
	}

	internal sealed class GroupPick
	{
		internal string Path;

		internal bool Extra;

		internal GameObject Object;

		internal VariantPick[] Choices;
	}

	internal sealed class VariantPick
	{
		internal int Index;

		internal string Name;

		internal bool Empty;

		internal GameObject Object;
	}

	internal const string Entrance = "Dust_Maze_09_entrance";

	internal const string Completed = "Dust_Maze_08_completed";

	private static readonly Dictionary<int, RoomObservation> Rooms = new Dictionary<int, RoomObservation>();

	internal readonly List<Spot>[] Spawns = new List<Spot>[2]
	{
		new List<Spot>(),
		new List<Spot>()
	};

	internal readonly List<TrapPick> TrapPicks = new List<TrapPick>();

	internal readonly Dictionary<int, GroupPick> Groups = new Dictionary<int, GroupPick>();

	internal float? TrapMultiplier;

	internal float? WraithMultiplier;

	internal bool Populated;

	internal static bool IsMist(string name)
	{
		switch (name)
		{
		default:
			return Catalog.Find(name) != null;
		case "Dust_Maze_09_entrance":
		case "Dust_Maze_crossing":
		case "Dust_Maze_Last_Hall":
		case "Dust_Maze_08_completed":
			return true;
		}
	}

	internal static RoomObservation For(Scene scene)
	{
		if (!((Scene)(ref scene)).IsValid() || !IsMist(((Scene)(ref scene)).name))
		{
			return null;
		}
		if (!Rooms.TryGetValue(((Scene)(ref scene)).handle, out var value))
		{
			value = new RoomObservation();
			Rooms.Add(((Scene)(ref scene)).handle, value);
		}
		return value;
	}

	internal static void Unload(Scene scene)
	{
		Rooms.Remove(((Scene)(ref scene)).handle);
	}

	internal static void Clear()
	{
		Rooms.Clear();
	}

	internal void RecordPick(int category, GameObject selected)
	{
		//IL_000a: Unknown result type (might be due to invalid IL or missing references)
		//IL_000f: Unknown result type (might be due to invalid IL or missing references)
		if (category < 2)
		{
			Vector3 position = selected.transform.position;
			Spawns[category].Add(new Spot
			{
				Name = ((Object)selected).name,
				X = position.x,
				Y = position.y
			});
			return;
		}
		int id = ((Object)selected).GetInstanceID();
		if (TrapPicks.All((TrapPick x) => x.Id != id))
		{
			TrapPicks.Add(new TrapPick
			{
				Id = id,
				Path = Catalog.PathOf(selected.transform),
				Object = selected
			});
		}
	}

	internal void RecordGroup(GameObject group, string path, bool extra, GameObject[] children)
	{
		List<VariantPick> list = new List<VariantPick>();
		for (int i = 0; i < children.Length; i++)
		{
			GameObject val = children[i];
			if (Object.op_Implicit((Object)(object)val) && val.activeSelf)
			{
				list.Add(new VariantPick
				{