Decompiled source of Empress Twilight Forest Compat Patch v3.5.0

TwilightForestCompatPatch.dll

Decompiled a month 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 HarmonyLib;
using Microsoft.CodeAnalysis;
using Photon.Pun;
using REPOLib;
using REPOLib.Modules;
using Unity.AI.Navigation;
using UnityEngine;
using UnityEngine.AI;
using UnityEngine.Audio;
using UnityEngine.SceneManagement;
using UnityEngine.UI;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("Empress")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.7.0")]
[assembly: AssemblyInformationalVersion("1.0.7")]
[assembly: AssemblyProduct("TwilightForestCompatPatch")]
[assembly: AssemblyTitle("TwilightForestCompatPatch")]
[assembly: AssemblyVersion("1.0.7.0")]
[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 TwilightForestCompatPatch
{
	[BepInPlugin("empress.repo.twilightforestcompatpatch", "Empress Twilight Forest Compat Patch", "1.0.7")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	public sealed class TwilightForestCompatPatchPlugin : BaseUnityPlugin
	{
		private sealed class TwilightPrefabBuckets
		{
			public List<GameObject> StartRooms { get; set; } = new List<GameObject>();


			public List<GameObject> Normal1 { get; set; } = new List<GameObject>();


			public List<GameObject> Passage1 { get; set; } = new List<GameObject>();


			public List<GameObject> DeadEnd1 { get; set; } = new List<GameObject>();


			public List<GameObject> Extraction1 { get; set; } = new List<GameObject>();


			public List<GameObject> Normal2 { get; set; } = new List<GameObject>();


			public List<GameObject> Passage2 { get; set; } = new List<GameObject>();


			public List<GameObject> DeadEnd2 { get; set; } = new List<GameObject>();


			public List<GameObject> Extraction2 { get; set; } = new List<GameObject>();


			public List<GameObject> Normal3 { get; set; } = new List<GameObject>();


			public List<GameObject> Passage3 { get; set; } = new List<GameObject>();


			public List<GameObject> DeadEnd3 { get; set; } = new List<GameObject>();


			public List<GameObject> Extraction3 { get; set; } = new List<GameObject>();


			public int TotalModuleCount => Normal1.Count + Passage1.Count + DeadEnd1.Count + Extraction1.Count + Normal2.Count + Passage2.Count + DeadEnd2.Count + Extraction2.Count + Normal3.Count + Passage3.Count + DeadEnd3.Count + Extraction3.Count;
		}

		private sealed class TwilightLoadingGraphic
		{
			public AssetBundle Bundle { get; }

			public Sprite Sprite { get; }

			public string ResourcePath { get; }

			public bool CanUsePrefabRef { get; }

			public TwilightLoadingGraphic(AssetBundle bundle, Sprite sprite, string resourcePath, bool canUsePrefabRef)
			{
				Bundle = bundle;
				Sprite = sprite;
				ResourcePath = resourcePath;
				CanUsePrefabRef = canUsePrefabRef;
			}
		}

		internal const string PluginGuid = "empress.repo.twilightforestcompatpatch";

		internal const string PluginName = "Empress Twilight Forest Compat Patch";

		internal const string PluginVersion = "1.0.7";

		private const string TwilightBundleFileName = "Minecraft_Twilight_Forest.repobundle";

		private const string TwilightLevelName = "Level - Twilightforest";

		private const string TwilightLevelResourcePath = "Twilightforest";

		private const float TwilightLevelPointCheckRadius = 0.5f;

		private const float TwilightLevelPointRepairRadius = 2f;

		private const float TwilightLevelPointConnectDistance = 15f;

		private const float TwilightLevelPointConnectForwardDot = -0.8f;

		private const float TwilightLevelPointConnectApproachDot = 0.8f;

		private const float TwilightLevelPointValidationDelay = 0.5f;

		private const int TwilightVehicleVolumeCount = 4;

		private const float TwilightVehicleVolumeSideOffset = 2f;

		private const float TwilightVehicleVolumeForwardOffset = 2.5f;

		private const float TwilightVehicleVolumeForwardSpacing = 2f;

		private const float TwilightChargingStationForwardOffset = 6.5f;

		private static readonly string[] TwilightStartRoomNames = new string[1] { "Start Room - Twilight - Entrance" };

		private static readonly string[] TwilightNormal1Names = new string[8] { "Module - Twilight - Lone Oak", "Module -- Twilight - Hedge Cross", "Module -- Twilight - TreeClimb", "Module -- Twilight - Ruined Portal", "Module -- Twilight - Labyrinth Entrance", "Module -- Twilight - Hedge Intersection", "Module -- Twilight - Hedge Spider Spawner", "Module -- Twilight - Hedge Transformation Tree" };

		private static readonly string[] TwilightPassage1Names = new string[2] { "Module -- Twilight - Log Passage", "Module -- Twilight - Naga Skeleton" };

		private static readonly string[] TwilightDeadEnd1Names = new string[1] { "Module -- Twilight - Witch Hut Dead End" };

		private static readonly string[] TwilightExtraction1Names = new string[1] { "Module -- Twilight - Questing_Grove" };

		private static readonly string[] TwilightNormal2Names = new string[2] { "Module -- Twilight  - Stone Pit", "Module -- Twilight - Hollow Hill" };

		private static readonly string[] TwilightPassage2Names = new string[1] { "Module -- Twilight - Maze Passage" };

		private static readonly string[] TwilightDeadEnd2Names = new string[1] { "Module -- Twilight - Lich Tower Dead End1" };

		private static readonly string[] TwilightExtraction2Names = new string[1] { "Module -- Twilight - Questing_Grove" };

		private static readonly string[] TwilightNormal3Names = new string[2] { "Module -- Twilight - Mangrove Tree", "Module -- Twilight - Castle Forcefields" };

		private static readonly string[] TwilightPassage3Names = new string[1] { "Module -- Twilight - Lava Passage" };

		private static readonly string[] TwilightDeadEnd3Names = new string[1] { "Module -- Twilight - Dark Tower Dead End" };

		private static readonly string[] TwilightExtraction3Names = new string[1] { "Module -- Twilight - Questing_Grove" };

		private static readonly string[] TwilightLoadingGraphicFieldNames = new string[3] { "LoadingGraphic01", "LoadingGraphic02", "LoadingGraphic03" };

		private static readonly string[] TwilightPreferredLoadingGraphicNames = new string[3] { "level twilightforest 04", "level twilightforest 05", "level twilightforest 06" };

		private static readonly List<Sprite> TwilightLoadingSprites = new List<Sprite>();

		private readonly Harmony _twilightHarmony = new Harmony("empress.repo.twilightforestcompatpatch");

		private AssetBundle? _twilightBundle;

		private bool _twilightRepairApplied;

		private bool _twilightRepairQueued;

		private bool _twilightLoggedMissingBundle;

		private bool _twilightLoggedMissingPrefabs;

		private bool _twilightLoggedDoorMapFallback;

		internal static TwilightForestCompatPatchPlugin? Instance { get; private set; }

		private void Awake()
		{
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0014: Unknown result type (might be due to invalid IL or missing references)
			Instance = this;
			GameObject gameObject = ((Component)this).gameObject;
			((Object)gameObject).hideFlags = (HideFlags)(((Object)gameObject).hideFlags | 0x23);
			BundleLoader.OnAllBundlesLoaded += TwilightHandleBundlesLoaded;
			_twilightHarmony.PatchAll();
			if ((Object)(object)RunManager.instance != (Object)null)
			{
				((MonoBehaviour)this).StartCoroutine(TwilightRepairWhenReady());
			}
		}

		private void TwilightHandleBundlesLoaded()
		{
			if (_twilightRepairQueued || _twilightRepairApplied)
			{
				return;
			}
			_twilightRepairQueued = true;
			try
			{
				TwilightTryRepairLevel();
			}
			finally
			{
				_twilightRepairQueued = false;
			}
		}

		private IEnumerator TwilightRepairWhenReady()
		{
			yield return null;
			for (int attempt = 0; attempt < 120; attempt++)
			{
				if (_twilightRepairApplied)
				{
					break;
				}
				if (TwilightTryRepairLevel())
				{
					break;
				}
				yield return null;
			}
			_twilightRepairQueued = false;
		}

		internal bool TwilightTryRepairCurrentLevel()
		{
			List<Level> list = new List<Level>();
			if ((Object)(object)LevelGenerator.Instance != (Object)null && (Object)(object)LevelGenerator.Instance.Level != (Object)null)
			{
				list.Add(LevelGenerator.Instance.Level);
			}
			if ((Object)(object)RunManager.instance != (Object)null && (Object)(object)RunManager.instance.levelCurrent != (Object)null)
			{
				list.Add(RunManager.instance.levelCurrent);
			}
			return TwilightTryRepairLevel(list);
		}

		private bool TwilightTryRepairLevel(IEnumerable<Level>? candidates = null)
		{
			if (_twilightRepairApplied)
			{
				return true;
			}
			Level val = TwilightFindLevel(candidates) ?? TwilightFindLevel(Levels.AllLevels);
			if ((Object)(object)val == (Object)null)
			{
				return false;
			}
			AssetBundle val2 = TwilightGetBundle();
			if ((Object)(object)val2 == (Object)null)
			{
				if (!_twilightLoggedMissingBundle)
				{
					_twilightLoggedMissingBundle = true;
					((BaseUnityPlugin)this).Logger.LogWarning((object)"Empress Twilight Forest Compat Patch could not locate the Twilight Forest bundle.");
				}
				return false;
			}
			_twilightLoggedMissingBundle = false;
			TwilightPrefabBuckets twilightPrefabBuckets = TwilightCollectPrefabs(val2);
			if (twilightPrefabBuckets.StartRooms.Count == 0 || twilightPrefabBuckets.TotalModuleCount == 0)
			{
				if (!_twilightLoggedMissingPrefabs)
				{
					_twilightLoggedMissingPrefabs = true;
					((BaseUnityPlugin)this).Logger.LogError((object)"Empress Twilight Forest Compat Patch could not rebuild the Twilight Forest prefab lists from the original bundle.");
				}
				return false;
			}
			_twilightLoggedMissingPrefabs = false;
			TwilightApplyHideFlags((Object)(object)val2);
			TwilightApplyHideFlags((Object)(object)val);
			TwilightEnsureLevelFallbackData(val);
			TwilightEnsureLevelLoadingGraphics(val, val2);
			TwilightRegisterLevelObjects(val);
			val.StartRooms = TwilightRegisterPrefabs(val, "StartRoom", twilightPrefabBuckets.StartRooms);
			val.ModulesNormal1 = TwilightRegisterPrefabs(val, "Normal", twilightPrefabBuckets.Normal1);
			val.ModulesPassage1 = TwilightRegisterPrefabs(val, "Passage", twilightPrefabBuckets.Passage1);
			val.ModulesDeadEnd1 = TwilightRegisterPrefabs(val, "DeadEnd", twilightPrefabBuckets.DeadEnd1);
			val.ModulesExtraction1 = TwilightRegisterPrefabs(val, "Extraction", twilightPrefabBuckets.Extraction1);
			val.ModulesNormal2 = TwilightRegisterPrefabs(val, "Normal", twilightPrefabBuckets.Normal2);
			val.ModulesPassage2 = TwilightRegisterPrefabs(val, "Passage", twilightPrefabBuckets.Passage2);
			val.ModulesDeadEnd2 = TwilightRegisterPrefabs(val, "DeadEnd", twilightPrefabBuckets.DeadEnd2);
			val.ModulesExtraction2 = TwilightRegisterPrefabs(val, "Extraction", twilightPrefabBuckets.Extraction2);
			val.ModulesNormal3 = TwilightRegisterPrefabs(val, "Normal", twilightPrefabBuckets.Normal3);
			val.ModulesPassage3 = TwilightRegisterPrefabs(val, "Passage", twilightPrefabBuckets.Passage3);
			val.ModulesDeadEnd3 = TwilightRegisterPrefabs(val, "DeadEnd", twilightPrefabBuckets.DeadEnd3);
			val.ModulesExtraction3 = TwilightRegisterPrefabs(val, "Extraction", twilightPrefabBuckets.Extraction3);
			_twilightRepairApplied = val.StartRooms.Count > 0 && TwilightCountModules(val) > 0;
			if (_twilightRepairApplied)
			{
				((BaseUnityPlugin)this).Logger.LogInfo((object)$"Empress Twilight Forest Compat Patch repaired {((Object)val).name} with {val.StartRooms.Count} start rooms and {TwilightCountModules(val)} modules.");
			}
			return _twilightRepairApplied;
		}

		private static Level? TwilightFindLevel(IEnumerable<Level>? candidates)
		{
			if (candidates == null)
			{
				return null;
			}
			foreach (Level candidate in candidates)
			{
				if (TwilightIsTwilightLevel(candidate))
				{
					return candidate;
				}
			}
			return null;
		}

		private AssetBundle? TwilightGetBundle()
		{
			if ((Object)(object)_twilightBundle != (Object)null)
			{
				return _twilightBundle;
			}
			foreach (AssetBundle allLoadedAssetBundle in AssetBundle.GetAllLoadedAssetBundles())
			{
				try
				{
					if (allLoadedAssetBundle.GetAllAssetNames().Any((string assetName) => assetName.EndsWith("level - twilightforest.asset", StringComparison.OrdinalIgnoreCase) || assetName.EndsWith("tfassettestmod.asset", StringComparison.OrdinalIgnoreCase)))
					{
						_twilightBundle = allLoadedAssetBundle;
						return _twilightBundle;
					}
				}
				catch
				{
				}
			}
			string text = Directory.GetFiles(Paths.PluginPath, "Minecraft_Twilight_Forest.repobundle", SearchOption.AllDirectories).FirstOrDefault();
			if (string.IsNullOrWhiteSpace(text))
			{
				return null;
			}
			_twilightBundle = AssetBundle.LoadFromFile(text);
			return _twilightBundle;
		}

		private static TwilightPrefabBuckets TwilightCollectPrefabs(AssetBundle bundle)
		{
			//IL_0113: Unknown result type (might be due to invalid IL or missing references)
			//IL_0118: Unknown result type (might be due to invalid IL or missing references)
			//IL_015c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0161: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a1: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a6: Unknown result type (might be due to invalid IL or missing references)
			Dictionary<string, GameObject> dictionary = new Dictionary<string, GameObject>(StringComparer.OrdinalIgnoreCase);
			StartRoom[] array = bundle.LoadAllAssets<StartRoom>();
			foreach (StartRoom val in array)
			{
				TwilightAddAssetByName(dictionary, ((Object)(object)val != (Object)null) ? ((Component)val).gameObject : null);
			}
			Module[] array2 = bundle.LoadAllAssets<Module>();
			foreach (Module val2 in array2)
			{
				TwilightAddAssetByName(dictionary, ((Object)(object)val2 != (Object)null) ? ((Component)val2).gameObject : null);
			}
			GameObject[] array3 = bundle.LoadAllAssets<GameObject>();
			foreach (GameObject prefab in array3)
			{
				TwilightAddAssetByName(dictionary, prefab);
			}
			if (!dictionary.Keys.Any((string name) => name.StartsWith("Start Room - Twilight -", StringComparison.OrdinalIgnoreCase)) || !dictionary.Keys.Any((string name) => name.Contains("Twilight", StringComparison.OrdinalIgnoreCase) && name.StartsWith("Module", StringComparison.OrdinalIgnoreCase)))
			{
				array = Resources.FindObjectsOfTypeAll<StartRoom>();
				Scene scene;
				foreach (StartRoom val3 in array)
				{
					if (!((Object)(object)val3 == (Object)null))
					{
						scene = ((Component)val3).gameObject.scene;
						if (!((Scene)(ref scene)).IsValid())
						{
							TwilightAddAssetByName(dictionary, ((Component)val3).gameObject);
						}
					}
				}
				array2 = Resources.FindObjectsOfTypeAll<Module>();
				foreach (Module val4 in array2)
				{
					if (!((Object)(object)val4 == (Object)null))
					{
						scene = ((Component)val4).gameObject.scene;
						if (!((Scene)(ref scene)).IsValid())
						{
							TwilightAddAssetByName(dictionary, ((Component)val4).gameObject);
						}
					}
				}
				array3 = Resources.FindObjectsOfTypeAll<GameObject>();
				foreach (GameObject val5 in array3)
				{
					if (!((Object)(object)val5 == (Object)null))
					{
						scene = val5.scene;
						if (!((Scene)(ref scene)).IsValid())
						{
							TwilightAddAssetByName(dictionary, val5);
						}
					}
				}
			}
			return new TwilightPrefabBuckets
			{
				StartRooms = TwilightResolvePrefabs(dictionary, TwilightStartRoomNames),
				Normal1 = TwilightResolvePrefabs(dictionary, TwilightNormal1Names),
				Passage1 = TwilightResolvePrefabs(dictionary, TwilightPassage1Names),
				DeadEnd1 = TwilightResolvePrefabs(dictionary, TwilightDeadEnd1Names),
				Extraction1 = TwilightResolvePrefabs(dictionary, TwilightExtraction1Names),
				Normal2 = TwilightResolvePrefabs(dictionary, TwilightNormal2Names),
				Passage2 = TwilightResolvePrefabs(dictionary, TwilightPassage2Names),
				DeadEnd2 = TwilightResolvePrefabs(dictionary, TwilightDeadEnd2Names),
				Extraction2 = TwilightResolvePrefabs(dictionary, TwilightExtraction2Names),
				Normal3 = TwilightResolvePrefabs(dictionary, TwilightNormal3Names),
				Passage3 = TwilightResolvePrefabs(dictionary, TwilightPassage3Names),
				DeadEnd3 = TwilightResolvePrefabs(dictionary, TwilightDeadEnd3Names),
				Extraction3 = TwilightResolvePrefabs(dictionary, TwilightExtraction3Names)
			};
		}

		private static void TwilightAddAssetByName(IDictionary<string, GameObject> prefabsByName, GameObject? prefab)
		{
			if (!((Object)(object)prefab == (Object)null) && !string.IsNullOrWhiteSpace(((Object)prefab).name) && !prefabsByName.ContainsKey(((Object)prefab).name))
			{
				prefabsByName[((Object)prefab).name] = prefab;
			}
		}

		private static List<GameObject> TwilightResolvePrefabs(IReadOnlyDictionary<string, GameObject> prefabsByName, IEnumerable<string> names)
		{
			List<GameObject> list = new List<GameObject>();
			foreach (string name in names)
			{
				if (prefabsByName.TryGetValue(name, out GameObject value))
				{
					list.Add(value);
				}
			}
			return list;
		}

		private static void TwilightRegisterLevelObjects(Level level)
		{
			if (level.ConnectObject != null)
			{
				GameObject val = TwilightResolvePrefab(level.ConnectObject);
				if ((Object)(object)val != (Object)null)
				{
					TwilightRegisterNetworkPrefab("Level/" + TwilightGetLevelPath(level) + "/Other/" + TwilightGetPrefabName(level.ConnectObject, val), val);
				}
			}
			if (level.BlockObject != null)
			{
				GameObject val2 = TwilightResolvePrefab(level.BlockObject);
				if ((Object)(object)val2 != (Object)null)
				{
					TwilightRegisterNetworkPrefab("Level/" + TwilightGetLevelPath(level) + "/Other/" + TwilightGetPrefabName(level.BlockObject, val2), val2);
				}
			}
		}

		private static string TwilightGetLevelPath(Level level)
		{
			if (!string.IsNullOrWhiteSpace(((Object)level).name))
			{
				return ((Object)level).name;
			}
			return "Twilightforest";
		}

		private static string TwilightGetPrefabName(PrefabRef prefabRef, GameObject prefab)
		{
			if (!string.IsNullOrWhiteSpace(prefabRef.PrefabName))
			{
				return prefabRef.PrefabName;
			}
			return ((Object)prefab).name;
		}

		private static GameObject? TwilightResolvePrefab(PrefabRef? prefabRef)
		{
			if (prefabRef == null)
			{
				return null;
			}
			if (prefabRef.IsValid())
			{
				return prefabRef.Prefab;
			}
			AssetBundle bundle = prefabRef.Bundle;
			if ((Object)(object)bundle == (Object)null || string.IsNullOrWhiteSpace(prefabRef.PrefabName))
			{
				return null;
			}
			GameObject[] array = bundle.LoadAllAssets<GameObject>();
			foreach (GameObject val in array)
			{
				if ((Object)(object)val != (Object)null && string.Equals(((Object)val).name, prefabRef.PrefabName, StringComparison.OrdinalIgnoreCase))
				{
					return val;
				}
			}
			return null;
		}

		private static List<PrefabRef> TwilightRegisterPrefabs(Level level, string moduleTypeName, IEnumerable<GameObject> prefabs)
		{
			List<PrefabRef> list = new List<PrefabRef>();
			foreach (GameObject item in prefabs.OrderBy<GameObject, string>((GameObject gameObject) => ((Object)gameObject).name, StringComparer.OrdinalIgnoreCase))
			{
				PrefabRef val = TwilightRegisterNetworkPrefab("Level/" + ((Object)level).name + "/" + moduleTypeName + "/" + ((Object)item).name, item);
				if (val != null)
				{
					list.Add(val);
				}
			}
			return list;
		}

		private static PrefabRef? TwilightRegisterNetworkPrefab(string prefabId, GameObject prefab)
		{
			PrefabRef val = TwilightGetRegisteredPrefabRef(prefabId, prefab);
			if (val != null)
			{
				return val;
			}
			TwilightPreparePrefab(prefab);
			Utilities.FixAudioMixerGroups(prefab);
			return NetworkPrefabs.RegisterNetworkPrefab(prefabId, prefab);
		}

		private static PrefabRef? TwilightGetRegisteredPrefabRef(string prefabId, GameObject prefab)
		{
			if (!NetworkPrefabs.PrefabRefs.TryGetValue(prefabId, out var value) || value == null)
			{
				return null;
			}
			if ((Object)(object)value.Prefab == (Object)null || (Object)(object)value.Prefab == (Object)(object)prefab)
			{
				return value;
			}
			return null;
		}

		private static void TwilightPreparePrefab(GameObject prefab)
		{
			TwilightApplyHideFlags((Object)(object)prefab);
			TwilightEnsureVehicleSupport(prefab);
			TwilightNormalizeBoxColliderSizes(prefab);
			TwilightIgnoreUnreadableMeshesForNavMesh(prefab);
			TwilightAssignFallbackAudioMixerGroups(prefab);
			TwilightAssignFallbackPhysAttributes(prefab);
			TwilightAssignFallbackChargingStationData(prefab);
		}

		private static void TwilightNormalizeBoxColliderSizes(GameObject prefab)
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_0029: Unknown result type (might be due to invalid IL or missing references)
			//IL_002c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0037: Unknown result type (might be due to invalid IL or missing references)
			//IL_0042: Unknown result type (might be due to invalid IL or missing references)
			//IL_0052: Unknown result type (might be due to invalid IL or missing references)
			//IL_0053: Unknown result type (might be due to invalid IL or missing references)
			//IL_005d: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)prefab == (Object)null)
			{
				return;
			}
			BoxCollider[] componentsInChildren = prefab.GetComponentsInChildren<BoxCollider>(true);
			Vector3 val2 = default(Vector3);
			foreach (BoxCollider val in componentsInChildren)
			{
				if (!((Object)(object)val == (Object)null))
				{
					Vector3 size = val.size;
					((Vector3)(ref val2))..ctor(Mathf.Abs(size.x), Mathf.Abs(size.y), Mathf.Abs(size.z));
					if (size != val2)
					{
						val.size = val2;
					}
				}
			}
		}

		private static void TwilightIgnoreUnreadableMeshesForNavMesh(GameObject prefab)
		{
			if ((Object)(object)prefab == (Object)null)
			{
				return;
			}
			MeshFilter[] componentsInChildren = prefab.GetComponentsInChildren<MeshFilter>(true);
			foreach (MeshFilter val in componentsInChildren)
			{
				if (!((Object)(object)((val != null) ? val.sharedMesh : null) == (Object)null) && !TwilightMeshIsReadable(val.sharedMesh))
				{
					TwilightIgnoreObjectFromNavMeshBuild(((Component)val).gameObject);
				}
			}
			SkinnedMeshRenderer[] componentsInChildren2 = prefab.GetComponentsInChildren<SkinnedMeshRenderer>(true);
			foreach (SkinnedMeshRenderer val2 in componentsInChildren2)
			{
				if (!((Object)(object)((val2 != null) ? val2.sharedMesh : null) == (Object)null) && !TwilightMeshIsReadable(val2.sharedMesh))
				{
					TwilightIgnoreObjectFromNavMeshBuild(((Component)val2).gameObject);
				}
			}
		}

		private static bool TwilightMeshIsReadable(Mesh mesh)
		{
			try
			{
				return mesh.isReadable;
			}
			catch
			{
				return false;
			}
		}

		private static void TwilightIgnoreObjectFromNavMeshBuild(GameObject gameObject)
		{
			if (!((Object)(object)gameObject == (Object)null))
			{
				NavMeshModifier obj = gameObject.GetComponent<NavMeshModifier>() ?? gameObject.AddComponent<NavMeshModifier>();
				obj.ignoreFromBuild = true;
				obj.applyToChildren = false;
			}
		}

		private static void TwilightEnsureVehicleSupport(GameObject prefab)
		{
			if (!((Object)(object)prefab == (Object)null) && TwilightIsStartRoomPrefab(prefab))
			{
				TwilightEnsureVehicleItemVolumes(prefab);
				TwilightEnsureVehicleChargingStation(prefab);
			}
		}

		private static bool TwilightIsStartRoomPrefab(GameObject prefab)
		{
			GameObject prefab2 = prefab;
			if (!((Object)(object)prefab2.GetComponentInChildren<StartRoom>(true) != (Object)null))
			{
				return TwilightStartRoomNames.Any((string name) => string.Equals(((Object)prefab2).name, name, StringComparison.OrdinalIgnoreCase));
			}
			return true;
		}

		private static void TwilightEnsureVehicleItemVolumes(GameObject prefab)
		{
			int num = prefab.GetComponentsInChildren<ItemVolume>(true).Count(TwilightIsVehicleItemVolume);
			if (num < 4)
			{
				Transform parent = TwilightFindOrCreateVehicleSupportRoot(prefab);
				Transform anchor = TwilightFindTruckAnchor(prefab);
				for (int i = num; i < 4; i++)
				{
					TwilightCreateVehicleItemVolume(parent, anchor, i);
				}
			}
		}

		private static bool TwilightIsVehicleItemVolume(ItemVolume itemVolume)
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_000e: Invalid comparison between Unknown and I4
			return (int)TwilightGetComponentField<itemVolume>((Component)(object)itemVolume, "itemVolume", (itemVolume)0) == 9;
		}

		private static void TwilightCreateVehicleItemVolume(Transform parent, Transform anchor, int index)
		{
			//IL_001a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0020: Expected O, but got Unknown
			//IL_003c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0042: Unknown result type (might be due to invalid IL or missing references)
			//IL_0069: Unknown result type (might be due to invalid IL or missing references)
			//IL_006f: Expected O, but got Unknown
			//IL_0087: Unknown result type (might be due to invalid IL or missing references)
			//IL_0097: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b6: Unknown result type (might be due to invalid IL or missing references)
			GameObject val = new GameObject((index == 0) ? "Item Volume vehicle" : $"Item Volume vehicle ({index})");
			val.SetActive(false);
			val.transform.SetParent(parent, false);
			val.transform.SetPositionAndRotation(TwilightGetVehicleVolumePosition(anchor, index), anchor.rotation);
			ItemVolume target = val.AddComponent<ItemVolume>();
			TwilightSetComponentField((Component)(object)target, "itemVolume", (object)(itemVolume)9);
			GameObject val2 = new GameObject("Vehicle");
			val2.transform.SetParent(val.transform, false);
			val2.transform.localPosition = Vector3.zero;
			val2.transform.localRotation = Quaternion.identity;
			val2.transform.localScale = new Vector3(2.6f, 1.4f, 4f);
			TwilightSetComponentField((Component)(object)target, "volumes", new List<GameObject> { val2 });
			TwilightApplyHideFlags((Object)(object)val);
		}

		private static Vector3 TwilightGetVehicleVolumePosition(Transform anchor, int index)
		{
			//IL_0024: 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)
			//IL_0030: Unknown result type (might be due to invalid IL or missing references)
			//IL_0035: Unknown result type (might be due to invalid IL or missing references)
			//IL_003b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0041: Unknown result type (might be due to invalid IL or missing references)
			//IL_0046: Unknown result type (might be due to invalid IL or missing references)
			//IL_004b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0055: Unknown result type (might be due to invalid IL or missing references)
			//IL_005a: Unknown result type (might be due to invalid IL or missing references)
			float num = ((index % 2 == 0) ? (-2f) : 2f);
			float num2 = 2.5f + (float)(index / 2) * 2f;
			return anchor.position + anchor.right * num + anchor.forward * num2 + Vector3.up * 0.25f;
		}

		private static Transform TwilightFindTruckAnchor(GameObject prefab)
		{
			LevelPoint[] componentsInChildren = prefab.GetComponentsInChildren<LevelPoint>(true);
			foreach (LevelPoint val in componentsInChildren)
			{
				if ((Object)(object)val != (Object)null && TwilightGetComponentField((Component)(object)val, "Truck", fallback: false))
				{
					return ((Component)val).transform;
				}
			}
			RoomVolume[] componentsInChildren2 = prefab.GetComponentsInChildren<RoomVolume>(true);
			foreach (RoomVolume val2 in componentsInChildren2)
			{
				if ((Object)(object)val2 != (Object)null && TwilightGetComponentField((Component)(object)val2, "Truck", fallback: false))
				{
					return ((Component)val2).transform;
				}
			}
			return prefab.transform;
		}

		private static Transform TwilightFindOrCreateVehicleSupportRoot(GameObject prefab)
		{
			//IL_003c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0041: Unknown result type (might be due to invalid IL or missing references)
			//IL_0053: Unknown result type (might be due to invalid IL or missing references)
			//IL_0059: Expected O, but got Unknown
			Transform val = ((IEnumerable<Transform>)prefab.GetComponentsInChildren<Transform>(true)).FirstOrDefault((Func<Transform, bool>)((Transform child) => (Object)(object)child != (Object)null && string.Equals(((Object)child).name, "Empress Vehicle Support", StringComparison.OrdinalIgnoreCase)));
			if ((Object)(object)val != (Object)null)
			{
				return val;
			}
			GameObject val2 = new GameObject("Empress Vehicle Support");
			val2.transform.SetParent(prefab.transform, false);
			TwilightApplyHideFlags((Object)val2);
			return val2.transform;
		}

		private static void TwilightEnsureVehicleChargingStation(GameObject prefab)
		{
			//IL_00ba: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ca: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cf: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00de: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e9: Unknown result type (might be due to invalid IL or missing references)
			//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_00f8: Unknown result type (might be due to invalid IL or missing references)
			//IL_008f: Unknown result type (might be due to invalid IL or missing references)
			//IL_009a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0123: Unknown result type (might be due to invalid IL or missing references)
			//IL_0139: Unknown result type (might be due to invalid IL or missing references)
			//IL_014f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0163: Unknown result type (might be due to invalid IL or missing references)
			if (prefab.GetComponentsInChildren<ChargingStation>(true).Any(TwilightIsVehicleChargingStation))
			{
				return;
			}
			ChargingStation val = TwilightFindFallbackChargingStationTemplate();
			if (!((Object)(object)val == (Object)null) && TwilightIsVehicleChargingStation(val))
			{
				ChargingStation val2 = TwilightFindLegacyChargingStation(prefab);
				Transform val3 = TwilightFindOrCreateVehicleSupportRoot(prefab);
				Transform val4 = TwilightFindTruckAnchor(prefab);
				GameObject val5 = TwilightCloneInactiveChargingStationTemplate(val);
				((Object)val5).name = "Charging Station New";
				val5.transform.SetParent(val3, false);
				if ((Object)(object)val2 != (Object)null)
				{
					val5.transform.SetPositionAndRotation(((Component)val2).transform.position, ((Component)val2).transform.rotation);
					((Component)val2).gameObject.SetActive(false);
				}
				else
				{
					val5.transform.SetPositionAndRotation(val4.position + val4.forward * 6.5f + Vector3.up * 0.05f, Quaternion.LookRotation(-val4.forward, Vector3.up));
				}
				Transform val6 = TwilightFindChildByExactName(val5.transform, "Charge Area");
				if ((Object)(object)val6 != (Object)null)
				{
					val6.localScale = new Vector3(Mathf.Max(val6.localScale.x, 4f), Mathf.Max(val6.localScale.y, 2f), Mathf.Max(val6.localScale.z, 4f));
				}
				ChargingStation component = val5.GetComponent<ChargingStation>();
				if ((Object)(object)component != (Object)null)
				{
					TwilightEnsureChargingStationCompatibility(component);
				}
				TwilightApplyHideFlags((Object)(object)val5);
				Utilities.FixAudioMixerGroups(val5);
			}
		}

		private static GameObject TwilightCloneInactiveChargingStationTemplate(ChargingStation template)
		{
			GameObject gameObject = ((Component)template).gameObject;
			bool activeSelf = gameObject.activeSelf;
			try
			{
				if (activeSelf)
				{
					gameObject.SetActive(false);
				}
				GameObject obj = Object.Instantiate<GameObject>(gameObject);
				obj.SetActive(false);
				return obj;
			}
			finally
			{
				if ((Object)(object)gameObject != (Object)null && activeSelf)
				{
					gameObject.SetActive(true);
				}
			}
		}

		internal static void TwilightActivateVehicleChargingStation(StartRoom? startRoom)
		{
			if ((Object)(object)startRoom == (Object)null || !TwilightIsCurrentLevel() || !TwilightIsStartRoomPrefab(((Component)startRoom).gameObject))
			{
				return;
			}
			ChargingStation[] componentsInChildren = ((Component)startRoom).GetComponentsInChildren<ChargingStation>(true);
			foreach (ChargingStation val in componentsInChildren)
			{
				if ((Object)(object)val != (Object)null && TwilightIsVehicleChargingStation(val) && string.Equals(((Object)((Component)val).gameObject).name, "Charging Station New", StringComparison.OrdinalIgnoreCase) && !((Component)val).gameObject.activeSelf)
				{
					((Component)val).gameObject.SetActive(true);
				}
			}
			ItemVolume[] componentsInChildren2 = ((Component)startRoom).GetComponentsInChildren<ItemVolume>(true);
			foreach (ItemVolume val2 in componentsInChildren2)
			{
				if ((Object)(object)val2 != (Object)null && TwilightIsVehicleItemVolume(val2) && !((Component)val2).gameObject.activeSelf)
				{
					((Component)val2).gameObject.SetActive(true);
				}
			}
		}

		private static T TwilightGetComponentField<T>(Component target, string fieldName, T fallback)
		{
			if ((Object)(object)target == (Object)null)
			{
				return fallback;
			}
			try
			{
				if (AccessTools.Field(((object)target).GetType(), fieldName) == null)
				{
					return fallback;
				}
				return (T)((Traverse.Create((object)target).Field(fieldName).GetValue() is T val) ? ((object)val) : ((object)fallback));
			}
			catch
			{
				return fallback;
			}
		}

		private static void TwilightSetComponentField(Component target, string fieldName, object value)
		{
			if ((Object)(object)target == (Object)null)
			{
				return;
			}
			try
			{
				if (!(AccessTools.Field(((object)target).GetType(), fieldName) == null))
				{
					Traverse.Create((object)target).Field(fieldName).SetValue(value);
				}
			}
			catch
			{
			}
		}

		private static void TwilightAssignFallbackAudioMixerGroups(GameObject prefab)
		{
			AudioMixerGroup val = TwilightGetFallbackAudioMixerGroup();
			if ((Object)(object)prefab == (Object)null || (Object)(object)val == (Object)null)
			{
				return;
			}
			AudioSource[] componentsInChildren = prefab.GetComponentsInChildren<AudioSource>(true);
			foreach (AudioSource val2 in componentsInChildren)
			{
				if (!((Object)(object)val2 == (Object)null) && !((Object)(object)val2.outputAudioMixerGroup != (Object)null))
				{
					val2.outputAudioMixerGroup = val;
				}
			}
		}

		private static void TwilightAssignFallbackPhysAttributes(GameObject prefab)
		{
			if ((Object)(object)prefab == (Object)null)
			{
				return;
			}
			NotValuableObject[] componentsInChildren = prefab.GetComponentsInChildren<NotValuableObject>(true);
			foreach (NotValuableObject val in componentsInChildren)
			{
				if (!((Object)(object)val == (Object)null) && !((Object)(object)val.physAttributePreset != (Object)null))
				{
					Rigidbody component = ((Component)val).GetComponent<Rigidbody>();
					float mass = (((Object)(object)component != (Object)null && component.mass > 0f) ? component.mass : 1f);
					val.physAttributePreset = TwilightCreateFallbackPhysAttribute(mass);
				}
			}
		}

		private static void TwilightAssignFallbackChargingStationData(GameObject prefab)
		{
			if (!((Object)(object)prefab == (Object)null))
			{
				ChargingStation[] componentsInChildren = prefab.GetComponentsInChildren<ChargingStation>(true);
				for (int i = 0; i < componentsInChildren.Length; i++)
				{
					TwilightEnsureChargingStationCompatibility(componentsInChildren[i]);
				}
			}
		}

		internal static void TwilightEnsureChargingStationCompatibility(ChargingStation? chargingStation)
		{
			//IL_01d8: Unknown result type (might be due to invalid IL or missing references)
			//IL_01dd: Unknown result type (might be due to invalid IL or missing references)
			//IL_02ee: Unknown result type (might be due to invalid IL or missing references)
			//IL_0302: Unknown result type (might be due to invalid IL or missing references)
			//IL_0370: Unknown result type (might be due to invalid IL or missing references)
			//IL_0384: Unknown result type (might be due to invalid IL or missing references)
			//IL_04ae: Unknown result type (might be due to invalid IL or missing references)
			//IL_052d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0609: Unknown result type (might be due to invalid IL or missing references)
			//IL_07bc: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)chargingStation == (Object)null)
			{
				return;
			}
			ChargingStation val = TwilightFindFallbackChargingStationTemplate();
			Transform templateRoot = (((Object)(object)val != (Object)null) ? ((Component)val).transform : null);
			Transform transform = ((Component)chargingStation).transform;
			int num = Mathf.Max(TwilightGetChargingStationField(chargingStation, "maxCrystals", 10), ((Object)(object)val != (Object)null) ? TwilightGetChargingStationField(val, "maxCrystals", 10) : 10);
			TwilightSetChargingStationField(chargingStation, "maxCrystals", num);
			int num2 = Mathf.Max(TwilightGetChargingStationField(chargingStation, "energyPerCrystal", 10), ((Object)(object)val != (Object)null) ? TwilightGetChargingStationField(val, "energyPerCrystal", 10) : 10);
			TwilightSetChargingStationField(chargingStation, "energyPerCrystal", num2);
			int num3 = Mathf.Max(TwilightGetChargingStationField(chargingStation, "chargeSegments", 40), ((Object)(object)val != (Object)null) ? TwilightGetChargingStationField(val, "chargeSegments", 40) : 40);
			TwilightSetChargingStationField(chargingStation, "chargeSegments", num3);
			List<ItemBattery> value = TwilightGetChargingStationField<List<ItemBattery>>(chargingStation, "itemsCharging") ?? new List<ItemBattery>();
			TwilightSetChargingStationField(chargingStation, "itemsCharging", value);
			List<Light> list = TwilightGetChargingStationField<List<Light>>(chargingStation, "stationLights") ?? new List<Light>();
			list.Clear();
			TwilightSetChargingStationField(chargingStation, "stationLights", list);
			List<float> list2 = TwilightGetChargingStationField<List<float>>(chargingStation, "stationLightMaxIntensities") ?? new List<float>();
			list2.Clear();
			TwilightSetChargingStationField(chargingStation, "stationLightMaxIntensities", list2);
			TwilightSetChargingStationField(chargingStation, "scanColliders", TwilightGetChargingStationField<Dictionary<ItemBattery, List<Collider>>>(chargingStation, "scanColliders") ?? new Dictionary<ItemBattery, List<Collider>>());
			TwilightSetChargingStationField(chargingStation, "scanColliderIndex", TwilightGetChargingStationField<Dictionary<ItemBattery, int>>(chargingStation, "scanColliderIndex") ?? new Dictionary<ItemBattery, int>());
			TwilightSetChargingStationField(chargingStation, "scanOrder", TwilightGetChargingStationField<List<ItemBattery>>(chargingStation, "scanOrder") ?? new List<ItemBattery>());
			List<Transform> list3 = TwilightGetChargingStationField<List<Transform>>(chargingStation, "crystals") ?? new List<Transform>();
			Scene scene = ((Component)chargingStation).gameObject.scene;
			if (!((Scene)(ref scene)).IsValid())
			{
				list3.Clear();
			}
			else
			{
				list3.RemoveAll((Transform crystal) => (Object)(object)crystal == (Object)null);
			}
			TwilightSetChargingStationField(chargingStation, "crystals", list3);
			PhotonView value2 = TwilightGetChargingStationField<PhotonView>(chargingStation, "photonView") ?? ((Component)chargingStation).GetComponent<PhotonView>();
			TwilightSetChargingStationField(chargingStation, "photonView", value2);
			GameObject value3 = TwilightMapGameObject(transform, templateRoot, ((Object)(object)val != (Object)null) ? TwilightGetChargingStationField<GameObject>(val, "meshObject") : null) ?? TwilightGetChargingStationField<GameObject>(chargingStation, "meshObject") ?? TwilightFindBestRendererGameObject(transform) ?? TwilightCreateFallbackMeshObject(transform);
			TwilightSetChargingStationField(chargingStation, "meshObject", value3);
			Transform value4 = TwilightMapTransform(transform, templateRoot, ((Object)(object)val != (Object)null) ? TwilightGetChargingStationField<Transform>(val, "chargeBar") : null) ?? TwilightGetChargingStationField<Transform>(chargingStation, "chargeBar") ?? TwilightFindChildByExactName(transform, "Charge") ?? TwilightCreateFallbackAnchor(transform, "Charge", new Vector3(0f, 0.38f, 0.12f), new Vector3(0.75f, 0.12f, 0.12f));
			TwilightSetChargingStationField(chargingStation, "chargeBar", value4);
			Transform value5 = TwilightMapTransform(transform, templateRoot, ((Object)(object)val != (Object)null) ? TwilightGetChargingStationField<Transform>(val, "chargeArea") : null) ?? TwilightGetChargingStationField<Transform>(chargingStation, "chargeArea") ?? TwilightFindChildByExactName(transform, "Charge Area") ?? TwilightCreateFallbackAnchor(transform, "Charge Area", new Vector3(0f, 0.65f, 0.7f), new Vector3(1.1f, 1.1f, 1.1f));
			TwilightSetChargingStationField(chargingStation, "chargeArea", value5);
			Transform value6 = TwilightMapTransform(transform, templateRoot, ((Object)(object)val != (Object)null) ? TwilightGetChargingStationField<Transform>(val, "lockedTransform") : null) ?? TwilightGetChargingStationField<Transform>(chargingStation, "lockedTransform") ?? TwilightFindChildByExactName(transform, "Locked");
			TwilightSetChargingStationField(chargingStation, "lockedTransform", value6);
			Transform value7 = TwilightMapTransform(transform, templateRoot, ((Object)(object)val != (Object)null) ? TwilightGetChargingStationField<Transform>(val, "crystalCylinder") : null) ?? TwilightGetChargingStationField<Transform>(chargingStation, "crystalCylinder") ?? TwilightFindChildByExactName(transform, "Crystal Cylinder") ?? TwilightFindChildContaining(transform, "crystal") ?? TwilightCreateFallbackCrystalCylinder(transform, num);
			TwilightSetChargingStationField(chargingStation, "crystalCylinder", value7);
			object obj = TwilightMapComponent<Light>(transform, templateRoot, ((Object)(object)val != (Object)null) ? TwilightGetChargingStationField<Light>(val, "light1") : null);
			if (obj == null)
			{
				obj = TwilightGetChargingStationField<Light>(chargingStation, "light1");
				if (obj == null)
				{
					Transform? obj2 = TwilightFindChildByExactName(transform, "Light1");
					obj = ((obj2 != null) ? ((Component)obj2).GetComponent<Light>() : null) ?? TwilightCreateFallbackLight(transform, "Light1", new Vector3(-0.16f, 0.62f, 0.16f), 0.8f);
				}
			}
			Light value8 = (Light)obj;
			TwilightSetChargingStationField(chargingStation, "light1", value8);
			object obj3 = TwilightMapComponent<Light>(transform, templateRoot, ((Object)(object)val != (Object)null) ? TwilightGetChargingStationField<Light>(val, "light2") : null);
			if (obj3 == null)
			{
				obj3 = TwilightGetChargingStationField<Light>(chargingStation, "light2");
				if (obj3 == null)
				{
					Transform? obj4 = TwilightFindChildByExactName(transform, "Light2");
					obj3 = ((obj4 != null) ? ((Component)obj4).GetComponent<Light>() : null) ?? TwilightCreateFallbackLight(transform, "Light2", new Vector3(0.16f, 0.62f, 0.16f), 0.8f);
				}
			}
			Light value9 = (Light)obj3;
			TwilightSetChargingStationField(chargingStation, "light2", value9);
			object obj5 = TwilightMapGameObject(transform, templateRoot, ((Object)(object)val != (Object)null) ? TwilightGetChargingStationField<GameObject>(val, "subtleLight") : null);
			if (obj5 == null)
			{
				obj5 = TwilightGetChargingStationField<GameObject>(chargingStation, "subtleLight");
				if (obj5 == null)
				{
					Transform? obj6 = TwilightFindChildByExactName(transform, "Subtle Light");
					obj5 = ((obj6 != null) ? ((Component)obj6).gameObject : null) ?? ((Component)TwilightCreateFallbackSubtleLight(transform)).gameObject;
				}
			}
			GameObject val2 = (GameObject)obj5;
			TwilightSetChargingStationField(chargingStation, "subtleLight", val2);
			Light value10 = TwilightMapComponent<Light>(transform, templateRoot, ((Object)(object)val != (Object)null) ? TwilightGetChargingStationField<Light>(val, "barLight") : null) ?? TwilightGetChargingStationField<Light>(chargingStation, "barLight") ?? ((val2 != null) ? val2.GetComponent<Light>() : null) ?? TwilightCreateFallbackLight(transform, "Bar Light", new Vector3(0f, 0.48f, 0.08f), 0.8f);
			TwilightSetChargingStationField(chargingStation, "barLight", value10);
			object obj7 = TwilightMapComponent<ParticleSystem>(transform, templateRoot, ((Object)(object)val != (Object)null) ? TwilightGetChargingStationField<ParticleSystem>(val, "lightParticle") : null);
			if (obj7 == null)
			{
				obj7 = TwilightGetChargingStationField<ParticleSystem>(chargingStation, "lightParticle");
				if (obj7 == null)
				{
					Transform? obj8 = TwilightFindChildByExactName(transform, "Light Particle");
					obj7 = ((obj8 != null) ? ((Component)obj8).GetComponent<ParticleSystem>() : null) ?? TwilightCreateFallbackParticleSystem(transform, "Light Particle");
				}
			}
			ParticleSystem value11 = (ParticleSystem)obj7;
			TwilightSetChargingStationField(chargingStation, "lightParticle", value11);
			object obj9 = TwilightMapComponent<ParticleSystem>(transform, templateRoot, ((Object)(object)val != (Object)null) ? TwilightGetChargingStationField<ParticleSystem>(val, "fireflyParticles") : null);
			if (obj9 == null)
			{
				obj9 = TwilightGetChargingStationField<ParticleSystem>(chargingStation, "fireflyParticles");
				if (obj9 == null)
				{
					Transform? obj10 = TwilightFindChildByExactName(transform, "Firefly Particles");
					obj9 = ((obj10 != null) ? ((Component)obj10).GetComponent<ParticleSystem>() : null) ?? TwilightCreateFallbackParticleSystem(transform, "Firefly Particles");
				}
			}
			ParticleSystem value12 = (ParticleSystem)obj9;
			TwilightSetChargingStationField(chargingStation, "fireflyParticles", value12);
			object obj11 = TwilightMapComponent<ParticleSystem>(transform, templateRoot, ((Object)(object)val != (Object)null) ? TwilightGetChargingStationField<ParticleSystem>(val, "bitsParticles") : null);
			if (obj11 == null)
			{
				obj11 = TwilightGetChargingStationField<ParticleSystem>(chargingStation, "bitsParticles");
				if (obj11 == null)
				{
					Transform? obj12 = TwilightFindChildByExactName(transform, "Bits Particles");
					obj11 = ((obj12 != null) ? ((Component)obj12).GetComponent<ParticleSystem>() : null) ?? TwilightCreateFallbackParticleSystem(transform, "Bits Particles");
				}
			}
			ParticleSystem value13 = (ParticleSystem)obj11;
			TwilightSetChargingStationField(chargingStation, "bitsParticles", value13);
			AnimationCurve val3 = TwilightGetChargingStationField<AnimationCurve>(chargingStation, "chargeCurve");
			if (val3 == null || val3.length == 0)
			{
				AnimationCurve val4 = (((Object)(object)val != (Object)null) ? TwilightGetChargingStationField<AnimationCurve>(val, "chargeCurve") : null);
				val3 = (AnimationCurve)((val4 == null || val4.length <= 0) ? ((object)AnimationCurve.EaseInOut(0f, 0f, 1f, 1f)) : ((object)new AnimationCurve(val4.keys)));
			}
			TwilightSetChargingStationField(chargingStation, "chargeCurve", val3);
			TwilightEnsureChargingStationCurve(chargingStation, val, "chargeLaserFlickerOnCurve", AnimationCurve.Linear(0f, 0f, 1f, 1f));
			TwilightEnsureChargingStationCurve(chargingStation, val, "chargeLaserFlickerOffCurve", AnimationCurve.Linear(0f, 0f, 1f, 1f));
			TwilightEnsureChargingStationCurve(chargingStation, val, "chargeLaserIntroBounceCurve", AnimationCurve.EaseInOut(0f, 0f, 1f, 1f));
			TwilightEnsureChargingStationCurve(chargingStation, val, "chargeLaserSettleBounceCurve", AnimationCurve.EaseInOut(0f, 0f, 1f, 1f));
			Sound value14 = TwilightEnsureChargingStationSound(TwilightGetChargingStationField<Sound>(chargingStation, "soundStart"), ((Object)(object)val != (Object)null) ? TwilightGetChargingStationField<Sound>(val, "soundStart") : null, transform, templateRoot, "Sound Start", requireSource: false);
			TwilightSetChargingStationField(chargingStation, "soundStart", value14);
			Sound value15 = TwilightEnsureChargingStationSound(TwilightGetChargingStationField<Sound>(chargingStation, "soundStop"), ((Object)(object)val != (Object)null) ? TwilightGetChargingStationField<Sound>(val, "soundStop") : null, transform, templateRoot, "Sound Stop", requireSource: false);
			TwilightSetChargingStationField(chargingStation, "soundStop", value15);
			Sound value16 = TwilightEnsureChargingStationSound(TwilightGetChargingStationField<Sound>(chargingStation, "soundLoop"), ((Object)(object)val != (Object)null) ? TwilightGetChargingStationField<Sound>(val, "soundLoop") : null, transform, templateRoot, "Sound Loop", requireSource: true);
			TwilightSetChargingStationField(chargingStation, "soundLoop", value16);
			Sound value17 = TwilightEnsureChargingStationSound(TwilightGetChargingStationField<Sound>(chargingStation, "soundPowerCrystalBreak"), ((Object)(object)val != (Object)null) ? TwilightGetChargingStationField<Sound>(val, "soundPowerCrystalBreak") : null, transform, templateRoot, "Sound Crystal Break", requireSource: false);
			TwilightSetChargingStationField(chargingStation, "soundPowerCrystalBreak", value17);
			Item value18 = TwilightGetChargingStationField<Item>(chargingStation, "item") ?? (((Object)(object)val != (Object)null) ? TwilightGetChargingStationField<Item>(val, "item") : null) ?? TwilightFindPowerCrystalItem();
			TwilightSetChargingStationField(chargingStation, "item", value18);
		}

		private static void TwilightEnsureChargingStationCurve(ChargingStation chargingStation, ChargingStation? template, string fieldName, AnimationCurve fallbackCurve)
		{
			//IL_0039: Unknown result type (might be due to invalid IL or missing references)
			//IL_004c: Expected O, but got Unknown
			//IL_0046: Unknown result type (might be due to invalid IL or missing references)
			AnimationCurve val = TwilightGetChargingStationField<AnimationCurve>(chargingStation, fieldName);
			if (val == null || val.length == 0)
			{
				AnimationCurve val2 = (((Object)(object)template != (Object)null) ? TwilightGetChargingStationField<AnimationCurve>(template, fieldName) : null);
				val = ((val2 != null && val2.length > 0) ? new AnimationCurve(val2.keys) : new AnimationCurve(fallbackCurve.keys));
			}
			TwilightSetChargingStationField(chargingStation, fieldName, val);
		}

		private static ChargingStation? TwilightFindFallbackChargingStationTemplate()
		{
			ChargingStation val = null;
			if (RunManager.instance?.levels != null)
			{
				foreach (Level level in RunManager.instance.levels)
				{
					if ((Object)(object)level == (Object)null || TwilightIsTwilightLevel(level))
					{
						continue;
					}
					GameObject val2 = TwilightGetFirstValidPrefab(level.StartRooms);
					if ((Object)(object)val2 == (Object)null)
					{
						continue;
					}
					ChargingStation[] componentsInChildren = val2.GetComponentsInChildren<ChargingStation>(true);
					foreach (ChargingStation val3 in componentsInChildren)
					{
						if (!((Object)(object)val3 == (Object)null))
						{
							if (TwilightIsVehicleChargingStation(val3))
							{
								return val3;
							}
							if (val == null)
							{
								val = val3;
							}
						}
					}
				}
			}
			return Resources.FindObjectsOfTypeAll<ChargingStation>().Where(delegate(ChargingStation candidate)
			{
				//IL_000f: Unknown result type (might be due to invalid IL or missing references)
				//IL_0014: Unknown result type (might be due to invalid IL or missing references)
				if ((Object)(object)candidate != (Object)null)
				{
					Scene scene = ((Component)candidate).gameObject.scene;
					return !((Scene)(ref scene)).IsValid();
				}
				return false;
			}).OrderByDescending(TwilightIsVehicleChargingStation)
				.FirstOrDefault() ?? val;
		}

		private static ChargingStation? TwilightFindLegacyChargingStation(GameObject prefab)
		{
			return ((IEnumerable<ChargingStation>)prefab.GetComponentsInChildren<ChargingStation>(true)).FirstOrDefault((Func<ChargingStation, bool>)((ChargingStation candidate) => (Object)(object)candidate != (Object)null && !TwilightIsVehicleChargingStation(candidate)));
		}

		private static bool TwilightIsVehicleChargingStation(ChargingStation? chargingStation)
		{
			if ((Object)(object)chargingStation == (Object)null)
			{
				return false;
			}
			Transform transform = ((Component)chargingStation).transform;
			if ((Object)(object)TwilightFindChildByExactName(transform, "Charge Area") != (Object)null)
			{
				return (Object)(object)TwilightFindChildByExactName(transform, "Line Between Two Points") != (Object)null;
			}
			return false;
		}

		private static GameObject? TwilightGetFirstValidPrefab(IEnumerable<PrefabRef>? prefabRefs)
		{
			if (prefabRefs == null)
			{
				return null;
			}
			foreach (PrefabRef prefabRef in prefabRefs)
			{
				if (prefabRef == null)
				{
					continue;
				}
				try
				{
					GameObject val = TwilightResolvePrefab(prefabRef);
					if ((Object)(object)val != (Object)null)
					{
						return val;
					}
				}
				catch
				{
				}
			}
			return null;
		}

		private static Sound TwilightEnsureChargingStationSound(Sound? currentSound, Sound? templateSound, Transform stationRoot, Transform? templateRoot, string audioName, bool requireSource)
		{
			//IL_0003: Unknown result type (might be due to invalid IL or missing references)
			//IL_000a: Expected O, but got Unknown
			//IL_002d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0032: Unknown result type (might be due to invalid IL or missing references)
			if (currentSound == null)
			{
				currentSound = new Sound();
			}
			TwilightNormalizeSound(currentSound);
			if (templateSound != null)
			{
				currentSound.Sounds = templateSound.Sounds ?? Array.Empty<AudioClip>();
				currentSound.Type = templateSound.Type;
				currentSound.Volume = templateSound.Volume;
				TwilightSetSoundVolumeDefault(currentSound, TwilightGetSoundVolumeDefault(templateSound, currentSound.Volume));
				currentSound.VolumeRandom = templateSound.VolumeRandom;
				currentSound.Pitch = templateSound.Pitch;
				currentSound.PitchRandom = templateSound.PitchRandom;
				currentSound.SpatialBlend = templateSound.SpatialBlend;
				currentSound.Doppler = templateSound.Doppler;
				currentSound.ReverbMix = templateSound.ReverbMix;
				currentSound.FalloffMultiplier = templateSound.FalloffMultiplier;
				currentSound.OffscreenVolume = templateSound.OffscreenVolume;
				currentSound.OffscreenFalloff = templateSound.OffscreenFalloff;
				currentSound.Source = TwilightMapComponent<AudioSource>(stationRoot, templateRoot, templateSound.Source) ?? currentSound.Source;
			}
			if (requireSource && (Object)(object)currentSound.Source == (Object)null)
			{
				currentSound.Source = TwilightCreateFallbackAudioSource(stationRoot, audioName);
			}
			return currentSound;
		}

		private static float TwilightGetSoundVolumeDefault(Sound? sound, float fallback)
		{
			if (sound == null)
			{
				return fallback;
			}
			try
			{
				FieldInfo fieldInfo = AccessTools.Field(((object)sound).GetType(), "VolumeDefault");
				if (fieldInfo == null)
				{
					return fallback;
				}
				return (fieldInfo.GetValue(sound) is float num) ? num : fallback;
			}
			catch
			{
				return fallback;
			}
		}

		private static void TwilightSetSoundVolumeDefault(Sound? sound, float value)
		{
			if (sound == null)
			{
				return;
			}
			try
			{
				AccessTools.Field(((object)sound).GetType(), "VolumeDefault")?.SetValue(sound, value);
			}
			catch
			{
			}
		}

		private static T? TwilightGetChargingStationField<T>(ChargingStation? chargingStation, string fieldName)
		{
			return TwilightGetChargingStationField(chargingStation, fieldName, default(T));
		}

		private static T TwilightGetChargingStationField<T>(ChargingStation? chargingStation, string fieldName, T fallback)
		{
			if ((Object)(object)chargingStation == (Object)null)
			{
				return fallback;
			}
			try
			{
				return (T)((Traverse.Create((object)chargingStation).Field(fieldName).GetValue() is T val) ? ((object)val) : ((object)fallback));
			}
			catch
			{
				return fallback;
			}
		}

		private static void TwilightSetChargingStationField(ChargingStation? chargingStation, string fieldName, object? value)
		{
			if ((Object)(object)chargingStation == (Object)null)
			{
				return;
			}
			try
			{
				Traverse.Create((object)chargingStation).Field(fieldName).SetValue(value);
			}
			catch
			{
			}
		}

		private static void TwilightNormalizeSound(Sound? sound)
		{
			if (sound != null)
			{
				Sound val = sound;
				if (val.Sounds == null)
				{
					val.Sounds = Array.Empty<AudioClip>();
				}
				val = sound;
				if (val.LowPassIgnoreColliders == null)
				{
					val.LowPassIgnoreColliders = new List<Collider>();
				}
			}
		}

		private static Transform? TwilightFindChildByExactName(Transform root, string name)
		{
			string name2 = name;
			return ((IEnumerable<Transform>)((Component)root).GetComponentsInChildren<Transform>(true)).FirstOrDefault((Func<Transform, bool>)((Transform child) => (Object)(object)child != (Object)null && string.Equals(((Object)child).name, name2, StringComparison.OrdinalIgnoreCase)));
		}

		private static Transform? TwilightFindChildContaining(Transform root, string value)
		{
			string value2 = value;
			return ((IEnumerable<Transform>)((Component)root).GetComponentsInChildren<Transform>(true)).FirstOrDefault((Func<Transform, bool>)((Transform child) => (Object)(object)child != (Object)null && ((Object)child).name.IndexOf(value2, StringComparison.OrdinalIgnoreCase) >= 0));
		}

		private static string? TwilightGetRelativePath(Transform root, Transform? target)
		{
			if ((Object)(object)root == (Object)null || (Object)(object)target == (Object)null)
			{
				return null;
			}
			if ((Object)(object)target == (Object)(object)root)
			{
				return string.Empty;
			}
			Stack<string> stack = new Stack<string>();
			Transform val = target;
			while ((Object)(object)val != (Object)null && (Object)(object)val != (Object)(object)root)
			{
				stack.Push(((Object)val).name);
				val = val.parent;
			}
			if ((Object)(object)val != (Object)(object)root)
			{
				return null;
			}
			return string.Join("/", stack);
		}

		private static Transform? TwilightMapTransform(Transform targetRoot, Transform? templateRoot, Transform? templateTransform)
		{
			if ((Object)(object)targetRoot == (Object)null || (Object)(object)templateRoot == (Object)null || (Object)(object)templateTransform == (Object)null)
			{
				return null;
			}
			string text = TwilightGetRelativePath(templateRoot, templateTransform);
			if (text == null)
			{
				return null;
			}
			if (text.Length != 0)
			{
				return targetRoot.Find(text);
			}
			return targetRoot;
		}

		private static TComponent? TwilightMapComponent<TComponent>(Transform targetRoot, Transform? templateRoot, TComponent? templateComponent) where TComponent : Component
		{
			Transform val = TwilightMapTransform(targetRoot, templateRoot, ((Object)(object)templateComponent != (Object)null) ? ((Component)templateComponent).transform : null);
			if (!((Object)(object)val != (Object)null))
			{
				return default(TComponent);
			}
			return ((Component)val).GetComponent<TComponent>();
		}

		private static GameObject? TwilightMapGameObject(Transform targetRoot, Transform? templateRoot, GameObject? templateObject)
		{
			Transform val = TwilightMapTransform(targetRoot, templateRoot, ((Object)(object)templateObject != (Object)null) ? templateObject.transform : null);
			if (!((Object)(object)val != (Object)null))
			{
				return null;
			}
			return ((Component)val).gameObject;
		}

		private static GameObject? TwilightFindBestRendererGameObject(Transform root)
		{
			Transform root2 = root;
			return (from renderer in (from renderer in ((Component)root2).GetComponentsInChildren<Renderer>(true)
					where (Object)(object)renderer != (Object)null && (Object)(object)((Component)renderer).gameObject != (Object)(object)((Component)root2).gameObject
					select renderer).OrderByDescending(delegate(Renderer renderer)
				{
					//IL_0001: Unknown result type (might be due to invalid IL or missing references)
					//IL_0006: Unknown result type (might be due to invalid IL or missing references)
					//IL_0009: Unknown result type (might be due to invalid IL or missing references)
					//IL_000e: Unknown result type (might be due to invalid IL or missing references)
					Bounds bounds = renderer.bounds;
					Vector3 size = ((Bounds)(ref bounds)).size;
					return ((Vector3)(ref size)).sqrMagnitude;
				})
				select ((Component)renderer).gameObject).FirstOrDefault();
		}

		private static GameObject TwilightCreateFallbackMeshObject(Transform stationRoot)
		{
			//IL_0033: Unknown result type (might be due to invalid IL or missing references)
			//IL_0052: Unknown result type (might be due to invalid IL or missing references)
			GameObject obj = GameObject.CreatePrimitive((PrimitiveType)3);
			((Object)obj).name = "Charging Station Mesh";
			obj.transform.SetParent(stationRoot, false);
			obj.transform.localPosition = new Vector3(0f, 0.45f, 0f);
			obj.transform.localScale = new Vector3(0.75f, 0.9f, 0.6f);
			Collider component = obj.GetComponent<Collider>();
			if ((Object)(object)component != (Object)null)
			{
				Object.DestroyImmediate((Object)(object)component);
			}
			TwilightApplyHideFlags((Object)(object)obj);
			return obj;
		}

		private static Transform TwilightCreateFallbackAnchor(Transform stationRoot, string name, Vector3 localPosition, Vector3 localScale)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			//IL_0019: 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: Unknown result type (might be due to invalid IL or missing references)
			//IL_002f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0035: Unknown result type (might be due to invalid IL or missing references)
			//IL_003b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0041: Expected O, but got Unknown
			GameObject val = new GameObject(name);
			val.transform.SetParent(stationRoot, false);
			val.transform.localPosition = localPosition;
			val.transform.localRotation = Quaternion.identity;
			val.transform.localScale = localScale;
			TwilightApplyHideFlags((Object)val);
			return val.transform;
		}

		private static Transform TwilightCreateFallbackCrystalCylinder(Transform stationRoot, int crystalCount)
		{
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			//IL_000b: Expected O, but got Unknown
			//IL_002d: Unknown result type (might be due to invalid IL or missing references)
			//IL_004c: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ca: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e9: Unknown result type (might be due to invalid IL or missing references)
			GameObject val = new GameObject("Crystal Cylinder");
			val.transform.SetParent(stationRoot, false);
			val.transform.localPosition = new Vector3(0f, 0.6f, 0f);
			val.transform.localRotation = Quaternion.Euler(90f, 0f, 0f);
			TwilightApplyHideFlags((Object)(object)val);
			int num = Mathf.Max(1, crystalCount);
			for (int i = 0; i < num; i++)
			{
				GameObject obj = GameObject.CreatePrimitive((PrimitiveType)3);
				((Object)obj).name = $"Crystal {i + 1}";
				obj.transform.SetParent(val.transform, false);
				float num2 = MathF.PI * 2f * (float)i / (float)num;
				obj.transform.localPosition = new Vector3(Mathf.Cos(num2) * 0.18f, Mathf.Sin(num2) * 0.18f, 0f);
				obj.transform.localScale = new Vector3(0.07f, 0.07f, 0.18f);
				Collider component = obj.GetComponent<Collider>();
				if ((Object)(object)component != (Object)null)
				{
					Object.DestroyImmediate((Object)(object)component);
				}
			}
			return val.transform;
		}

		private static Light TwilightCreateFallbackLight(Transform stationRoot, string name, Vector3 localPosition, float intensity)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Expected O, but got Unknown
			//IL_001a: Unknown result type (might be due to invalid IL or missing references)
			//IL_004f: Unknown result type (might be due to invalid IL or missing references)
			GameObject val = new GameObject(name);
			val.transform.SetParent(stationRoot, false);
			val.transform.localPosition = localPosition;
			Light obj = val.AddComponent<Light>();
			obj.type = (LightType)2;
			obj.range = 2f;
			obj.intensity = intensity;
			obj.color = new Color(1f, 0.9f, 0.35f);
			TwilightApplyHideFlags((Object)(object)val);
			return obj;
		}

		private static Light TwilightCreateFallbackSubtleLight(Transform stationRoot)
		{
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			//IL_003f: Unknown result type (might be due to invalid IL or missing references)
			Light obj = TwilightCreateFallbackLight(stationRoot, "Subtle Light", new Vector3(0f, 0.55f, 0.05f), 0.5f);
			obj.range = 2.5f;
			obj.color = new Color(0.7f, 0.7f, 0.3f);
			return obj;
		}

		private static ParticleSystem TwilightCreateFallbackParticleSystem(Transform stationRoot, string name)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Expected O, but got Unknown
			//IL_001a: Unknown result type (might be due to invalid IL or missing references)
			//IL_002b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0030: Unknown result type (might be due to invalid IL or missing references)
			//IL_0054: Unknown result type (might be due to invalid IL or missing references)
			//IL_0065: Unknown result type (might be due to invalid IL or missing references)
			//IL_0076: Unknown result type (might be due to invalid IL or missing references)
			//IL_0081: Unknown result type (might be due to invalid IL or missing references)
			//IL_0086: Unknown result type (might be due to invalid IL or missing references)
			GameObject val = new GameObject(name);
			val.transform.SetParent(stationRoot, false);
			val.transform.localPosition = Vector3.zero;
			ParticleSystem obj = val.AddComponent<ParticleSystem>();
			MainModule main = obj.main;
			((MainModule)(ref main)).playOnAwake = false;
			((MainModule)(ref main)).loop = false;
			((MainModule)(ref main)).duration = 0.25f;
			((MainModule)(ref main)).startLifetime = MinMaxCurve.op_Implicit(0.15f);
			((MainModule)(ref main)).startSpeed = MinMaxCurve.op_Implicit(0.05f);
			((MainModule)(ref main)).startSize = MinMaxCurve.op_Implicit(0.02f);
			EmissionModule emission = obj.emission;
			((EmissionModule)(ref emission)).enabled = false;
			TwilightApplyHideFlags((Object)(object)val);
			return obj;
		}

		private static AudioSource TwilightCreateFallbackAudioSource(Transform stationRoot, string name)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Expected O, but got Unknown
			//IL_001a: Unknown result type (might be due to invalid IL or missing references)
			GameObject val = new GameObject(name);
			val.transform.SetParent(stationRoot, false);
			val.transform.localPosition = Vector3.zero;
			AudioSource obj = val.AddComponent<AudioSource>();
			obj.playOnAwake = false;
			obj.spatialBlend = 1f;
			obj.outputAudioMixerGroup = TwilightGetFallbackAudioMixerGroup();
			TwilightApplyHideFlags((Object)(object)val);
			return obj;
		}

		private static Item? TwilightFindPowerCrystalItem()
		{
			return ((IEnumerable<Item>)Resources.FindObjectsOfTypeAll<Item>()).FirstOrDefault((Func<Item, bool>)((Item item) => (Object)(object)item != (Object)null && (string.Equals(item.itemName, "Power Crystal", StringComparison.OrdinalIgnoreCase) || string.Equals(((Object)item).name, "Item Power Crystal", StringComparison.OrdinalIgnoreCase) || ((Object)item).name.IndexOf("Power Crystal", StringComparison.OrdinalIgnoreCase) >= 0)));
		}

		private static PhysAttribute TwilightCreateFallbackPhysAttribute(float mass)
		{
			PhysAttribute obj = ScriptableObject.CreateInstance<PhysAttribute>();
			obj.mass = Mathf.Max(0.01f, mass);
			TwilightApplyHideFlags((Object)(object)obj);
			return obj;
		}

		private static AudioMixerGroup? TwilightGetFallbackAudioMixerGroup()
		{
			if ((Object)(object)AudioManager.instance == (Object)null)
			{
				return null;
			}
			return AudioManager.instance.SoundMasterGroup ?? AudioManager.instance.PersistentSoundGroup ?? AudioManager.instance.MusicMasterGroup ?? AudioManager.instance.MicrophoneSoundGroup ?? AudioManager.instance.MicrophoneSpectateGroup ?? AudioManager.instance.TTSSoundGroup ?? AudioManager.instance.TTSSpectateGroup;
		}

		private static int TwilightCountModules(Level level)
		{
			return (level.ModulesNormal1?.Count ?? 0) + (level.ModulesPassage1?.Count ?? 0) + (level.ModulesDeadEnd1?.Count ?? 0) + (level.ModulesExtraction1?.Count ?? 0) + (level.ModulesNormal2?.Count ?? 0) + (level.ModulesPassage2?.Count ?? 0) + (level.ModulesDeadEnd2?.Count ?? 0) + (level.ModulesExtraction2?.Count ?? 0) + (level.ModulesNormal3?.Count ?? 0) + (level.ModulesPassage3?.Count ?? 0) + (level.ModulesDeadEnd3?.Count ?? 0) + (level.ModulesExtraction3?.Count ?? 0);
		}

		internal static bool TwilightIsCurrentLevel()
		{
			if (!TwilightIsTwilightLevel(((Object)(object)LevelGenerator.Instance != (Object)null) ? LevelGenerator.Instance.Level : null))
			{
				return TwilightIsTwilightLevel(((Object)(object)RunManager.instance != (Object)null) ? RunManager.instance.levelCurrent : null);
			}
			return true;
		}

		private static bool TwilightIsTwilightLevel(Level? level)
		{
			if ((Object)(object)level == (Object)null)
			{
				return false;
			}
			if (!string.Equals(((Object)level).name, "Level - Twilightforest", StringComparison.OrdinalIgnoreCase) && !string.Equals(((Object)level).name, "Twilightforest", StringComparison.OrdinalIgnoreCase) && (string.IsNullOrWhiteSpace(((Object)level).name) || ((Object)level).name.IndexOf("twilight", StringComparison.OrdinalIgnoreCase) < 0))
			{
				if (!string.IsNullOrWhiteSpace(level.NarrativeName))
				{
					return level.NarrativeName.IndexOf("twilight", StringComparison.OrdinalIgnoreCase) >= 0;
				}
				return false;
			}
			return true;
		}

		internal static void TwilightEnsureLevelFallbackData(Level? level)
		{
			if (TwilightIsTwilightLevel(level))
			{
				Level val = level;
				if (val.ValuablePresets == null)
				{
					val.ValuablePresets = new List<LevelValuables>();
				}
				val = level;
				if (val.AmbiencePresets == null)
				{
					val.AmbiencePresets = new List<LevelAmbience>();
				}
				if (level.ValuablePresets.Count == 0 && (Object)(object)ValuablePresets.GenericValuablePreset != (Object)null)
				{
					level.ValuablePresets.Add(ValuablePresets.GenericValuablePreset);
				}
				if (level.AmbiencePresets.Count == 0 && TwilightTryGetFallbackAmbience(out LevelAmbience ambience))
				{
					level.AmbiencePresets.Add(ambience);
				}
			}
		}

		private static void TwilightEnsureLevelLoadingGraphics(Level level, AssetBundle bundle)
		{
			List<TwilightLoadingGraphic> list = TwilightCollectLoadingGraphics(bundle);
			TwilightCacheLoadingSprites(list);
			string[] twilightLoadingGraphicFieldNames = TwilightLoadingGraphicFieldNames;
			foreach (string text in twilightLoadingGraphicFieldNames)
			{
				if (list.Count != 0 || !TwilightLevelLoadingGraphicValid(level, text))
				{
					TwilightLoadingGraphic twilightLoadingGraphic = ((list.Count > 0) ? list[Math.Min(Array.IndexOf(TwilightLoadingGraphicFieldNames, text), list.Count - 1)] : null);
					if (twilightLoadingGraphic == null || !TwilightSetLevelLoadingGraphic(level, text, twilightLoadingGraphic))
					{
						TwilightCopyFallbackLevelLoadingGraphic(level, text);
					}
				}
			}
		}

		private static List<TwilightLoadingGraphic> TwilightCollectLoadingGraphics(AssetBundle bundle)
		{
			List<TwilightLoadingGraphic> list = new List<TwilightLoadingGraphic>();
			HashSet<string> hashSet = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
			List<Sprite> source = (from sprite in bundle.LoadAllAssets<Sprite>()
				where (Object)(object)sprite != (Object)null && !string.IsNullOrWhiteSpace(((Object)sprite).name)
				select sprite).ToList();
			string[] twilightPreferredLoadingGraphicNames = TwilightPreferredLoadingGraphicNames;
			foreach (string preferredName in twilightPreferredLoadingGraphicNames)
			{
				Sprite val = ((IEnumerable<Sprite>)source).FirstOrDefault((Func<Sprite, bool>)((Sprite candidate) => string.Equals(((Object)candidate).name, preferredName, StringComparison.OrdinalIgnoreCase)));
				if (!((Object)(object)val == (Object)null) && hashSet.Add(((Object)val).name))
				{
					bool canUsePrefabRef = (Object)(object)bundle.LoadAsset<Sprite>(((Object)val).name) != (Object)null;
					list.Add(new TwilightLoadingGraphic(bundle, val, ((Object)val).name, canUsePrefabRef));
				}
			}
			foreach (string item in bundle.GetAllAssetNames().OrderBy(TwilightLoadingGraphicRank).ThenBy<string, string>((string name) => name, StringComparer.OrdinalIgnoreCase))
			{
				Sprite val2 = bundle.LoadAsset<Sprite>(item);
				if (!((Object)(object)val2 == (Object)null) && hashSet.Add(item))
				{
					list.Add(new TwilightLoadingGraphic(bundle, val2, item, canUsePrefabRef: true));
				}
			}
			foreach (Sprite item2 in source.OrderBy((Sprite sprite) => TwilightLoadingGraphicRank(((Object)sprite).name)).ThenBy<Sprite, string>((Sprite sprite) => ((Object)sprite).name, StringComparer.OrdinalIgnoreCase))
			{
				if (!((Object)(object)item2 == (Object)null) && !string.IsNullOrWhiteSpace(((Object)item2).name) && hashSet.Add(((Object)item2).name))
				{
					bool canUsePrefabRef2 = (Object)(object)bundle.LoadAsset<Sprite>(((Object)item2).name) != (Object)null;
					list.Add(new TwilightLoadingGraphic(bundle, item2, ((Object)item2).name, canUsePrefabRef2));
				}
			}
			return list;
		}

		private static void TwilightCacheLoadingSprites(IEnumerable<TwilightLoadingGraphic> graphics)
		{
			TwilightLoadingSprites.Clear();
			foreach (TwilightLoadingGraphic graphic in graphics)
			{
				if ((Object)(object)graphic.Sprite != (Object)null && !TwilightLoadingSprites.Contains(graphic.Sprite))
				{
					TwilightLoadingSprites.Add(graphic.Sprite);
				}
				if (TwilightLoadingSprites.Count >= TwilightLoadingGraphicFieldNames.Length)
				{
					break;
				}
			}
		}

		internal static void TwilightApplyLoadingGraphics(LoadingUI? loadingUI)
		{
			if (!((Object)(object)loadingUI == (Object)null) && TwilightIsCurrentLevel() && TwilightLoadingSprites.Count != 0)
			{
				TwilightApplyLoadingGraphic(loadingUI.loadingGraphic01, 0);
				TwilightApplyLoadingGraphic(loadingUI.loadingGraphic02, 1);
				TwilightApplyLoadingGraphic(loadingUI.loadingGraphic03, 2);
			}
		}

		private static void TwilightApplyLoadingGraphic(Image? image, int index)
		{
			//IL_002f: Unknown result type (might be due to invalid IL or missing references)
			if (!((Object)(object)image == (Object)null))
			{
				Sprite sprite = TwilightLoadingSprites[Math.Min(index, TwilightLoadingSprites.Count - 1)];
				image.sprite = sprite;
				((Graphic)image).color = Color.white;
			}
		}

		private static int TwilightLoadingGraphicRank(string value)
		{
			if (string.IsNullOrWhiteSpace(value))
			{
				return 1000;
			}
			string text = value.ToLowerInvariant();
			int num = 0;
			if (text.Contains("loading"))
			{
				num -= 100;
			}
			if (text.Contains("graphic"))
			{
				num -= 50;
			}
			if (text.Contains("twilight"))
			{
				num -= 25;
			}
			if (text.Contains("forest"))
			{
				num -= 10;
			}
			if (text.Contains("icon"))
			{
				num += 100;
			}
			return num;
		}

		private static bool TwilightLevelLoadingGraphicValid(Level level, string fieldName)
		{
			try
			{
				object obj = AccessTools.Field(((object)level).GetType(), fieldName)?.GetValue(level);
				if (obj == null)
				{
					return false;
				}
				Sprite val = (Sprite)((obj is Sprite) ? obj : null);
				if (val != null)
				{
					return (Object)(object)val != (Object)null;
				}
				object obj2 = obj.GetType().GetMethod("IsValid", Type.EmptyTypes)?.Invoke(obj, Array.Empty<object>());
				return obj2 is bool && (bool)obj2;
			}
			catch
			{
				return false;
			}
		}

		private static bool TwilightSetLevelLoadingGraphic(Level level, string fieldName, TwilightLoadingGraphic graphic)
		{
			try
			{
				FieldInfo fieldInfo = AccessTools.Field(((object)level).GetType(), fieldName);
				if (fieldInfo == null)
				{
					return false;
				}
				if (typeof(Sprite).IsAssignableFrom(fieldInfo.FieldType))
				{
					fieldInfo.SetValue(level, graphic.Sprite);
					return true;
				}
				if (!fieldInfo.FieldType.Name.StartsWith("PrefabRef", StringComparison.Ordinal))
				{
					return false;
				}
				if (!graphic.CanUsePrefabRef)
				{
					return false;
				}
				object obj = fieldInfo.GetValue(level) ?? Activator.CreateInstance(fieldInfo.FieldType);
				if (obj == null)
				{
					return false;
				}
				MethodInfo method = fieldInfo.FieldType.GetMethod("SetPrefab", new Type[2]
				{
					typeof(AssetBundle),
					typeof(string)
				});
				if (method != null)
				{
					method.Invoke(obj, new object[2] { graphic.Bundle, graphic.ResourcePath });
				}
				else
				{
					AccessTools.Field(fieldInfo.FieldType, "bundle")?.SetValue(obj, graphic.Bundle);
					AccessTools.Field(fieldInfo.FieldType, "resourcePath")?.SetValue(obj, graphic.ResourcePath);
					AccessTools.Field(fieldInfo.FieldType, "prefabName")?.SetValue(obj, Path.GetFileNameWithoutExtension(graphic.ResourcePath));
				}
				fieldInfo.SetValue(level, obj);
				return TwilightLevelLoadingGraphicValid(level, fieldName);
			}
			catch
			{
				return false;
			}
		}

		private static bool TwilightCopyFallbackLevelLoadingGraphic(Level level, string fieldName)
		{
			if (RunManager.instance?.levels == null)
			{
				return false;
			}
			FieldInfo fieldInfo = AccessTools.Field(((object)level).GetType(), fieldName);
			if (fieldInfo == null)
			{
				return false;
			}
			foreach (Level level2 in RunManager.instance.levels)
			{
				if ((Object)(object)level2 == (Object)null || TwilightIsTwilightLevel(level2))
				{
					continue;
				}
				object value = fieldInfo.GetValue(level2);
				if (value != null)
				{
					fieldInfo.SetValue(level, value);
					if (TwilightLevelLoadingGraphicValid(level, fieldName))
					{
						return true;
					}
				}
			}
			return false;
		}

		private static bool TwilightTryGetFallbackAmbience(out LevelAmbience ambience)
		{
			ambience = null;
			if ((Object)(object)AudioManager.instance != (Object)null && AudioManager.instance.levelAmbiences != null)
			{
				foreach (LevelAmbience levelAmbience in AudioManager.instance.levelAmbiences)
				{
					if (!((Object)(object)levelAmbience == (Object)null))
					{
						ambience = levelAmbience;
						return true;
					}
				}
			}
			if ((Object)(object)RunManager.instance != (Object)null && RunManager.instance.levels != null)
			{
				foreach (Level level in RunManager.instance.levels)
				{
					if (level?.AmbiencePresets == null)
					{
						continue;
					}
					foreach (LevelAmbience ambiencePreset in level.AmbiencePresets)
					{
						if (!((Object)(object)ambiencePreset == (Object)null))
						{
							ambience = ambiencePreset;
							return true;
						}
					}
				}
			}
			return false;
		}

		internal static bool TwilightShouldSuppressUnityLog(LogType logType, string? format, object[]? args)
		{
			//IL_001b: Unknown result type (might be due to invalid IL or missing references)
			//IL_001d: Invalid comparison between Unknown and I4
			//IL_002f: 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)
			if (!TwilightIsCurrentLevel())
			{
				return false;
			}
			string text = TwilightFormatUnityLogMessage(format, args);
			if (string.IsNullOrWhiteSpace(text))
			{
				return false;
			}
			if ((int)logType == 2 && text.StartsWith("BoxCollider does not support negative scale or size.", StringComparison.Ordinal))
			{
				return true;
			}
			if ((int)logType == 0 && text.StartsWith("RuntimeNavMeshBuilder: Source mesh ", StringComparison.Ordinal) && text.IndexOf("does not allow read access", StringComparison.OrdinalIgnoreCase) >= 0)
			{
				return true;
			}
			if ((int)logType == 0)
			{
				if (!text.StartsWith("Level Point: ", StringComparison.Ordinal))
				{
					return text.StartsWith("          Point Name: ", StringComparison.Ordinal);
				}
				return true;
			}
			return false;
		}

		private static string TwilightFormatUnityLogMessage(string? format, object[]? args)
		{
			if (format == null)
			{
				return string.Empty;
			}
			if (args == null || args.Length == 0)
			{
				return format;
			}
			try
			{
				return string.Format(format, args);
			}
			catch
			{
				return format;
			}
		}

		internal static void TwilightEnsureExtractionPointCompatibility(ExtractionPoint extractionPoint)
		{
			//IL_004c: Unknown result type (might be due to invalid IL or missing references)
			//IL_005c: Unknown result type (might be due to invalid IL or missing references)
			//IL_006c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0076: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00da: Expected O, but got Unknown
			if ((Object)(object)extractionPoint == (Object)null || !TwilightIsCurrentLevel())
			{
				return;
			}
			if ((Object)(object)extractionPoint.extractionArea == (Object)null)
			{
				GameObject val = GameObject.CreatePrimitive((PrimitiveType)2);
				((Object)val).name = "Twilight Patch Extraction Area";
				val.transform.SetParent(((Component)extractionPoint).transform, false);
				val.transform.localPosition = Vector3.zero;
				val.transform.localRotation = Quaternion.identity;
				val.transform.localScale = Vector3.one * 0.1f;
				MeshRenderer component = val.GetComponent<MeshRenderer>();
				if ((Object)(object)component != (Object)null)
				{
					((Renderer)component).enabled = false;
				}
				Collider component2 = val.GetComponent<Collider>();
				if ((Object)(object)component2 != (Object)null)
				{
					Object.Destroy((Object)(object)component2);
				}
				val.SetActive(false);
				TwilightApplyHideFlags((Object)(object)val);
				extractionPoint.extractionArea = val;
			}
			if ((Object)(object)extractionPoint.grossUp == (Object)null)
			{
				GameObject val2 = new GameObject("Twilight Patch GrossUp");
				val2.transform.SetParent(((Component)extractionPoint).transform, false);
				val2.SetActive(false);
				TwilightApplyHideFlags((Object)(object)val2);
				extractionPoint.grossUp = val2;
			}
		}

		internal void TwilightRepairLevelPoints(LevelGenerator levelGenerator)
		{
			if ((Object)(object)levelGenerator == (Object)null || !TwilightIsTwilightLevel(levelGenerator.Level) || levelGenerator.LevelPathPoints == null)
			{
				return;
			}
			int num = 0;
			int num2 = 0;
			foreach (LevelPoint levelPathPoint in levelGenerator.LevelPathPoints)
			{
				if (TwilightRepairLevelPoint(levelPathPoint))
				{
					num++;
				}
				if (TwilightRepairLevelPointRoom(levelPathPoint))
				{
					num2++;
				}
			}
			if (num > 0 || num2 > 0)
			{
				((BaseUnityPlugin)this).Logger.LogInfo((object)$"Empress Twilight Forest Compat Patch repaired {num} Twilight Forest level points onto the navmesh and restored {num2} room links.");
			}
		}

		internal bool TwilightTryStartSilentLevelPoint(LevelPoint levelPoint)
		{
			if (!TwilightIsTwilightLevelPoint(levelPoint))
			{
				return false;
			}
			if ((Object)(object)LevelGenerator.Instance != (Object)null)
			{
				LevelGenerator instance = LevelGenerator.Instance;
				if (instance.LevelPathPoints == null)
				{
					instance.LevelPathPoints = new List<LevelPoint>();
				}
				if (!LevelGenerator.Instance.LevelPathPoints.Contains(levelPoint))
				{
					LevelGenerator.Instance.LevelPathPoints.Add(levelPoint);
				}
				if (levelPoint.Truck)
				{
					LevelGenerator.Instance.LevelPathTruck = levelPoint;
				}
			}
			if ((Object)(object)((Component)levelPoint).GetComponentInParent<StartRoom>() != (Object)null)
			{
				TwilightSetLevelPointBool(levelPoint, "inStartRoom", value: true);
			}
			((MonoBehaviour)this).StartCoroutine(TwilightSilentLevelPointCheck(levelPoint));
			return true;
		}

		private static void TwilightSetLevelPointBool(LevelPoint levelPoint, string fieldName, bool value)
		{
			try
			{
				AccessTools.Field(((object)levelPoint).GetType(), fieldName)?.SetValue(levelPoint, value);
			}
			catch
			{
			}
		}

		private static bool TwilightIsTwilightLevelPoint(LevelPoint? levelPoint)
		{
			if ((Object)(object)levelPoint == (Object)null)
			{
				return false;
			}
			if (TwilightIsCurrentLevel())
			{
				return true;
			}
			Module componentInParent = ((Component)levelPoint).GetComponentInParent<Module>();
			if ((Object)(object)componentInParent != (Object)null && !string.IsNullOrWhiteSpace(((Object)componentInParent).name) && ((Object)componentInParent).name.IndexOf("twilight", StringComparison.OrdinalIgnoreCase) >= 0)
			{
				return true;
			}
			StartRoom componentInParent2 = ((Component)levelPoint).GetComponentInParent<StartRoom>();
			if ((Object)(object)componentInParent2 != (Object)null && !string.IsNullOrWhiteSpace(((Object)componentInParent2).name) && ((Object)componentInParent2).name.IndexOf("twilight", StringComparison.OrdinalIgnoreCase) >= 0)
			{
				return true;
			}
			Transform val = ((Component)levelPoint).transform;
			while ((Object)(object)val != (Object)null)
			{
				if (!string.IsNullOrWhiteSpace(((Object)val).name) && ((Object)val).name.IndexOf("twilight", StringComparison.OrdinalIgnoreCase) >= 0)
				{
					return true;
				}
				val = val.parent;
			}
			return false;
		}

		private static bool TwilightRepairLevelPoint(LevelPoint? levelPoint)
		{
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_0016: 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_0029: Unknown result type (might be due to invalid IL or missing references)
			//IL_0043: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)levelPoint == (Object)null)
			{
				return false;
			}
			Vector3 position = ((Component)levelPoint).transform.position;
			NavMeshHit val = default(NavMeshHit);
			if (NavMesh.SamplePosition(position, ref val, 0.5f, -1))
			{
				return false;
			}
			NavMeshHit val2 = default(NavMeshHit);
			if (!NavMesh.SamplePosition(position, ref val2, 2f, -1))
			{
				return false;
			}
			((Component)levelPoint).transform.position = ((NavMeshHit)(ref val2)).position;
			TwilightRepairLevelPointRoom(levelPoint);
			return true;
		}

		private static bool TwilightRepairLevelPointRoom(LevelPoint? levelPoint)
		{
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)levelPoint == (Object)null || (Object)(object)levelPoint.Room != (Object)null)
			{
				return false;
			}
			RoomVolume room = default(RoomVolume);
			Vector3 val = default(Vector3);
			if (!SemiFunc.GetRoomVolumeAtPosition(((Component)levelPoint).transform.position, ref room, ref val))
			{
				return false;
			}
			levelPoint.Room = room;
			return true;
		}

		internal IEnumerator TwilightSilentLevelPointCheck(LevelPoint levelPoint)
		{
			if ((Object)(object)levelPoint == (Object)null)
			{
				yield break;
			}
			while ((Object)(object)LevelGenerator.Instance == (Object)null || !LevelGenerator.Instance.Generated)
			{
				yield return (object)new WaitForSeconds(0.1f);
			}
			yield return (object)new WaitForSeconds(0.5f);
			if (TwilightIsCurrentLevel())
			{
				TwilightRepairLevelPoint(levelPoint);
				TwilightRepairLevelPointRoom(levelPoint);
				TwilightRepairLevelPointConnections(levelPoint, LevelGenerator.Instance?.LevelPathPoints);
				if (levelPoint.ModuleConnect)
				{
					TwilightSetLevelPointBool(levelPoint, "ModuleConnected", value: true);
				}
			}
		}

		private static void TwilightRepairLevelPointConnections(LevelPoint? levelPoint, IList<LevelPoint>? allLevelPoints)
		{
			if ((Object)(object)levelPoint == (Object)null)
			{
				return;
			}
			if (levelPoint.ConnectedPoints == null)
			{
				levelPoint.ConnectedPoints = new List<LevelPoint>();
			}
			levelPoint.ConnectedPoints.RemoveAll((LevelPoint connectedPoint) => (Object)(object)connectedPoint == (Object)null);
			LevelPoint[] array = levelPoint.ConnectedPoints.ToArray();
			for (int i = 0; i < array.Length; i++)
			{
				TwilightAddLevelPointConnection(array[i], levelPoint);
			}
			if (!levelPoint.ModuleConnect || allLevelPoints == null || levelPoint.ConnectedPoints.Count > 0)
			{
				return;
			}
			LevelPoint val = null;
			float currentBestDistance = float.MaxValue;
			foreach (LevelPoint allLevelPoint in allLevelPoints)
			{
				if (TwilightCanConnectLevelPoints(levelPoint, allLevelPoint, currentBestDistance, out var distance))
				{
					val = allLevelPoint;
					currentBestDistance = distance;
				}
			}
			TwilightAddLevelPointConnection(levelPoint, val);
			TwilightAddLevelPointConnection(val, levelPoint);
		}

		private static bool TwilightCanConnectLevelPoints(LevelPoint source, LevelPoint? candidate, float currentBestDistance, out float distance)
		{
			//IL_0032: Unknown result type (might be due to invalid IL or missing references)
			//IL_003d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0042: Unknown result type (might be due to invalid IL or missing references)
			//IL_0047: Unknown result type (might be due to invalid IL or missing references)
			//IL_0077: Unknown result type (might be due to invalid IL or missing references)
			//IL_0082: Unknown result type (might be due to invalid IL or missing references)
			//IL_009b: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a2: Unknown result type (might be due to invalid IL or missing references)
			distance = 0f;
			if ((Object)(object)source == (Object)null || (Object)(object)candidate == (Object)null || (Object)(object)source == (Object)(object)candidate || !candidate.ModuleConnect)
			{
				return false;
			}
			Vector3 val = ((Component)source).transform.position - ((Component)candidate).transform.position;
			if (((Vector3)(ref val)).sqrMagnitude <= Mathf.Epsilon)
			{
				return false;
			}
			distance = ((Vector3)(ref val)).magnitude;
			if (distance >= 15f || distance >= currentBestDistance)
			{
				return false;
			}
			if (Vector3.Dot(((Component)candidate).transform.forward, ((Component)source).transform.forward) > -0.8f)
			{
				return false;
			}
			return Vector3.Dot(((Component)candidate).transform.forward, ((Vector3)(ref val)).normalized) > 0.8f;
		}

		private static void TwilightAddLevelPointConnection(LevelPoint? source, LevelPoint? target)
		{
			if (!((Object)(object)source == (Object)null) && !((Object)(object)target == (Object)null))
			{
				if (source.ConnectedPoints == null)
				{
					source.ConnectedPoints = new List<LevelPoint>();
				}
				if (!source.ConnectedPoints.Contains(target))
				{
					source.ConnectedPoints.Add(target);
				}
			}
		}

		internal GameObject TwilightCreateFallbackDoorMapObject(Map map, DirtFinderMapDoor door)
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			MapLayer layerParent = map.GetLayerParent(((Component)door).transform.position.y);
			GameObject val = TwilightInstantiateFallbackDoorMapObject(map, ((Component)layerParent).transform);
			((Object)val).name = ((Object)((Component)door).gameObject).name;
			door.Target = val.transform;
			DirtFinderMapDoorTarget val2 = val.GetComponent<DirtFinderMapDoorTarget>() ?? val.AddComponent<DirtFinderMapDoorTarget>();
			val2.Target = ((Component)door).transform;
			val2.Layer = layerParent;
			DirtFinderMapDoorTarget val3 = val2;
			if (val3.HingeTransform == null)
			{
				val3.HingeTransform = val.transform;
			}
			map.DoorUpdate(val2.HingeTransform, ((Component)door).transform, layerParent);
			if (!_twilightLoggedDoorMapFallback)
			{
				_twilightLoggedDoorMapFallback = true;
				((BaseUnityPlugin)this).Logger.LogWarning((object)"Empress Twilight Forest Compat Patch injected fallback minimap door markers for missing Twilight Forest door prefabs.");
			}
			return val;
		}

		private static GameObject TwilightInstantiateFallbackDoorMapObject(Map map, Transform parent)
		{
			//IL_0064: Unknown result type (might be due to invalid IL or missing references)
			//IL_008a: Unknown result type (might be due to invalid IL or missing references)
			//IL_009a: Unknown result type (might be due to invalid IL or missing references)
			GameObject val;
			if ((Object)(object)map.Door1x1Object != (Object)null)
			{
				val = Object.Instantiate<GameObject>(map.Door1x1Object, parent);
				Collider[] componentsInChildren = val.GetComponentsInChildren<Collider>(true);
				for (int i = 0; i < componentsInChildren.Length; i++)
				{
					Object.Destroy((Object)(object)componentsInChildren[i]);
				}
			}
			else
			{
				val = GameObject.CreatePrimitive((PrimitiveType)3);
				val.transform.SetParent(parent, false);
				val.transform.localScale = new Vector3(0.12f, 0.12f, 0.3f);
				Collider component = val.GetComponent<Collider>();
				if ((Object)(object)component != (Object)null)
				{
					Object.Destroy((Object)(object)component);
				}
			}
			val.transform.localPosition = Vector3.zero;
			val.transform.localRotation = Quaternion.identity;
			DirtFinderMapDoorTarget val2 = val.GetComponent<DirtFinderMapDoorTarget>() ?? val.AddComponent<DirtFinderMapDoorTarget>();
			if (val2.HingeTransform == null)
			{
				val2.HingeTransform = val.transform;
			}
			TwilightApplyHideFlags((Object)(object)val);
			return val;
		}

		private static void TwilightApplyHideFlags(Object obj)
		{
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			//IL_0035: Unknown result type (might be due to invalid IL or missing references)
			//IL_003c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0049: Unknown result type (might be due to invalid IL or missing references)
			//IL_0050: Unknown result type (might be due to invalid IL or missing references)
			//IL_0074: 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)
			if (obj == (Object)null)
			{
				return;
			}
			obj.hideFlags = (HideFlags)(obj.hideFlags | 0x23);
			GameObject val = (GameObject)(object)((obj is GameObject) ? obj : null);
			if (val == null)
			{
				return;
			}
			Transform[] componentsInChildren = val.GetComponentsInChildren<Transform>(true);
			foreach (Transform obj2 in componentsInChildren)
			{
				((Object)obj2).hideFlags = (HideFlags)(((Object)obj2).hideFlags | 0x23);
				GameObject gameObject = ((Component)obj2).gameObject;
				((Object)gameObject).hideFlags = (HideFlags)(((Object)gameObject).hideFlags | 0x23);
				Component[] components = ((Component)obj2).GetComponents<Component>();
				foreach (Component val2 in components)
				{
					if ((Object)(object)val2 != (Object)null)
					{
						((Object)val2).hideFlags = (HideFlags)(((Object)val2).hideFlags | 0x23);
					}
				}
			}
		}
	}
	[HarmonyPatch(typeof(LevelPoint), "Start")]
	internal static class TwilightForestCompatPatchLevelPointStartPatch
	{
		[HarmonyPrefix]
		private static bool TwilightPrefix(LevelPoint __instance)
		{
			TwilightForestCompatPatchPlugin instance = TwilightForestCompatPatchPlugin.Instance;
			if ((Object)(object)instance == (Object)null || !instance.TwilightTryStartSilentLevelPoint(__instance))
			{
				return true;
			}
			return false;
		}
	}
	[HarmonyPatch(typeof(LoadingUI), "LevelAnimationStart")]
	internal static class TwilightForestCompatPatchLoadingUILevelAnimationStartPatch
	{
		[HarmonyPostfix]
		private static void TwilightPostfix(LoadingUI __instance)
		{
			TwilightForestCompatPatchPlugin.TwilightApplyLoadingGraphics(__instance);
		}
	}
	[HarmonyPatch(typeof(LevelGenerator), "StartRoomGeneration")]
	internal static class TwilightForestCompatPatchStartRoomGenerationPatch
	{
		[HarmonyPrefix]
		private static void TwilightPrefix()
		{
			TwilightForestCompatPatchPlugin.Instance?.TwilightTryRepairCurrentLevel();
		}
	}
	[HarmonyPatch(typeof(StartRoom), "Start")]
	internal static class TwilightForestCompatPatchStartRoomStartPatch
	{
		[HarmonyPostfix]
		private static void TwilightPostfix(StartRoom __instance)
		{
			TwilightForestCompatPatchPlugin.TwilightActivateVehicleChargingStation(__instance);
		}
	}
	[HarmonyPatch(typeof(ExtractionPoint), "Start")]
	internal static class TwilightForestCompatPatchExtractionPointStartPatch
	{
		[HarmonyPostfix]
		private static void TwilightPostfix(ExtractionPoint __instance)
		{
			TwilightForestCompatPatchPlugin.TwilightEnsureExtractionPointCompatibility(__instance);
		}
	}
	[HarmonyPatch(typeof(ChargingStation), "Start")]
	internal static class TwilightForestCompatPatchChargingStationStartPatch
	{
		[HarmonyPrefix]
		private static void TwilightPrefix(ChargingStation __instance)
		{
			if (TwilightForestCompatPatchPlugin.TwilightIsCurrentLevel())
			{
				TwilightForestCompatPatchPlugin.TwilightEnsureChargingStationCompatibility(__instance);
			}
		}
	}
	[HarmonyPatch(typeof(Levels), "RegisterLevelWithGame")]
	internal static class TwilightForestCompatPatchRegisterLevelPatch
	{
		[HarmonyPrefix]
		private static void TwilightPrefix(Level level)
		{
			TwilightForestCompatPatchPlugin.TwilightEnsureLevelFallbackData(level);
		}
	}
	[HarmonyPatch(typeof(Map), "AddDoor")]
	internal static class TwilightForestCompatPatchMapAddDoorPatch
	{
		[HarmonyPrefix]
		private static bool TwilightPrefix(Map __instance, DirtFinderMapDoor door, GameObject doorPrefab, ref GameObject __result)
		{
			if (!TwilightForestCompatPatchPlugin.TwilightIsCurrentLevel() || (Object)(object)door == (Object)null || (Object)(object)doorPrefab != (Object)null)
			{
				return true;
			}
			TwilightForestCompatPatchPlugin instance = TwilightForestCompatPatchPlugin.Instance;
			if ((Object)(object)instance == (Object)null)
			{
				return true;
			}
			__result = instance.TwilightCreateFallbackDoorMapObject(__instance, door);
			return false;
		}
	}
	[HarmonyPatch(typeof(LevelGenerator), "NavMeshSetupRPC")]
	internal static class TwilightForestCompatPatchNavMeshSetupPatch
	{
		[HarmonyPostfix]
		private static void TwilightPostfix(LevelGenerator __instance)
		{
			TwilightForestCompatPatchPlugin.Instance?.TwilightRepairLevelPoints(__instance);
		}
	}
	[HarmonyPatch(typeof(LevelPoint), "NavMeshCheck")]
	internal static class TwilightForestCompatPatchLevelPointNavMeshCheckPatch
	{
		[HarmonyPrefix]
		private static bo