Decompiled source of Equal Interiors v1.5.0

BepInEx/plugins/EqualInteriors/EqualInteriors.dll

Decompiled an hour ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Text;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using DunGen;
using DunGen.Graph;
using HarmonyLib;
using LethalConfig;
using LethalConfig.ConfigItems;
using LethalConfig.ConfigItems.Options;
using LethalLevelLoader;
using Microsoft.CodeAnalysis;
using TMPro;
using Unity.Netcode;
using UnityEngine;
using UnityEngine.UI;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("EqualInteriors")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.5.0.0")]
[assembly: AssemblyInformationalVersion("1.5.0")]
[assembly: AssemblyProduct("EqualInteriors")]
[assembly: AssemblyTitle("EqualInteriors")]
[assembly: AssemblyVersion("1.5.0.0")]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

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

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

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

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace EqualInteriors
{
	internal static class ConfigMenu
	{
		[CompilerGenerated]
		private static class <>O
		{
			public static CanModifyDelegate <0>__CanChangePool;
		}

		internal static void Initialize(ConfigEntry<bool> enabled)
		{
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			//IL_0020: Unknown result type (might be due to invalid IL or missing references)
			//IL_002b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0032: Unknown result type (might be due to invalid IL or missing references)
			//IL_0058: Expected O, but got Unknown
			//IL_0053: Unknown result type (might be due to invalid IL or missing references)
			//IL_005d: Expected O, but got Unknown
			//IL_0043: Unknown result type (might be due to invalid IL or missing references)
			//IL_0048: Unknown result type (might be due to invalid IL or missing references)
			//IL_004e: Expected O, but got Unknown
			LethalConfigManager.SkipAutoGen();
			LethalConfigManager.SetModDescription("Equal chances on every playable moon. Check interiors to allow them; uncheck to disable them. Configure extra scrap and size-based loot density under Loot, and the local loading bar under Loading Screen. The host controls interior selection and loot. Apply gameplay changes in orbit for the next landing. Host or join once to populate all installed modded interiors.");
			BoolCheckBoxOptions val = new BoolCheckBoxOptions
			{
				Name = "Enable Equal Interiors",
				Section = "General",
				RequiresRestart = false
			};
			object obj = <>O.<0>__CanChangePool;
			if (obj == null)
			{
				CanModifyDelegate val2 = CanChangePool;
				<>O.<0>__CanChangePool = val2;
				obj = (object)val2;
			}
			((BaseOptions)val).CanModifyCallback = (CanModifyDelegate)obj;
			LethalConfigManager.AddConfigItem((BaseConfigItem)new BoolCheckBoxConfigItem(enabled, val));
		}

		internal static void AddLoadingBar(ConfigEntry<bool> entry)
		{
			//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)
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_001c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0028: Expected O, but got Unknown
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			//IL_002d: Expected O, but got Unknown
			LethalConfigManager.AddConfigItem((BaseConfigItem)new BoolCheckBoxConfigItem(entry, new BoolCheckBoxOptions
			{
				Name = "Show loading bar",
				Section = "Loading Screen",
				RequiresRestart = false
			}));
		}

		internal static void AddInterior(ConfigEntry<bool> entry, string flowName, string displayName)
		{
			//IL_007d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0082: Unknown result type (might be due to invalid IL or missing references)
			//IL_0089: Unknown result type (might be due to invalid IL or missing references)
			//IL_009e: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bb: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e1: Expected O, but got Unknown
			//IL_00dc: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e6: Expected O, but got Unknown
			//IL_00cc: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d7: Expected O, but got Unknown
			bool flag = true;
			string text;
			switch (flowName)
			{
			case "Level1Flow":
				text = "Facility";
				break;
			case "Level2Flow":
				text = "Mansion";
				break;
			case "Level3Flow":
				text = "Mineshaft";
				break;
			case "Level1Flow3Exits":
				text = "Facility (three exits)";
				break;
			case "Level1FlowExtraLarge":
				text = "Facility (extra large)";
				break;
			default:
				text = (string.IsNullOrWhiteSpace(displayName) ? flowName : displayName);
				flag = false;
				break;
			}
			BoolCheckBoxOptions val = new BoolCheckBoxOptions
			{
				Name = text,
				Section = (flag ? "Vanilla interiors" : "Modded interiors"),
				Description = "Checked: allow " + text + " on every playable moon. Unchecked: disable it. All checked interiors have equal chances. Keep at least one checked.",
				RequiresRestart = false
			};
			object obj = <>O.<0>__CanChangePool;
			if (obj == null)
			{
				CanModifyDelegate val2 = CanChangePool;
				<>O.<0>__CanChangePool = val2;
				obj = (object)val2;
			}
			((BaseOptions)val).CanModifyCallback = (CanModifyDelegate)obj;
			LethalConfigManager.AddConfigItem((BaseConfigItem)new BoolCheckBoxConfigItem(entry, val));
		}

		internal static void AddVanillaEntries(InteriorSettings settings)
		{
			settings.GetOrCreate("Level1Flow", "Facility");
			settings.GetOrCreate("Level2Flow", "Haunted Mansion");
			settings.GetOrCreate("Level3Flow", "Mineshaft");
			settings.GetOrCreate("Level1Flow3Exits", "Facility3Exits");
			settings.GetOrCreate("Level1FlowExtraLarge", "FacilityExtraLarge");
		}

		private static CanModifyResult CanChangePool()
		{
			//IL_002a: 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)
			StartOfRound instance = StartOfRound.Instance;
			if ((Object)(object)instance != (Object)null && (!instance.inShipPhase || instance.beganLoadingNewLevel))
			{
				return CanModifyResult.False("Return to orbit before changing the interior pool.");
			}
			return CanModifyResult.True();
		}
	}
	internal sealed class InteriorSettings
	{
		private readonly ConfigFile config;

		private readonly Func<string> legacyExclusions;

		private readonly Action<ConfigEntry<bool>, string, string>? onCreated;

		private readonly Dictionary<string, ConfigEntry<bool>> entries = new Dictionary<string, ConfigEntry<bool>>(StringComparer.Ordinal);

		internal int Count => entries.Count;

		internal InteriorSettings(ConfigFile config, Func<string> legacyExclusions, Action<ConfigEntry<bool>, string, string>? onCreated = null)
		{
			this.config = config;
			this.legacyExclusions = legacyExclusions;
			this.onCreated = onCreated;
		}

		internal ConfigEntry<bool> GetOrCreate(string flowName, string displayName)
		{
			if (entries.TryGetValue(flowName, out ConfigEntry<bool> value))
			{
				return value;
			}
			bool flag = !IsFacilityVariant(flowName) && !IsLegacyExcluded(flowName, displayName, legacyExclusions());
			value = config.Bind<bool>("Interiors", GetConfigKey(flowName), flag, displayName + " (" + flowName + "). True: allow on every playable moon. False: disable spawning. Enabled interiors have equal chances. Keep at least one enabled.");
			entries.Add(flowName, value);
			onCreated?.Invoke(value, flowName, displayName);
			return value;
		}

		private static bool IsFacilityVariant(string flowName)
		{
			if (!(flowName == "Level1FlowExtraLarge"))
			{
				return flowName == "Level1Flow3Exits";
			}
			return true;
		}

		private static bool IsLegacyExcluded(string flowName, string displayName, string exclusions)
		{
			string[] array = (exclusions ?? string.Empty).Split(',');
			for (int i = 0; i < array.Length; i++)
			{
				string text = array[i].Trim();
				if (text.Length > 0 && (string.Equals(text, flowName, StringComparison.OrdinalIgnoreCase) || string.Equals(text, displayName, StringComparison.OrdinalIgnoreCase)))
				{
					return true;
				}
			}
			return false;
		}

		internal static string GetConfigKey(string flowName)
		{
			StringBuilder stringBuilder = new StringBuilder();
			foreach (char c in flowName)
			{
				if (char.IsLetterOrDigit(c) || c == '_' || c == '-' || c == '.')
				{
					stringBuilder.Append(c);
					continue;
				}
				StringBuilder stringBuilder2 = stringBuilder.Append('%');
				int num = c;
				stringBuilder2.Append(num.ToString("X4", CultureInfo.InvariantCulture));
			}
			return stringBuilder.ToString();
		}
	}
	internal sealed class LegacyExclusionMigration
	{
		private readonly ConfigFile config;

		private bool complete;

		internal ConfigEntry<string> Entry { get; }

		internal LegacyExclusionMigration(ConfigFile config)
		{
			this.config = config;
			Entry = config.Bind<string>("General", "ExcludedInteriors", string.Empty, "Retired setting. Automatically migrated to individual interior checkboxes when the lobby loads.");
		}

		internal void CompleteIfReady(bool registryReady)
		{
			//IL_002e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0038: Expected O, but got Unknown
			if (!complete && (registryReady || string.IsNullOrWhiteSpace(Entry.Value)))
			{
				config.Remove(new ConfigDefinition("General", "ExcludedInteriors"));
				config.Save();
				complete = true;
			}
		}
	}
	internal enum LoadingStage
	{
		None,
		Scene,
		SceneCrew,
		Interior,
		Finalizing,
		Crew,
		Ready,
		Failed
	}
	internal enum InteriorPhase
	{
		Preparing,
		MainPath,
		Branches,
		PlacingRooms,
		PostProcessing
	}
	internal sealed class LoadingProgress
	{
		private double startedAt;

		private double endedAt;

		internal LoadingStage Stage { get; private set; }

		internal float Progress { get; private set; }

		internal string Title { get; private set; } = string.Empty;

		internal int Attempt { get; private set; }

		internal bool LocalInteriorReady { get; private set; }

		internal bool Active => Stage != LoadingStage.None;

		internal bool Terminal
		{
			get
			{
				if (Stage != LoadingStage.Ready)
				{
					return Stage == LoadingStage.Failed;
				}
				return true;
			}
		}

		internal void Begin(double now)
		{
			Reset();
			startedAt = now;
			Set(LoadingStage.Scene, 0.02f, "LOADING MOON");
		}

		internal void SceneProgress(float fraction)
		{
			if (Stage == LoadingStage.Scene && !float.IsNaN(fraction))
			{
				Progress = Math.Max(Progress, 0.02f + 0.23f * Math.Max(0f, Math.Min(1f, fraction)));
			}
		}

		internal void SceneLoaded()
		{
			if (Stage == LoadingStage.Scene)
			{
				Set(LoadingStage.SceneCrew, 0.25f, "WAITING FOR CREW TO LOAD MOON");
			}
		}

		internal void Generating(InteriorPhase phase)
		{
			if (Active && !Terminal && !LocalInteriorReady && Stage != LoadingStage.Finalizing)
			{
				Attempt = Math.Max(1, Attempt);
				switch (phase)
				{
				case InteriorPhase.MainPath:
					Set(LoadingStage.Interior, 0.4f, "BUILDING CORRIDORS");
					break;
				case InteriorPhase.Branches:
					Set(LoadingStage.Interior, 0.55f, "ADDING SIDE ROOMS");
					break;
				case InteriorPhase.PlacingRooms:
					Set(LoadingStage.Interior, 0.68f, "PLACING INTERIOR ROOMS");
					break;
				case InteriorPhase.PostProcessing:
					Set(LoadingStage.Interior, 0.78f, "FINISHING INTERIOR");
					break;
				default:
					Set(LoadingStage.Interior, 0.3f, "PREPARING INTERIOR");
					break;
				}
			}
		}

		internal void Retrying()
		{
			if (Active && !Terminal && !LocalInteriorReady && Stage != LoadingStage.Finalizing)
			{
				Attempt = Math.Max(1, Attempt) + 1;
				Set(LoadingStage.Interior, 0.3f, "RETRYING INTERIOR GENERATION");
			}
		}

		internal void Finalizing(bool placingObjects = false)
		{
			if (Active && !Terminal)
			{
				Set(LoadingStage.Finalizing, placingObjects ? 0.96f : 0.85f, placingObjects ? "PLACING LOOT AND OBJECTS" : "PREPARING LEVEL AND ENEMY PATHS");
			}
		}

		internal void LocalFinished()
		{
			if (Active && !Terminal)
			{
				LocalInteriorReady = true;
				Set(LoadingStage.Crew, 0.92f, "WAITING FOR CREW AND HOST");
			}
		}

		internal void Ready(double now)
		{
			if (Active && !Terminal)
			{
				endedAt = now;
				Set(LoadingStage.Ready, 1f, "READY TO LAND");
			}
		}

		internal void Failed(double now)
		{
			if (Active && !Terminal)
			{
				endedAt = now;
				Set(LoadingStage.Failed, Progress, "INTERIOR GENERATION FAILED");
			}
		}

		internal double Elapsed(double now)
		{
			if (!Active)
			{
				return 0.0;
			}
			return Math.Max(0.0, (Terminal ? endedAt : now) - startedAt);
		}

		internal bool CompletionExpired(double now)
		{
			if (Stage == LoadingStage.Ready)
			{
				return now - endedAt >= 1.25;
			}
			return false;
		}

		internal void Reset()
		{
			Stage = LoadingStage.None;
			Progress = 0f;
			Title = string.Empty;
			Attempt = 0;
			LocalInteriorReady = false;
			startedAt = (endedAt = 0.0);
		}

		private void Set(LoadingStage stage, float progress, string title)
		{
			Stage = stage;
			Progress = progress;
			Title = title;
		}
	}
	internal static class LoadingScreen
	{
		[HarmonyPatch(typeof(StartOfRound), "SceneManager_OnLoad")]
		private static class SceneBeginPatch
		{
			[HarmonyPostfix]
			private static void Postfix(StartOfRound __instance, ulong clientId, string sceneName, AsyncOperation asyncOperation)
			{
				Guard(delegate
				{
					Begin(__instance, clientId, sceneName, asyncOperation);
				});
			}
		}

		[HarmonyPatch(typeof(StartOfRound), "SceneManager_OnLoadComplete1")]
		private static class SceneCompletePatch
		{
			[HarmonyPostfix]
			private static void Postfix(StartOfRound __instance, ulong clientId, string sceneName)
			{
				Guard(delegate
				{
					if ((Object)(object)session == (Object)(object)__instance && (Object)(object)NetworkManager.Singleton != (Object)null && clientId == NetworkManager.Singleton.LocalClientId && (Object)(object)__instance.currentLevel != (Object)null && sceneName == __instance.currentLevel.sceneName)
					{
						progress.SceneLoaded();
					}
				});
			}
		}

		[HarmonyPatch(typeof(RoundManager), "FinishGeneratingLevel")]
		private static class FinalizePatch
		{
			[HarmonyPrefix]
			[HarmonyPriority(800)]
			private static void Prefix()
			{
				Guard(delegate
				{
					progress.Finalizing();
				});
			}

			[HarmonyPostfix]
			[HarmonyPriority(0)]
			private static void Postfix()
			{
				Guard(progress.LocalFinished);
			}
		}

		[HarmonyPatch(typeof(RoundManager), "GeneratedFloorPostProcessing")]
		private static class PlaceObjectsPatch
		{
			[HarmonyPrefix]
			private static void Prefix()
			{
				Guard(delegate
				{
					progress.Finalizing(placingObjects: true);
				});
			}
		}

		[HarmonyPatch(typeof(StartOfRound), "openingDoorsSequence")]
		private static class ReadyPatch
		{
			[HarmonyPostfix]
			private static void Postfix(StartOfRound __instance)
			{
				Guard(delegate
				{
					if ((Object)(object)session == (Object)(object)__instance)
					{
						progress.Ready(Now);
					}
				});
			}
		}

		[HarmonyPatch(typeof(StartOfRound), "OnDisable")]
		private static class CancelPatch
		{
			[HarmonyPostfix]
			private static void Postfix(StartOfRound __instance)
			{
				Guard(delegate
				{
					if ((Object)(object)session == (Object)(object)__instance)
					{
						Cancel();
					}
				});
			}
		}

		[CompilerGenerated]
		private static class <>O
		{
			public static DungeonGenerationDelegate <0>__DungeonStarted;

			public static GenerationStatusDelegate <1>__DungeonStatus;

			public static Action <2>__DungeonRetrying;
		}

		private static readonly LoadingProgress progress = new LoadingProgress();

		private static Harmony? patches;

		private static StartOfRound? session;

		private static AsyncOperation? sceneOperation;

		private static DungeonGenerator? watchedGenerator;

		private static LoadingView? view;

		private static bool faulted;

		private static double nextRefresh;

		private static double Now => Time.realtimeSinceStartupAsDouble;

		internal static void Initialize()
		{
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			//IL_000f: Expected O, but got Unknown
			//IL_0097: Unknown result type (might be due to invalid IL or missing references)
			//IL_009c: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a2: Expected O, but got Unknown
			//IL_00b7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bc: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c2: Expected O, but got Unknown
			try
			{
				patches = new Harmony("sockpoop.equalinteriors.loading");
				patches.PatchAll(typeof(SceneBeginPatch));
				patches.PatchAll(typeof(SceneCompletePatch));
				patches.PatchAll(typeof(FinalizePatch));
				patches.PatchAll(typeof(PlaceObjectsPatch));
				patches.PatchAll(typeof(ReadyPatch));
				patches.PatchAll(typeof(CancelPatch));
				object obj = <>O.<0>__DungeonStarted;
				if (obj == null)
				{
					DungeonGenerationDelegate val = DungeonStarted;
					<>O.<0>__DungeonStarted = val;
					obj = (object)val;
				}
				DungeonGenerator.OnAnyDungeonGenerationStarted += (DungeonGenerationDelegate)obj;
				object obj2 = <>O.<1>__DungeonStatus;
				if (obj2 == null)
				{
					GenerationStatusDelegate val2 = DungeonStatus;
					<>O.<1>__DungeonStatus = val2;
					obj2 = (object)val2;
				}
				DungeonGenerator.OnAnyDungeonGenerationStatusChanged += (GenerationStatusDelegate)obj2;
			}
			catch (Exception exception)
			{
				Harmony? obj3 = patches;
				if (obj3 != null)
				{
					obj3.UnpatchSelf();
				}
				DisableAfterError(exception);
			}
		}

		internal static void Shutdown()
		{
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			//IL_001b: Expected O, but got Unknown
			//IL_0030: Unknown result type (might be due to invalid IL or missing references)
			//IL_0035: Unknown result type (might be due to invalid IL or missing references)
			//IL_003b: Expected O, but got Unknown
			object obj = <>O.<0>__DungeonStarted;
			if (obj == null)
			{
				DungeonGenerationDelegate val = DungeonStarted;
				<>O.<0>__DungeonStarted = val;
				obj = (object)val;
			}
			DungeonGenerator.OnAnyDungeonGenerationStarted -= (DungeonGenerationDelegate)obj;
			object obj2 = <>O.<1>__DungeonStatus;
			if (obj2 == null)
			{
				GenerationStatusDelegate val2 = DungeonStatus;
				<>O.<1>__DungeonStatus = val2;
				obj2 = (object)val2;
			}
			DungeonGenerator.OnAnyDungeonGenerationStatusChanged -= (GenerationStatusDelegate)obj2;
			Unwatch();
			Harmony? obj3 = patches;
			if (obj3 != null)
			{
				obj3.UnpatchSelf();
			}
			patches = null;
			view?.Dispose();
			view = null;
			progress.Reset();
			session = null;
			sceneOperation = null;
		}

		internal static void Tick()
		{
			if (faulted)
			{
				return;
			}
			try
			{
				if (!progress.Active)
				{
					view?.Hide();
					return;
				}
				NetworkManager singleton = NetworkManager.Singleton;
				if ((Object)(object)session == (Object)null || (Object)(object)session != (Object)(object)StartOfRound.Instance || (Object)(object)singleton == (Object)null || !singleton.IsListening || singleton.ShutdownInProgress || progress.CompletionExpired(Now))
				{
					Cancel();
					return;
				}
				if (sceneOperation != null && progress.Stage == LoadingStage.Scene)
				{
					progress.SceneProgress(sceneOperation.progress / 0.9f);
					if (sceneOperation.isDone)
					{
						progress.SceneLoaded();
					}
				}
				if (!session.inShipPhase && !session.beganLoadingNewLevel && !progress.Terminal)
				{
					progress.Ready(Now);
				}
				if (!Plugin.ShowLoadingBar.Value)
				{
					view?.Hide();
				}
				else
				{
					if (Now < nextRefresh)
					{
						return;
					}
					nextRefresh = Now + 0.1;
					HUDManager instance = HUDManager.Instance;
					if (!((Object)(object)instance == (Object)null) && !((Object)(object)instance.loadingText == (Object)null) && !((Object)(object)((TMP_Text)instance.loadingText).font == (Object)null))
					{
						if (view == null || !view.IsAlive)
						{
							view?.Dispose();
							view = new LoadingView(((TMP_Text)instance.loadingText).font);
						}
						int num = (int)progress.Elapsed(Now);
						string text = (num / 60).ToString("00", CultureInfo.InvariantCulture) + ":" + (num % 60).ToString("00", CultureInfo.InvariantCulture) + " elapsed";
						if (progress.Attempt > 1)
						{
							text = text + "  |  Attempt " + progress.Attempt;
						}
						string text2 = CrewDetail();
						if (text2.Length > 0)
						{
							text = text + "  |  " + text2;
						}
						if (progress.Stage == LoadingStage.Failed)
						{
							text += "  |  Check the game log";
						}
						view.Show(progress.Progress, progress.Title, text, progress.Stage == LoadingStage.Failed);
					}
				}
			}
			catch (Exception exception)
			{
				DisableAfterError(exception);
			}
		}

		private static string CrewDetail()
		{
			if ((Object)(object)session == (Object)null)
			{
				return string.Empty;
			}
			int expected = Math.Max(1, ((Object)(object)GameNetworkManager.Instance != (Object)null) ? GameNetworkManager.Instance.connectedPlayers : (session.connectedPlayersAmount + 1));
			if (progress.Stage == LoadingStage.SceneCrew)
			{
				return ReadyCount(session.fullyLoadedPlayers, expected) + " crew loaded";
			}
			if (progress.Stage == LoadingStage.Crew)
			{
				RoundManager instance = RoundManager.Instance;
				if ((Object)(object)instance != (Object)null && ((NetworkBehaviour)instance).IsServer)
				{
					return ReadyCount(instance.playersFinishedGeneratingFloor, expected) + " interiors ready";
				}
				return "Your interior is ready";
			}
			return string.Empty;
		}

		private static string ReadyCount(List<ulong> ids, int expected)
		{
			return Math.Min(new HashSet<ulong>(ids).Count, expected) + "/" + expected;
		}

		private static void Begin(StartOfRound round, ulong clientId, string sceneName, AsyncOperation operation)
		{
			NetworkManager singleton = NetworkManager.Singleton;
			if (!((Object)(object)singleton == (Object)null) && clientId == singleton.LocalClientId && !((Object)(object)round.currentLevel == (Object)null) && !(sceneName != round.currentLevel.sceneName) && (round.inShipPhase || round.beganLoadingNewLevel) && (!((Object)(object)session == (Object)(object)round) || !progress.Active || sceneOperation != operation))
			{
				Unwatch();
				session = round;
				sceneOperation = operation;
				nextRefresh = 0.0;
				progress.Begin(Now);
			}
		}

		private static bool IsMainGenerator(DungeonGenerator generator)
		{
			RoundManager instance = RoundManager.Instance;
			if (progress.Active && !progress.Terminal && (Object)(object)session != (Object)null && (Object)(object)instance != (Object)null && (Object)(object)instance.dungeonGenerator != (Object)null)
			{
				return instance.dungeonGenerator.Generator == generator;
			}
			return false;
		}

		private static void Watch(DungeonGenerator generator)
		{
			if (watchedGenerator != generator)
			{
				Unwatch();
				watchedGenerator = generator;
				watchedGenerator.Retrying += DungeonRetrying;
			}
		}

		private static void Unwatch()
		{
			if (watchedGenerator != null)
			{
				watchedGenerator.Retrying -= DungeonRetrying;
			}
			watchedGenerator = null;
		}

		private static void DungeonStarted(DungeonGenerator generator)
		{
			Guard(delegate
			{
				if (IsMainGenerator(generator))
				{
					Watch(generator);
					progress.Generating(InteriorPhase.Preparing);
				}
			});
		}

		private static void DungeonRetrying()
		{
			Guard(progress.Retrying);
		}

		private static void DungeonStatus(DungeonGenerator generator, GenerationStatus status)
		{
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			Guard(delegate
			{
				//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_0020: Unknown result type (might be due to invalid IL or missing references)
				//IL_0022: Unknown result type (might be due to invalid IL or missing references)
				//IL_004c: Expected I4, but got Unknown
				if (IsMainGenerator(generator))
				{
					Watch(generator);
					GenerationStatus val = status;
					switch (val - 1)
					{
					case 0:
					case 1:
						progress.Generating(InteriorPhase.Preparing);
						break;
					case 2:
						progress.Generating(InteriorPhase.MainPath);
						break;
					case 3:
					case 4:
						progress.Generating(InteriorPhase.Branches);
						break;
					case 5:
						progress.Generating(InteriorPhase.PlacingRooms);
						break;
					case 6:
						progress.Generating(InteriorPhase.PostProcessing);
						break;
					case 7:
						if (!progress.LocalInteriorReady)
						{
							progress.Finalizing();
						}
						break;
					case 8:
						progress.Failed(Now);
						break;
					}
				}
			});
		}

		private static void Cancel()
		{
			Unwatch();
			progress.Reset();
			session = null;
			sceneOperation = null;
			view?.Hide();
		}

		private static void Guard(Action action)
		{
			if (faulted)
			{
				return;
			}
			try
			{
				action();
			}
			catch (Exception exception)
			{
				DisableAfterError(exception);
			}
		}

		private static void DisableAfterError(Exception exception)
		{
			if (!faulted)
			{
				faulted = true;
				Plugin.Log.LogError((object)("Loading display disabled after an error; interior selection remains active. " + exception));
				progress.Reset();
				Unwatch();
				view?.Hide();
			}
		}
	}
	internal sealed class LoadingView : IDisposable
	{
		private readonly GameObject root;

		private readonly Canvas canvas;

		private readonly Image fill;

		private readonly TMP_Text heading;

		private readonly TMP_Text detail;

		private static readonly Color Accent = new Color(1f, 0.53f, 0.18f, 1f);

		internal bool IsAlive => (Object)(object)root != (Object)null;

		internal LoadingView(TMP_FontAsset font)
		{
			//IL_0039: Unknown result type (might be due to invalid IL or missing references)
			//IL_0043: Expected O, but got Unknown
			//IL_00a4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f7: Unknown result type (might be due to invalid IL or missing references)
			//IL_0106: Unknown result type (might be due to invalid IL or missing references)
			//IL_0126: Unknown result type (might be due to invalid IL or missing references)
			//IL_0141: Unknown result type (might be due to invalid IL or missing references)
			//IL_0150: Unknown result type (might be due to invalid IL or missing references)
			//IL_0155: Unknown result type (might be due to invalid IL or missing references)
			//IL_0164: Unknown result type (might be due to invalid IL or missing references)
			//IL_016e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0190: Unknown result type (might be due to invalid IL or missing references)
			//IL_019f: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c5: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d4: Unknown result type (might be due to invalid IL or missing references)
			//IL_01fd: Unknown result type (might be due to invalid IL or missing references)
			//IL_020d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0212: Unknown result type (might be due to invalid IL or missing references)
			//IL_0221: Unknown result type (might be due to invalid IL or missing references)
			//IL_0230: Unknown result type (might be due to invalid IL or missing references)
			//IL_0250: Unknown result type (might be due to invalid IL or missing references)
			//IL_0261: Unknown result type (might be due to invalid IL or missing references)
			//IL_0266: Unknown result type (might be due to invalid IL or missing references)
			//IL_026b: Unknown result type (might be due to invalid IL or missing references)
			//IL_027a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0287: Unknown result type (might be due to invalid IL or missing references)
			//IL_02b9: Unknown result type (might be due to invalid IL or missing references)
			//IL_02be: Unknown result type (might be due to invalid IL or missing references)
			//IL_02d0: Unknown result type (might be due to invalid IL or missing references)
			//IL_02df: Unknown result type (might be due to invalid IL or missing references)
			//IL_02fd: Unknown result type (might be due to invalid IL or missing references)
			root = new GameObject("EqualInteriors.LoadingBar", new Type[3]
			{
				typeof(RectTransform),
				typeof(Canvas),
				typeof(CanvasScaler)
			});
			Object.DontDestroyOnLoad((Object)(object)root);
			canvas = root.GetComponent<Canvas>();
			canvas.renderMode = (RenderMode)0;
			canvas.sortingOrder = 5000;
			((Behaviour)canvas).enabled = false;
			CanvasScaler component = root.GetComponent<CanvasScaler>();
			component.uiScaleMode = (ScaleMode)1;
			component.referenceResolution = new Vector2(1920f, 1080f);
			component.screenMatchMode = (ScreenMatchMode)0;
			component.matchWidthOrHeight = 0.5f;
			try
			{
				RectTransform val = Rect("Panel", root.transform, new Vector2(0.5f, 0f), new Vector2(0.5f, 0f), new Vector2(0f, 96f), new Vector2(620f, 112f));
				AddImage(val, new Color(0.025f, 0.035f, 0.045f, 0.94f));
				AddImage(Rect("Accent", (Transform)(object)val, new Vector2(0f, 1f), new Vector2(0f, 1f), Vector2.zero, new Vector2(620f, 2f)), Accent);
				heading = Text("Stage", val, font, 21f, new Vector2(20f, 68f), new Vector2(580f, 30f));
				detail = Text("ElapsedAndCrew", val, font, 16f, new Vector2(20f, 12f), new Vector2(580f, 26f));
				((Graphic)detail).color = new Color(0.8f, 0.84f, 0.86f, 1f);
				RectTransform val2 = Rect("Track", (Transform)(object)val, Vector2.zero, Vector2.zero, new Vector2(20f, 47f), new Vector2(580f, 8f));
				AddImage(val2, new Color(0.2f, 0.24f, 0.27f, 1f));
				RectTransform rect = Rect("Fill", (Transform)(object)val2, Vector2.zero, Vector2.zero, Vector2.zero, new Vector2(0f, 8f));
				fill = AddImage(rect, Accent);
				float[] array = new float[3] { 0.25f, 0.8f, 0.92f };
				foreach (float num in array)
				{
					AddImage(Rect("Milestone", (Transform)(object)val2, Vector2.zero, Vector2.zero, new Vector2(580f * num, -2f), new Vector2(2f, 12f)), new Color(0.025f, 0.035f, 0.045f, 1f));
				}
			}
			catch
			{
				Object.Destroy((Object)(object)root);
				throw;
			}
		}

		internal void Show(float fraction, string title, string description, bool failed)
		{
			//IL_0025: 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_0039: Unknown result type (might be due to invalid IL or missing references)
			if (IsAlive)
			{
				((Graphic)fill).rectTransform.sizeDelta = new Vector2(580f * Mathf.Clamp01(fraction), 8f);
				((Graphic)fill).color = (Color)(failed ? new Color(1f, 0.25f, 0.2f, 1f) : Accent);
				if (heading.text != title)
				{
					heading.text = title;
				}
				if (detail.text != description)
				{
					detail.text = description;
				}
				((Behaviour)canvas).enabled = true;
			}
		}

		internal void Hide()
		{
			if (IsAlive)
			{
				((Behaviour)canvas).enabled = false;
			}
		}

		public void Dispose()
		{
			if (IsAlive)
			{
				Object.Destroy((Object)(object)root);
			}
		}

		private static RectTransform Rect(string name, Transform parent, Vector2 anchor, Vector2 pivot, Vector2 position, Vector2 size)
		{
			//IL_0014: Unknown result type (might be due to invalid IL or missing references)
			//IL_001e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			//IL_002b: Unknown result type (might be due to invalid IL or missing references)
			//IL_002c: Unknown result type (might be due to invalid IL or missing references)
			//IL_002d: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Unknown result type (might be due to invalid IL or missing references)
			//IL_002f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0035: 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_003c: 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_0043: Unknown result type (might be due to invalid IL or missing references)
			//IL_004a: Unknown result type (might be due to invalid IL or missing references)
			//IL_004b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0053: Expected O, but got Unknown
			RectTransform val = (RectTransform)new GameObject(name, new Type[1] { typeof(RectTransform) }).transform;
			((Transform)val).SetParent(parent, false);
			Vector2 anchorMin = (val.anchorMax = anchor);
			val.anchorMin = anchorMin;
			val.pivot = pivot;
			val.anchoredPosition = position;
			val.sizeDelta = size;
			return val;
		}

		private static Image AddImage(RectTransform rect, Color color)
		{
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			Image obj = ((Component)rect).gameObject.AddComponent<Image>();
			((Graphic)obj).color = color;
			((Graphic)obj).raycastTarget = false;
			return obj;
		}

		private static TMP_Text Text(string name, RectTransform parent, TMP_FontAsset font, float size, Vector2 position, Vector2 dimensions)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0042: Unknown result type (might be due to invalid IL or missing references)
			TextMeshProUGUI obj = ((Component)Rect(name, (Transform)(object)parent, Vector2.zero, Vector2.zero, position, dimensions)).gameObject.AddComponent<TextMeshProUGUI>();
			((TMP_Text)obj).font = font;
			((TMP_Text)obj).fontSize = size;
			((Graphic)obj).color = new Color(0.96f, 0.96f, 0.93f, 1f);
			((TMP_Text)obj).alignment = (TextAlignmentOptions)4097;
			((TMP_Text)obj).enableWordWrapping = false;
			((TMP_Text)obj).overflowMode = (TextOverflowModes)1;
			((TMP_Text)obj).richText = false;
			((Graphic)obj).raycastTarget = false;
			return (TMP_Text)(object)obj;
		}
	}
	internal static class LootCountTranspiler
	{
		internal static IEnumerable<CodeInstruction> Apply(IEnumerable<CodeInstruction> instructions, FieldInfo multiplierField, MethodInfo adjustCount, Action<string> warn)
		{
			//IL_0108: Unknown result type (might be due to invalid IL or missing references)
			//IL_010e: Expected O, but got Unknown
			//IL_0116: Unknown result type (might be due to invalid IL or missing references)
			//IL_011c: Expected O, but got Unknown
			List<CodeInstruction> list = new List<CodeInstruction>(instructions);
			int index = -1;
			int num = 0;
			foreach (CodeInstruction item in list)
			{
				if (CodeInstructionExtensions.Calls(item, adjustCount))
				{
					return list;
				}
			}
			for (int i = 0; i + 3 < list.Count; i++)
			{
				if (CodeInstructionExtensions.LoadsField(list[i], multiplierField, false) && list[i + 1].opcode == OpCodes.Mul && list[i + 2].opcode == OpCodes.Conv_I4 && IsStoreLocal(list[i + 3].opcode))
				{
					index = i + 3;
					num++;
				}
			}
			if (num != 1 || list[index].labels.Count != 0 || list[index].blocks.Count != 0)
			{
				warn("Loot boost could not identify the scrap-count calculation safely. Loot is unchanged; interior selection and the loading bar remain available.");
				return list;
			}
			list.InsertRange(index, (IEnumerable<CodeInstruction>)(object)new CodeInstruction[2]
			{
				new CodeInstruction(OpCodes.Ldarg_0, (object)null),
				new CodeInstruction(OpCodes.Call, (object)adjustCount)
			});
			return list;
		}

		private static bool IsStoreLocal(OpCode op)
		{
			if (!(op == OpCodes.Stloc) && !(op == OpCodes.Stloc_S) && !(op == OpCodes.Stloc_0) && !(op == OpCodes.Stloc_1) && !(op == OpCodes.Stloc_2))
			{
				return op == OpCodes.Stloc_3;
			}
			return true;
		}
	}
	internal static class LootPolicy
	{
		internal static int Count(int original, bool enabled, double baseMultiplier, bool densityEnabled, double area, double areaPerItem, double maximumMultiplier, int itemLimit, int minimumItems)
		{
			if (!enabled || original < 0)
			{
				return original;
			}
			minimumItems = Math.Max(0, Math.Min(500, minimumItems));
			if (original == 0 && minimumItems == 0)
			{
				return original;
			}
			baseMultiplier = Sanitize(baseMultiplier, 1.5, 1.0, 10.0);
			maximumMultiplier = Sanitize(maximumMultiplier, 3.0, 1.0, 10.0);
			areaPerItem = Sanitize(areaPerItem, 250.0, 25.0, 2000.0);
			itemLimit = Math.Max(1, Math.Min(500, itemLimit));
			double val = Math.Ceiling((double)original * baseMultiplier);
			if (densityEnabled && IsFinite(area) && area > 0.0)
			{
				val = Math.Max(val, Math.Ceiling(area / areaPerItem));
			}
			double val2 = Math.Max(original, Math.Min(Math.Floor((double)original * maximumMultiplier), itemLimit));
			return (int)Math.Max(Math.Min(minimumItems, itemLimit), Math.Max(original, Math.Min(val, val2)));
		}

		internal static double Footprint(double width, double depth, double scaleX, double scaleZ)
		{
			if (!IsFinite(width) || !IsFinite(depth) || !IsFinite(scaleX) || !IsFinite(scaleZ) || width <= 0.0 || depth <= 0.0)
			{
				return 0.0;
			}
			double num = width * depth * Math.Abs(scaleX * scaleZ);
			if (!IsFinite(num) || !(num > 0.0))
			{
				return 0.0;
			}
			return num;
		}

		private static bool IsFinite(double value)
		{
			if (!double.IsNaN(value))
			{
				return !double.IsInfinity(value);
			}
			return false;
		}

		private static double Sanitize(double value, double fallback, double min, double max)
		{
			if (!IsFinite(value))
			{
				return fallback;
			}
			return Math.Max(min, Math.Min(max, value));
		}
	}
	internal static class LootSettings
	{
		[CompilerGenerated]
		private static class <>O
		{
			public static CanModifyDelegate <0>__CanChange;
		}

		internal static ConfigEntry<bool> Enabled;

		internal static ConfigEntry<float> BaseMultiplier;

		internal static ConfigEntry<int> MinimumItems;

		internal static ConfigEntry<bool> SizeScaling;

		internal static ConfigEntry<int> AreaPerItem;

		internal static ConfigEntry<float> MaximumMultiplier;

		internal static ConfigEntry<int> ItemLimit;

		private const string Section = "Loot";

		internal static void Initialize(ConfigFile config)
		{
			//IL_0044: Unknown result type (might be due to invalid IL or missing references)
			//IL_004e: Expected O, but got Unknown
			//IL_0075: Unknown result type (might be due to invalid IL or missing references)
			//IL_007f: Expected O, but got Unknown
			//IL_00c5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cf: Expected O, but got Unknown
			//IL_00fd: Unknown result type (might be due to invalid IL or missing references)
			//IL_0107: Expected O, but got Unknown
			//IL_012e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0138: Expected O, but got Unknown
			Enabled = config.Bind<bool>("Loot", "Enable Loot Boost", true, "Host only: increase the number of normal interior scrap items. Uses the moon's existing item pool and value rules. Independent of the equal-interior selection switch. Apply changes in orbit for the next landing.");
			BaseMultiplier = config.Bind<float>("Loot", "Base Scrap Multiplier", 1.5f, new ConfigDescription("Multiply the rolled scrap count by this amount before applying limits. 1.5 means about 50% more items on ordinary maps.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(1f, 10f), Array.Empty<object>()));
			MinimumItems = config.Bind<int>("Loot", "Minimum Scrap Items", 20, new ConfigDescription("Minimum requested number of normal scrap items on a loot-enabled moon, including a roll of zero. 0 disables the minimum. Takes priority over Maximum Scrap Multiplier, but cannot exceed Boosted Scrap Limit. Existing spawn points and the moon's item pool still determine what can actually spawn.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 500), Array.Empty<object>()));
			SizeScaling = config.Bind<bool>("Loot", "Scale Loot With Interior Size", true, "Raise the scrap count further when the generated interior's estimated room area needs more loot. Uses the sum of room footprints, not empty space between rooms. Never reduces the base boost.");
			AreaPerItem = config.Bind<int>("Loot", "Area Per Scrap Item", 250, new ConfigDescription("Target one normal scrap item per this many square metres of estimated room footprint. LOWER means denser loot. An estimate, not a promise of one item in each room; existing spawn points control placement. Used only when size scaling is enabled.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(25, 2000), Array.Empty<object>()));
			MaximumMultiplier = config.Bind<float>("Loot", "Maximum Scrap Multiplier", 3f, new ConfigDescription("Maximum multiplier for the base boost and size scaling. The default allows up to three times the normal number of items. Minimum Scrap Items can exceed this multiplier; Boosted Scrap Limit still caps additions.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(1f, 10f), Array.Empty<object>()));
			ItemLimit = config.Bind<int>("Loot", "Boosted Scrap Limit", 100, new ConfigDescription("Stop adding normal scrap at this count to limit performance cost, including additions from Minimum Scrap Items. Never removes existing loot if another mod already requests more. Interior-specific bonuses and separately spawned items are additional.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(1, 500), Array.Empty<object>()));
			AddBool(Enabled, "Enable loot boost");
			AddFloat(BaseMultiplier, "Base scrap multiplier", 1f, 10f);
			AddInt(MinimumItems, "Minimum scrap items", 0, 500);
			AddBool(SizeScaling, "Scale loot with interior size");
			AddInt(AreaPerItem, "Area per scrap item (lower = more loot)", 25, 2000);
			AddFloat(MaximumMultiplier, "Maximum scrap multiplier", 1f, 10f);
			AddInt(ItemLimit, "Boosted scrap limit", 1, 500);
		}

		private static CanModifyResult CanChange()
		{
			//IL_0046: Unknown result type (might be due to invalid IL or missing references)
			//IL_001c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0040: Unknown result type (might be due to invalid IL or missing references)
			StartOfRound instance = StartOfRound.Instance;
			if ((Object)(object)instance != (Object)null && !((NetworkBehaviour)instance).IsServer)
			{
				return CanModifyResult.False("The host controls loot settings. Change yours from the main menu before hosting.");
			}
			if ((Object)(object)instance != (Object)null && (!instance.inShipPhase || instance.beganLoadingNewLevel))
			{
				return CanModifyResult.False("Return to orbit before changing loot settings.");
			}
			return CanModifyResult.True();
		}

		private static void AddBool(ConfigEntry<bool> entry, string name)
		{
			//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)
			//IL_000d: 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_001f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0045: Expected O, but got Unknown
			//IL_0040: Unknown result type (might be due to invalid IL or missing references)
			//IL_004a: Expected O, but got Unknown
			//IL_0030: Unknown result type (might be due to invalid IL or missing references)
			//IL_0035: Unknown result type (might be due to invalid IL or missing references)
			//IL_003b: Expected O, but got Unknown
			BoolCheckBoxOptions val = new BoolCheckBoxOptions
			{
				Name = name,
				Section = "Loot",
				RequiresRestart = false
			};
			object obj = <>O.<0>__CanChange;
			if (obj == null)
			{
				CanModifyDelegate val2 = CanChange;
				<>O.<0>__CanChange = val2;
				obj = (object)val2;
			}
			((BaseOptions)val).CanModifyCallback = (CanModifyDelegate)obj;
			LethalConfigManager.AddConfigItem((BaseConfigItem)new BoolCheckBoxConfigItem(entry, val));
		}

		private static void AddFloat(ConfigEntry<float> entry, string name, float min, float max)
		{
			//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)
			//IL_000d: 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_001f: Expected O, but got Unknown
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0026: Expected O, but got Unknown
			//IL_0026: Unknown result type (might be due to invalid IL or missing references)
			//IL_002d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0053: Expected O, but got Unknown
			//IL_004e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0058: Expected O, but got Unknown
			//IL_003e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0043: Unknown result type (might be due to invalid IL or missing references)
			//IL_0049: Expected O, but got Unknown
			FloatSliderOptions val = new FloatSliderOptions
			{
				Name = name,
				Section = "Loot"
			};
			((BaseRangeOptions<float>)val).Min = min;
			((BaseRangeOptions<float>)val).Max = max;
			((BaseOptions)val).RequiresRestart = false;
			object obj = <>O.<0>__CanChange;
			if (obj == null)
			{
				CanModifyDelegate val2 = CanChange;
				<>O.<0>__CanChange = val2;
				obj = (object)val2;
			}
			((BaseOptions)val).CanModifyCallback = (CanModifyDelegate)obj;
			LethalConfigManager.AddConfigItem((BaseConfigItem)new FloatSliderConfigItem(entry, val));
		}

		private static void AddInt(ConfigEntry<int> entry, string name, int min, int max)
		{
			//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)
			//IL_000d: 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_001f: Expected O, but got Unknown
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0026: Expected O, but got Unknown
			//IL_0026: Unknown result type (might be due to invalid IL or missing references)
			//IL_002d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0053: Expected O, but got Unknown
			//IL_004e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0058: Expected O, but got Unknown
			//IL_003e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0043: Unknown result type (might be due to invalid IL or missing references)
			//IL_0049: Expected O, but got Unknown
			IntSliderOptions val = new IntSliderOptions
			{
				Name = name,
				Section = "Loot"
			};
			((BaseRangeOptions<int>)val).Min = min;
			((BaseRangeOptions<int>)val).Max = max;
			((BaseOptions)val).RequiresRestart = false;
			object obj = <>O.<0>__CanChange;
			if (obj == null)
			{
				CanModifyDelegate val2 = CanChange;
				<>O.<0>__CanChange = val2;
				obj = (object)val2;
			}
			((BaseOptions)val).CanModifyCallback = (CanModifyDelegate)obj;
			LethalConfigManager.AddConfigItem((BaseConfigItem)new IntSliderConfigItem(entry, val));
		}
	}
	internal static class LootSpawning
	{
		[HarmonyPatch(typeof(RoundManager), "SpawnScrapInLevel")]
		private static class ScrapCountPatch
		{
			[HarmonyTranspiler]
			[HarmonyPriority(0)]
			private static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions)
			{
				return LootCountTranspiler.Apply(instructions, AccessTools.Field(typeof(RoundManager), "scrapAmountMultiplier"), AccessTools.Method(typeof(LootSpawning), "AdjustCount", (Type[])null, (Type[])null), delegate(string message)
				{
					Plugin.Log.LogWarning((object)message);
				});
			}
		}

		private static Harmony? patches;

		private static bool warned;

		internal static void Initialize()
		{
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			//IL_000f: Expected O, but got Unknown
			try
			{
				patches = new Harmony("sockpoop.equalinteriors.loot");
				patches.PatchAll(typeof(ScrapCountPatch));
			}
			catch (Exception ex)
			{
				Harmony? obj = patches;
				if (obj != null)
				{
					obj.UnpatchSelf();
				}
				Plugin.Log.LogError((object)("Could not enable the optional loot boost. " + ex));
			}
		}

		internal static void Shutdown()
		{
			Harmony? obj = patches;
			if (obj != null)
			{
				obj.UnpatchSelf();
			}
			patches = null;
		}

		internal static int AdjustCount(int original, RoundManager round)
		{
			if ((Object)(object)round == (Object)null || !((NetworkBehaviour)round).IsServer || !LootSettings.Enabled.Value || original < 0 || (Object)(object)round.currentLevel == (Object)null || !round.currentLevel.spawnEnemiesAndScrap || round.currentLevel.spawnableScrap == null || round.currentLevel.spawnableScrap.Count == 0)
			{
				return original;
			}
			try
			{
				double area = (LootSettings.SizeScaling.Value ? MeasureArea(round) : 0.0);
				int result = LootPolicy.Count(original, enabled: true, LootSettings.BaseMultiplier.Value, LootSettings.SizeScaling.Value, area, LootSettings.AreaPerItem.Value, LootSettings.MaximumMultiplier.Value, LootSettings.ItemLimit.Value, LootSettings.MinimumItems.Value);
				Plugin.Log.LogInfo((object)("Loot boost: " + original + " -> " + result + " normal scrap items; estimated room area " + area.ToString("0", CultureInfo.InvariantCulture) + " m2. Existing interior bonuses are additional."));
				return result;
			}
			catch (Exception ex)
			{
				if (!warned)
				{
					warned = true;
					Plugin.Log.LogWarning((object)("Could not calculate the loot boost; using the game's original count. " + ex));
				}
				return original;
			}
		}

		private static double MeasureArea(RoundManager round)
		{
			//IL_0090: Unknown result type (might be due to invalid IL or missing references)
			//IL_0095: Unknown result type (might be due to invalid IL or missing references)
			//IL_0099: Unknown result type (might be due to invalid IL or missing references)
			//IL_009e: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ac: Unknown result type (might be due to invalid IL or missing references)
			//IL_00af: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bf: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c7: Unknown result type (might be due to invalid IL or missing references)
			Dungeon val = (((Object)(object)round.dungeonGenerator != (Object)null) ? round.dungeonGenerator.Generator.CurrentDungeon : null);
			if ((Object)(object)val == (Object)null)
			{
				return 0.0;
			}
			double num = 0.0;
			HashSet<Tile> hashSet = new HashSet<Tile>();
			foreach (Tile allTile in val.AllTiles)
			{
				if (!((Object)(object)allTile == (Object)null) && ((Component)allTile).gameObject.activeInHierarchy && allTile.Placement != null && hashSet.Add(allTile))
				{
					Bounds localBounds = allTile.Placement.LocalBounds;
					Vector3 size = ((Bounds)(ref localBounds)).size;
					Vector3 lossyScale = ((Component)allTile).transform.lossyScale;
					num += LootPolicy.Footprint(size.x, size.z, lossyScale.x, lossyScale.z);
				}
			}
			return num;
		}
	}
	[BepInPlugin("sockpoop.equalinteriors", "Equal Interiors", "1.5.0")]
	[BepInDependency("imabatby.lethallevelloader", "1.7.13")]
	[BepInDependency("ainavt.lc.lethalconfig", "1.4.6")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	public sealed class Plugin : BaseUnityPlugin
	{
		[HarmonyPatch(typeof(DungeonManager), "GetValidExtendedDungeonFlows")]
		internal static class InteriorSelectionPatch
		{
			[HarmonyPostfix]
			[HarmonyPriority(0)]
			internal static void Postfix(ExtendedLevel extendedLevel, bool debugResults, ref List<ExtendedDungeonFlowWithRarity> __result)
			{
				if (!EnabledSetting.Value || (Object)(object)extendedLevel == (Object)null || (Object)(object)extendedLevel.SelectableLevel == (Object)null || !extendedLevel.SelectableLevel.spawnEnemiesAndScrap)
				{
					return;
				}
				try
				{
					List<ExtendedDungeonFlowWithRarity> list = BuildEqualPool();
					if (list == null)
					{
						return;
					}
					if (list.Count == 0)
					{
						if (!warnedAboutEmptyPool)
						{
							Log.LogWarning((object)"All registered interiors are disabled. Landing is blocked until at least one interior is enabled in Equal Interiors settings.");
							warnedAboutEmptyPool = true;
						}
					}
					else
					{
						warnedAboutEmptyPool = false;
						if (debugResults)
						{
							List<string> list2 = new List<string>(list.Count);
							foreach (ExtendedDungeonFlowWithRarity item in list)
							{
								list2.Add(item.extendedDungeonFlow.DungeonName);
							}
							string text = (100.0 / (double)list.Count).ToString("0.##", CultureInfo.InvariantCulture);
							Log.LogInfo((object)(extendedLevel.NumberlessPlanetName + ": " + list.Count + " interiors, weight " + 100 + " each (" + text + "% each): " + string.Join(", ", list2)));
						}
					}
					__result = list;
				}
				catch (Exception ex)
				{
					Log.LogError((object)("Could not build the equal interior pool; retaining the original result. " + ex));
				}
			}
		}

		[HarmonyPatch(typeof(StartOfRound), "StartGame")]
		internal static class NoInteriorsLaunchPatch
		{
			[HarmonyPrefix]
			internal static bool Prefix(StartOfRound __instance)
			{
				if (!EnabledSetting.Value || (Object)(object)__instance == (Object)null || !((NetworkBehaviour)__instance).IsServer || !__instance.inShipPhase || (Object)(object)__instance.currentLevel == (Object)null || !__instance.currentLevel.spawnEnemiesAndScrap)
				{
					return true;
				}
				List<ExtendedDungeonFlowWithRarity> list = BuildEqualPool();
				if (list == null || list.Count > 0)
				{
					return true;
				}
				StartMatchLever val = Object.FindObjectOfType<StartMatchLever>();
				if ((Object)(object)val != (Object)null)
				{
					val.CancelStartGameClientRpc();
				}
				if ((Object)(object)HUDManager.Instance != (Object)null)
				{
					HUDManager.Instance.DisplayTip("No interiors enabled", "Enable at least one interior in Equal Interiors settings before landing.", true, false, "LC_Tip1");
				}
				Log.LogWarning((object)"Landing cancelled because all interiors are disabled. The Company remains accessible.");
				return false;
			}
		}

		public const string PluginGuid = "sockpoop.equalinteriors";

		public const string PluginName = "Equal Interiors";

		public const string PluginVersion = "1.5.0";

		private Harmony? harmony;

		internal static ConfigEntry<bool> EnabledSetting;

		internal static ConfigEntry<bool> ShowLoadingBar;

		internal static ConfigEntry<string> ExcludedInteriors;

		internal static InteriorSettings InteriorToggles;

		internal static ManualLogSource Log;

		internal static LegacyExclusionMigration? LegacyMigration;

		private static bool warnedAboutEmptyPool;

		private void Awake()
		{
			//IL_0128: Unknown result type (might be due to invalid IL or missing references)
			//IL_0132: Expected O, but got Unknown
			Log = ((BaseUnityPlugin)this).Logger;
			EnabledSetting = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "Enabled", true, "Give every playable moon the same interior pool and equal chances. The host controls actual selections. Changes apply to the next landing.");
			ShowLoadingBar = ((BaseUnityPlugin)this).Config.Bind<bool>("Loading Screen", "Show Loading Bar", true, "Show local moon-loading stages, elapsed time, and interior generation retries. The bar tracks stages, not a percentage of time remaining. Works independently of the equal-interior selection setting; changes apply immediately.");
			LegacyMigration = new LegacyExclusionMigration(((BaseUnityPlugin)this).Config);
			ExcludedInteriors = LegacyMigration.Entry;
			ConfigMenu.Initialize(EnabledSetting);
			ConfigMenu.AddLoadingBar(ShowLoadingBar);
			LootSettings.Initialize(((BaseUnityPlugin)this).Config);
			InteriorToggles = new InteriorSettings(((BaseUnityPlugin)this).Config, () => ExcludedInteriors.Value, ConfigMenu.AddInterior);
			ConfigMenu.AddVanillaEntries(InteriorToggles);
			Plugin.onSetupComplete += RefreshInteriorConfigs;
			Plugin.onLobbyInitialized += RefreshInteriorConfigs;
			RefreshInteriorConfigs();
			harmony = new Harmony("sockpoop.equalinteriors");
			harmony.PatchAll(typeof(InteriorSelectionPatch));
			harmony.PatchAll(typeof(NoInteriorsLaunchPatch));
			LootSpawning.Initialize();
			LoadingScreen.Initialize();
			Log.LogInfo((object)"Equal Interiors 1.5.0 loaded. Every installed LLL interior gets a config toggle; enabled interiors receive weight 100 on every playable moon.");
		}

		private void Update()
		{
			LoadingScreen.Tick();
		}

		private void OnDestroy()
		{
			LoadingScreen.Shutdown();
			LootSpawning.Shutdown();
			Plugin.onSetupComplete -= RefreshInteriorConfigs;
			Plugin.onLobbyInitialized -= RefreshInteriorConfigs;
			Harmony? obj = harmony;
			if (obj != null)
			{
				obj.UnpatchSelf();
			}
		}

		internal static void RefreshInteriorConfigs()
		{
			try
			{
				foreach (ExtendedDungeonFlow extendedDungeonFlow in PatchedContent.ExtendedDungeonFlows)
				{
					if ((Object)(object)extendedDungeonFlow != (Object)null && (Object)(object)extendedDungeonFlow.DungeonFlow != (Object)null && !string.IsNullOrWhiteSpace(((Object)extendedDungeonFlow.DungeonFlow).name))
					{
						InteriorToggles.GetOrCreate(((Object)extendedDungeonFlow.DungeonFlow).name, extendedDungeonFlow.DungeonName);
					}
				}
				LegacyMigration?.CompleteIfReady(Plugin.IsSetupComplete);
			}
			catch (Exception ex)
			{
				Log.LogError((object)("Could not refresh interior config entries. " + ex));
			}
		}

		internal static List<ExtendedDungeonFlowWithRarity>? BuildEqualPool()
		{
			//IL_015d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0167: Expected O, but got Unknown
			RoundManager instance = RoundManager.Instance;
			if ((Object)(object)instance == (Object)null || instance.dungeonFlowTypes == null)
			{
				return null;
			}
			HashSet<DungeonFlow> hashSet = new HashSet<DungeonFlow>();
			IndoorMapType[] dungeonFlowTypes = instance.dungeonFlowTypes;
			foreach (IndoorMapType val in dungeonFlowTypes)
			{
				if (val != null && (Object)(object)val.dungeonFlow != (Object)null)
				{
					hashSet.Add(val.dungeonFlow);
				}
			}
			List<PoolPolicy.Candidate<ExtendedDungeonFlow>> list = new List<PoolPolicy.Candidate<ExtendedDungeonFlow>>();
			int num = 0;
			foreach (ExtendedDungeonFlow extendedDungeonFlow in PatchedContent.ExtendedDungeonFlows)
			{
				if (!((Object)(object)extendedDungeonFlow == (Object)null) && !((Object)(object)extendedDungeonFlow.DungeonFlow == (Object)null) && hashSet.Contains(extendedDungeonFlow.DungeonFlow) && !string.IsNullOrWhiteSpace(((Object)extendedDungeonFlow.DungeonFlow).name))
				{
					num++;
					if (InteriorToggles.GetOrCreate(((Object)extendedDungeonFlow.DungeonFlow).name, extendedDungeonFlow.DungeonName).Value)
					{
						list.Add(new PoolPolicy.Candidate<ExtendedDungeonFlow>(((Object)extendedDungeonFlow.DungeonFlow).name, extendedDungeonFlow.DungeonName, extendedDungeonFlow));
					}
				}
			}
			if (num == 0)
			{
				return null;
			}
			List<PoolPolicy.Candidate<ExtendedDungeonFlow>> list2 = PoolPolicy.Select(list, string.Empty);
			List<ExtendedDungeonFlowWithRarity> list3 = new List<ExtendedDungeonFlowWithRarity>(list2.Count);
			foreach (PoolPolicy.Candidate<ExtendedDungeonFlow> item in list2)
			{
				list3.Add(new ExtendedDungeonFlowWithRarity(item.Value, 100));
			}
			return list3;
		}
	}
	internal static class PoolPolicy
	{
		internal sealed class Candidate<T>
		{
			internal string FlowName { get; }

			internal string DisplayName { get; }

			internal T Value { get; }

			internal Candidate(string flowName, string displayName, T value)
			{
				FlowName = flowName;
				DisplayName = displayName;
				Value = value;
			}
		}

		internal const int EqualWeight = 100;

		internal const string DefaultExclusions = "Level1FlowExtraLarge,Level1Flow3Exits";

		internal static List<Candidate<T>> Select<T>(IEnumerable<Candidate<T>> candidates, string excludedInteriors)
		{
			HashSet<string> hashSet = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
			string[] array = (excludedInteriors ?? string.Empty).Split(',');
			foreach (string text in array)
			{
				if (!string.IsNullOrWhiteSpace(text))
				{
					hashSet.Add(text.Trim());
				}
			}
			HashSet<string> hashSet2 = new HashSet<string>(StringComparer.Ordinal);
			List<Candidate<T>> list = new List<Candidate<T>>();
			foreach (Candidate<T> candidate in candidates)
			{
				if (!string.IsNullOrWhiteSpace(candidate.FlowName) && !hashSet.Contains(candidate.FlowName) && !hashSet.Contains(candidate.DisplayName) && hashSet2.Add(candidate.FlowName))
				{
					list.Add(candidate);
				}
			}
			list.Sort((Candidate<T> left, Candidate<T> right) => StringComparer.Ordinal.Compare(left.FlowName, right.FlowName));
			return list;
		}
	}
}