Decompiled source of Larger Levels v1.0.0

LevelGenX.dll

Decompiled a week 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 BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using UnityEngine;

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

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

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

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

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace LevelGenX
{
	[BepInPlugin("Omniscye.LevelGenX", "LevelGenX", "1.0")]
	public class LevelGenX : BaseUnityPlugin
	{
		internal static LevelGenX Instance { get; private set; }

		internal static ManualLogSource Logger => Instance._logger;

		private ManualLogSource _logger => ((BaseUnityPlugin)this).Logger;

		internal Harmony? Harmony { get; set; }

		private void Awake()
		{
			Instance = this;
			((Component)this).gameObject.transform.parent = null;
			((Object)((Component)this).gameObject).hideFlags = (HideFlags)61;
			Patch();
			Logger.LogInfo((object)$"{((BaseUnityPlugin)this).Info.Metadata.GUID} v{((BaseUnityPlugin)this).Info.Metadata.Version} has loaded!");
		}

		internal void Patch()
		{
			//IL_001a: Unknown result type (might be due to invalid IL or missing references)
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0021: Expected O, but got Unknown
			//IL_0026: Expected O, but got Unknown
			if (Harmony == null)
			{
				Harmony val = new Harmony(((BaseUnityPlugin)this).Info.Metadata.GUID);
				Harmony val2 = val;
				Harmony = val;
			}
			Harmony.PatchAll();
		}

		internal void Unpatch()
		{
			Harmony? harmony = Harmony;
			if (harmony != null)
			{
				harmony.UnpatchSelf();
			}
		}

		private void Update()
		{
		}
	}
}
namespace Empress.RepoMods.CursedMegaModules
{
	[BepInPlugin("empress.repo.cursedmegamodules", "Empress - Cursed Mega Modules", "1.1.0")]
	public class CursedMegaModulesPlugin : BaseUnityPlugin
	{
		public const string Guid = "empress.repo.cursedmegamodules";

		public const string Name = "Empress - Cursed Mega Modules";

		public const string Version = "1.1.0";

		internal static ManualLogSource Log;

		internal static Harmony Harmony;

		internal static ConfigEntry<int> CfgMultiplier;

		internal static ConfigEntry<bool> CfgAutoGridScale;

		internal static ConfigEntry<float> CfgGridScaleExtra;

		internal static ConfigEntry<int> CfgKeepRangeModules;

		internal static ConfigEntry<int> CfgKeepRangeHysteresis;

		internal static ConfigEntry<float> CfgUpdateInterval;

		internal static ConfigEntry<bool> CfgCullColliders;

		internal static ConfigEntry<bool> CfgCullEnemies;

		internal static ConfigEntry<bool> CfgCullValuables;

		internal static ConfigEntry<bool> CfgCullAudio;

		internal static ConfigEntry<int> CfgValuableMultiplier;

		private void Awake()
		{
			//IL_017d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0187: Expected O, but got Unknown
			//IL_01b6: Unknown result type (might be due to invalid IL or missing references)
			//IL_01bc: Expected O, but got Unknown
			Log = ((BaseUnityPlugin)this).Logger;
			CfgMultiplier = ((BaseUnityPlugin)this).Config.Bind<int>("Scale", "ModuleMultiplier", 10000, "Multiply base Level.ModuleAmount by this factor (master only).");
			CfgAutoGridScale = ((BaseUnityPlugin)this).Config.Bind<bool>("Scale", "AutoGridScale", true, "Automatically enlarge level grid based on multiplier.");
			CfgGridScaleExtra = ((BaseUnityPlugin)this).Config.Bind<float>("Scale", "GridScaleExtra", 100.5f, "Extra grid scale added on top of sqrt(multiplier) to avoid cramped layouts.");
			CfgKeepRangeModules = ((BaseUnityPlugin)this).Config.Bind<int>("Streaming", "KeepRangeModules", 3, "Chebyshev grid distance around any player to keep modules active.");
			CfgKeepRangeHysteresis = ((BaseUnityPlugin)this).Config.Bind<int>("Streaming", "KeepRangeHysteresis", 1, "Extra buffer to prevent rapid on/off flapping.");
			CfgUpdateInterval = ((BaseUnityPlugin)this).Config.Bind<float>("Streaming", "UpdateInterval", 0.5f, "Seconds between culling passes.");
			CfgCullColliders = ((BaseUnityPlugin)this).Config.Bind<bool>("Streaming", "CullColliders", true, "Disable non-trigger colliders on culled modules.");
			CfgCullEnemies = ((BaseUnityPlugin)this).Config.Bind<bool>("Streaming", "CullEnemies", true, "Disable EnemyParent GameObjects on culled modules.");
			CfgCullValuables = ((BaseUnityPlugin)this).Config.Bind<bool>("Streaming", "CullValuables", true, "Disable ValuableObject GameObjects on culled modules.");
			CfgCullAudio = ((BaseUnityPlugin)this).Config.Bind<bool>("Streaming", "CullAudio", true, "Disable AudioSources on culled modules.");
			CfgValuableMultiplier = ((BaseUnityPlugin)this).Config.Bind<int>("Valuables", "ValuableSpawnMultiplier", 3, "Multiply each ValuableDirector.Spawn call by this factor. 1 = off.");
			Harmony = new Harmony("empress.repo.cursedmegamodules");
			Harmony.PatchAll(typeof(LevelGenerator_Start_Patch));
			Harmony.PatchAll(typeof(ValuableDirector_Spawn_Patch));
			GameObject val = new GameObject("Empress_ModuleStreamer");
			Object.DontDestroyOnLoad((Object)(object)val);
			((Object)val).hideFlags = (HideFlags)61;
			val.AddComponent<ModuleStreamer>();
			Log.LogInfo((object)"Empress - Cursed Mega Modules v1.1.0 loaded. Try not to melt your GPU.");
		}

		private void OnDestroy()
		{
			try
			{
				Harmony harmony = Harmony;
				if (harmony != null)
				{
					harmony.UnpatchSelf();
				}
			}
			catch
			{
			}
		}
	}
	[HarmonyPatch(typeof(LevelGenerator), "Start")]
	internal static class LevelGenerator_Start_Patch
	{
		[HarmonyPostfix]
		private static void Postfix(LevelGenerator __instance)
		{
			try
			{
				RunManager instance = RunManager.instance;
				Level val = (((Object)(object)instance != (Object)null) ? instance.levelCurrent : null);
				if ((Object)(object)val == (Object)null)
				{
					CursedMegaModulesPlugin.Log.LogWarning((object)"[Cursed] RunManager.levelCurrent is null; skipping multiplier this scene.");
					return;
				}
				int moduleAmount = val.ModuleAmount;
				int num = Mathf.Max(1, moduleAmount * CursedMegaModulesPlugin.CfgMultiplier.Value);
				FieldInfo fieldInfo = AccessTools.Field(typeof(LevelGenerator), "DebugAmount");
				FieldInfo fieldInfo2 = AccessTools.Field(typeof(LevelGenerator), "DebugLevelSize");
				if (fieldInfo == null || fieldInfo2 == null)
				{
					CursedMegaModulesPlugin.Log.LogError((object)"[Cursed] Could not find LevelGenerator.DebugAmount/DebugLevelSize fields. Aborting patch.");
					return;
				}
				fieldInfo.SetValue(__instance, num);
				if (CursedMegaModulesPlugin.CfgAutoGridScale.Value)
				{
					float num2 = (float)fieldInfo2.GetValue(__instance);
					float num3 = Mathf.Sqrt((float)CursedMegaModulesPlugin.CfgMultiplier.Value) + CursedMegaModulesPlugin.CfgGridScaleExtra.Value;
					float num4 = Mathf.Max(num2, num3);
					fieldInfo2.SetValue(__instance, num4);
				}
				CursedMegaModulesPlugin.Log.LogInfo((object)$"[Cursed] Level module count bumped: {moduleAmount} -> {num}. Grid scale adjusted.");
			}
			catch (Exception arg)
			{
				CursedMegaModulesPlugin.Log.LogError((object)$"[Cursed] LevelGenerator.Start postfix failed: {arg}");
			}
		}
	}
	[HarmonyPatch(typeof(ValuableDirector), "Spawn")]
	internal static class ValuableDirector_Spawn_Patch
	{
		private static readonly MethodInfo SpawnMI = AccessTools.Method(typeof(ValuableDirector), "Spawn", new Type[3]
		{
			typeof(GameObject),
			typeof(ValuableVolume),
			typeof(string)
		}, (Type[])null);

		[ThreadStatic]
		private static bool _reentry;

		[HarmonyPostfix]
		private static void Postfix(ValuableDirector __instance, GameObject _valuable, ValuableVolume _volume, string _path)
		{
			if (_reentry)
			{
				return;
			}
			int num = Mathf.Max(1, CursedMegaModulesPlugin.CfgValuableMultiplier.Value);
			if (num <= 1)
			{
				return;
			}
			if (SpawnMI == null)
			{
				CursedMegaModulesPlugin.Log.LogError((object)"[Cursed] ValuableDirector.Spawn reflection failed; valuables multiplier disabled.");
				return;
			}
			try
			{
				_reentry = true;
				for (int i = 1; i < num; i++)
				{
					SpawnMI.Invoke(__instance, new object[3] { _valuable, _volume, _path });
				}
			}
			catch (Exception arg)
			{
				CursedMegaModulesPlugin.Log.LogError((object)$"[Cursed] Valuable multiply failed: {arg}");
			}
			finally
			{
				_reentry = false;
			}
		}
	}
	internal class ModuleStreamer : MonoBehaviour
	{
		private class ModuleEntry
		{
			public readonly Module Module;

			public readonly bool IsTruckOrExtraction;

			public readonly int CachedGridX;

			public readonly int CachedGridY;

			private readonly Renderer[] _renderers;

			private readonly Light[] _lights;

			private readonly ParticleSystem[] _particles;

			private readonly AudioSource[] _audio;

			private readonly Collider[] _colliders;

			private readonly ValuableObject[] _valuables;

			private readonly EnemyParent[] _enemies;

			private readonly Dictionary<Behaviour, bool> _origBehaviourEnabled = new Dictionary<Behaviour, bool>();

			private readonly Dictionary<Collider, bool> _origColliderEnabled = new Dictionary<Collider, bool>();

			private readonly Dictionary<Renderer, bool> _origRendererEnabled = new Dictionary<Renderer, bool>();

			private readonly Dictionary<ParticleSystem, bool> _origParticleGOActive = new Dictionary<ParticleSystem, bool>();

			private readonly HashSet<ParticleSystem> _origParticleWasPlaying = new HashSet<ParticleSystem>();

			public bool Culled { get; private set; }

			public ModuleEntry(Module m, bool truckOrExtraction, int gridX, int gridY)
			{
				Module = m;
				IsTruckOrExtraction = truckOrExtraction;
				CachedGridX = gridX;
				CachedGridY = gridY;
				_renderers = ((Component)m).GetComponentsInChildren<Renderer>(true);
				_lights = ((Component)m).GetComponentsInChildren<Light>(true);
				_particles = ((Component)m).GetComponentsInChildren<ParticleSystem>(true);
				_audio = ((Component)m).GetComponentsInChildren<AudioSource>(true);
				_colliders = ((Component)m).GetComponentsInChildren<Collider>(true);
				_valuables = ((Component)m).GetComponentsInChildren<ValuableObject>(true);
				_enemies = ((Component)m).GetComponentsInChildren<EnemyParent>(true);
				Light[] lights = _lights;
				foreach (Light b in lights)
				{
					Remember((Behaviour)(object)b);
				}
				AudioSource[] audio = _audio;
				foreach (AudioSource b2 in audio)
				{
					Remember((Behaviour)(object)b2);
				}
				EnemyParent[] enemies = _enemies;
				foreach (EnemyParent b3 in enemies)
				{
					Remember((Behaviour)(object)b3);
				}
				Collider[] colliders = _colliders;
				foreach (Collider val in colliders)
				{
					if (Object.op_Implicit((Object)(object)val))
					{
						_origColliderEnabled[val] = val.enabled;
					}
				}
				Renderer[] renderers = _renderers;
				foreach (Renderer val2 in renderers)
				{
					if (Object.op_Implicit((Object)(object)val2))
					{
						_origRendererEnabled[val2] = val2.enabled;
					}
				}
				ParticleSystem[] particles = _particles;
				foreach (ParticleSystem val3 in particles)
				{
					if (Object.op_Implicit((Object)(object)val3))
					{
						_origParticleGOActive[val3] = ((Component)val3).gameObject.activeSelf;
						if (val3.isPlaying)
						{
							_origParticleWasPlaying.Add(val3);
						}
					}
				}
			}

			private void Remember(Behaviour b)
			{
				if (Object.op_Implicit((Object)(object)b) && !_origBehaviourEnabled.ContainsKey(b))
				{
					_origBehaviourEnabled[b] = b.enabled;
				}
			}

			public void SetCulled(bool culled)
			{
				if (culled == Culled)
				{
					return;
				}
				Culled = culled;
				Renderer[] renderers = _renderers;
				foreach (Renderer val in renderers)
				{
					if (Object.op_Implicit((Object)(object)val))
					{
						val.enabled = !culled && (!_origRendererEnabled.TryGetValue(val, out var value) || value);
					}
				}
				Light[] lights = _lights;
				foreach (Light val2 in lights)
				{
					if (Object.op_Implicit((Object)(object)val2))
					{
						((Behaviour)val2).enabled = !culled && (!_origBehaviourEnabled.TryGetValue((Behaviour)(object)val2, out var value2) || value2);
					}
				}
				ParticleSystem[] particles = _particles;
				foreach (ParticleSystem val3 in particles)
				{
					if (!Object.op_Implicit((Object)(object)val3))
					{
						continue;
					}
					if (culled)
					{
						val3.Pause(true);
						((Component)val3).gameObject.SetActive(false);
						continue;
					}
					bool value3;
					bool flag = !_origParticleGOActive.TryGetValue(val3, out value3) || value3;
					((Component)val3).gameObject.SetActive(flag);
					if (flag && _origParticleWasPlaying.Contains(val3))
					{
						val3.Play(true);
					}
				}
				if (CursedMegaModulesPlugin.CfgCullAudio.Value)
				{
					AudioSource[] audio = _audio;
					foreach (AudioSource val4 in audio)
					{
						if (Object.op_Implicit((Object)(object)val4))
						{
							((Behaviour)val4).enabled = !culled && (!_origBehaviourEnabled.TryGetValue((Behaviour)(object)val4, out var value4) || value4);
						}
					}
				}
				if (CursedMegaModulesPlugin.CfgCullColliders.Value)
				{
					Collider[] colliders = _colliders;
					foreach (Collider val5 in colliders)
					{
						if (Object.op_Implicit((Object)(object)val5) && !val5.isTrigger)
						{
							val5.enabled = !culled && (!_origColliderEnabled.TryGetValue(val5, out var value5) || value5);
						}
					}
				}
				if (CursedMegaModulesPlugin.CfgCullEnemies.Value)
				{
					EnemyParent[] enemies = _enemies;
					foreach (EnemyParent val6 in enemies)
					{
						if (Object.op_Implicit((Object)(object)val6) && Object.op_Implicit((Object)(object)((Component)val6).gameObject))
						{
							((Component)val6).gameObject.SetActive(!culled);
						}
					}
				}
				if (!CursedMegaModulesPlugin.CfgCullValuables.Value)
				{
					return;
				}
				ValuableObject[] valuables = _valuables;
				foreach (ValuableObject val7 in valuables)
				{
					if (Object.op_Implicit((Object)(object)val7) && Object.op_Implicit((Object)(object)((Component)val7).gameObject))
					{
						((Component)val7).gameObject.SetActive(!culled);
					}
				}
			}
		}

		[CompilerGenerated]
		private sealed class <Bootstrap>d__10 : IEnumerator<object>, IEnumerator, IDisposable
		{
			private int <>1__state;

			private object <>2__current;

			public ModuleStreamer <>4__this;

			private Module[] <allMods>5__1;

			private Module[] <>s__2;

			private int <>s__3;

			private Module <mod>5__4;

			private RoomVolume[] <rooms>5__5;

			private bool <isTruckOrExtraction>5__6;

			private int <gx>5__7;

			private int <gy>5__8;

			object IEnumerator<object>.Current
			{
				[DebuggerHidden]
				get
				{
					return <>2__current;
				}
			}

			object IEnumerator.Current
			{
				[DebuggerHidden]
				get
				{
					return <>2__current;
				}
			}

			[DebuggerHidden]
			public <Bootstrap>d__10(int <>1__state)
			{
				this.<>1__state = <>1__state;
			}

			[DebuggerHidden]
			void IDisposable.Dispose()
			{
				<allMods>5__1 = null;
				<>s__2 = null;
				<mod>5__4 = null;
				<rooms>5__5 = null;
				<>1__state = -2;
			}

			private bool MoveNext()
			{
				switch (<>1__state)
				{
				default:
					return false;
				case 0:
					<>1__state = -1;
					goto IL_004d;
				case 1:
					<>1__state = -1;
					goto IL_004d;
				case 2:
					<>1__state = -1;
					goto IL_0075;
				case 3:
					{
						<>1__state = -1;
						return false;
					}
					IL_004d:
					if ((Object)(object)LevelGenerator.Instance == (Object)null)
					{
						<>2__current = null;
						<>1__state = 1;
						return true;
					}
					goto IL_0075;
					IL_0075:
					if (!LevelGenerator.Instance.Generated)
					{
						<>2__current = null;
						<>1__state = 2;
						return true;
					}
					<>4__this._modules.Clear();
					<allMods>5__1 = Object.FindObjectsOfType<Module>(true);
					<>s__2 = <allMods>5__1;
					for (<>s__3 = 0; <>s__3 < <>s__2.Length; <>s__3++)
					{
						<mod>5__4 = <>s__2[<>s__3];
						if (!((Object)(object)<mod>5__4 == (Object)null))
						{
							<rooms>5__5 = ((Component)<mod>5__4).GetComponentsInChildren<RoomVolume>(true);
							<isTruckOrExtraction>5__6 = <rooms>5__5.Any((RoomVolume r) => (Object)(object)r != (Object)null && (r.Truck || r.Extraction));
							<gx>5__7 = SafeGridCoord(FGridX, <mod>5__4);
							<gy>5__8 = SafeGridCoord(FGridY, <mod>5__4);
							<>4__this._modules.Add(new ModuleEntry(<mod>5__4, <isTruckOrExtraction>5__6, <gx>5__7, <gy>5__8));
							<rooms>5__5 = null;
							<mod>5__4 = null;
						}
					}
					<>s__2 = null;
					<>4__this._ready = true;
					CursedMegaModulesPlugin.Log.LogInfo((object)$"[Cursed] ModuleStreamer ready. Tracking {<>4__this._modules.Count} modules.");
					<>2__current = ((MonoBehaviour)<>4__this).StartCoroutine(<>4__this.TickLoop());
					<>1__state = 3;
					return true;
				}
			}

			bool IEnumerator.MoveNext()
			{
				//ILSpy generated this explicit interface implementation from .override directive in MoveNext
				return this.MoveNext();
			}

			[DebuggerHidden]
			void IEnumerator.Reset()
			{
				throw new NotSupportedException();
			}
		}

		[CompilerGenerated]
		private sealed class <TickLoop>d__12 : IEnumerator<object>, IEnumerator, IDisposable
		{
			private int <>1__state;

			private object <>2__current;

			public ModuleStreamer <>4__this;

			private Exception <e>5__1;

			object IEnumerator<object>.Current
			{
				[DebuggerHidden]
				get
				{
					return <>2__current;
				}
			}

			object IEnumerator.Current
			{
				[DebuggerHidden]
				get
				{
					return <>2__current;
				}
			}

			[DebuggerHidden]
			public <TickLoop>d__12(int <>1__state)
			{
				this.<>1__state = <>1__state;
			}

			[DebuggerHidden]
			void IDisposable.Dispose()
			{
				<e>5__1 = null;
				<>1__state = -2;
			}

			private bool MoveNext()
			{
				//IL_0075: Unknown result type (might be due to invalid IL or missing references)
				//IL_007f: Expected O, but got Unknown
				switch (<>1__state)
				{
				default:
					return false;
				case 0:
					<>1__state = -1;
					break;
				case 1:
					<>1__state = -1;
					break;
				}
				try
				{
					if (<>4__this._ready)
					{
						<>4__this.Evaluate();
					}
				}
				catch (Exception ex)
				{
					<e>5__1 = ex;
					CursedMegaModulesPlugin.Log.LogError((object)$"[Cursed] Stream tick failed: {<e>5__1}");
				}
				<>2__current = (object)new WaitForSeconds(<>4__this._interval);
				<>1__state = 1;
				return true;
			}

			bool IEnumerator.MoveNext()
			{
				//ILSpy generated this explicit interface implementation from .override directive in MoveNext
				return this.MoveNext();
			}

			[DebuggerHidden]
			void IEnumerator.Reset()
			{
				throw new NotSupportedException();
			}
		}

		private readonly List<ModuleEntry> _modules = new List<ModuleEntry>();

		private int _keepRange;

		private int _keepRangeHysteresis;

		private float _interval;

		private bool _ready;

		private Coroutine _runner;

		private static readonly FieldInfo FGridX = AccessTools.Field(typeof(Module), "GridX");

		private static readonly FieldInfo FGridY = AccessTools.Field(typeof(Module), "GridY");

		private void OnEnable()
		{
			_keepRange = Mathf.Max(0, CursedMegaModulesPlugin.CfgKeepRangeModules.Value);
			_keepRangeHysteresis = Mathf.Max(0, CursedMegaModulesPlugin.CfgKeepRangeHysteresis.Value);
			_interval = Mathf.Max(0.05f, CursedMegaModulesPlugin.CfgUpdateInterval.Value);
			_runner = ((MonoBehaviour)this).StartCoroutine(Bootstrap());
		}

		private void OnDisable()
		{
			if (_runner != null)
			{
				((MonoBehaviour)this).StopCoroutine(_runner);
			}
			_runner = null;
			_modules.Clear();
			_ready = false;
		}

		[IteratorStateMachine(typeof(<Bootstrap>d__10))]
		private IEnumerator Bootstrap()
		{
			//yield-return decompiler failed: Unexpected instruction in Iterator.Dispose()
			return new <Bootstrap>d__10(0)
			{
				<>4__this = this
			};
		}

		private static int SafeGridCoord(FieldInfo fi, Module m)
		{
			try
			{
				if (fi == null)
				{
					return 0;
				}
				object value = fi.GetValue(m);
				if (value is int)
				{
					int result = (int)value;
					if (true)
					{
						return result;
					}
				}
			}
			catch
			{
			}
			return 0;
		}

		[IteratorStateMachine(typeof(<TickLoop>d__12))]
		private IEnumerator TickLoop()
		{
			//yield-return decompiler failed: Unexpected instruction in Iterator.Dispose()
			return new <TickLoop>d__12(0)
			{
				<>4__this = this
			};
		}

		private void Evaluate()
		{
			//IL_0149: Unknown result type (might be due to invalid IL or missing references)
			HashSet<ModuleEntry> occupiedModules = GetOccupiedModules();
			List<ModuleEntry> list = occupiedModules.ToList();
			foreach (ModuleEntry module in _modules)
			{
				if ((Object)(object)module.Module == (Object)null)
				{
					continue;
				}
				if (module.IsTruckOrExtraction)
				{
					module.SetCulled(culled: false);
					continue;
				}
				if (occupiedModules.Contains(module))
				{
					module.SetCulled(culled: false);
					continue;
				}
				bool flag;
				if (list.Count > 0)
				{
					int num = int.MaxValue;
					foreach (ModuleEntry item in list)
					{
						int num2 = Mathf.Abs(item.CachedGridX - module.CachedGridX);
						int num3 = Mathf.Abs(item.CachedGridY - module.CachedGridY);
						int num4 = Mathf.Max(num2, num3);
						if (num4 < num)
						{
							num = num4;
						}
					}
					int keepRange = _keepRange;
					int num5 = _keepRange + _keepRangeHysteresis;
					flag = (module.Culled ? (num <= keepRange) : (num <= num5));
				}
				else
				{
					float num6 = SemiFunc.PlayerNearestDistance(((Component)module.Module).transform.position);
					float num7 = LevelGenerator.TileSize * LevelGenerator.ModuleWidth;
					float num8 = Mathf.Max(num7 * (float)_keepRange, 15f);
					flag = (module.Culled ? (num6 <= num8) : (num6 <= num8 * 1.3f));
				}
				module.SetCulled(!flag);
			}
		}

		private HashSet<ModuleEntry> GetOccupiedModules()
		{
			HashSet<ModuleEntry> hashSet = new HashSet<ModuleEntry>();
			List<PlayerAvatar> list = (((Object)(object)GameDirector.instance != (Object)null) ? GameDirector.instance.PlayerList : null);
			if (list == null || list.Count == 0)
			{
				return hashSet;
			}
			foreach (PlayerAvatar item in list)
			{
				if ((Object)(object)item == (Object)null || (Object)(object)item.RoomVolumeCheck == (Object)null)
				{
					continue;
				}
				List<RoomVolume> currentRooms = item.RoomVolumeCheck.CurrentRooms;
				if (currentRooms == null)
				{
					continue;
				}
				foreach (RoomVolume item2 in currentRooms)
				{
					if ((Object)(object)item2 == (Object)null)
					{
						continue;
					}
					Module i = ((Component)item2).GetComponentInParent<Module>();
					if (!((Object)(object)i == (Object)null))
					{
						ModuleEntry moduleEntry = _modules.FirstOrDefault((ModuleEntry e) => (Object)(object)e.Module == (Object)(object)i);
						if (moduleEntry != null)
						{
							hashSet.Add(moduleEntry);
						}
					}
				}
			}
			return hashSet;
		}
	}
}