Decompiled source of MonsterManager v2.0.0

MonsterManager.dll

Decompiled 2 months ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using DunGen.Graph;
using GameNetcodeStuff;
using HarmonyLib;
using Unity.Netcode;
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(".NETFramework,Version=v4.7.2", FrameworkDisplayName = ".NET Framework 4.7.2")]
[assembly: AssemblyCompany("MonsterManager")]
[assembly: AssemblyConfiguration("Debug")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0")]
[assembly: AssemblyProduct("MonsterManager")]
[assembly: AssemblyTitle("MonsterManager")]
[assembly: AssemblyVersion("1.0.0.0")]
namespace MonsterManager;

public enum MoonSpawningMode
{
	Enabled,
	OnlyUseMoonMonsters,
	Disabled
}
[BepInPlugin("com.Hibyhii.Monstermanager", "MonsterManager", "2.5.1")]
public class Plugin : BaseUnityPlugin
{
	public static ConfigFile ConfigFile;

	internal static ManualLogSource mls;

	private readonly Harmony harmony = new Harmony("com.Hibyhii.monsterManager");

	public static ConfigEntry<bool> UseRandomization;

	public static ConfigEntry<int> PowerOffset;

	public static ConfigEntry<int> AbsoluteMaxActiveEntities;

	public static ConfigEntry<double> MonsterSpawnMultiplier;

	public static ConfigEntry<float> MonsterSpacing;

	public static ConfigEntry<bool> DoNotRepeatMonsters;

	public static ConfigEntry<bool> UseExactAmountOfMonsters;

	public static ConfigEntry<int> ExactAmountHardMonsters;

	public static ConfigEntry<int> ExactAmountEasyMonsters;

	public static ConfigEntry<int> OffsetHardMonsters;

	public static ConfigEntry<int> OffsetEasyMonsters;

	public static ConfigEntry<float> IndoorSpawnTimeThreshold;

	public static ConfigEntry<float> OutdoorSpawnTimeThreshold;

	public static ConfigEntry<float> SpawnIntervalOffset;

	public static ConfigEntry<bool> EnabledExactSpawnTiming;

	public static ConfigEntry<float> ExactSpawnTiming;

	public static ConfigEntry<string> DefineHardMonsterPowerLevel;

	public static ConfigEntry<string> DefineEasyMonsterPowerLevel;

	public static ConfigEntry<float> DungeonSizeMultiplier;

	public static Dictionary<string, ConfigEntry<MoonSpawningMode>> MoonSpawningModes = new Dictionary<string, ConfigEntry<MoonSpawningMode>>();

	private void Awake()
	{
		mls = ((BaseUnityPlugin)this).Logger;
		ConfigFile = ((BaseUnityPlugin)this).Config;
		SpawnEnginePatch.LoadPersistentNoRepeatState();
		UseRandomization = ((BaseUnityPlugin)this).Config.Bind<bool>("1. General", "Use Formula For Monster Amounts?", true, "If TRUE, uses the mod's custom random spawn pools and power-based equations. If FALSE and 'UseExactAmountOfMonsters' is also FALSE, the mod defaults back to vanilla game spawning.");
		PowerOffset = ((BaseUnityPlugin)this).Config.Bind<int>("1. General", "PowerOffset", 0, "Offset added to the moon's base power level. Can be positive or negative.");
		AbsoluteMaxActiveEntities = ((BaseUnityPlugin)this).Config.Bind<int>("1. General", "AbsoluteMaxActiveEntities", 40, "Hard cap on total active enemies alive on the map before the mod pauses spawning.");
		MonsterSpawnMultiplier = ((BaseUnityPlugin)this).Config.Bind<double>("1. General", "MonsterSpawnMultiplier", 1.0, "Multiplier applied to calculated targets. Accepts decimal values (e.g. 0.5 for half spawns). Final target will be rounded up/down to the nearest whole integer.");
		MonsterSpacing = ((BaseUnityPlugin)this).Config.Bind<float>("1. General", "Monster Spacing", 10f, "Controls the horizontal exclusion radius around recently used monster spawn vents/nodes. Measured in Unity world units. 0 disables spacing entirely and allows any valid vent/node to be chosen at random. Larger values spread monsters farther apart.");
		DoNotRepeatMonsters = ((BaseUnityPlugin)this).Config.Bind<bool>("1. General", "Do Not Repeat Monsters", false, "If TRUE, a successfully spawned monster is removed from its current random pool until every other eligible monster in that same pool has been used. Each of the four pools (Interior Easy, Interior Hard, Exterior Easy, Exterior Hard) tracks this separately, then resets when exhausted. No-repeat progress is saved so it survives game restarts.");
		UseExactAmountOfMonsters = ((BaseUnityPlugin)this).Config.Bind<bool>("2. Exact Amounts", "UseExactAmountOfMonsters", false, "If TRUE, strictly uses 'ExactAmountHardMonsters' and 'ExactAmountEasyMonsters' instead of the mathematical formula.");
		ExactAmountHardMonsters = ((BaseUnityPlugin)this).Config.Bind<int>("2. Exact Amounts", "ExactAmountHardMonsters", 4, "Strictly sets the number of Hard monsters to spawn.");
		ExactAmountEasyMonsters = ((BaseUnityPlugin)this).Config.Bind<int>("2. Exact Amounts", "ExactAmountEasyMonsters", 4, "Strictly sets the number of Easy monsters to spawn.");
		OffsetHardMonsters = ((BaseUnityPlugin)this).Config.Bind<int>("3. Target Offsets", "OffsetHardMonsters", 0, "Adds or subtracts from the mathematically calculated Hard monster target.");
		OffsetEasyMonsters = ((BaseUnityPlugin)this).Config.Bind<int>("3. Target Offsets", "OffsetEasyMonsters", 0, "Adds or subtracts from the mathematically calculated Easy monster target.");
		IndoorSpawnTimeThreshold = ((BaseUnityPlugin)this).Config.Bind<float>("4. Timing", "IndoorSpawnTimeThreshold", 0f, "Time of day interior monsters begin spawning (0.0 to 1.0).");
		OutdoorSpawnTimeThreshold = ((BaseUnityPlugin)this).Config.Bind<float>("4. Timing", "OutdoorSpawnTimeThreshold", 0.65f, "Time of day outdoor monsters begin spawning (0.0 to 1.0).");
		SpawnIntervalOffset = ((BaseUnityPlugin)this).Config.Bind<float>("4. Timing", "SpawnIntervalOffset", 0f, "Offset added or subtracted from the time between monster spawns in seconds. Can intake double values like 1.5 or negative like -1.5.");
		EnabledExactSpawnTiming = ((BaseUnityPlugin)this).Config.Bind<bool>("4. Timing", "EnabledExactSpawnTiming", false, "If TRUE, completely ignores standard math equation and offsets for spawn intervals. Instead, monsters will spawn strictly at the interval defined below.");
		ExactSpawnTiming = ((BaseUnityPlugin)this).Config.Bind<float>("4. Timing", "ExactSpawnTiming", 10f, "The exact interval in seconds between monster spawns (Only functions if EnabledExactSpawnTiming is TRUE).");
		DefineHardMonsterPowerLevel = ((BaseUnityPlugin)this).Config.Bind<string>("5. Power Definitions", "DefineHardMonsterPowerLevel", ">1", "Defines required base game Power Level for a 'Hard' monster.");
		DefineEasyMonsterPowerLevel = ((BaseUnityPlugin)this).Config.Bind<string>("5. Power Definitions", "DefineEasyMonsterPowerLevel", "<=1", "Defines required base game Power Level for an 'Easy' monster.");
		DungeonSizeMultiplier = ((BaseUnityPlugin)this).Config.Bind<float>("6. Dungeon Expansion", "DungeonSizeMultiplier", 1f, "The exact size multiplier used to overwrite the facility's interior layout size.");
		DiscoverAndBindAllInteriors();
		harmony.PatchAll();
		mls.LogInfo((object)"MonsterManager v2.5.1 loaded and patched successfully!");
	}

	public static void DiscoverAndBindAllInteriors()
	{
		//IL_006c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0076: Expected O, but got Unknown
		DungeonFlow[] array = Resources.FindObjectsOfTypeAll<DungeonFlow>();
		int num = 0;
		DungeonFlow[] array2 = array;
		foreach (DungeonFlow val in array2)
		{
			if (!((Object)(object)val == (Object)null) && !string.IsNullOrEmpty(((Object)val).name))
			{
				string text = ((Object)val).name.Replace(" ", "");
				string text2 = "Expand_" + text;
				if (!ConfigFile.ContainsKey(new ConfigDefinition("7. Target Interiors For Expansion", text2)))
				{
					ConfigFile.Bind<bool>("7. Target Interiors For Expansion", text2, true, "If TRUE, applies the DungeonSizeMultiplier to the '" + text + "' interior layout.");
					num++;
				}
			}
		}
		if (num > 0)
		{
			mls.LogInfo((object)$"[INTERIOR DISCOVERY] Dynamically registered {num} new interior dungeon flows into config files.");
		}
	}

	public static void DiscoverAndBindAllMoons()
	{
		//IL_006f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0079: Expected O, but got Unknown
		SelectableLevel[] array = Resources.FindObjectsOfTypeAll<SelectableLevel>();
		int num = 0;
		SelectableLevel[] array2 = array;
		foreach (SelectableLevel val in array2)
		{
			if (!((Object)(object)val == (Object)null) && !string.IsNullOrEmpty(val.PlanetName))
			{
				string text = val.PlanetName.Replace(" ", "");
				string text2 = "Behavior For_" + text;
				if (!ConfigFile.ContainsKey(new ConfigDefinition("9. Moon Specific Spawning", text2)))
				{
					MoonSpawningModes[text] = ConfigFile.Bind<MoonSpawningMode>("9. Moon Specific Spawning", text2, MoonSpawningMode.Enabled, "Set the spawning behavior for " + val.PlanetName + ".\nEnabled = Uses mod pools entirely.\nOnlyUseMoonMonsters = Randomizes exclusively from the vanilla monster pool native to this moon, but maintains mod limits/math.\nDisabled = Turns off all modded spawning mechanics for this moon entirely (100% vanilla behavior).");
					num++;
				}
				else if (!MoonSpawningModes.ContainsKey(text))
				{
					MoonSpawningModes[text] = ConfigFile.Bind<MoonSpawningMode>("9. Moon Specific Spawning", text2, MoonSpawningMode.Enabled, "");
				}
			}
		}
		if (num > 0)
		{
			mls.LogInfo((object)$"[MOON DISCOVERY] Dynamically registered {num} new moons into config files.");
		}
	}
}
[HarmonyPatch(typeof(RoundManager))]
public class SpawnEnginePatch
{
	private sealed class SpawnSpacingState
	{
		private readonly int resolution;

		private readonly bool[,] coveredCells;

		private float minX;

		private float maxX;

		private float minZ;

		private float maxZ;

		private bool initialized;

		private int coveredCellCount;

		public readonly List<Vector3> ActiveCenters = new List<Vector3>();

		public SpawnSpacingState(int gridResolution)
		{
			resolution = gridResolution;
			coveredCells = new bool[resolution, resolution];
		}

		public void Reset()
		{
			ActiveCenters.Clear();
			initialized = false;
			coveredCellCount = 0;
			for (int i = 0; i < resolution; i++)
			{
				for (int j = 0; j < resolution; j++)
				{
					coveredCells[i, j] = false;
				}
			}
		}

		public bool EnsureGrid(List<Vector3> points)
		{
			if (points == null || points.Count == 0)
			{
				Reset();
				return false;
			}
			float num = points.Min((Vector3 p) => p.x);
			float num2 = points.Max((Vector3 p) => p.x);
			float num3 = points.Min((Vector3 p) => p.z);
			float num4 = points.Max((Vector3 p) => p.z);
			if (initialized && !(Mathf.Abs(minX - num) > 0.01f) && !(Mathf.Abs(maxX - num2) > 0.01f) && !(Mathf.Abs(minZ - num3) > 0.01f) && !(Mathf.Abs(maxZ - num4) > 0.01f))
			{
				return true;
			}
			minX = num;
			maxX = num2;
			minZ = num3;
			maxZ = num4;
			initialized = true;
			coveredCellCount = 0;
			ActiveCenters.Clear();
			for (int num5 = 0; num5 < resolution; num5++)
			{
				for (int num6 = 0; num6 < resolution; num6++)
				{
					coveredCells[num5, num6] = false;
				}
			}
			return true;
		}

		public bool IsBlocked(Vector3 candidate, float radius)
		{
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			//IL_0021: Unknown result type (might be due to invalid IL or missing references)
			if (radius <= 0f)
			{
				return false;
			}
			for (int i = 0; i < ActiveCenters.Count; i++)
			{
				if (FlatDistance(candidate, ActiveCenters[i]) < radius)
				{
					return true;
				}
			}
			return false;
		}

		public void RegisterSuccessfulSpawn(Vector3 spawnPosition, List<Vector3> mapPoints, float radius, string areaLabel)
		{
			//IL_003c: Unknown result type (might be due to invalid IL or missing references)
			//IL_006e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0073: Unknown result type (might be due to invalid IL or missing references)
			//IL_007b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0085: Unknown result type (might be due to invalid IL or missing references)
			if (radius <= 0f || mapPoints == null || mapPoints.Count == 0 || !EnsureGrid(mapPoints))
			{
				return;
			}
			ActiveCenters.Add(spawnPosition);
			for (int i = 0; i < resolution; i++)
			{
				for (int j = 0; j < resolution; j++)
				{
					if (coveredCells[i, j])
					{
						continue;
					}
					Vector3 cellCenter = GetCellCenter(i, j);
					for (int k = 0; k < ActiveCenters.Count; k++)
					{
						if (FlatDistance(cellCenter, ActiveCenters[k]) < radius)
						{
							coveredCells[i, j] = true;
							coveredCellCount++;
							break;
						}
					}
				}
			}
			float num = (float)coveredCellCount / (float)(resolution * resolution);
			if (num > 0.6f)
			{
				Plugin.mls.LogInfo((object)$"[SPACING RESET] {areaLabel} spawn area exceeded {0.6f:P0} covered grid area ({num:P1}). Resetting spacing map for the next spawn.");
				Reset();
			}
		}

		private Vector3 GetCellCenter(int cellX, int cellZ)
		{
			//IL_004c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0051: Unknown result type (might be due to invalid IL or missing references)
			//IL_0054: Unknown result type (might be due to invalid IL or missing references)
			float num = ((float)cellX + 0.5f) / (float)resolution;
			float num2 = ((float)cellZ + 0.5f) / (float)resolution;
			return new Vector3(Mathf.Lerp(minX, maxX, num), 0f, Mathf.Lerp(minZ, maxZ, num2));
		}

		private static float FlatDistance(Vector3 a, Vector3 b)
		{
			//IL_0001: 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_000f: 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)
			float num = a.x - b.x;
			float num2 = a.z - b.z;
			return Mathf.Sqrt(num * num + num2 * num2);
		}
	}

	[HarmonyPatch(typeof(StartOfRound), "ShipHasLeft")]
	public static class ShipHasLeftPatch
	{
		[HarmonyPrefix]
		public static void Prefix()
		{
			StopAndResetSpawnEngine(logReason: true);
		}
	}

	private enum SpawnAttemptResult
	{
		Failed,
		Spawned,
		RetryImmediately
	}

	private const int SpacingGridResolution = 10;

	private const float SpacingGridResetThreshold = 0.6f;

	private const float PlayerSafeRadius = 15f;

	private static List<EnemyType> InteriorEasyPool = new List<EnemyType>();

	private static List<EnemyType> InteriorHardPool = new List<EnemyType>();

	private static List<EnemyType> ExteriorEasyPool = new List<EnemyType>();

	private static List<EnemyType> ExteriorHardPool = new List<EnemyType>();

	private static Dictionary<EnemyType, int> SpawnedCounts = new Dictionary<EnemyType, int>();

	private static HashSet<EnemyType> UsedInteriorEasy = new HashSet<EnemyType>();

	private static HashSet<EnemyType> UsedInteriorHard = new HashSet<EnemyType>();

	private static HashSet<EnemyType> UsedExteriorEasy = new HashSet<EnemyType>();

	private static HashSet<EnemyType> UsedExteriorHard = new HashSet<EnemyType>();

	private static readonly HashSet<string> PersistentInteriorEasy = new HashSet<string>(StringComparer.OrdinalIgnoreCase);

	private static readonly HashSet<string> PersistentInteriorHard = new HashSet<string>(StringComparer.OrdinalIgnoreCase);

	private static readonly HashSet<string> PersistentExteriorEasy = new HashSet<string>(StringComparer.OrdinalIgnoreCase);

	private static readonly HashSet<string> PersistentExteriorHard = new HashSet<string>(StringComparer.OrdinalIgnoreCase);

	private const string PersistentStateFileName = "MonsterManager_NoRepeatState.cfg";

	private static SpawnSpacingState InteriorSpacing = new SpawnSpacingState(10);

	private static SpawnSpacingState ExteriorSpacing = new SpawnSpacingState(10);

	private static Coroutine InteriorSpawnCoroutine;

	private static Coroutine ExteriorSpawnCoroutine;

	private static int SpawnLoopGeneration;

	private static RoundManager ActiveRoundManager;

	private static SelectableLevel ActiveRoundLevel;

	private static readonly HashSet<string> VanillaEnemyNames = new HashSet<string>(StringComparer.OrdinalIgnoreCase)
	{
		"Flowerman", "Crawler", "Bunker Spider", "Hoarding bug", "Blob", "Centipede", "Puffer", "Jester", "Nutcracker", "Masked",
		"Butler", "Clay Surgeon", "Maneater", "Docile Locust Bees", "Red Locust Bees", "Baboon hawk", "MouthDog", "Forest Giant", "Earth Leviathan", "Radmech",
		"Tulip Snake", "Butler Bees", "Kidnapper Fox"
	};

	private static string PersistentStateFilePath => Path.Combine(Paths.ConfigPath, "MonsterManager_NoRepeatState.cfg");

	private static string GetEnemyStateId(EnemyType enemy)
	{
		if ((Object)(object)enemy == (Object)null)
		{
			return string.Empty;
		}
		if (!string.IsNullOrEmpty(enemy.enemyName))
		{
			return enemy.enemyName.Trim();
		}
		return (((Object)enemy).name != null) ? ((Object)enemy).name.Trim() : string.Empty;
	}

	internal static void LoadPersistentNoRepeatState()
	{
		PersistentInteriorEasy.Clear();
		PersistentInteriorHard.Clear();
		PersistentExteriorEasy.Clear();
		PersistentExteriorHard.Clear();
		string persistentStateFilePath = PersistentStateFilePath;
		if (!File.Exists(persistentStateFilePath))
		{
			return;
		}
		try
		{
			string text = string.Empty;
			string[] array = File.ReadAllLines(persistentStateFilePath);
			foreach (string text2 in array)
			{
				string text3 = ((text2 == null) ? string.Empty : text2.Trim());
				if (text3.Length == 0 || text3.StartsWith("#"))
				{
					continue;
				}
				if (text3.StartsWith("[") && text3.EndsWith("]"))
				{
					text = text3.Substring(1, text3.Length - 2).Trim();
				}
				else if (!text3.StartsWith("Version=", StringComparison.OrdinalIgnoreCase))
				{
					switch (text)
					{
					case "InteriorEasy":
						PersistentInteriorEasy.Add(text3);
						break;
					case "InteriorHard":
						PersistentInteriorHard.Add(text3);
						break;
					case "ExteriorEasy":
						PersistentExteriorEasy.Add(text3);
						break;
					case "ExteriorHard":
						PersistentExteriorHard.Add(text3);
						break;
					}
				}
			}
			int num = PersistentInteriorEasy.Count + PersistentInteriorHard.Count + PersistentExteriorEasy.Count + PersistentExteriorHard.Count;
			Plugin.mls.LogInfo((object)string.Format("[NO REPEAT SAVE] Loaded persistent no-repeat progress from '{0}' ({1} stored monster entries across the four pools).", "MonsterManager_NoRepeatState.cfg", num));
		}
		catch (Exception ex)
		{
			Plugin.mls.LogWarning((object)("[NO REPEAT SAVE] Failed to load persistent no-repeat progress from 'MonsterManager_NoRepeatState.cfg'. Starting with no restored exclusions. Error: " + ex.Message));
		}
	}

	private static void SavePersistentNoRepeatState()
	{
		try
		{
			Directory.CreateDirectory(Paths.ConfigPath);
			string persistentStateFilePath = PersistentStateFilePath;
			string text = persistentStateFilePath + ".tmp";
			using (StreamWriter streamWriter = new StreamWriter(text, append: false))
			{
				streamWriter.WriteLine("# MonsterManager persistent no-repeat progress");
				streamWriter.WriteLine("Version=1");
				WritePersistentSection(streamWriter, "InteriorEasy", PersistentInteriorEasy);
				WritePersistentSection(streamWriter, "InteriorHard", PersistentInteriorHard);
				WritePersistentSection(streamWriter, "ExteriorEasy", PersistentExteriorEasy);
				WritePersistentSection(streamWriter, "ExteriorHard", PersistentExteriorHard);
			}
			if (File.Exists(persistentStateFilePath))
			{
				try
				{
					File.Replace(text, persistentStateFilePath, null, ignoreMetadataErrors: true);
					return;
				}
				catch
				{
					File.Copy(text, persistentStateFilePath, overwrite: true);
					File.Delete(text);
					return;
				}
			}
			File.Move(text, persistentStateFilePath);
		}
		catch (Exception ex)
		{
			Plugin.mls.LogWarning((object)("[NO REPEAT SAVE] Failed to save persistent no-repeat progress to 'MonsterManager_NoRepeatState.cfg'. Error: " + ex.Message));
		}
	}

	private static void WritePersistentSection(StreamWriter writer, string sectionName, HashSet<string> values)
	{
		writer.WriteLine("[" + sectionName + "]");
		foreach (string item in values.OrderBy<string, string>((string v) => v, StringComparer.OrdinalIgnoreCase))
		{
			if (!string.IsNullOrWhiteSpace(item))
			{
				writer.WriteLine(item);
			}
		}
	}

	private static HashSet<string> GetPersistentSetForUsedPool(HashSet<EnemyType> used)
	{
		if (used == UsedInteriorEasy)
		{
			return PersistentInteriorEasy;
		}
		if (used == UsedInteriorHard)
		{
			return PersistentInteriorHard;
		}
		if (used == UsedExteriorEasy)
		{
			return PersistentExteriorEasy;
		}
		if (used == UsedExteriorHard)
		{
			return PersistentExteriorHard;
		}
		return null;
	}

	private static void RestorePersistentPool(IEnumerable<EnemyType> pool, HashSet<EnemyType> used, HashSet<string> persistentNames)
	{
		used.Clear();
		if (pool == null || persistentNames == null)
		{
			return;
		}
		foreach (EnemyType item in pool)
		{
			string enemyStateId = GetEnemyStateId(item);
			if (!string.IsNullOrEmpty(enemyStateId) && persistentNames.Contains(enemyStateId))
			{
				used.Add(item);
			}
		}
	}

	private static void LogNoRepeatPoolStatus(string poolLabel, List<EnemyType> pool, HashSet<EnemyType> used)
	{
		if (Plugin.DoNotRepeatMonsters.Value)
		{
			List<string> list = (from name in (pool ?? new List<EnemyType>()).Where((EnemyType enemy) => (Object)(object)enemy != (Object)null && used.Contains(enemy)).Select(GetEnemyStateId)
				where !string.IsNullOrEmpty(name)
				select name).Distinct<string>(StringComparer.OrdinalIgnoreCase).OrderBy<string, string>((string name) => name, StringComparer.OrdinalIgnoreCase).ToList();
			List<string> list2 = (from name in (pool ?? new List<EnemyType>()).Where((EnemyType enemy) => (Object)(object)enemy != (Object)null && !used.Contains(enemy) && !HasReachedMaxCount(enemy)).Select(GetEnemyStateId)
				where !string.IsNullOrEmpty(name)
				select name).Distinct<string>(StringComparer.OrdinalIgnoreCase).OrderBy<string, string>((string name) => name, StringComparer.OrdinalIgnoreCase).ToList();
			string text = ((list.Count > 0) ? string.Join(", ", list) : "None");
			string text2 = ((list2.Count > 0) ? string.Join(", ", list2) : "None");
			Plugin.mls.LogInfo((object)$"[NO REPEAT STATUS] {poolLabel} | Temporarily removed from RNG: {text} | Available this cycle: {list2.Count} -> {text2}");
		}
	}

	private static void ApplyPersistentNoRepeatStateToCurrentPools()
	{
		UsedInteriorEasy.Clear();
		UsedInteriorHard.Clear();
		UsedExteriorEasy.Clear();
		UsedExteriorHard.Clear();
		if (Plugin.DoNotRepeatMonsters.Value)
		{
			RestorePersistentPool(InteriorEasyPool, UsedInteriorEasy, PersistentInteriorEasy);
			RestorePersistentPool(InteriorHardPool, UsedInteriorHard, PersistentInteriorHard);
			RestorePersistentPool(ExteriorEasyPool, UsedExteriorEasy, PersistentExteriorEasy);
			RestorePersistentPool(ExteriorHardPool, UsedExteriorHard, PersistentExteriorHard);
			Plugin.mls.LogInfo((object)"=== PERSISTENT NO-REPEAT POOL STATUS ===");
			LogNoRepeatPoolStatus("Interior Easy", InteriorEasyPool, UsedInteriorEasy);
			LogNoRepeatPoolStatus("Interior Hard", InteriorHardPool, UsedInteriorHard);
			LogNoRepeatPoolStatus("Exterior Easy", ExteriorEasyPool, UsedExteriorEasy);
			LogNoRepeatPoolStatus("Exterior Hard", ExteriorHardPool, UsedExteriorHard);
		}
	}

	private static void MarkNoRepeatMonsterUsed(EnemyType enemy, HashSet<EnemyType> used, List<EnemyType> pool, string poolLabel)
	{
		if (!Plugin.DoNotRepeatMonsters.Value || (Object)(object)enemy == (Object)null || used == null)
		{
			return;
		}
		used.Add(enemy);
		HashSet<string> persistentSetForUsedPool = GetPersistentSetForUsedPool(used);
		if (persistentSetForUsedPool != null)
		{
			string enemyStateId = GetEnemyStateId(enemy);
			if (!string.IsNullOrEmpty(enemyStateId))
			{
				persistentSetForUsedPool.Add(enemyStateId);
			}
		}
		if (pool != null && pool.Count > 0 && pool.Where((EnemyType candidate) => (Object)(object)candidate != (Object)null && !HasReachedMaxCount(candidate)).All((EnemyType candidate) => used.Contains(candidate)))
		{
			used.Clear();
			persistentSetForUsedPool?.Clear();
			SavePersistentNoRepeatState();
			Plugin.mls.LogInfo((object)("[NO REPEAT RESET] " + poolLabel + " RNG pool cycle is exhausted after spawning '" + GetEnemyStateId(enemy) + "'. Reopened the full eligible pool for the next spawn."));
		}
		else
		{
			SavePersistentNoRepeatState();
			int num = pool?.Count((EnemyType candidate) => (Object)(object)candidate != (Object)null && !used.Contains(candidate) && !HasReachedMaxCount(candidate)) ?? 0;
			Plugin.mls.LogInfo((object)$"[NO REPEAT] Temporarily removed '{GetEnemyStateId(enemy)}' from {poolLabel}. Eligible monsters remaining in this cycle: {num}. Progress saved.");
		}
	}

	[HarmonyPatch("GenerateNewFloor")]
	[HarmonyPrefix]
	public static void PrefixGenerateNewFloor(RoundManager __instance)
	{
		Plugin.DiscoverAndBindAllInteriors();
		Plugin.DiscoverAndBindAllMoons();
		Plugin.mls.LogInfo((object)"=== MOON LANDING CONFIG & COMPATIBILITY SUMMARY ===");
		Plugin.mls.LogInfo((object)$"[CONFIG] Use Randomization: {Plugin.UseRandomization.Value} | Exact Amounts Enabled: {Plugin.UseExactAmountOfMonsters.Value}");
		Plugin.mls.LogInfo((object)$"[CONFIG] Dungeon Multiplier: {Plugin.DungeonSizeMultiplier.Value}x | Monster Spacing: {Plugin.MonsterSpacing.Value} | Max Active Entities: {Plugin.AbsoluteMaxActiveEntities.Value} | Do Not Repeat Monsters: {Plugin.DoNotRepeatMonsters.Value}");
		Plugin.mls.LogInfo((object)$"[CONFIG] Power Offset: {Plugin.PowerOffset.Value} | Spawn Multiplier: {Plugin.MonsterSpawnMultiplier.Value}x | Interval Offset: {Plugin.SpawnIntervalOffset.Value}s");
		if (Plugin.EnabledExactSpawnTiming.Value)
		{
			Plugin.mls.LogInfo((object)$"[CONFIG] EXACT SPAWN TIMING IS ENABLED: Forcing math override to spawn exactly every {Plugin.ExactSpawnTiming.Value}s.");
		}
		if (Plugin.DoNotRepeatMonsters.Value)
		{
			Plugin.mls.LogInfo((object)"[NO REPEAT] Enabled: Interior Easy, Interior Hard, Exterior Easy, and Exterior Hard each use independent non-repeating RNG cycles with persistent progress.");
		}
		else
		{
			Plugin.mls.LogInfo((object)"[NO REPEAT] Disabled: Monster selection uses the normal unrestricted random pool behavior. Saved no-repeat progress is not applied.");
		}
		if (Plugin.MonsterSpacing.Value > 0f)
		{
			Plugin.mls.LogInfo((object)$"[SPACING] Enabled: {Plugin.MonsterSpacing.Value:F1} world-unit exclusion radius. Using a {10}x{10} X/Z coverage grid with reset above {0.6f:P0} coverage; exhausted vent/node spacing retries immediately without consuming another spawn interval.");
		}
		else
		{
			Plugin.mls.LogInfo((object)"[SPACING] Disabled: Monster spawns may use any player-safe vent/node at random.");
		}
		if ((Object)(object)__instance.currentLevel != (Object)null)
		{
			int maxEnemyPowerCount = __instance.currentLevel.maxEnemyPowerCount;
			int num = ((maxEnemyPowerCount + Plugin.PowerOffset.Value <= 1) ? 1 : (maxEnemyPowerCount + Plugin.PowerOffset.Value));
			if (!string.IsNullOrEmpty(__instance.currentLevel.riskLevel))
			{
				string text = __instance.currentLevel.riskLevel;
				int num2 = text.IndexOf(" Power Level: ");
				if (num2 != -1)
				{
					text = text.Substring(0, num2);
				}
				__instance.currentLevel.riskLevel = text + $" Power Level: {num}";
			}
			else
			{
				__instance.currentLevel.riskLevel = $"Power Level: {num}";
			}
			Plugin.mls.LogInfo((object)("[UI UPDATE] Appended adjusted Power Level to Moon Risk UI Display -> '" + __instance.currentLevel.riskLevel + "'"));
		}
		if (!Plugin.UseRandomization.Value && !Plugin.UseExactAmountOfMonsters.Value)
		{
			Plugin.mls.LogWarning((object)"[COMPATIBILITY NOTICE] Both 'Use Randomization?' and 'UseExactAmountOfMonsters' are FALSE. DEFAULTING: Mod will step aside and use vanilla game spawning logic.");
		}
		if (!((Object)(object)__instance.currentLevel != (Object)null))
		{
			return;
		}
		string text2 = "UnknownInterior";
		if (__instance.currentLevel.dungeonFlowTypes != null && __instance.currentLevel.dungeonFlowTypes.Length != 0)
		{
			IntWithRarity val = __instance.currentLevel.dungeonFlowTypes.OrderByDescending((IntWithRarity f) => f.rarity).First();
			if (RoundManager.Instance.dungeonFlowTypes != null && val.id >= 0 && val.id < RoundManager.Instance.dungeonFlowTypes.Length)
			{
				IndoorMapType val2 = RoundManager.Instance.dungeonFlowTypes[val.id];
				if (val2 != null && (Object)(object)val2.dungeonFlow != (Object)null)
				{
					text2 = ((Object)val2.dungeonFlow).name.Replace(" ", "");
				}
			}
		}
		ConfigEntry<bool> val3 = Plugin.ConfigFile.Bind<bool>("7. Target Interiors For Expansion", "Expand_" + text2, true, "If TRUE, applies the DungeonSizeMultiplier to the '" + text2 + "' interior layout.");
		if (val3.Value)
		{
			__instance.currentLevel.factorySizeMultiplier = Plugin.DungeonSizeMultiplier.Value;
			Plugin.mls.LogInfo((object)$"[DUNGEON EXPANSION] Applied size multiplier ({Plugin.DungeonSizeMultiplier.Value}x) to active interior '{text2}'.");
		}
		else
		{
			Plugin.mls.LogInfo((object)("[DUNGEON EXPANSION] Skipped expanding '" + text2 + "' due to configuration setting."));
		}
	}

	[HarmonyPatch("BeginEnemySpawning")]
	[HarmonyPrefix]
	public static bool PrefixBeginEnemySpawning(RoundManager __instance)
	{
		if (!((NetworkBehaviour)__instance).IsServer)
		{
			return false;
		}
		StopAndResetSpawnEngine(logReason: false);
		ActiveRoundManager = __instance;
		ActiveRoundLevel = __instance.currentLevel;
		string text = __instance.currentLevel.PlanetName.Replace(" ", "");
		MoonSpawningMode moonSpawningMode = MoonSpawningMode.Enabled;
		if (Plugin.MoonSpawningModes.TryGetValue(text, out var value))
		{
			moonSpawningMode = value.Value;
		}
		if (moonSpawningMode == MoonSpawningMode.Disabled)
		{
			Plugin.mls.LogInfo((object)("[SPAWN ENGINE] MoonSpawningMode is set to 'Disabled' for " + text + ". Bypassing custom spawner and reverting to 100% vanilla."));
			return true;
		}
		if (!Plugin.UseRandomization.Value && !Plugin.UseExactAmountOfMonsters.Value)
		{
			Plugin.mls.LogInfo((object)"[SPAWN ENGINE] Bypassing custom spawner due to vanilla fallback rules.");
			return true;
		}
		Plugin.mls.LogInfo((object)"=== INITIALIZING MONSTER MANAGER SPAWN ENGINE ===");
		InitializeGlobalMonsterPools(__instance, moonSpawningMode);
		SpawnedCounts.Clear();
		ApplyPersistentNoRepeatStateToCurrentPools();
		InteriorSpacing.Reset();
		ExteriorSpacing.Reset();
		int maxEnemyPowerCount = __instance.currentLevel.maxEnemyPowerCount;
		int num = ((maxEnemyPowerCount + Plugin.PowerOffset.Value <= 1) ? 1 : (maxEnemyPowerCount + Plugin.PowerOffset.Value));
		CalculateTargets(num, out var hardTarget, out var easyTarget);
		Plugin.mls.LogInfo((object)$"[INTERIOR MATH] Effective Power: {num} | Target -> {hardTarget} Hard monsters, {easyTarget} Easy monsters");
		int maxOutsideEnemyPowerCount = __instance.currentLevel.maxOutsideEnemyPowerCount;
		int num2 = ((maxOutsideEnemyPowerCount + Plugin.PowerOffset.Value <= 1) ? 1 : (maxOutsideEnemyPowerCount + Plugin.PowerOffset.Value));
		CalculateTargets(num2, out var hardTarget2, out var easyTarget2);
		Plugin.mls.LogInfo((object)$"[EXTERIOR MATH] Effective Power: {num2} | Target -> {hardTarget2} Hard monsters, {easyTarget2} Easy monsters");
		int spawnLoopGeneration = SpawnLoopGeneration;
		InteriorSpawnCoroutine = ((MonoBehaviour)__instance).StartCoroutine(CustomInteriorSpawnLoop(__instance, spawnLoopGeneration, ActiveRoundLevel));
		ExteriorSpawnCoroutine = ((MonoBehaviour)__instance).StartCoroutine(CustomExteriorSpawnLoop(__instance, spawnLoopGeneration, ActiveRoundLevel));
		return false;
	}

	private static void StopAndResetSpawnEngine(bool logReason)
	{
		SpawnLoopGeneration++;
		if ((Object)(object)ActiveRoundManager != (Object)null)
		{
			if (InteriorSpawnCoroutine != null)
			{
				try
				{
					((MonoBehaviour)ActiveRoundManager).StopCoroutine(InteriorSpawnCoroutine);
				}
				catch (Exception ex)
				{
					Plugin.mls.LogWarning((object)("[SPAWN ENGINE] Failed to stop interior spawn coroutine cleanly: " + ex.Message));
				}
			}
			if (ExteriorSpawnCoroutine != null)
			{
				try
				{
					((MonoBehaviour)ActiveRoundManager).StopCoroutine(ExteriorSpawnCoroutine);
				}
				catch (Exception ex2)
				{
					Plugin.mls.LogWarning((object)("[SPAWN ENGINE] Failed to stop exterior spawn coroutine cleanly: " + ex2.Message));
				}
			}
		}
		InteriorSpawnCoroutine = null;
		ExteriorSpawnCoroutine = null;
		ActiveRoundManager = null;
		ActiveRoundLevel = null;
		SpawnedCounts.Clear();
		UsedInteriorEasy.Clear();
		UsedInteriorHard.Clear();
		UsedExteriorEasy.Clear();
		UsedExteriorHard.Clear();
		InteriorSpacing.Reset();
		ExteriorSpacing.Reset();
		if (logReason)
		{
			if (Plugin.DoNotRepeatMonsters.Value)
			{
				Plugin.mls.LogInfo((object)"[SPAWN ENGINE] Moon has been left. Stopped MonsterManager spawn loops and reset active round state. Persistent no-repeat progress was preserved for the next moon/session.");
			}
			else
			{
				Plugin.mls.LogInfo((object)"[SPAWN ENGINE] Moon has been left. Stopped MonsterManager spawn loops and reset active round spawn state.");
			}
		}
	}

	private static bool IsSpawnLoopStillValid(int loopGeneration, RoundManager rm, SelectableLevel roundLevel)
	{
		if (loopGeneration != SpawnLoopGeneration)
		{
			return false;
		}
		if ((Object)(object)rm == (Object)null || (Object)(object)RoundManager.Instance != (Object)(object)rm)
		{
			return false;
		}
		if ((Object)(object)roundLevel == (Object)null || (Object)(object)rm.currentLevel != (Object)(object)roundLevel)
		{
			return false;
		}
		return true;
	}

	private static void InitializeGlobalMonsterPools(RoundManager rm, MoonSpawningMode mode)
	{
		InteriorEasyPool.Clear();
		InteriorHardPool.Clear();
		ExteriorEasyPool.Clear();
		ExteriorHardPool.Clear();
		IEnumerable<EnemyType> enumerable;
		if (mode == MoonSpawningMode.OnlyUseMoonMonsters)
		{
			List<EnemyType> list = new List<EnemyType>();
			if (rm.currentLevel.Enemies != null)
			{
				list.AddRange(rm.currentLevel.Enemies.Select((SpawnableEnemyWithRarity e) => e.enemyType));
			}
			if (rm.currentLevel.OutsideEnemies != null)
			{
				list.AddRange(rm.currentLevel.OutsideEnemies.Select((SpawnableEnemyWithRarity e) => e.enemyType));
			}
			enumerable = list.Where((EnemyType e) => (Object)(object)e != (Object)null).Distinct();
			Plugin.mls.LogInfo((object)$"[POOL SETUP] 'OnlyUseMoonMonsters' is active. Sourced {enumerable.Count()} unique native enemies for {rm.currentLevel.PlanetName}.");
		}
		else
		{
			enumerable = Resources.FindObjectsOfTypeAll<EnemyType>();
		}
		List<string> list2 = new List<string>();
		foreach (EnemyType item in enumerable)
		{
			if (item.isDaytimeEnemy || item.MaxCount <= 0 || (Object)(object)item.enemyPrefab == (Object)null)
			{
				continue;
			}
			string text = item.enemyName.Replace(" ", "");
			ConfigEntry<bool> val = Plugin.ConfigFile.Bind<bool>("8. Include Monster In Random Pool", "Include_" + text, true, "If TRUE, " + item.enemyName + " is allowed into the mod's randomized spawn pools.");
			if (!val.Value)
			{
				list2.Add(item.enemyName);
				continue;
			}
			bool flag = EvaluatePowerLogic(item.PowerLevel, Plugin.DefineHardMonsterPowerLevel.Value);
			bool flag2 = EvaluatePowerLogic(item.PowerLevel, Plugin.DefineEasyMonsterPowerLevel.Value);
			if (item.isOutsideEnemy)
			{
				if (flag)
				{
					ExteriorHardPool.Add(item);
				}
				if (flag2)
				{
					ExteriorEasyPool.Add(item);
				}
			}
			else
			{
				if (flag)
				{
					InteriorHardPool.Add(item);
				}
				if (flag2)
				{
					InteriorEasyPool.Add(item);
				}
			}
		}
		if (list2.Count > 0)
		{
			Plugin.mls.LogInfo((object)("[POOL SETUP] Excluded monsters from randomization pool: " + string.Join(", ", list2)));
		}
		InteriorEasyPool = InteriorEasyPool.Distinct().ToList();
		InteriorHardPool = InteriorHardPool.Distinct().ToList();
		ExteriorEasyPool = ExteriorEasyPool.Distinct().ToList();
		ExteriorHardPool = ExteriorHardPool.Distinct().ToList();
		Plugin.mls.LogInfo((object)$"[SETUP] Interior Pools: {InteriorEasyPool.Count} Easy, {InteriorHardPool.Count} Hard.");
		Plugin.mls.LogInfo((object)$"[SETUP] Exterior Pools: {ExteriorEasyPool.Count} Easy, {ExteriorHardPool.Count} Hard.");
	}

	private static bool IsVanillaEnemy(EnemyType enemy)
	{
		return VanillaEnemyNames.Contains(enemy.enemyName) || VanillaEnemyNames.Contains(((Object)enemy).name);
	}

	private static void CalculateTargets(int effectivePower, out int hardTarget, out int easyTarget)
	{
		if (Plugin.UseExactAmountOfMonsters.Value)
		{
			hardTarget = Plugin.ExactAmountHardMonsters.Value;
			easyTarget = Plugin.ExactAmountEasyMonsters.Value;
			return;
		}
		double num = effectivePower;
		double num2 = (num - 8.0) / 14.0;
		if (num2 < 0.0)
		{
			num2 = 0.0;
		}
		if (num2 > 1.0)
		{
			num2 = 1.0;
		}
		double num3 = 2.0 + 4.0 * num2;
		double num4 = Math.Sin(num2 * Math.PI);
		double num5 = 3.0 + 2.0 * num4;
		double value = Plugin.MonsterSpawnMultiplier.Value;
		int num6 = (int)Math.Round(num3 * value, MidpointRounding.AwayFromZero);
		int num7 = (int)Math.Round(num5 * value, MidpointRounding.AwayFromZero);
		int num8 = num6 + Plugin.OffsetHardMonsters.Value;
		int num9 = num7 + Plugin.OffsetEasyMonsters.Value;
		hardTarget = ((num8 > 0) ? num8 : 0);
		easyTarget = ((num9 > 0) ? num9 : 0);
	}

	private static float CalculateSpawnInterval(int effectivePower)
	{
		if (Plugin.EnabledExactSpawnTiming.Value)
		{
			float value = Plugin.ExactSpawnTiming.Value;
			if (value < 1f)
			{
				Plugin.mls.LogWarning((object)$"[COMPATIBILITY DEFAULT] ExactSpawnTiming override ({value}) is exceptionally low. Clamped to minimum safe interval of 1.0s to prevent freezing.");
				return 1f;
			}
			return value;
		}
		double num = 25.0 - 10.0 * (((double)effectivePower - 8.0) / 14.0);
		float num2 = (float)((num > 15.0) ? num : 15.0);
		float num3 = num2 + Plugin.SpawnIntervalOffset.Value;
		if (num3 < 1f)
		{
			Plugin.mls.LogWarning((object)$"[COMPATIBILITY DEFAULT] SpawnIntervalOffset ({Plugin.SpawnIntervalOffset.Value}) pushed interval to {num3}s. DEFAULTING: Clamped to minimum safe interval of 1.0s to prevent game freezing/locking.");
			return 1f;
		}
		return num3;
	}

	private static IEnumerator CustomInteriorSpawnLoop(RoundManager rm, int loopGeneration, SelectableLevel roundLevel)
	{
		yield return (object)new WaitUntil((Func<bool>)(() => !IsSpawnLoopStillValid(loopGeneration, rm, roundLevel) || rm.dungeonCompletedGenerating));
		if (!IsSpawnLoopStillValid(loopGeneration, rm, roundLevel))
		{
			yield break;
		}
		if (Plugin.IndoorSpawnTimeThreshold.Value > 0f)
		{
			Plugin.mls.LogInfo((object)$"[INTERIOR] Waiting for time of day to reach threshold: {Plugin.IndoorSpawnTimeThreshold.Value}");
			yield return (object)new WaitUntil((Func<bool>)(() => !IsSpawnLoopStillValid(loopGeneration, rm, roundLevel) || ((Object)(object)TimeOfDay.Instance != (Object)null && TimeOfDay.Instance.normalizedTimeOfDay >= Plugin.IndoorSpawnTimeThreshold.Value)));
			if (!IsSpawnLoopStillValid(loopGeneration, rm, roundLevel))
			{
				yield break;
			}
		}
		int basePower = rm.currentLevel.maxEnemyPowerCount;
		int effectivePower = ((basePower + Plugin.PowerOffset.Value <= 1) ? 1 : (basePower + Plugin.PowerOffset.Value));
		CalculateTargets(effectivePower, out var hardTarget, out var easyTarget);
		int totalMonsters = hardTarget + easyTarget;
		if (InteriorEasyPool.Count == 0)
		{
			hardTarget = totalMonsters;
			easyTarget = 0;
		}
		if (InteriorHardPool.Count == 0)
		{
			easyTarget = totalMonsters;
			hardTarget = 0;
		}
		float spawnInterval = CalculateSpawnInterval(effectivePower);
		Plugin.mls.LogInfo((object)$"[INTERIOR] Starting loop. Target: {totalMonsters} Total ({hardTarget} Hard, {easyTarget} Easy). Interval: {spawnInterval:F1}s");
		int spawnedHard = 0;
		int spawnedEasy = 0;
		while (spawnedHard + spawnedEasy < totalMonsters)
		{
			yield return (object)new WaitForSeconds(spawnInterval);
			if (!IsSpawnLoopStillValid(loopGeneration, rm, roundLevel))
			{
				yield break;
			}
			try
			{
				bool spawnResolved = false;
				while (!spawnResolved)
				{
					if (IsSpawnLoopStillValid(loopGeneration, rm, roundLevel))
					{
						int activeEnemies = rm.SpawnedEnemies.Count((EnemyAI x) => (Object)(object)x != (Object)null && !x.isEnemyDead);
						if (activeEnemies >= Plugin.AbsoluteMaxActiveEntities.Value)
						{
							break;
						}
						int remainingHard = hardTarget - spawnedHard;
						int remainingEasy = easyTarget - spawnedEasy;
						bool requiresHard = false;
						if (remainingHard > 0 && remainingEasy > 0)
						{
							float hardProgress = ((hardTarget > 0) ? ((float)spawnedHard / (float)hardTarget) : 1f);
							float easyProgress = ((easyTarget > 0) ? ((float)spawnedEasy / (float)easyTarget) : 1f);
							requiresHard = hardProgress <= easyProgress;
						}
						else if (remainingHard > 0)
						{
							requiresHard = true;
						}
						switch (TrySpawnMonster(rm, requiresHard, isOutside: false, ref spawnedHard, ref spawnedEasy, hardTarget, easyTarget))
						{
						case SpawnAttemptResult.Spawned:
							spawnResolved = true;
							break;
						default:
							spawnResolved = true;
							break;
						case SpawnAttemptResult.RetryImmediately:
							break;
						}
						continue;
					}
					yield break;
				}
			}
			catch (Exception ex)
			{
				Plugin.mls.LogError((object)("[INTERIOR ERROR]: " + ex.Message));
			}
		}
		Plugin.mls.LogInfo((object)$"[INTERIOR COMPLETE] Finished spawning all interior monsters. Final Count -> ({spawnedHard}/{hardTarget}) Hard, ({spawnedEasy}/{easyTarget}) Easy.");
	}

	private static IEnumerator CustomExteriorSpawnLoop(RoundManager rm, int loopGeneration, SelectableLevel roundLevel)
	{
		Plugin.mls.LogInfo((object)$"[EXTERIOR] Waiting for time of day to reach threshold: {Plugin.OutdoorSpawnTimeThreshold.Value}");
		yield return (object)new WaitUntil((Func<bool>)(() => !IsSpawnLoopStillValid(loopGeneration, rm, roundLevel) || ((Object)(object)TimeOfDay.Instance != (Object)null && TimeOfDay.Instance.normalizedTimeOfDay >= Plugin.OutdoorSpawnTimeThreshold.Value)));
		if (!IsSpawnLoopStillValid(loopGeneration, rm, roundLevel))
		{
			yield break;
		}
		int basePower = rm.currentLevel.maxOutsideEnemyPowerCount;
		int effectivePower = ((basePower + Plugin.PowerOffset.Value <= 1) ? 1 : (basePower + Plugin.PowerOffset.Value));
		CalculateTargets(effectivePower, out var hardTarget, out var easyTarget);
		int totalMonsters = hardTarget + easyTarget;
		if (ExteriorEasyPool.Count == 0)
		{
			hardTarget = totalMonsters;
			easyTarget = 0;
		}
		if (ExteriorHardPool.Count == 0)
		{
			easyTarget = totalMonsters;
			hardTarget = 0;
		}
		float spawnInterval = CalculateSpawnInterval(effectivePower);
		Plugin.mls.LogInfo((object)$"[EXTERIOR] Starting loop. Target: {totalMonsters} Total ({hardTarget} Hard, {easyTarget} Easy). Interval: {spawnInterval:F1}s");
		int spawnedHard = 0;
		int spawnedEasy = 0;
		while (spawnedHard + spawnedEasy < totalMonsters)
		{
			yield return (object)new WaitForSeconds(spawnInterval);
			if (!IsSpawnLoopStillValid(loopGeneration, rm, roundLevel))
			{
				yield break;
			}
			try
			{
				bool spawnResolved = false;
				while (!spawnResolved)
				{
					if (IsSpawnLoopStillValid(loopGeneration, rm, roundLevel))
					{
						int activeEnemies = rm.SpawnedEnemies.Count((EnemyAI x) => (Object)(object)x != (Object)null && !x.isEnemyDead);
						if (activeEnemies >= Plugin.AbsoluteMaxActiveEntities.Value)
						{
							break;
						}
						int remainingHard = hardTarget - spawnedHard;
						int remainingEasy = easyTarget - spawnedEasy;
						bool requiresHard = false;
						if (remainingHard > 0 && remainingEasy > 0)
						{
							float hardProgress = ((hardTarget > 0) ? ((float)spawnedHard / (float)hardTarget) : 1f);
							float easyProgress = ((easyTarget > 0) ? ((float)spawnedEasy / (float)easyTarget) : 1f);
							requiresHard = hardProgress <= easyProgress;
						}
						else if (remainingHard > 0)
						{
							requiresHard = true;
						}
						switch (TrySpawnMonster(rm, requiresHard, isOutside: true, ref spawnedHard, ref spawnedEasy, hardTarget, easyTarget))
						{
						case SpawnAttemptResult.Spawned:
							spawnResolved = true;
							break;
						default:
							spawnResolved = true;
							break;
						case SpawnAttemptResult.RetryImmediately:
							break;
						}
						continue;
					}
					yield break;
				}
			}
			catch (Exception ex)
			{
				Plugin.mls.LogError((object)("[EXTERIOR ERROR]: " + ex.Message));
			}
		}
		Plugin.mls.LogInfo((object)$"[EXTERIOR COMPLETE] Finished spawning all exterior monsters. Final Count -> ({spawnedHard}/{hardTarget}) Hard, ({spawnedEasy}/{easyTarget}) Easy.");
	}

	private static void ResolvePoolSelection(bool requiresHard, bool isOutside, out List<EnemyType> pool, out HashSet<EnemyType> used, out string poolLabel)
	{
		if (requiresHard)
		{
			if (isOutside)
			{
				pool = ExteriorHardPool;
				used = UsedExteriorHard;
				poolLabel = "Exterior Hard";
				if (pool.Count == 0)
				{
					pool = ExteriorEasyPool;
					used = UsedExteriorEasy;
					poolLabel = "Exterior Easy (fallback)";
				}
			}
			else
			{
				pool = InteriorHardPool;
				used = UsedInteriorHard;
				poolLabel = "Interior Hard";
				if (pool.Count == 0)
				{
					pool = InteriorEasyPool;
					used = UsedInteriorEasy;
					poolLabel = "Interior Easy (fallback)";
				}
			}
		}
		else if (isOutside)
		{
			pool = ExteriorEasyPool;
			used = UsedExteriorEasy;
			poolLabel = "Exterior Easy";
			if (pool.Count == 0)
			{
				pool = ExteriorHardPool;
				used = UsedExteriorHard;
				poolLabel = "Exterior Hard (fallback)";
			}
		}
		else
		{
			pool = InteriorEasyPool;
			used = UsedInteriorEasy;
			poolLabel = "Interior Easy";
			if (pool.Count == 0)
			{
				pool = InteriorHardPool;
				used = UsedInteriorHard;
				poolLabel = "Interior Hard (fallback)";
			}
		}
	}

	private static EnemyType SelectEnemyFromPool(List<EnemyType> pool, HashSet<EnemyType> used, string poolLabel)
	{
		if (pool == null || pool.Count == 0)
		{
			return null;
		}
		if (!Plugin.DoNotRepeatMonsters.Value)
		{
			return pool[Random.Range(0, pool.Count)];
		}
		List<EnemyType> list = (from enemy in pool
			where !used.Contains(enemy)
			where !HasReachedMaxCount(enemy)
			select enemy).ToList();
		if (list.Count == 0)
		{
			bool flag = pool.Any((EnemyType enemy) => !used.Contains(enemy));
			bool flag2 = pool.Any((EnemyType enemy) => !used.Contains(enemy) && !HasReachedMaxCount(enemy));
			if (!flag)
			{
				used.Clear();
				GetPersistentSetForUsedPool(used)?.Clear();
				list = pool.Where((EnemyType enemy) => !HasReachedMaxCount(enemy)).ToList();
				SavePersistentNoRepeatState();
				Plugin.mls.LogInfo((object)("[NO REPEAT RESET] " + poolLabel + " RNG pool was exhausted. Reopened the full eligible pool for another random cycle."));
				LogNoRepeatPoolStatus(poolLabel, pool, used);
			}
			else if (!flag2)
			{
				Plugin.mls.LogWarning((object)("[NO REPEAT WARNING] " + poolLabel + " has unused monsters remaining, but all of them have reached MaxCount. Preserving the current no-repeat progress and retrying at the normal spawn interval."));
			}
		}
		if (list.Count == 0)
		{
			return null;
		}
		return list[Random.Range(0, list.Count)];
	}

	private static bool HasReachedMaxCount(EnemyType enemy)
	{
		int value;
		return SpawnedCounts.TryGetValue(enemy, out value) && value >= enemy.MaxCount;
	}

	private static float GetMonsterSpacingRadius()
	{
		return (Plugin.MonsterSpacing.Value > 0f) ? Plugin.MonsterSpacing.Value : 0f;
	}

	private static float FlatDistance(Vector3 a, Vector3 b)
	{
		//IL_0001: 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_000f: 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)
		float num = a.x - b.x;
		float num2 = a.z - b.z;
		return Mathf.Sqrt(num * num + num2 * num2);
	}

	private static SpawnAttemptResult TrySpawnMonster(RoundManager rm, bool requiresHard, bool isOutside, ref int spawnedHard, ref int spawnedEasy, int hardTarget, int easyTarget)
	{
		//IL_00ee: Unknown result type (might be due to invalid IL or missing references)
		//IL_00f3: Unknown result type (might be due to invalid IL or missing references)
		//IL_04b7: Unknown result type (might be due to invalid IL or missing references)
		//IL_04bc: Unknown result type (might be due to invalid IL or missing references)
		//IL_04c5: Unknown result type (might be due to invalid IL or missing references)
		//IL_031e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0323: Unknown result type (might be due to invalid IL or missing references)
		//IL_051e: Unknown result type (might be due to invalid IL or missing references)
		//IL_052c: Unknown result type (might be due to invalid IL or missing references)
		//IL_05fa: Unknown result type (might be due to invalid IL or missing references)
		//IL_0671: Unknown result type (might be due to invalid IL or missing references)
		ResolvePoolSelection(requiresHard, isOutside, out var pool, out var used, out var poolLabel);
		if (pool == null || pool.Count == 0)
		{
			return SpawnAttemptResult.Failed;
		}
		EnemyType val = SelectEnemyFromPool(pool, used, poolLabel);
		if ((Object)(object)val == (Object)null)
		{
			return SpawnAttemptResult.Failed;
		}
		if (!SpawnedCounts.ContainsKey(val))
		{
			SpawnedCounts[val] = 0;
		}
		if (SpawnedCounts[val] >= val.MaxCount)
		{
			if (Plugin.DoNotRepeatMonsters.Value || !IsVanillaEnemy(val) || !(Random.value > 0.5f))
			{
				return SpawnAttemptResult.Failed;
			}
			Plugin.mls.LogInfo((object)("[CAP BYPASS] Forcing extra vanilla spawn for " + val.enemyName + "."));
		}
		Vector3 zero = Vector3.zero;
		float num = 0f;
		List<Vector3> list = null;
		SpawnSpacingState spacingState = (isOutside ? ExteriorSpacing : InteriorSpacing);
		float spacingRadius = GetMonsterSpacingRadius();
		List<PlayerControllerB> activePlayers = new List<PlayerControllerB>();
		if ((Object)(object)StartOfRound.Instance != (Object)null && StartOfRound.Instance.allPlayerScripts != null)
		{
			activePlayers = StartOfRound.Instance.allPlayerScripts.Where((PlayerControllerB p) => (Object)(object)p != (Object)null && p.isPlayerControlled && !p.isPlayerDead).ToList();
		}
		if (isOutside)
		{
			if (rm.outsideAINodes == null || rm.outsideAINodes.Length == 0)
			{
				return SpawnAttemptResult.Failed;
			}
			List<GameObject> source = rm.outsideAINodes.Where((GameObject n) => (Object)(object)n != (Object)null).ToList();
			list = source.Select((GameObject n) => n.transform.position).ToList();
			spacingState.EnsureGrid(list);
			List<GameObject> list2 = source.Where(delegate(GameObject n)
			{
				//IL_001f: Unknown result type (might be due to invalid IL or missing references)
				//IL_002a: Unknown result type (might be due to invalid IL or missing references)
				foreach (PlayerControllerB item in activePlayers)
				{
					if (Vector3.Distance(n.transform.position, ((Component)item).transform.position) < 15f)
					{
						return false;
					}
				}
				return true;
			}).ToList();
			if (list2.Count == 0)
			{
				Plugin.mls.LogInfo((object)$"[PROXIMITY WARNING] All exterior nodes are within {15f} units of a player! Skipping '{val.enemyName}' spawn tick to prevent spawn-camping.");
				return SpawnAttemptResult.Failed;
			}
			List<GameObject> list3 = list2;
			if (spacingRadius > 0f)
			{
				list3 = list2.Where((GameObject node) => !spacingState.IsBlocked(node.transform.position, spacingRadius)).ToList();
				if (list3.Count == 0)
				{
					Plugin.mls.LogInfo((object)$"[SPACING RESET] All player-safe exterior nodes are within the current {spacingRadius:F1} world-unit spacing radius. Resetting exterior spacing and rerolling immediately.");
					spacingState.Reset();
					spacingState.EnsureGrid(list);
					return SpawnAttemptResult.RetryImmediately;
				}
			}
			GameObject val2 = list3[Random.Range(0, list3.Count)];
			zero = val2.transform.position;
		}
		else
		{
			if (rm.allEnemyVents == null || rm.allEnemyVents.Length == 0)
			{
				return SpawnAttemptResult.Failed;
			}
			List<EnemyVent> source2 = rm.allEnemyVents.Where((EnemyVent v) => (Object)(object)v != (Object)null && (Object)(object)v.floorNode != (Object)null).ToList();
			list = source2.Select((EnemyVent v) => v.floorNode.position).ToList();
			spacingState.EnsureGrid(list);
			List<EnemyVent> list4 = source2.Where(delegate(EnemyVent v)
			{
				//IL_001f: Unknown result type (might be due to invalid IL or missing references)
				//IL_002a: Unknown result type (might be due to invalid IL or missing references)
				foreach (PlayerControllerB item2 in activePlayers)
				{
					if (Vector3.Distance(v.floorNode.position, ((Component)item2).transform.position) < 15f)
					{
						return false;
					}
				}
				return true;
			}).ToList();
			if (list4.Count == 0)
			{
				Plugin.mls.LogInfo((object)$"[PROXIMITY WARNING] All interior vents are within {15f} units of a player! Skipping '{val.enemyName}' spawn tick to prevent spawn-camping.");
				return SpawnAttemptResult.Failed;
			}
			List<EnemyVent> list5 = list4;
			if (spacingRadius > 0f)
			{
				list5 = list4.Where((EnemyVent vent) => !spacingState.IsBlocked(vent.floorNode.position, spacingRadius)).ToList();
				if (list5.Count == 0)
				{
					Plugin.mls.LogInfo((object)$"[SPACING RESET] All player-safe interior vents are within the current {spacingRadius:F1} world-unit spacing radius. Resetting interior spacing and rerolling immediately.");
					spacingState.Reset();
					spacingState.EnsureGrid(list);
					return SpawnAttemptResult.RetryImmediately;
				}
			}
			EnemyVent val3 = list5[Random.Range(0, list5.Count)];
			zero = val3.floorNode.position;
			num = val3.floorNode.eulerAngles.y;
			if ((Object)(object)val3.ventAudio != (Object)null)
			{
				val3.ventAudio.Play();
			}
			if ((Object)(object)val3.ventAnimator != (Object)null)
			{
				val3.ventAnimator.SetTrigger("open");
			}
		}
		GameObject val4 = Object.Instantiate<GameObject>(val.enemyPrefab, zero, Quaternion.Euler(0f, num, 0f));
		NetworkObject componentInChildren = val4.GetComponentInChildren<NetworkObject>();
		if ((Object)(object)componentInChildren == (Object)null)
		{
			Object.Destroy((Object)(object)val4);
			return SpawnAttemptResult.Failed;
		}
		componentInChildren.Spawn(true);
		EnemyAI component = val4.GetComponent<EnemyAI>();
		if ((Object)(object)component != (Object)null)
		{
			rm.SpawnedEnemies.Add(component);
		}
		SpawnedCounts[val]++;
		MarkNoRepeatMonsterUsed(val, used, pool, poolLabel);
		if (requiresHard)
		{
			spawnedHard++;
		}
		else
		{
			spawnedEasy++;
		}
		if (spacingRadius > 0f && list != null && list.Count > 0)
		{
			spacingState.RegisterSuccessfulSpawn(zero, list, spacingRadius, isOutside ? "Exterior" : "Interior");
		}
		Plugin.mls.LogInfo((object)string.Format("[SPAWN SUCCESS] ({0}/{1}) Hard Monsters | ({2}/{3}) Easy Monsters — Spawned {4} '{5}' at position {6}", spawnedHard, hardTarget, spawnedEasy, easyTarget, isOutside ? "Outdoor" : "Indoor", val.enemyName, zero));
		return SpawnAttemptResult.Spawned;
	}

	private static bool EvaluatePowerLogic(float powerLevel, string logic)
	{
		logic = logic.Trim();
		if (logic.StartsWith(">=") && float.TryParse(logic.Substring(2), out var result))
		{
			return powerLevel >= result;
		}
		if (logic.StartsWith("<=") && float.TryParse(logic.Substring(2), out var result2))
		{
			return powerLevel <= result2;
		}
		if (logic.StartsWith("==") && float.TryParse(logic.Substring(2), out var result3))
		{
			return powerLevel == result3;
		}
		if (logic.StartsWith(">") && float.TryParse(logic.Substring(1), out var result4))
		{
			return powerLevel > result4;
		}
		if (logic.StartsWith("<") && float.TryParse(logic.Substring(1), out var result5))
		{
			return powerLevel < result5;
		}
		if (logic.StartsWith("=") && float.TryParse(logic.Substring(1), out var result6))
		{
			return powerLevel == result6;
		}
		if (float.TryParse(logic, out var result7))
		{
			return powerLevel == result7;
		}
		return false;
	}
}