Decompiled source of ChaosMoons v1.6.2

ChaosMoons.dll

Decompiled 5 hours ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using System.Text;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Configuration;
using BepInEx.Logging;
using GameNetcodeStuff;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using Unity.Netcode;
using UnityEngine;
using UnityEngine.AI;

[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("ChaosMoons")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0")]
[assembly: AssemblyProduct("ChaosMoons")]
[assembly: AssemblyTitle("ChaosMoons")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.0.0.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace ChaosMoons
{
	internal static class LguCompat
	{
		private const string Guid = "com.malco.lethalcompany.moreshipupgrades";

		private static bool _logged;

		internal static bool Present => Chainloader.PluginInfos.ContainsKey("com.malco.lethalcompany.moreshipupgrades");

		internal static int GetMidasLevel()
		{
			int value = ChaosPlugin.MidasLevelOverride.Value;
			if (value >= 0)
			{
				return value;
			}
			if (!Present)
			{
				return 0;
			}
			try
			{
				List<Type> list = (from t in ((object)Chainloader.PluginInfos["com.malco.lethalcompany.moreshipupgrades"].Instance).GetType().Assembly.GetTypes()
					where !t.IsAbstract && t.Name.IndexOf("midas", StringComparison.OrdinalIgnoreCase) >= 0
					select t).ToList();
				foreach (Type item in list)
				{
					object obj = FindInstance(item);
					if (obj != null && TryReadLevel(item, obj, out var level, out var member))
					{
						Log($"Midas Touch level {level} read from {item.FullName}.{member}");
						return Mathf.Max(0, level);
					}
				}
				Log("Lategame Upgrades found, but Midas Touch level could not be read automatically. Candidate types: " + ((list.Count == 0) ? "none" : string.Join(", ", list.Select((Type c) => c.FullName))) + ". Set 'MidasLevelOverride' in the config to apply the penalty manually.");
			}
			catch (Exception ex)
			{
				Log("Midas Touch lookup failed: " + ex.Message);
			}
			return 0;
		}

		private static object FindInstance(Type type)
		{
			if (typeof(Object).IsAssignableFrom(type))
			{
				return Object.FindObjectOfType(type);
			}
			PropertyInfo property = type.GetProperty("Instance", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
			if (property != null)
			{
				return property.GetValue(null);
			}
			return type.GetField("Instance", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic)?.GetValue(null);
		}

		private static bool TryReadLevel(Type type, object inst, out int level, out string member)
		{
			level = 0;
			member = null;
			FieldInfo[] fields = type.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
			foreach (FieldInfo fieldInfo in fields)
			{
				if (fieldInfo.FieldType == typeof(int) && fieldInfo.Name.IndexOf("level", StringComparison.OrdinalIgnoreCase) >= 0)
				{
					level = (int)fieldInfo.GetValue(inst);
					member = fieldInfo.Name;
					return true;
				}
			}
			PropertyInfo[] properties = type.GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
			foreach (PropertyInfo propertyInfo in properties)
			{
				if (propertyInfo.PropertyType == typeof(int) && propertyInfo.CanRead && propertyInfo.GetIndexParameters().Length == 0 && propertyInfo.Name.IndexOf("level", StringComparison.OrdinalIgnoreCase) >= 0)
				{
					level = (int)propertyInfo.GetValue(inst);
					member = propertyInfo.Name;
					return true;
				}
			}
			MethodInfo[] methods = type.GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
			foreach (MethodInfo methodInfo in methods)
			{
				if (methodInfo.ReturnType == typeof(int) && methodInfo.GetParameters().Length == 0 && methodInfo.Name.IndexOf("level", StringComparison.OrdinalIgnoreCase) >= 0)
				{
					level = (int)methodInfo.Invoke(inst, null);
					member = methodInfo.Name + "()";
					return true;
				}
			}
			return false;
		}

		private static void Log(string msg)
		{
			if (!_logged)
			{
				_logged = true;
				ChaosPlugin.Log.LogInfo((object)("[LGU compat] " + msg));
			}
		}
	}
	internal class ChaosEvent
	{
		public int Tier;

		public string Name;

		public string Description;

		public bool UsesOutside;

		public Func<IEnumerator> Run;

		public ChaosEvent(int tier, string name, string desc, Func<IEnumerator> run, bool outside = false)
		{
			Tier = tier;
			Name = name;
			Description = desc;
			Run = run;
			UsesOutside = outside;
		}
	}
	internal static class Events
	{
		private const string Hoarder = "hoarder|hoarding";

		private const string Snare = "centipede|snare";

		private const string Puffer = "puffer|spore";

		private const string Blob = "blob|hygrodere";

		private const string Spider = "sandspider|bunker";

		private const string Bracken = "flowerman|bracken";

		private const string Thumper = "crawler|thumper";

		private const string Nutcracker = "nutcracker";

		private const string Jester = "jester";

		private const string CoilHead = "springman|coil|spring";

		private const string Hawk = "baboon";

		private const string Dog = "mouthdog|dog";

		public static readonly List<ChaosEvent> All = new List<ChaosEvent>
		{
			new ChaosEvent(1, "Stirring Vents", "one small thing crawls out of a vent", StirringVents),
			new ChaosEvent(1, "Faulty Wiring", "lights flicker; a spore lizard wanders in", FaultyWiring),
			new ChaosEvent(2, "Brownout", "breaker trips mid-run, a snare flea in the dark", Brownout),
			new ChaosEvent(2, "Crowded Vents", "two small waves of minor critters", CrowdedVents),
			new ChaosEvent(2, "Hawk Patrol", "baboon hawks roam outside", HawkPatrol, outside: true),
			new ChaosEvent(3, "Hunters In The Walls", "a bracken, then a pair of hoarding bugs", HuntersInTheWalls),
			new ChaosEvent(3, "Blackout Hunt", "breaker trips, spider and fleas follow", BlackoutHunt),
			new ChaosEvent(3, "Hungry Pack", "an eyeless dog outside, trouble inside", HungryPack, outside: true),
			new ChaosEvent(4, "Heavy Footsteps", "a thumper, then a nutcracker", HeavyFootsteps),
			new ChaosEvent(4, "Twisted Ensemble", "bracken, blackout, then a spider", TwistedEnsemble),
			new ChaosEvent(4, "Jester's Invitation", "long warning, then a jester", JestersInvitation),
			new ChaosEvent(5, "Apex Hunt", "three telegraphed waves of heavy hitters", ApexHunt),
			new ChaosEvent(5, "Coil Symphony", "blackout, then three coil-heads", CoilSymphony),
			new ChaosEvent(5, "The Gauntlet", "bracken, thumper, nutcracker, jester in turn", Gauntlet)
		};

		private static int _extras;

		private static Random R => ChaosDirector.Rng;

		private static bool Active
		{
			get
			{
				if ((Object)(object)StartOfRound.Instance != (Object)null && StartOfRound.Instance.shipHasLanded && !StartOfRound.Instance.shipIsLeaving)
				{
					return !StartOfRound.Instance.inShipPhase;
				}
				return false;
			}
		}

		private static bool Stop
		{
			get
			{
				if (Active)
				{
					if ((Object)(object)TimeOfDay.Instance != (Object)null)
					{
						return TimeOfDay.Instance.normalizedTimeOfDay > 0.82f;
					}
					return false;
				}
				return true;
			}
		}

		private static float Rand(float a, float b)
		{
			return a + (float)R.NextDouble() * (b - a);
		}

		public static IEnumerator RunEvent(ChaosEvent ev)
		{
			float waited = 0f;
			while (!Active && waited < 180f)
			{
				yield return (object)new WaitForSeconds(1f);
				waited += 1f;
			}
			if (!Active)
			{
				yield break;
			}
			_extras = 0;
			if (ev.Tier == 5 && R.NextDouble() < (double)ChaosPlugin.NightmareDarkStartChance.Value)
			{
				yield return (object)new WaitForSeconds(2f);
				if (Active)
				{
					PowerOff();
				}
			}
			if (ChaosPlugin.ShowIndicator.Value)
			{
				yield return (object)new WaitForSeconds(6f);
				if (!Active)
				{
					yield break;
				}
				ShowIndicator(ev);
			}
			yield return ev.Run();
		}

		private static void ShowIndicator(ChaosEvent ev)
		{
			try
			{
				string text = new string('*', ev.Tier) + new string('-', 5 - ev.Tier);
				string text2 = (ChaosPlugin.IndicatorShowsEventName.Value ? (" - " + ev.Name) : "");
				string[] array = new string[5] { "#9fd6a0", "#e6e68a", "#f0b45a", "#e87a4a", "#e03a3a" };
				string text3 = "Tension: " + text + text2;
				if (ChaosPlugin.IndicatorForEveryone.Value)
				{
					HUDManager.Instance.AddTextToChatOnServer("<color=" + array[ev.Tier - 1] + ">" + text3 + "</color>", -1);
				}
				else
				{
					HUDManager.Instance.DisplayTip("Tension", text + text2, false, false, "LC_Tip1");
				}
			}
			catch (Exception ex)
			{
				ChaosPlugin.Log.LogWarning((object)("Indicator failed: " + ex.Message));
			}
		}

		private static IEnumerator Wait(float seconds)
		{
			float end = Time.time + seconds * Mathf.Max(0.1f, ChaosPlugin.SpawnDelayMultiplier.Value);
			while (Time.time < end && !Stop)
			{
				yield return (object)new WaitForSeconds(0.5f);
			}
		}

		private static IEnumerator Telegraph(int flickers = 1)
		{
			for (int i = 0; i < flickers; i++)
			{
				Flicker();
				yield return (object)new WaitForSeconds(1.5f);
			}
			yield return (object)new WaitForSeconds(2.5f);
		}

		private static void Flicker()
		{
			try
			{
				RoundManager.Instance.FlickerLights(false, false);
			}
			catch
			{
			}
		}

		private static void PowerOff()
		{
			try
			{
				BreakerBox val = Object.FindObjectOfType<BreakerBox>();
				if ((Object)(object)val != (Object)null)
				{
					val.SetSwitchesOff();
				}
				RoundManager.Instance.SwitchPower(false);
			}
			catch (Exception ex)
			{
				ChaosPlugin.Log.LogWarning((object)("PowerOff failed: " + ex.Message));
			}
		}

		private static float NightmareBlackoutWait()
		{
			return ChaosPlugin.NightmareBlackoutDelay.Value * Rand(0.8f, 1.25f);
		}

		private static string[] CompanionPool(int tier)
		{
			List<string> list = new List<string> { "hoarder|hoarding", "centipede|snare", "puffer|spore", "blob|hygrodere" };
			if (tier >= 3)
			{
				list.Add("sandspider|bunker");
			}
			if (tier >= 4)
			{
				list.Add("crawler|thumper");
			}
			if (tier >= 5)
			{
				list.Add("flowerman|bracken");
				list.Add("nutcracker");
				list.Add("springman|coil|spring");
			}
			return list.ToArray();
		}

		private static void In(params string[] options)
		{
			string chosen = options[R.Next(options.Length)];
			Transform val = Spawner.SpawnInside(chosen);
			if (!((Object)(object)val == (Object)null) && _extras < 4 && R.NextDouble() < (double)ChaosPlugin.ExtraMobChance.Value)
			{
				string[] array = (from a in CompanionPool(ChaosDirector.ActiveTier)
					where a != chosen
					select a).ToArray();
				if (array.Length != 0)
				{
					_extras++;
					Spawner.SpawnInside(array[R.Next(array.Length)], val);
				}
			}
		}

		private static void Out(string alias)
		{
			Spawner.SpawnOutside(alias);
		}

		private static IEnumerator StirringVents()
		{
			yield return Wait(Rand(60f, 100f));
			if (!Stop)
			{
				yield return Telegraph();
				if (!Stop)
				{
					In("hoarder|hoarding", "centipede|snare");
				}
			}
		}

		private static IEnumerator FaultyWiring()
		{
			for (int i = 0; i < 5; i++)
			{
				yield return Wait(Rand(45f, 80f));
				if (Stop)
				{
					break;
				}
				Flicker();
				if (i == 2)
				{
					yield return (object)new WaitForSeconds(4f);
					if (Stop)
					{
						break;
					}
					In("puffer|spore");
				}
			}
		}

		private static IEnumerator Brownout()
		{
			yield return Wait(Rand(100f, 160f));
			if (Stop)
			{
				yield break;
			}
			yield return Telegraph(2);
			if (!Stop)
			{
				PowerOff();
				yield return Wait(20f);
				if (!Stop)
				{
					In("centipede|snare");
				}
			}
		}

		private static IEnumerator CrowdedVents()
		{
			yield return Wait(Rand(60f, 90f));
			if (Stop)
			{
				yield break;
			}
			yield return Telegraph();
			if (Stop)
			{
				yield break;
			}
			In("hoarder|hoarding", "centipede|snare", "puffer|spore", "blob|hygrodere");
			In("hoarder|hoarding", "centipede|snare", "puffer|spore", "blob|hygrodere");
			yield return Wait(Rand(100f, 140f));
			if (!Stop)
			{
				yield return Telegraph();
				if (!Stop)
				{
					In("hoarder|hoarding", "centipede|snare", "puffer|spore", "blob|hygrodere");
					In("hoarder|hoarding", "centipede|snare", "puffer|spore", "blob|hygrodere");
				}
			}
		}

		private static IEnumerator HawkPatrol()
		{
			yield return Wait(Rand(30f, 60f));
			if (!Stop)
			{
				Out("baboon");
				Out("baboon");
			}
		}

		private static IEnumerator HuntersInTheWalls()
		{
			yield return Wait(Rand(90f, 120f));
			if (Stop)
			{
				yield break;
			}
			yield return Telegraph(2);
			if (Stop)
			{
				yield break;
			}
			In("flowerman|bracken");
			yield return Wait(Rand(90f, 120f));
			if (!Stop)
			{
				yield return Telegraph();
				if (!Stop)
				{
					In("hoarder|hoarding");
					In("hoarder|hoarding");
				}
			}
		}

		private static IEnumerator BlackoutHunt()
		{
			yield return Wait(Rand(90f, 140f));
			if (Stop)
			{
				yield break;
			}
			yield return Telegraph(2);
			if (Stop)
			{
				yield break;
			}
			PowerOff();
			yield return Wait(12f);
			if (!Stop)
			{
				In("sandspider|bunker");
				yield return Wait(45f);
				if (!Stop)
				{
					In("centipede|snare");
					In("centipede|snare");
				}
			}
		}

		private static IEnumerator HungryPack()
		{
			yield return Wait(Rand(40f, 70f));
			if (Stop)
			{
				yield break;
			}
			Out("mouthdog|dog");
			yield return Wait(Rand(60f, 90f));
			if (!Stop)
			{
				yield return Telegraph();
				if (!Stop)
				{
					In("puffer|spore");
					In("hoarder|hoarding");
				}
			}
		}

		private static IEnumerator HeavyFootsteps()
		{
			yield return Wait(Rand(80f, 110f));
			if (Stop)
			{
				yield break;
			}
			yield return Telegraph(2);
			if (Stop)
			{
				yield break;
			}
			In("crawler|thumper");
			yield return Wait(Rand(70f, 100f));
			if (!Stop)
			{
				yield return Telegraph(2);
				if (!Stop)
				{
					In("nutcracker");
				}
			}
		}

		private static IEnumerator TwistedEnsemble()
		{
			yield return Wait(Rand(70f, 100f));
			if (Stop)
			{
				yield break;
			}
			yield return Telegraph(2);
			if (Stop)
			{
				yield break;
			}
			In("flowerman|bracken");
			yield return Wait(75f);
			if (!Stop)
			{
				Flicker();
				yield return (object)new WaitForSeconds(3f);
				PowerOff();
				yield return Wait(20f);
				if (!Stop)
				{
					In("sandspider|bunker");
				}
			}
		}

		private static IEnumerator JestersInvitation()
		{
			yield return Wait(Rand(100f, 150f));
			if (Stop)
			{
				yield break;
			}
			yield return Telegraph(4);
			if (!Stop)
			{
				In("jester");
				yield return Wait(40f);
				if (!Stop)
				{
					In("centipede|snare");
				}
			}
		}

		private static IEnumerator ApexHunt()
		{
			yield return Wait(NightmareBlackoutWait());
			if (Stop)
			{
				yield break;
			}
			yield return Telegraph(3);
			if (Stop)
			{
				yield break;
			}
			PowerOff();
			yield return Wait(10f);
			if (Stop)
			{
				yield break;
			}
			In("flowerman|bracken");
			In("crawler|thumper");
			yield return Wait(Rand(80f, 110f));
			if (Stop)
			{
				yield break;
			}
			yield return Telegraph(3);
			if (Stop)
			{
				yield break;
			}
			In("jester");
			In("springman|coil|spring");
			yield return Wait(Rand(80f, 110f));
			if (!Stop)
			{
				yield return Telegraph(3);
				if (!Stop)
				{
					In("nutcracker");
					In("sandspider|bunker");
				}
			}
		}

		private static IEnumerator CoilSymphony()
		{
			yield return Wait(NightmareBlackoutWait() * 0.8f);
			if (Stop)
			{
				yield break;
			}
			yield return Telegraph(3);
			if (Stop)
			{
				yield break;
			}
			PowerOff();
			yield return Wait(10f);
			if (Stop)
			{
				yield break;
			}
			for (int i = 0; i < 3; i++)
			{
				In("springman|coil|spring");
				yield return Wait(12f);
				if (Stop)
				{
					break;
				}
			}
		}

		private static IEnumerator Gauntlet()
		{
			yield return Wait(NightmareBlackoutWait());
			if (Stop)
			{
				yield break;
			}
			yield return Telegraph(3);
			if (Stop)
			{
				yield break;
			}
			PowerOff();
			string[] array = new string[4] { "flowerman|bracken", "crawler|thumper", "nutcracker", "jester" };
			string[] array2 = array;
			foreach (string enemy in array2)
			{
				yield return Wait(Rand(45f, 65f));
				if (Stop)
				{
					break;
				}
				yield return Telegraph(3);
				if (Stop)
				{
					break;
				}
				In(enemy);
			}
		}
	}
	internal static class Spawner
	{
		private static readonly Dictionary<string, EnemyType> Cache = new Dictionary<string, EnemyType>();

		internal static void ClearCache()
		{
			Cache.Clear();
		}

		private static EnemyType FindEnemy(string aliases)
		{
			if (Cache.TryGetValue(aliases, out var value))
			{
				return value;
			}
			string[] keys = aliases.Split('|');
			EnemyType val = null;
			SelectableLevel currentLevel = RoundManager.Instance.currentLevel;
			List<SpawnableEnemyWithRarity>[] array = new List<SpawnableEnemyWithRarity>[3] { currentLevel.Enemies, currentLevel.OutsideEnemies, currentLevel.DaytimeEnemies };
			foreach (List<SpawnableEnemyWithRarity> list in array)
			{
				if (list != null)
				{
					SpawnableEnemyWithRarity val2 = ((IEnumerable<SpawnableEnemyWithRarity>)list).FirstOrDefault((Func<SpawnableEnemyWithRarity, bool>)((SpawnableEnemyWithRarity e) => Match(e.enemyType)));
					if (val2 != null)
					{
						val = val2.enemyType;
						break;
					}
				}
			}
			if ((Object)(object)val == (Object)null)
			{
				val = ((IEnumerable<EnemyType>)Resources.FindObjectsOfTypeAll<EnemyType>()).FirstOrDefault((Func<EnemyType, bool>)Match);
			}
			if ((Object)(object)val == (Object)null)
			{
				ChaosPlugin.Log.LogWarning((object)("Enemy not found for '" + aliases + "', skipping spawn."));
			}
			Cache[aliases] = val;
			return val;
			bool Match(EnemyType t)
			{
				if ((Object)(object)t != (Object)null && (Object)(object)t.enemyPrefab != (Object)null)
				{
					return keys.Any((string k) => (t.enemyName ?? "").ToLowerInvariant().Contains(k) || (((Object)t).name ?? "").ToLowerInvariant().Contains(k));
				}
				return false;
			}
		}

		private static List<Vector3> LivingPlayerPositions()
		{
			//IL_0039: Unknown result type (might be due to invalid IL or missing references)
			List<Vector3> list = new List<Vector3>();
			PlayerControllerB[] allPlayerScripts = StartOfRound.Instance.allPlayerScripts;
			foreach (PlayerControllerB val in allPlayerScripts)
			{
				if ((Object)(object)val != (Object)null && val.isPlayerControlled && !val.isPlayerDead)
				{
					list.Add(((Component)val).transform.position);
				}
			}
			return list;
		}

		private static float DistanceToPlayers(List<Vector3> players, Vector3 pos)
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			if (players.Count != 0)
			{
				return players.Min((Vector3 p) => Vector3.Distance(p, pos));
			}
			return 999f;
		}

		internal static Transform SpawnInside(string alias, Transform at = null)
		{
			//IL_0118: Unknown result type (might be due to invalid IL or missing references)
			//IL_011e: Unknown result type (might be due to invalid IL or missing references)
			//IL_012a: Unknown result type (might be due to invalid IL or missing references)
			EnemyType val = FindEnemy(alias);
			EnemyVent[] allEnemyVents = RoundManager.Instance.allEnemyVents;
			if ((Object)(object)val == (Object)null || allEnemyVents == null || allEnemyVents.Length == 0)
			{
				return null;
			}
			Transform val2 = at;
			if ((Object)(object)val2 == (Object)null)
			{
				List<Vector3> players = LivingPlayerPositions();
				var list = (from v in allEnemyVents
					where (Object)(object)v != (Object)null && (Object)(object)v.floorNode != (Object)null
					select new
					{
						v = v,
						d = DistanceToPlayers(players, v.floorNode.position)
					}).ToList();
				if (list.Count == 0)
				{
					return null;
				}
				var list2 = list.Where(s2 => s2.d >= ChaosPlugin.MinSpawnDistance.Value).ToList();
				val2 = ((list2.Count > 0) ? list2[ChaosDirector.Rng.Next(list2.Count)] : list.OrderByDescending(s2 => s2.d).First()).v.floorNode;
			}
			RoundManager.Instance.SpawnEnemyGameObject(val2.position, val2.eulerAngles.y, -1, val);
			return val2;
		}

		internal static bool SpawnOutside(string alias)
		{
			//IL_00cb: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00dd: Unknown result type (might be due to invalid IL or missing references)
			//IL_00df: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00eb: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f4: Unknown result type (might be due to invalid IL or missing references)
			EnemyType val = FindEnemy(alias);
			GameObject[] outsideAINodes = RoundManager.Instance.outsideAINodes;
			if ((Object)(object)val == (Object)null || outsideAINodes == null || outsideAINodes.Length == 0)
			{
				return false;
			}
			List<Vector3> players = LivingPlayerPositions();
			List<GameObject> list = outsideAINodes.Where((GameObject n) => (Object)(object)n != (Object)null).ToList();
			if (list.Count == 0)
			{
				return false;
			}
			List<GameObject> list2 = list.Where((GameObject n) => DistanceToPlayers(players, n.transform.position) >= ChaosPlugin.MinSpawnDistance.Value).ToList();
			GameObject val2 = ((list2.Count > 0) ? list2[ChaosDirector.Rng.Next(list2.Count)] : list[ChaosDirector.Rng.Next(list.Count)]);
			Vector3 randomNavMeshPositionInRadius = RoundManager.Instance.GetRandomNavMeshPositionInRadius(val2.transform.position, 8f, default(NavMeshHit));
			RoundManager.Instance.SpawnEnemyGameObject(randomNavMeshPositionInRadius, 0f, -1, val);
			return true;
		}
	}
	[BepInPlugin("com.chaosmoons.lethalcompany", "Chaos Moons", "1.6.0")]
	public class ChaosPlugin : BaseUnityPlugin
	{
		public const string GUID = "com.chaosmoons.lethalcompany";

		internal static ChaosPlugin Instance;

		internal static ManualLogSource Log;

		internal static readonly string[] TierNames = new string[5] { "Uneasy", "Tense", "Hostile", "Brutal", "Nightmare" };

		internal static readonly float[] DefaultReward = new float[5] { 5f, 12f, 20f, 30f, 45f };

		internal static ConfigEntry<float>[] RewardPercent = new ConfigEntry<float>[5];

		internal static ConfigEntry<float> EventChance;

		internal static ConfigEntry<float> MoonBias;

		internal static ConfigEntry<float> MinSpawnDistance;

		internal static ConfigEntry<bool> AllowOutsideEvents;

		internal static ConfigEntry<float> NormalDayChance;

		internal static ConfigEntry<int> NormalDayMaxRating;

		internal static ConfigEntry<float> ExtraMobChance;

		internal static ConfigEntry<float> NightmareDarkStartChance;

		internal static ConfigEntry<float> SpawnDelayMultiplier;

		internal static ConfigEntry<float> NightmareBlackoutDelay;

		internal static ConfigEntry<float> MidasPenaltyPerLevel;

		internal static ConfigEntry<int> MidasLevelOverride;

		internal static ConfigEntry<bool> ShowOnScreen;

		internal static ConfigEntry<string> OnScreenCorner;

		internal static ConfigEntry<bool> OnScreenShowsTierName;

		internal static ConfigEntry<bool> ShowIndicator;

		internal static ConfigEntry<bool> IndicatorForEveryone;

		internal static ConfigEntry<bool> IndicatorShowsEventName;

		private void Awake()
		{
			//IL_02e7: Unknown result type (might be due to invalid IL or missing references)
			Instance = this;
			Log = ((BaseUnityPlugin)this).Logger;
			((Object)((Component)this).gameObject).hideFlags = (HideFlags)61;
			EventChance = ((BaseUnityPlugin)this).Config.Bind<float>("General", "EventChance", 1f, "Chance (0-1) that a moon gets an event. 1 = every moon.");
			MoonBias = ((BaseUnityPlugin)this).Config.Bind<float>("General", "MoonDifficultyBias", 1.1f, "How strongly moon danger rating shifts tier odds. 0 = tiers are equally likely everywhere (shaped by base weights). Higher = safer moons favour low tiers harder, dangerous moons favour high tiers harder.");
			MinSpawnDistance = ((BaseUnityPlugin)this).Config.Bind<float>("Fairness", "MinSpawnDistance", 18f, "Event enemies try to spawn at least this many metres away from every living player.");
			AllowOutsideEvents = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "AllowOutsideEvents", true, "Allow the few events that spawn something outside the facility.");
			NormalDayChance = ((BaseUnityPlugin)this).Config.Bind<float>("General", "NormalDayChance", 0.3f, "Chance (0-1) that a low-risk moon gets no event at all (a normal day, normal loot).");
			NormalDayMaxRating = ((BaseUnityPlugin)this).Config.Bind<int>("General", "NormalDayMaxRating", 1, "Which moons count as low-risk for NormalDayChance, by risk rating: 0 = Safe only, 1 = Safe and D, 2 = up to C, and so on.");
			ExtraMobChance = ((BaseUnityPlugin)this).Config.Bind<float>("Difficulty", "ExtraMobChance", 0.35f, "Chance (0-1) that a spawned event mob arrives with a second, different mob from the same vent. The companion is picked to suit the tier. Capped at 4 companions per event. 0 = off.");
			NightmareDarkStartChance = ((BaseUnityPlugin)this).Config.Bind<float>("Difficulty", "NightmareDarkStartChance", 0.5f, "Chance (0-1) that a Nightmare (tier 5) moon starts with the facility lights off. Flip the breaker to restore power.");
			SpawnDelayMultiplier = ((BaseUnityPlugin)this).Config.Bind<float>("Pacing", "SpawnDelayMultiplier", 0.7f, "Multiplies every event timer. 0.7 = event mobs spawn 30% sooner. 1 = original pacing. Warning flickers before spawns are NOT shortened.");
			NightmareBlackoutDelay = ((BaseUnityPlugin)this).Config.Bind<float>("Pacing", "NightmareBlackoutDelay", 40f, "Seconds (roughly) after landing before the blackout hits on Nightmare (tier 5) events.");
			MidasPenaltyPerLevel = ((BaseUnityPlugin)this).Config.Bind<float>("LategameUpgrades", "MidasPenaltyPerLevel", 2f, "Each Midas Touch level reduces the tier scrap bonus by this many percentage points (never below 0).");
			MidasLevelOverride = ((BaseUnityPlugin)this).Config.Bind<int>("LategameUpgrades", "MidasLevelOverride", -1, "-1 = auto-detect from Lategame Upgrades. 0 or higher = use this level instead (use it if auto-detect fails; check the BepInEx log for '[LGU compat]').");
			ShowOnScreen = ((BaseUnityPlugin)this).Config.Bind<bool>("Indicator", "ShowOnScreen", true, "Show a small always-on tier readout in a screen corner while you're on the moon. Set to false to remove it.");
			OnScreenCorner = ((BaseUnityPlugin)this).Config.Bind<string>("Indicator", "OnScreenCorner", "TopRight", "Where the readout sits: TopRight, TopLeft, BottomRight or BottomLeft.");
			OnScreenShowsTierName = ((BaseUnityPlugin)this).Config.Bind<bool>("Indicator", "OnScreenShowsTierName", true, "Include the tier name (e.g. 'Hostile') next to the stars. Set to false for stars only.");
			ShowIndicator = ((BaseUnityPlugin)this).Config.Bind<bool>("Indicator", "ShowIndicator", true, "Show a subtle tension line (e.g. 'Tension: ***--') shortly after landing.");
			IndicatorForEveryone = ((BaseUnityPlugin)this).Config.Bind<bool>("Indicator", "ShowToEveryone", true, "true = posted in chat so every player sees it (others don't need the mod). false = only the host sees it as a HUD tip.");
			IndicatorShowsEventName = ((BaseUnityPlugin)this).Config.Bind<bool>("Indicator", "ShowEventName", false, "Also reveal the event name in the indicator (spoils the surprise).");
			for (int i = 0; i < 5; i++)
			{
				RewardPercent[i] = ((BaseUnityPlugin)this).Config.Bind<float>("Rewards", $"Tier{i + 1}_{TierNames[i]}_ScrapValueBonusPercent", DefaultReward[i], $"Bonus % to scrap value on moons rolling tier {i + 1} ({TierNames[i]}).");
			}
			new Harmony("com.chaosmoons.lethalcompany").PatchAll();
			Log.LogInfo((object)"Chaos Moons 1.6.0 loaded.");
		}
	}
	internal class ChaosRunner : MonoBehaviour
	{
		private static ChaosRunner _inst;

		private static readonly Color[] TierColors = (Color[])(object)new Color[5]
		{
			new Color(0.62f, 0.84f, 0.63f),
			new Color(0.9f, 0.9f, 0.54f),
			new Color(0.94f, 0.71f, 0.35f),
			new Color(0.91f, 0.48f, 0.29f),
			new Color(0.88f, 0.23f, 0.23f)
		};

		private GUIStyle _style;

		internal static ChaosRunner Get()
		{
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			//IL_0017: 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_0025: Expected O, but got Unknown
			if ((Object)(object)_inst == (Object)null)
			{
				GameObject val = new GameObject("ChaosMoonsRunner")
				{
					hideFlags = (HideFlags)61
				};
				Object.DontDestroyOnLoad((Object)val);
				_inst = val.AddComponent<ChaosRunner>();
			}
			return _inst;
		}

		private void OnGUI()
		{
			//IL_0083: Unknown result type (might be due to invalid IL or missing references)
			//IL_0088: Unknown result type (might be due to invalid IL or missing references)
			//IL_0094: Expected O, but got Unknown
			//IL_01b1: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e3: Unknown result type (might be due to invalid IL or missing references)
			//IL_0208: 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)
			if (!ChaosPlugin.ShowOnScreen.Value)
			{
				return;
			}
			int activeTier = ChaosDirector.ActiveTier;
			if (activeTier < 1 || activeTier > 5)
			{
				return;
			}
			StartOfRound instance = StartOfRound.Instance;
			if (!((Object)(object)instance == (Object)null) && instance.shipHasLanded && !instance.inShipPhase)
			{
				string text = (ChaosPlugin.OnScreenCorner.Value ?? "TopRight").Trim().ToLowerInvariant();
				bool flag = text.Contains("right");
				bool flag2 = text.Contains("bottom");
				if (_style == null)
				{
					_style = new GUIStyle(GUI.skin.label)
					{
						fontStyle = (FontStyle)1
					};
				}
				_style.fontSize = Mathf.Max(13, Mathf.RoundToInt((float)Screen.height / 70f));
				_style.alignment = (TextAnchor)((!flag) ? (flag2 ? 6 : 0) : (flag2 ? 8 : 2));
				string text2 = "Tension: " + new string('*', activeTier) + new string('-', 5 - activeTier);
				if (ChaosPlugin.OnScreenShowsTierName.Value)
				{
					text2 = text2 + "  " + ChaosPlugin.TierNames[activeTier - 1];
				}
				if (ChaosPlugin.IndicatorShowsEventName.Value && ChaosDirector.ActiveEvent != null)
				{
					text2 = text2 + "  - " + ChaosDirector.ActiveEvent.Name;
				}
				float num = (flag ? ((float)Screen.width - 420f - 14f) : 14f);
				float num2 = (flag2 ? ((float)Screen.height - 30f - 14f) : 14f);
				Rect val = default(Rect);
				((Rect)(ref val))..ctor(num, num2, 420f, 30f);
				_style.normal.textColor = new Color(0f, 0f, 0f, 0.75f);
				GUI.Label(new Rect(((Rect)(ref val)).x + 1.5f, ((Rect)(ref val)).y + 1.5f, ((Rect)(ref val)).width, ((Rect)(ref val)).height), text2, _style);
				_style.normal.textColor = TierColors[activeTier - 1];
				GUI.Label(val, text2, _style);
			}
		}
	}
	[HarmonyPatch(typeof(RoundManager), "LoadNewLevel")]
	internal static class LoadNewLevelPatch
	{
		private static void Prefix(RoundManager __instance, SelectableLevel newLevel)
		{
			ChaosDirector.Reset();
			if (!((NetworkBehaviour)__instance).IsServer || (Object)(object)newLevel == (Object)null)
			{
				return;
			}
			try
			{
				ChaosDirector.Roll(newLevel);
			}
			catch (Exception ex)
			{
				ChaosPlugin.Log.LogError((object)ex);
			}
		}
	}
	[HarmonyPatch(typeof(RoundManager), "SpawnScrapInLevel")]
	internal static class ScrapValuePatch
	{
		private static void Prefix(RoundManager __instance, out float __state)
		{
			__state = __instance.scrapValueMultiplier;
			if (ChaosDirector.ActiveTier > 0)
			{
				float num = ChaosDirector.EffectiveBonusPercent(ChaosDirector.ActiveTier) / 100f;
				__instance.scrapValueMultiplier *= 1f + num;
			}
		}

		private static void Postfix(RoundManager __instance, float __state)
		{
			__instance.scrapValueMultiplier = __state;
		}
	}
	[HarmonyPatch(typeof(Terminal), "ParsePlayerSentence")]
	internal static class TerminalPatch
	{
		private static bool Prefix(Terminal __instance, ref TerminalNode __result)
		{
			try
			{
				string text = __instance.screenText.text;
				string text2 = text.Substring(text.Length - __instance.textAdded).Trim().ToLowerInvariant();
				if (text2 == "chaos" || text2 == "events")
				{
					TerminalNode val = ScriptableObject.CreateInstance<TerminalNode>();
					val.displayText = ChaosDirector.BuildTerminalText();
					val.clearPreviousText = true;
					__result = val;
					return false;
				}
			}
			catch (Exception ex)
			{
				ChaosPlugin.Log.LogError((object)ex);
			}
			return true;
		}
	}
	internal static class ChaosDirector
	{
		internal static readonly Random Rng = new Random();

		internal static int ActiveTier;

		internal static ChaosEvent ActiveEvent;

		private static readonly double[] BaseShape = new double[5] { 1.0, 1.0, 0.8, 0.5, 0.3 };

		internal static void Reset()
		{
			((MonoBehaviour)ChaosRunner.Get()).StopAllCoroutines();
			ActiveTier = 0;
			ActiveEvent = null;
			Spawner.ClearCache();
		}

		internal static void Roll(SelectableLevel level)
		{
			if (!level.spawnEnemiesAndScrap || Rng.NextDouble() > (double)ChaosPlugin.EventChance.Value)
			{
				return;
			}
			if (Rating(level) <= ChaosPlugin.NormalDayMaxRating.Value && Rng.NextDouble() < (double)ChaosPlugin.NormalDayChance.Value)
			{
				ChaosPlugin.Log.LogInfo((object)("Moon '" + level.PlanetName + "' (risk " + level.riskLevel + ") rolled a normal day."));
				return;
			}
			double[] w = TierWeights(level);
			int tier = PickIndex(w) + 1;
			List<ChaosEvent> list = Events.All.Where((ChaosEvent e) => e.Tier == tier && (!e.UsesOutside || ChaosPlugin.AllowOutsideEvents.Value)).ToList();
			if (list.Count != 0)
			{
				ActiveTier = tier;
				ActiveEvent = list[Rng.Next(list.Count)];
				ChaosPlugin.Log.LogInfo((object)$"Moon '{level.PlanetName}' (risk {level.riskLevel}) rolled tier {tier} ({ChaosPlugin.TierNames[tier - 1]}): {ActiveEvent.Name}");
				((MonoBehaviour)ChaosRunner.Get()).StartCoroutine(Events.RunEvent(ActiveEvent));
			}
		}

		internal static float EffectiveBonusPercent(int tier)
		{
			float value = ChaosPlugin.RewardPercent[tier - 1].Value;
			value -= (float)LguCompat.GetMidasLevel() * ChaosPlugin.MidasPenaltyPerLevel.Value;
			return Mathf.Max(0f, value);
		}

		internal static int Rating(SelectableLevel l)
		{
			return (l?.riskLevel ?? "").Trim().ToUpperInvariant() switch
			{
				"SAFE" => 0, 
				"D" => 1, 
				"C" => 2, 
				"B" => 3, 
				"A" => 4, 
				"S" => 5, 
				"S+" => 6, 
				"S++" => 7, 
				_ => 3, 
			};
		}

		internal static double[] TierWeights(SelectableLevel level)
		{
			double num = ((double)Rating(level) - 3.5) / 3.5;
			double[] array = new double[5];
			for (int i = 0; i < 5; i++)
			{
				array[i] = BaseShape[i] * Math.Exp((double)(i - 2) * num * (double)ChaosPlugin.MoonBias.Value);
			}
			return array;
		}

		private static int PickIndex(double[] w)
		{
			double num = Rng.NextDouble() * w.Sum();
			for (int i = 0; i < w.Length; i++)
			{
				num -= w[i];
				if (num <= 0.0)
				{
					return i;
				}
			}
			return w.Length - 1;
		}

		internal static string BuildTerminalText()
		{
			StringBuilder stringBuilder = new StringBuilder();
			stringBuilder.AppendLine();
			stringBuilder.AppendLine("CHAOS MOONS - POSSIBLE EVENTS");
			stringBuilder.AppendLine("Every moon rolls one event. Harder = more scrap value.");
			if (LguCompat.Present)
			{
				stringBuilder.AppendLine("Bonuses are reduced slightly per Midas Touch level.");
			}
			stringBuilder.AppendLine();
			int t;
			for (t = 1; t <= 5; t++)
			{
				stringBuilder.AppendLine($"[Tier {t}] {ChaosPlugin.TierNames[t - 1]}  (+{EffectiveBonusPercent(t):0}% scrap value)");
				foreach (ChaosEvent item in Events.All.Where((ChaosEvent e) => e.Tier == t))
				{
					stringBuilder.AppendLine("   * " + item.Name + " - " + item.Description);
				}
				stringBuilder.AppendLine();
			}
			SelectableLevel val = (((Object)(object)StartOfRound.Instance != (Object)null) ? StartOfRound.Instance.currentLevel : null);
			if ((Object)(object)val != (Object)null && val.spawnEnemiesAndScrap)
			{
				double[] source = TierWeights(val);
				double sum = source.Sum();
				stringBuilder.AppendLine("Tier odds for " + val.PlanetName + " (risk " + val.riskLevel + "):");
				stringBuilder.AppendLine("   " + string.Join("  ", source.Select((double x, int i) => $"T{i + 1}: {x / sum * 100.0:0}%")));
				if (Rating(val) <= ChaosPlugin.NormalDayMaxRating.Value)
				{
					stringBuilder.AppendLine($"   Normal day (no event): {ChaosPlugin.NormalDayChance.Value * 100f:0}%");
				}
				stringBuilder.AppendLine();
			}
			return stringBuilder.ToString() + "\n";
		}
	}
}