Decompiled source of MorePeak v1.9.2

BepInEx/plugins/MorePeak/MorePeak.dll

Decompiled 2 weeks ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using MorePeak.MonoBehaviours;
using Peak.Network;
using TMPro;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("MorePeak")]
[assembly: AssemblyConfiguration("Debug")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0+53accd818d94032e4030cc979f59b4b0f5ecc60e")]
[assembly: AssemblyProduct("MorePeak")]
[assembly: AssemblyTitle("MorePeak")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.0.0.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace MorePeak
{
	[BepInPlugin("com.smckeen.morepeak", "MorePeak", "1.9.2")]
	public class MorePeakPlugin : BaseUnityPlugin
	{
		[HarmonyPatch(typeof(MapBaker), "GetLevel")]
		private static class MapBaker_GetLevel_Patch
		{
			private static bool hasLoggedLevels;

			private static bool Prefix(MapBaker __instance, int levelIndex, ref string __result)
			{
				try
				{
					if (__instance?.ScenePaths == null || __instance.ScenePaths.Length == 0)
					{
						LogVerbose("MapBaker.GetLevel called with empty ScenePaths — deferring to original.");
						return true;
					}
					if (!hasLoggedLevels)
					{
						ModLogger.LogInfo((object)"=== AVAILABLE LEVELS ===");
						for (int i = 0; i < __instance.ScenePaths.Length; i++)
						{
							string text = __instance.ScenePaths[i] ?? "Unknown";
							string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(text);
							ModLogger.LogInfo((object)$"  [{i}] {fileNameWithoutExtension}  (path: {text})");
						}
						ModLogger.LogInfo((object)"========================");
						ModLogger.LogInfo((object)"Set 'SelectedLevel' in the config (or via the in-game cog) to any level name above, or leave as 'Random'.");
						hasLoggedLevels = true;
					}
					if (NetCode.Session.InRoom && !NetCode.Session.IsHost)
					{
						LogVerbose("[CLIENT] Non-host called GetLevel — deferring to original method.");
						return true;
					}
					int instanceID = ((Object)__instance).GetInstanceID();
					float time = Time.time;
					if (lastRandomizeTime.TryGetValue(instanceID, out var value) && time - value < 1f)
					{
						LogVerbose($"MapBaker.GetLevel on instance {instanceID} within cooldown window — deferring.");
						return true;
					}
					lastRandomizeTime[instanceID] = time;
					if (lastRandomizeTime.Count > 10)
					{
						PruneRandomizeTimeCache(time);
					}
					string text2 = selectedLevelConfig?.Value?.Trim() ?? "Random";
					string text3 = (NetCode.Session.InRoom ? "[HOST]" : "[OFFLINE]");
					LogVerbose($"{text3} MapBaker.GetLevel — configValue='{text2}', levelIndex={levelIndex}");
					if (text2.Equals("Daily", StringComparison.OrdinalIgnoreCase))
					{
						ModLogger.LogInfo((object)(text3 + " Using vanilla daily map (deferred to original GetLevel)."));
						return true;
					}
					if (text2.Equals("Random", StringComparison.OrdinalIgnoreCase))
					{
						int num = Random.Range(0, __instance.ScenePaths.Length);
						string path = __instance.ScenePaths[num] ?? "";
						__result = Path.GetFileNameWithoutExtension(path);
						ModLogger.LogInfo((object)$"{text3} Random level selected: '{__result}' (index {num} of {__instance.ScenePaths.Length}).");
						currentLevelName = __result;
						showLevelGUI = true;
						return false;
					}
					if (text2.Contains(","))
					{
						return HandleLevelList(text2, __instance, ref __result, text3);
					}
					return HandleSpecificLevel(text2, __instance, ref __result, text3);
				}
				catch (Exception arg)
				{
					ModLogger.LogError((object)$"[MorePeak] Unhandled exception in MapBaker.GetLevel patch: {arg}");
					return true;
				}
			}

			private static bool HandleLevelList(string configValue, MapBaker instance, ref string result, string clientInfo)
			{
				string[] array = configValue.Split(',');
				List<string> list = new List<string>();
				string[] array2 = array;
				foreach (string text in array2)
				{
					string value = text.Trim();
					if (string.IsNullOrEmpty(value))
					{
						continue;
					}
					for (int j = 0; j < instance.ScenePaths.Length; j++)
					{
						string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(instance.ScenePaths[j] ?? "");
						if (fileNameWithoutExtension.Equals(value, StringComparison.OrdinalIgnoreCase))
						{
							list.Add(fileNameWithoutExtension);
							LogVerbose("  Validated level from list: '" + fileNameWithoutExtension + "'.");
							break;
						}
					}
				}
				if (list.Count > 0)
				{
					result = list[Random.Range(0, list.Count)];
					ModLogger.LogInfo((object)(clientInfo + " Random level from list selected: '" + result + "' " + $"({list.Count} valid option(s) from the configured pool)."));
				}
				else
				{
					ModLogger.LogWarning((object)("[MorePeak] No valid levels found in list '" + configValue + "'. Falling back to fully random selection."));
					int num = Random.Range(0, instance.ScenePaths.Length);
					result = Path.GetFileNameWithoutExtension(instance.ScenePaths[num] ?? "");
					ModLogger.LogInfo((object)$"{clientInfo} Fallback random level: '{result}' (index {num}).");
				}
				currentLevelName = result;
				showLevelGUI = true;
				return false;
			}

			private static bool HandleSpecificLevel(string configValue, MapBaker instance, ref string result, string clientInfo)
			{
				for (int i = 0; i < instance.ScenePaths.Length; i++)
				{
					string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(instance.ScenePaths[i] ?? "");
					if (fileNameWithoutExtension.Equals(configValue, StringComparison.OrdinalIgnoreCase))
					{
						result = fileNameWithoutExtension;
						ModLogger.LogInfo((object)$"{clientInfo} Specific level selected: '{result}' (index {i}).");
						currentLevelName = result;
						showLevelGUI = true;
						return false;
					}
				}
				ModLogger.LogWarning((object)("[MorePeak] Level '" + configValue + "' not found in ScenePaths. Falling back to random selection."));
				int num = Random.Range(0, instance.ScenePaths.Length);
				result = Path.GetFileNameWithoutExtension(instance.ScenePaths[num] ?? "");
				ModLogger.LogInfo((object)$"{clientInfo} Fallback random level: '{result}' (index {num}).");
				currentLevelName = result;
				showLevelGUI = true;
				return false;
			}

			private static void PruneRandomizeTimeCache(float currentTime)
			{
				float num = currentTime - 300f;
				List<int> list = new List<int>();
				foreach (KeyValuePair<int, float> item in lastRandomizeTime)
				{
					if (item.Value < num)
					{
						list.Add(item.Key);
					}
				}
				foreach (int item2 in list)
				{
					lastRandomizeTime.Remove(item2);
				}
				if (list.Count > 0)
				{
					LogVerbose($"Pruned {list.Count} stale entry/entries from randomize-time cache.");
				}
			}
		}

		[HarmonyPatch(typeof(AirportCheckInKiosk), "BeginIslandLoadRPC")]
		private static class AirportCheckInKiosk_BeginIslandLoadRPC_Patch
		{
			private static void Prefix(string sceneName, int ascent)
			{
				try
				{
					currentLevelName = sceneName;
					showLevelGUI = true;
					string text = (NetCode.Session.IsHost ? "[HOST]" : "[CLIENT]");
					ModLogger.LogInfo((object)$"{text} BeginIslandLoadRPC received — loading level: '{sceneName}' (ascent: {ascent}).");
					LogVerbose(text + " GUI updated: currentLevelName='" + currentLevelName + "', showLevelGUI=true.");
				}
				catch (Exception arg)
				{
					ModLogger.LogError((object)$"[MorePeak] Exception in BeginIslandLoadRPC patch: {arg}");
				}
			}
		}

		[HarmonyPatch(typeof(LoadingScreenHandler), "LoadSceneProcess")]
		private static class LoadingScreenHandler_LoadSceneProcess_Patch
		{
			private static void Prefix(string sceneName)
			{
				try
				{
					if (sceneName.Equals("Airport", StringComparison.OrdinalIgnoreCase))
					{
						showLevelGUI = false;
						currentLevelName = "";
						ModLogger.LogInfo((object)"[MorePeak] Returning to Airport — level overlay cleared.");
						LogVerbose("LoadSceneProcess detected Airport load; showLevelGUI set to false.");
					}
					else
					{
						LogVerbose("LoadSceneProcess called for scene '" + sceneName + "' (not Airport, no action).");
					}
				}
				catch (Exception arg)
				{
					ModLogger.LogError((object)$"[MorePeak] Exception in LoadSceneProcess patch: {arg}");
				}
			}
		}

		[HarmonyPatch(typeof(NetworkConnector), "OnLeftRoom")]
		private static class NetworkConnector_OnLeftRoom_Patch
		{
			private static void Postfix()
			{
				try
				{
					showLevelGUI = false;
					currentLevelName = "";
					ModLogger.LogInfo((object)"[MorePeak] Left multiplayer room — level overlay cleared.");
					LogVerbose("NetworkConnector.OnLeftRoom fired; GUI state reset.");
				}
				catch (Exception arg)
				{
					ModLogger.LogError((object)$"[MorePeak] Exception in OnLeftRoom patch: {arg}");
				}
			}
		}

		[HarmonyPatch(typeof(LevelGeneration), "RandomizeBiomeVariants")]
		private static class LevelGeneration_RandomizeBiomeVariants_Patch
		{
			private static void Postfix()
			{
				try
				{
					int num = Random.Range(0, int.MaxValue);
					Random.InitState(num);
					LogVerbose($"BiomeVariants randomised — RNG re-seeded with {num}.");
				}
				catch (Exception arg)
				{
					ManualLogSource modLogger = ModLogger;
					if (modLogger != null)
					{
						modLogger.LogError((object)$"[MorePeak] Exception in RandomizeBiomeVariants patch: {arg}");
					}
				}
			}
		}

		[HarmonyPatch(typeof(GUIManager), "Start")]
		private static class GUIManagerPatch
		{
			[HarmonyPostfix]
			public static void Postfix(GUIManager __instance)
			{
				//IL_0060: Unknown result type (might be due to invalid IL or missing references)
				//IL_0066: Expected O, but got Unknown
				//IL_00b3: Unknown result type (might be due to invalid IL or missing references)
				//IL_00b8: Unknown result type (might be due to invalid IL or missing references)
				//IL_00b9: Unknown result type (might be due to invalid IL or missing references)
				//IL_00c1: Unknown result type (might be due to invalid IL or missing references)
				//IL_00c3: Unknown result type (might be due to invalid IL or missing references)
				//IL_00c4: Unknown result type (might be due to invalid IL or missing references)
				//IL_00cc: Unknown result type (might be due to invalid IL or missing references)
				//IL_00d5: Unknown result type (might be due to invalid IL or missing references)
				try
				{
					AscentUI componentInChildren = ((Component)__instance).GetComponentInChildren<AscentUI>(true);
					if ((Object)(object)componentInChildren == (Object)null)
					{
						ModLogger.LogWarning((object)"[MorePeak] AscentUI not found in GUIManager children — MorePeak HUD will not be shown. If the game was recently updated, AscentUI may have been moved or renamed.");
						return;
					}
					LogVerbose("Found AscentUI on '" + ((Object)((Component)componentInChildren).gameObject).name + "' — cloning for MorePeak HUD.");
					Transform transform = ((Component)componentInChildren).transform;
					RectTransform val = (RectTransform)Object.Instantiate<Transform>(transform, transform.parent);
					((Object)val).name = "MorePeakLevelDisplay";
					AscentUI component = ((Component)val).GetComponent<AscentUI>();
					if ((Object)(object)component != (Object)null)
					{
						LogVerbose("Destroying cloned AscentUI component from MorePeak HUD object.");
						Object.Destroy((Object)(object)component);
					}
					((Component)val).gameObject.AddComponent<MorePeakHUD>();
					Vector2 val3 = (val.anchorMin = new Vector2(1f, 1f));
					Vector2 pivot = (val.anchorMax = val3);
					val.pivot = pivot;
					val.anchoredPosition = Vector2.zero;
					ModLogger.LogInfo((object)"[MorePeak] HUD initialised successfully.");
					LogVerbose("MorePeakHUD anchored to top-right of '" + ((Object)((Transform)val).parent).name + "'.");
				}
				catch (Exception arg)
				{
					ModLogger.LogError((object)$"[MorePeak] Exception while initialising HUD in GUIManager.Start patch: {arg}");
				}
			}
		}

		internal static ManualLogSource ModLogger;

		internal static ConfigEntry<string> selectedLevelConfig;

		internal static ConfigEntry<bool> showCurrentLevelGUIConfig;

		internal static ConfigEntry<bool> showSelectedLevelConfigGUIConfig;

		internal static ConfigEntry<bool> verboseLoggingConfig;

		internal static string currentLevelName = "";

		private static bool showLevelGUI = false;

		private const float RANDOMIZE_COOLDOWN = 1f;

		private static readonly Dictionary<int, float> lastRandomizeTime = new Dictionary<int, float>();

		private static Texture2D guiBackgroundTexture;

		private static Texture2D settingsCogTexture;

		private static bool showSettingsGUI = false;

		private static Rect settingsWindowRect = new Rect(0f, 0f, 330f, 255f);

		private static string tempSelectedLevel = "";

		private static bool tempShowCurrentLevel = true;

		private static bool tempShowSelectedLevelConfig = true;

		private static bool tempVerboseLogging = false;

		private static Vector2 scrollPosition = Vector2.zero;

		private static int onGUICallCount = 0;

		private static GUIStyle cachedCogStyle;

		private static GUIStyle cachedLabelStyle;

		private static GUIStyle cachedTextFieldStyle;

		private static GUIStyle cachedButtonStyle;

		private static GUIStyle cachedToggleStyle;

		private static GUIStyle cachedWindowStyle;

		private static Texture2D cachedDarkBackgroundTexture;

		private static Texture2D cachedButtonBackgroundTexture;

		private static Texture2D cachedButtonHoverTexture;

		private static Texture2D cachedButtonActiveTexture;

		private static Texture2D cachedTextFieldBackgroundTexture;

		private static Texture2D cachedWindowBackgroundTexture;

		private void Awake()
		{
			//IL_013b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0141: Expected O, but got Unknown
			ModLogger = ((BaseUnityPlugin)this).Logger;
			LoadSettingsCogTexture();
			selectedLevelConfig = ((BaseUnityPlugin)this).Config.Bind<string>("Settings", "SelectedLevel", "Random", "Set to 'Daily' for the daily map, 'Random' for a fully random level, an exact level name (e.g. 'Level_0'), or a comma-separated list for random selection from that pool (e.g. 'Level_0, Level_1, Level_2').");
			showCurrentLevelGUIConfig = ((BaseUnityPlugin)this).Config.Bind<bool>("GUI", "ShowCurrentLevel", false, "Show the active level name in the top-right corner during a round.");
			showSelectedLevelConfigGUIConfig = ((BaseUnityPlugin)this).Config.Bind<bool>("GUI", "ShowSelectedLevelConfig", false, "Show the current SelectedLevel config value in the top-right corner during a round.");
			verboseLoggingConfig = ((BaseUnityPlugin)this).Config.Bind<bool>("Debug", "VerboseLogging", false, "Emit detailed diagnostic log messages. Leave disabled during normal play to avoid log spam. Can also be toggled in-game via the settings cog.");
			ModLogger.LogInfo((object)"MorePeak v1.9.2 loaded.");
			ModLogger.LogInfo((object)("Config  |  SelectedLevel=" + selectedLevelConfig.Value + $"  ShowCurrentLevel={showCurrentLevelGUIConfig.Value}" + $"  ShowSelectedLevelConfig={showSelectedLevelConfigGUIConfig.Value}" + $"  VerboseLogging={verboseLoggingConfig.Value}"));
			ModLogger.LogInfo((object)"Available levels will be listed in the log the first time a game is started.");
			Harmony val = new Harmony("com.smckeen.morepeak");
			val.PatchAll();
			LogVerbose("Harmony patches applied successfully.");
		}

		private void OnGUI()
		{
			onGUICallCount++;
			if (cachedCogStyle == null)
			{
				LogVerbose("First OnGUI call — initialising cached GUI styles.");
				InitializeCachedStyles();
			}
			if (onGUICallCount % 300 == 0)
			{
				LogVerbose($"OnGUI heartbeat — frame {onGUICallCount}, showLevelGUI={showLevelGUI}, showSettingsGUI={showSettingsGUI}");
			}
			DrawSettingsCog();
			if (showSettingsGUI)
			{
				DrawSettingsWindow();
			}
		}

		private void OnDestroy()
		{
			LogVerbose("MorePeakPlugin.OnDestroy — releasing GUI resources.");
			DestroyTextureSafe(ref guiBackgroundTexture);
			DestroyTextureSafe(ref settingsCogTexture);
			DestroyTextureSafe(ref cachedDarkBackgroundTexture);
			DestroyTextureSafe(ref cachedButtonBackgroundTexture);
			DestroyTextureSafe(ref cachedButtonHoverTexture);
			DestroyTextureSafe(ref cachedButtonActiveTexture);
			DestroyTextureSafe(ref cachedTextFieldBackgroundTexture);
			DestroyTextureSafe(ref cachedWindowBackgroundTexture);
			cachedCogStyle = null;
			cachedLabelStyle = null;
			cachedTextFieldStyle = null;
			cachedButtonStyle = null;
			cachedToggleStyle = null;
			cachedWindowStyle = null;
		}

		internal static void LogVerbose(string message)
		{
			ConfigEntry<bool> obj = verboseLoggingConfig;
			if (obj != null && obj.Value)
			{
				ManualLogSource modLogger = ModLogger;
				if (modLogger != null)
				{
					modLogger.LogDebug((object)("[VERBOSE] " + message));
				}
			}
		}

		private void DrawSettingsCog()
		{
			//IL_008b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0070: Unknown result type (might be due to invalid IL or missing references)
			//IL_018d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0192: Unknown result type (might be due to invalid IL or missing references)
			if (showLevelGUI)
			{
				if (showSettingsGUI)
				{
					showSettingsGUI = false;
					LogVerbose("Settings window auto-closed because a round started.");
				}
				return;
			}
			float num = 32f;
			float num2 = (float)Screen.width - num - 10f;
			float num3 = 10f;
			GUIStyle val = cachedCogStyle ?? GUI.skin.button;
			if (!(((Object)(object)settingsCogTexture != (Object)null) ? GUI.Button(new Rect(num2, num3, num, num), (Texture)(object)settingsCogTexture, val) : GUI.Button(new Rect(num2, num3, num, num), "⚙", BuildFallbackCogStyle())))
			{
				return;
			}
			showSettingsGUI = !showSettingsGUI;
			LogVerbose("Settings cog clicked — settings window is now " + (showSettingsGUI ? "open" : "closed") + ".");
			if (showSettingsGUI)
			{
				tempSelectedLevel = selectedLevelConfig.Value;
				tempShowCurrentLevel = showCurrentLevelGUIConfig.Value;
				tempShowSelectedLevelConfig = showSelectedLevelConfigGUIConfig.Value;
				tempVerboseLogging = verboseLoggingConfig.Value;
				float num4 = num2 - 330f + num;
				float num5 = num3 + num + 5f;
				if (num4 < 10f)
				{
					num4 = 10f;
				}
				if (num5 + 255f > (float)Screen.height - 10f)
				{
					num5 = (float)Screen.height - 265f;
				}
				settingsWindowRect = new Rect(num4, num5, 330f, 255f);
			}
		}

		private GUIStyle BuildFallbackCogStyle()
		{
			//IL_0014: Unknown result type (might be due to invalid IL or missing references)
			//IL_001a: Expected O, but got Unknown
			//IL_0031: 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)
			GUIStyle val = new GUIStyle(cachedCogStyle ?? GUI.skin.button);
			val.fontSize = 14;
			val.fontStyle = (FontStyle)1;
			val.normal.textColor = Color.white;
			val.hover.textColor = Color.yellow;
			return val;
		}

		private void DrawSettingsWindow()
		{
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			//IL_0036: Unknown result type (might be due to invalid IL or missing references)
			//IL_0046: Unknown result type (might be due to invalid IL or missing references)
			//IL_006a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0076: Unknown result type (might be due to invalid IL or missing references)
			//IL_0086: Expected O, but got Unknown
			//IL_0081: Unknown result type (might be due to invalid IL or missing references)
			//IL_0086: Unknown result type (might be due to invalid IL or missing references)
			GUI.color = new Color(0f, 0f, 0f, 0.85f);
			GUI.Box(new Rect(0f, 0f, (float)Screen.width, (float)Screen.height), "");
			GUI.color = Color.white;
			GUIStyle val = cachedWindowStyle ?? GUI.skin.window;
			settingsWindowRect = GUI.Window(12345, settingsWindowRect, new WindowFunction(DrawSettingsWindowContents), "MorePeak Settings", val);
		}

		private void DrawSettingsWindowContents(int windowID)
		{
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			//IL_0091: Unknown result type (might be due to invalid IL or missing references)
			//IL_010c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0165: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c6: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ef: Unknown result type (might be due to invalid IL or missing references)
			//IL_0270: Unknown result type (might be due to invalid IL or missing references)
			//IL_02f1: Unknown result type (might be due to invalid IL or missing references)
			//IL_031a: Unknown result type (might be due to invalid IL or missing references)
			//IL_03ae: Unknown result type (might be due to invalid IL or missing references)
			//IL_03f6: Unknown result type (might be due to invalid IL or missing references)
			float num = 30f;
			GUIStyle val = cachedLabelStyle ?? GUI.skin.label;
			GUIStyle val2 = cachedTextFieldStyle ?? GUI.skin.textField;
			GUIStyle val3 = cachedButtonStyle ?? GUI.skin.button;
			GUIStyle val4 = cachedToggleStyle ?? GUI.skin.toggle;
			GUI.Label(new Rect(10f, num, 150f, 20f), "Selected Level:", val);
			num += 25f;
			string text = GUI.TextField(new Rect(10f, num, 150f, 20f), tempSelectedLevel, val2);
			if (text != tempSelectedLevel)
			{
				tempSelectedLevel = text;
				selectedLevelConfig.Value = tempSelectedLevel;
				((BaseUnityPlugin)this).Config.Save();
				LogVerbose("SelectedLevel updated via GUI to: '" + tempSelectedLevel + "'.");
			}
			num += 30f;
			if (GUI.Button(new Rect(10f, num, 70f, 20f), "Random", val3))
			{
				tempSelectedLevel = "Random";
				selectedLevelConfig.Value = "Random";
				((BaseUnityPlugin)this).Config.Save();
				LogVerbose("SelectedLevel set to 'Random' via quick-preset button.");
			}
			if (GUI.Button(new Rect(85f, num, 70f, 20f), "Daily", val3))
			{
				tempSelectedLevel = "Daily";
				selectedLevelConfig.Value = "Daily";
				((BaseUnityPlugin)this).Config.Save();
				LogVerbose("SelectedLevel set to 'Daily' via quick-preset button.");
			}
			num += 35f;
			GUI.Label(new Rect(10f, num, 150f, 20f), "Display Options:", val);
			num += 25f;
			bool flag = GUI.Toggle(new Rect(10f, num, 150f, 20f), tempShowCurrentLevel, "Show Current Level", val4);
			if (flag != tempShowCurrentLevel)
			{
				tempShowCurrentLevel = flag;
				showCurrentLevelGUIConfig.Value = tempShowCurrentLevel;
				((BaseUnityPlugin)this).Config.Save();
				LogVerbose($"ShowCurrentLevel toggled to {tempShowCurrentLevel} via GUI.");
			}
			num += 25f;
			bool flag2 = GUI.Toggle(new Rect(10f, num, 150f, 20f), tempShowSelectedLevelConfig, "Show Config", val4);
			if (flag2 != tempShowSelectedLevelConfig)
			{
				tempShowSelectedLevelConfig = flag2;
				showSelectedLevelConfigGUIConfig.Value = tempShowSelectedLevelConfig;
				((BaseUnityPlugin)this).Config.Save();
				LogVerbose($"ShowSelectedLevelConfig toggled to {tempShowSelectedLevelConfig} via GUI.");
			}
			num += 35f;
			GUI.Label(new Rect(10f, num, 150f, 20f), "Debug Options:", val);
			num += 25f;
			bool flag3 = GUI.Toggle(new Rect(10f, num, 150f, 20f), tempVerboseLogging, "Verbose Logging", val4);
			if (flag3 != tempVerboseLogging)
			{
				tempVerboseLogging = flag3;
				verboseLoggingConfig.Value = tempVerboseLogging;
				((BaseUnityPlugin)this).Config.Save();
				ModLogger.LogInfo((object)("[MorePeak] Verbose logging " + (tempVerboseLogging ? "enabled" : "disabled") + " via in-game settings."));
			}
			num += 35f;
			if (GUI.Button(new Rect(10f, num, 70f, 20f), "Close", val3))
			{
				showSettingsGUI = false;
				LogVerbose("Settings window closed via Close button.");
			}
			if (GUI.Button(new Rect(((Rect)(ref settingsWindowRect)).width - 25f, 5f, 20f, 20f), "X", val3))
			{
				showSettingsGUI = false;
				LogVerbose("Settings window closed via X button.");
			}
			GUI.DragWindow();
		}

		private void LoadSettingsCogTexture()
		{
			//IL_00b2: Unknown result type (might be due to invalid IL or missing references)
			//IL_0070: Unknown result type (might be due to invalid IL or missing references)
			//IL_0036: Unknown result type (might be due to invalid IL or missing references)
			//IL_0040: Expected O, but got Unknown
			try
			{
				using Stream stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("MorePeak.assets.settings-cog.png");
				if (stream != null)
				{
					byte[] array = new byte[stream.Length];
					stream.Read(array, 0, array.Length);
					settingsCogTexture = new Texture2D(2, 2);
					ImageConversion.LoadImage(settingsCogTexture, array);
					LogVerbose("settings-cog.png loaded from embedded resources.");
				}
				else
				{
					ModLogger.LogWarning((object)"[MorePeak] Embedded resource 'MorePeak.assets.settings-cog.png' not found — using fallback grey square.");
					settingsCogTexture = MakeTexture(32, 32, Color.gray);
				}
			}
			catch (Exception ex)
			{
				ModLogger.LogError((object)("[MorePeak] Failed to load settings-cog texture: " + ex.Message));
				settingsCogTexture = MakeTexture(32, 32, Color.gray);
			}
		}

		private void InitializeCachedStyles()
		{
			//IL_0018: Unknown result type (might be due to invalid IL or missing references)
			//IL_003e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0064: Unknown result type (might be due to invalid IL or missing references)
			//IL_008a: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ef: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f4: Unknown result type (might be due to invalid IL or missing references)
			//IL_0105: Unknown result type (might be due to invalid IL or missing references)
			//IL_0116: Unknown result type (might be due to invalid IL or missing references)
			//IL_012c: Expected O, but got Unknown
			//IL_0136: Unknown result type (might be due to invalid IL or missing references)
			//IL_013b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0144: Unknown result type (might be due to invalid IL or missing references)
			//IL_014c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0152: Unknown result type (might be due to invalid IL or missing references)
			//IL_0162: Expected O, but got Unknown
			//IL_016c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0171: Unknown result type (might be due to invalid IL or missing references)
			//IL_017a: Unknown result type (might be due to invalid IL or missing references)
			//IL_018b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0191: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a1: Expected O, but got Unknown
			//IL_01ab: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b0: 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)
			//IL_01ca: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d0: Unknown result type (might be due to invalid IL or missing references)
			//IL_01db: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ec: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f2: Unknown result type (might be due to invalid IL or missing references)
			//IL_0202: Expected O, but got Unknown
			//IL_020c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0211: Unknown result type (might be due to invalid IL or missing references)
			//IL_021a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0220: Unknown result type (might be due to invalid IL or missing references)
			//IL_0230: Expected O, but got Unknown
			//IL_023a: Unknown result type (might be due to invalid IL or missing references)
			//IL_023f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0248: Unknown result type (might be due to invalid IL or missing references)
			//IL_0259: Unknown result type (might be due to invalid IL or missing references)
			//IL_026f: Expected O, but got Unknown
			cachedDarkBackgroundTexture = MakeTexture(2, 2, new Color(0f, 0f, 0f, 0.7f));
			cachedButtonBackgroundTexture = MakeTexture(2, 2, new Color(0.2f, 0.2f, 0.2f, 0.8f));
			cachedButtonHoverTexture = MakeTexture(2, 2, new Color(0.3f, 0.3f, 0.3f, 0.9f));
			cachedButtonActiveTexture = MakeTexture(2, 2, new Color(0.4f, 0.4f, 0.4f, 0.9f));
			cachedTextFieldBackgroundTexture = MakeTexture(2, 2, new Color(0.2f, 0.2f, 0.2f, 0.9f));
			cachedWindowBackgroundTexture = MakeTexture(2, 2, new Color(0.1f, 0.1f, 0.1f, 0.95f));
			GUIStyle val = new GUIStyle(GUI.skin.button);
			val.normal.background = cachedButtonBackgroundTexture;
			val.hover.background = cachedButtonHoverTexture;
			val.active.background = cachedButtonActiveTexture;
			cachedCogStyle = val;
			GUIStyle val2 = new GUIStyle(GUI.skin.label)
			{
				fontSize = 12,
				wordWrap = true
			};
			val2.normal.textColor = Color.white;
			cachedLabelStyle = val2;
			GUIStyle val3 = new GUIStyle(GUI.skin.textField)
			{
				fontSize = 12
			};
			val3.normal.background = cachedTextFieldBackgroundTexture;
			val3.normal.textColor = Color.white;
			cachedTextFieldStyle = val3;
			GUIStyle val4 = new GUIStyle(GUI.skin.button)
			{
				fontSize = 12
			};
			val4.normal.background = cachedButtonBackgroundTexture;
			val4.normal.textColor = Color.white;
			val4.hover.background = cachedButtonHoverTexture;
			val4.hover.textColor = Color.yellow;
			cachedButtonStyle = val4;
			GUIStyle val5 = new GUIStyle(GUI.skin.toggle)
			{
				fontSize = 12
			};
			val5.normal.textColor = Color.white;
			cachedToggleStyle = val5;
			GUIStyle val6 = new GUIStyle(GUI.skin.window)
			{
				fontSize = 14
			};
			val6.normal.background = cachedWindowBackgroundTexture;
			val6.onNormal.background = cachedWindowBackgroundTexture;
			cachedWindowStyle = val6;
			LogVerbose("Cached GUI styles and textures initialised.");
		}

		private Texture2D MakeTexture(int width, int height, Color color)
		{
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_0026: Unknown result type (might be due to invalid IL or missing references)
			//IL_002c: Expected O, but got Unknown
			Color[] array = (Color[])(object)new Color[width * height];
			for (int i = 0; i < array.Length; i++)
			{
				array[i] = color;
			}
			Texture2D val = new Texture2D(width, height);
			val.SetPixels(array);
			val.Apply();
			return val;
		}

		private static void DestroyTextureSafe(ref Texture2D texture)
		{
			if ((Object)(object)texture != (Object)null)
			{
				Object.DestroyImmediate((Object)(object)texture);
				texture = null;
			}
		}
	}
	public static class MyPluginInfo
	{
		public const string PLUGIN_GUID = "MorePeak";

		public const string PLUGIN_NAME = "MorePeak";

		public const string PLUGIN_VERSION = "1.0.0";
	}
}
namespace MorePeak.MonoBehaviours
{
	internal sealed class MorePeakHUD : MonoBehaviour
	{
		private TMP_Text tmpText;

		private string lastDisplayedText = null;

		private bool lastEnabledState = false;

		private bool hasLoggedFirstDisplay = false;

		private void Start()
		{
			//IL_006b: Unknown result type (might be due to invalid IL or missing references)
			tmpText = ((Component)this).GetComponent<TMP_Text>();
			if ((Object)(object)tmpText == (Object)null)
			{
				MorePeakPlugin.ModLogger.LogError((object)"[MorePeak] MorePeakHUD: no TMP_Text component found on its GameObject. The HUD will be non-functional. This likely means the AscentUI clone did not carry a TextMeshProUGUI component — check whether AscentUI's layout changed.");
				((Behaviour)this).enabled = false;
				return;
			}
			tmpText.fontSize = 24f;
			tmpText.alignment = (TextAlignmentOptions)260;
			tmpText.outlineColor = new Color32((byte)0, (byte)0, (byte)0, byte.MaxValue);
			tmpText.outlineWidth = 0.055f;
			tmpText.autoSizeTextContainer = true;
			((Behaviour)tmpText).enabled = false;
			lastEnabledState = false;
			MorePeakPlugin.ModLogger.LogInfo((object)("[MorePeak] MorePeakHUD ready on '" + ((Object)((Component)this).gameObject).name + "' " + $"(ShowCurrentLevel={MorePeakPlugin.showCurrentLevelGUIConfig.Value}, " + $"ShowConfig={MorePeakPlugin.showSelectedLevelConfigGUIConfig.Value})."));
			MorePeakPlugin.LogVerbose("MorePeakHUD.Start complete — TMP_Text found and styled.");
		}

		private void Update()
		{
			if ((Object)(object)tmpText == (Object)null)
			{
				return;
			}
			try
			{
				List<string> list = new List<string>(2);
				if (MorePeakPlugin.showCurrentLevelGUIConfig.Value && !string.IsNullOrEmpty(MorePeakPlugin.currentLevelName))
				{
					list.Add("Current Level: " + MorePeakPlugin.currentLevelName);
				}
				if (MorePeakPlugin.showSelectedLevelConfigGUIConfig.Value)
				{
					list.Add("Config: " + MorePeakPlugin.selectedLevelConfig.Value);
				}
				bool flag = list.Count > 0;
				string text = (flag ? string.Join("\n", list) : string.Empty);
				if (flag != lastEnabledState)
				{
					((Behaviour)tmpText).enabled = flag;
					lastEnabledState = flag;
					MorePeakPlugin.LogVerbose($"MorePeakHUD visibility changed to {flag} " + "(currentLevel='" + MorePeakPlugin.currentLevelName + "').");
				}
				if (flag && text != lastDisplayedText)
				{
					tmpText.text = text;
					lastDisplayedText = text;
					if (!hasLoggedFirstDisplay)
					{
						MorePeakPlugin.ModLogger.LogInfo((object)("[MorePeak] HUD displaying: \"" + text + "\""));
						hasLoggedFirstDisplay = true;
					}
					else
					{
						MorePeakPlugin.LogVerbose("MorePeakHUD text updated to: \"" + text + "\".");
					}
				}
				if (!flag && hasLoggedFirstDisplay)
				{
					hasLoggedFirstDisplay = false;
					lastDisplayedText = null;
					MorePeakPlugin.LogVerbose("MorePeakHUD content cleared (no lines to display).");
				}
			}
			catch (Exception arg)
			{
				MorePeakPlugin.ModLogger.LogError((object)$"[MorePeak] Exception in MorePeakHUD.Update: {arg}");
			}
		}
	}
}