Decompiled source of TrickyBalls Paradise v1.0.22

plugins/TrickyBall's Paradise/Custom/DeleteMeIfGay.dll

Decompiled 8 months ago
using System;
using System.CodeDom.Compiler;
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 System.Text.Json;
using System.Text.Json.Serialization;
using BepInEx;
using BepInEx.Logging;
using BepInEx.Unity.IL2CPP;
using BoosterImplants;
using BoosterPack.Manager;
using BoosterPack.Models;
using BoosterPack.Patches;
using CellMenu;
using DropServer.BoosterImplants;
using GameData;
using HarmonyLib;
using Il2CppInterop.Runtime.InteropTypes.Arrays;
using Il2CppSystem;
using Il2CppSystem.Collections.Generic;
using Il2CppSystem.Threading.Tasks;
using Localization;
using MTFO.API;
using Microsoft.CodeAnalysis;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: TargetFramework(".NETCoreApp,Version=v6.0", FrameworkDisplayName = "")]
[assembly: AssemblyCompany("BoosterPack")]
[assembly: AssemblyConfiguration("Debug")]
[assembly: AssemblyFileVersion("1.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0+git465baee-dirty-master")]
[assembly: AssemblyProduct("BoosterPack")]
[assembly: AssemblyTitle("BoosterPack")]
[assembly: AssemblyVersion("1.0.0.0")]
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;
		}
	}
}
namespace BoosterPack
{
	[BepInPlugin("Endskill.CustomBoosters", "CustomBoosters", "1.0.0")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	public class BepinExLoader : BasePlugin
	{
		public const string MODNAME = "CustomBoosters";

		public const string AUTHOR = "Endskill";

		public const string GUID = "Endskill.CustomBoosters";

		public const string VERSION = "1.0.0";

		public override void Load()
		{
			//IL_0037: Unknown result type (might be due to invalid IL or missing references)
			//IL_003d: Expected O, but got Unknown
			LogManager.SetLogger(((BasePlugin)this).Log);
			LogManager._debugMessagesActive = ((BasePlugin)this).Config.Bind<bool>("Dev Settings", "DebugMessages", false, "This settings activates/deactivates debug messages in the console for this specific plugin.").Value;
			Harmony val = new Harmony("Endskill.CustomBoosters");
			val.PatchAll(typeof(PersistentInventoryManagerPatches));
			val.PatchAll(typeof(DropServerPatches));
			val.PatchAll(typeof(BoosterImplantInventoryItemPatches));
			val.PatchAll(typeof(CmPageLoadoutPatches));
			MTFOHotReloadAPI.OnHotReload += ScriptManager.HotReaload;
		}
	}
	public static class CacheApiWrapper
	{
		internal static BoosterImplantPlayerData _inv;

		public static bool UseCustomData { get; set; }

		public static BoosterImplantPlayerData Inventory
		{
			get
			{
				return _inv;
			}
			set
			{
				_inv = value;
			}
		}
	}
	internal static class LogManager
	{
		private static ManualLogSource logger;

		internal static bool _debugMessagesActive;

		internal static void SetLogger(ManualLogSource log)
		{
			logger = log;
		}

		public static void Verbose(object msg)
		{
			if (_debugMessagesActive)
			{
				logger.LogInfo(msg);
			}
		}

		public static void Debug(object msg)
		{
			if (_debugMessagesActive)
			{
				logger.LogDebug(msg);
			}
		}

		public static void Message(object msg)
		{
			if (_debugMessagesActive)
			{
				logger.LogMessage(msg);
			}
		}

		public static void Error(object msg)
		{
			logger.LogError(msg);
		}

		public static void Warn(object msg)
		{
			logger.LogWarning(msg);
		}
	}
	[GeneratedCode("VersionInfoGenerator", "2.0.0+git50a4b1a-master")]
	[CompilerGenerated]
	internal static class VersionInfo
	{
		public const string RootNamespace = "BoosterPack";

		public const string Version = "1.0.0";

		public const string VersionPrerelease = null;

		public const string VersionMetadata = "git465baee-dirty-master";

		public const string SemVer = "1.0.0+git465baee-dirty-master";

		public const string GitRevShort = "465baee-dirty";

		public const string GitRevLong = "465baeed0cd33374f3d2e30104b8e8fe99e66f59-dirty";

		public const string GitBranch = "master";

		public const string GitTag = null;

		public const bool GitIsDirty = true;
	}
}
namespace BoosterPack.Patches
{
	[HarmonyPatch(typeof(BoosterImplantInventoryItem))]
	public class BoosterImplantInventoryItemPatches
	{
		[HarmonyPatch(/*Could not decode attribute arguments.*/)]
		[HarmonyPrefix]
		public static bool Prefix(ref bool __result)
		{
			__result = true;
			return false;
		}
	}
	[HarmonyPatch(typeof(CM_PageLoadout))]
	public static class CmPageLoadoutPatches
	{
		[HarmonyPatch("ProcessBoosterImplantEvents")]
		[HarmonyPrefix]
		public static bool ProcessBoosterImplantEventsPrefix()
		{
			return false;
		}
	}
	[HarmonyPatch(typeof(DropServerManager))]
	public static class DropServerManagerPatches
	{
		private static PlayerInventoryData _cachedInventory;

		[HarmonyPatch("GetBoosterImplantPlayerDataAsync")]
		[HarmonyPrefix]
		public static bool GetBoosterImplantPlayerDataAsyncPrefix(ref Task<PlayerInventoryData> __result)
		{
			LogManager.Debug("Booster Patch");
			__result = GetInventory();
			return false;
		}

		[HarmonyPatch("GetInventoryPlayerDataAsync")]
		[HarmonyPrefix]
		public static bool GetInventoryPlayerDataAsyncPrefix(ref Task<PlayerInventoryData> __result)
		{
			LogManager.Debug("Inventar Patch");
			__result = GetInventory();
			return false;
		}

		private static Task<PlayerInventoryData> GetInventory()
		{
			//IL_001b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0025: Expected O, but got Unknown
			//IL_002a: 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_0030: Unknown result type (might be due to invalid IL or missing references)
			//IL_003a: Expected O, but got Unknown
			//IL_003b: Unknown result type (might be due to invalid IL or missing references)
			//IL_003c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0046: Expected O, but got Unknown
			//IL_0047: Unknown result type (might be due to invalid IL or missing references)
			//IL_0048: Unknown result type (might be due to invalid IL or missing references)
			//IL_0052: Expected O, but got Unknown
			//IL_0058: Expected O, but got Unknown
			if (_cachedInventory != null)
			{
				return Task.FromResult<PlayerInventoryData>(_cachedInventory);
			}
			_cachedInventory = new PlayerInventoryData();
			_cachedInventory.BoosterData = new Nullable<BoosterImplantPlayerData>(new BoosterImplantPlayerData
			{
				Basic = new Category(),
				Advanced = new Category(),
				Specialized = new Category()
			});
			return Task.FromResult<PlayerInventoryData>(_cachedInventory);
		}
	}
	[HarmonyPatch(typeof(DropServerGameSession))]
	internal class DropServerPatches
	{
		[HarmonyPatch("ConsumeBoosters")]
		[HarmonyPrefix]
		public static bool ConsumeBoostersPrefix()
		{
			return false;
		}
	}
	[HarmonyPatch(typeof(PersistentInventoryManager))]
	public class PersistentInventoryManagerPatches
	{
		private static uint _id = 9599u;

		[HarmonyPatch("UpdateBoosterImplants")]
		[HarmonyPrefix]
		[HarmonyWrapSafe]
		public static bool UpdateBoosterImplantsPrefix(PersistentInventoryManager __instance)
		{
			//IL_0050: Unknown result type (might be due to invalid IL or missing references)
			//IL_0056: Invalid comparison between Unknown and I4
			ScriptManager.Initialize();
			if (!CacheApiWrapper.UseCustomData)
			{
				CreateData();
			}
			BoosterImplant[] array = ((IEnumerable<BoosterImplantCategory>)BoosterImplantConstants.Categories).Select((BoosterImplantCategory c) => PersistentInventoryManager.GetActiveBoosterImplant((BoosterImplantCategory)c)).ToArray();
			UpdateBoosterImplantInventoryModelMock(__instance);
			if ((int)__instance.m_boosterImplantDirtyState == 0)
			{
				__instance.ClearPendingBoosterImplantTransactions();
			}
			else
			{
				PersistentInventoryManager.CleanupPendingBoosterImplantTransactions(__instance.m_boosterImplantPendingTransactions, __instance.m_boosterImplantInventory);
				PersistentInventoryManager.ApplyPendingBoosterImplantTransactionsToModel(__instance.m_boosterImplantInventory, __instance.m_boosterImplantPendingTransactions);
			}
			for (int i = 0; i < array.Length; i++)
			{
				if (PersistentInventoryManager.GetActiveBoosterImplant((BoosterImplantCategory)i) != array[i])
				{
					Action onActiveBoosterImplantsChanged = __instance.OnActiveBoosterImplantsChanged;
					if (onActiveBoosterImplantsChanged != null)
					{
						onActiveBoosterImplantsChanged.Invoke();
					}
					break;
				}
			}
			Action onBoosterImplantInventoryChanged = __instance.OnBoosterImplantInventoryChanged;
			if ((Delegate)(object)onBoosterImplantInventoryChanged == (Delegate)null)
			{
				return false;
			}
			onBoosterImplantInventoryChanged.Invoke();
			return false;
		}

		private static void CreateData()
		{
			//IL_003f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0046: Expected O, but got Unknown
			//IL_0384: Unknown result type (might be due to invalid IL or missing references)
			//IL_038b: Expected O, but got Unknown
			//IL_038b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0392: Expected O, but got Unknown
			//IL_0392: Unknown result type (might be due to invalid IL or missing references)
			//IL_0399: Expected O, but got Unknown
			//IL_03d4: Unknown result type (might be due to invalid IL or missing references)
			//IL_03db: Expected O, but got Unknown
			//IL_00d5: Unknown result type (might be due to invalid IL or missing references)
			//IL_0110: Unknown result type (might be due to invalid IL or missing references)
			//IL_013e: Unknown result type (might be due to invalid IL or missing references)
			//IL_01dc: Unknown result type (might be due to invalid IL or missing references)
			//IL_0217: Unknown result type (might be due to invalid IL or missing references)
			//IL_0245: Unknown result type (might be due to invalid IL or missing references)
			//IL_028e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0293: Unknown result type (might be due to invalid IL or missing references)
			//IL_02af: Unknown result type (might be due to invalid IL or missing references)
			//IL_02cb: Unknown result type (might be due to invalid IL or missing references)
			//IL_0325: Unknown result type (might be due to invalid IL or missing references)
			//IL_032a: Unknown result type (might be due to invalid IL or missing references)
			//IL_032c: Unknown result type (might be due to invalid IL or missing references)
			//IL_032e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0330: Unknown result type (might be due to invalid IL or missing references)
			//IL_0343: Expected I4, but got Unknown
			Il2CppArrayBase<BoosterImplantTemplateDataBlock> allBlocks = GameDataBlockBase<BoosterImplantTemplateDataBlock>.GetAllBlocks();
			Il2CppArrayBase<BoosterImplantEffectDataBlock> allBlocks2 = GameDataBlockBase<BoosterImplantEffectDataBlock>.GetAllBlocks();
			Il2CppArrayBase<BoosterImplantConditionDataBlock> allBlocks3 = GameDataBlockBase<BoosterImplantConditionDataBlock>.GetAllBlocks();
			List<BoosterImplantInventoryItem> list = new List<BoosterImplantInventoryItem>();
			List<BoosterImplantInventoryItem> list2 = new List<BoosterImplantInventoryItem>();
			List<BoosterImplantInventoryItem> list3 = new List<BoosterImplantInventoryItem>();
			foreach (BoosterImplantTemplateDataBlock item3 in allBlocks)
			{
				BoosterImplantInventoryItem val = new BoosterImplantInventoryItem();
				((BoosterImplantBase)val).Id = _id++;
				((BoosterImplantBase)val).TemplateId = ((GameDataBlockBase<BoosterImplantTemplateDataBlock>)(object)item3).persistentID;
				((BoosterImplantBase)val).UsesRemaining = 88;
				List<BoosterImplantEffect> list4 = new List<BoosterImplantEffect>();
				Enumerator<BoosterImplantEffectInstance> enumerator2 = item3.Effects.GetEnumerator();
				while (enumerator2.MoveNext())
				{
					BoosterImplantEffectInstance effect2 = enumerator2.Current;
					BoosterImplantEffectDataBlock val2 = ((IEnumerable<BoosterImplantEffectDataBlock>)allBlocks2).First((BoosterImplantEffectDataBlock x) => ((GameDataBlockBase<BoosterImplantEffectDataBlock>)(object)x).persistentID == effect2.BoosterImplantEffect);
					LogManager.Debug($"Effect has: {val2.BoosterEffectCategory}, Param: {effect2.MaxValue}");
					BoosterImplantEffect item = default(BoosterImplantEffect);
					item.Id = effect2.BoosterImplantEffect;
					item.Param = effect2.MaxValue;
					list4.Add(item);
				}
				bool flag = true;
				Enumerator<List<BoosterImplantEffectInstance>> enumerator3 = item3.RandomEffects.GetEnumerator();
				while (enumerator3.MoveNext())
				{
					List<BoosterImplantEffectInstance> current2 = enumerator3.Current;
					if (!flag)
					{
						continue;
					}
					flag = false;
					Enumerator<BoosterImplantEffectInstance> enumerator4 = current2.GetEnumerator();
					while (enumerator4.MoveNext())
					{
						BoosterImplantEffectInstance effect = enumerator4.Current;
						BoosterImplantEffectDataBlock val3 = ((IEnumerable<BoosterImplantEffectDataBlock>)allBlocks2).First((BoosterImplantEffectDataBlock x) => ((GameDataBlockBase<BoosterImplantEffectDataBlock>)(object)x).persistentID == effect.BoosterImplantEffect);
						LogManager.Debug($"Effect has: {val3.BoosterEffectCategory}, Param: {effect.MaxValue}");
						BoosterImplantEffect item2 = default(BoosterImplantEffect);
						item2.Id = effect.BoosterImplantEffect;
						item2.Param = effect.MaxValue;
						list4.Add(item2);
					}
				}
				((BoosterImplantBase)val).Effects = Il2CppStructArray<BoosterImplantEffect>.op_Implicit(list4.ToArray());
				foreach (BoosterImplantEffect item4 in (Il2CppArrayBase<BoosterImplantEffect>)(object)((BoosterImplantBase)val).Effects)
				{
					LogManager.Debug($"Effect2 has: {item4.Id}, Param: {item4.Param}");
				}
				((BoosterImplantBase)val).Conditions = new Il2CppStructArray<uint>(Il2CppArrayBase<uint>.op_Implicit(item3.Conditions?.ToArray()));
				BoosterImplantCategory implantCategory = item3.ImplantCategory;
				BoosterImplantCategory val4 = implantCategory;
				switch ((int)val4)
				{
				case 0:
					list.Add(val);
					break;
				case 1:
					list2.Add(val);
					break;
				case 2:
					list3.Add(val);
					break;
				}
			}
			Category val5 = new Category();
			Category val6 = new Category();
			Category val7 = new Category();
			val5.Inventory = new Il2CppReferenceArray<BoosterImplantInventoryItem>(list.ToArray());
			val6.Inventory = new Il2CppReferenceArray<BoosterImplantInventoryItem>(list2.ToArray());
			val7.Inventory = new Il2CppReferenceArray<BoosterImplantInventoryItem>(list3.ToArray());
			BoosterImplantPlayerData val8 = new BoosterImplantPlayerData();
			val8.Basic = val5;
			val8.Advanced = val6;
			val8.Specialized = val7;
			val8.New = Il2CppStructArray<uint>.op_Implicit(new uint[0]);
			CacheApiWrapper.Inventory = val8;
		}

		private static void UpdateBoosterImplantInventoryModelMock(PersistentInventoryManager instance)
		{
			//IL_0119: Unknown result type (might be due to invalid IL or missing references)
			//IL_011e: Unknown result type (might be due to invalid IL or missing references)
			//IL_013a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0156: Unknown result type (might be due to invalid IL or missing references)
			//IL_0197: Unknown result type (might be due to invalid IL or missing references)
			//IL_019e: Expected O, but got Unknown
			BoosterImplantPlayerData inventory = CacheApiWrapper.Inventory;
			BoosterImplantInventoryModel boosterImplantInventory = instance.m_boosterImplantInventory;
			boosterImplantInventory.New.Clear();
			int num = 0;
			while (true)
			{
				int num2 = num;
				uint[] array = Il2CppArrayBase<uint>.op_Implicit((Il2CppArrayBase<uint>)(object)inventory.New);
				int num3 = ((array != null) ? array.Length : 0);
				if (num2 < num3)
				{
					boosterImplantInventory.New.Add(((Il2CppArrayBase<uint>)(object)inventory.New)[num]);
					num++;
					continue;
				}
				break;
			}
			Category[] array2 = (Category[])(object)new Category[3] { inventory.Basic, inventory.Advanced, inventory.Specialized };
			int num4 = default(int);
			for (int i = 0; i < array2.Length; i++)
			{
				Category val = array2[i];
				Category val2 = ((Il2CppArrayBase<Category>)(object)boosterImplantInventory.Categories)[i];
				uint num5 = (boosterImplantInventory.FindPrepared((BoosterImplantCategory)i, ref num4) ? ((Il2CppArrayBase<Category>)(object)boosterImplantInventory.Categories)[i].Inventory[num4].InstanceId : uint.MaxValue);
				val2.Inventory.Clear();
				for (int j = 0; j < ((Il2CppArrayBase<BoosterImplantInventoryItem>)(object)val.Inventory).Length; j++)
				{
					try
					{
						BoosterImplantInventoryItem val3 = ((Il2CppArrayBase<BoosterImplantInventoryItem>)(object)val.Inventory)[j];
						foreach (BoosterImplantEffect item in (Il2CppArrayBase<BoosterImplantEffect>)(object)((BoosterImplantBase)val3).Effects)
						{
							LogManager.Debug($"testItem has: {item.Id} {item.Param}");
						}
						BoosterImplantInventoryItem val4 = new BoosterImplantInventoryItem(((Il2CppArrayBase<BoosterImplantInventoryItem>)(object)val.Inventory)[j]);
						val4.Prepared = val4.InstanceId == num5;
						val2.Inventory.Add(val4);
					}
					catch (Exception ex)
					{
						PersistentInventoryManager.LogError(ex.Message);
					}
				}
				val2.Currency = val.Currency;
				val2.Missed = val.Missed;
				val2.MissedAcknowledged = Mathf.Clamp(val2.MissedAcknowledged, val.MissedAck, val.Missed);
			}
		}
	}
}
namespace BoosterPack.Models
{
	public class ActivateableBoosterData
	{
		public bool UseCustomData { get; set; }

		public List<CustomBooster> CustomBoosters { get; set; }
	}
	public class CustomBooster
	{
		private List<CustomEffect> _effects;

		private List<CustomCondition> _conditions;

		public string PublicName { get; set; }

		public string Description { get; set; }

		public BoosterEffectCategory MainEffectType { get; set; }

		public BoosterImplantCategory ImplantCategory { get; set; }

		public List<CustomEffect> Effects
		{
			get
			{
				if (_effects == null)
				{
					_effects = new List<CustomEffect>();
				}
				return _effects;
			}
			set
			{
				_effects = value;
			}
		}

		public List<CustomCondition> Conditions
		{
			get
			{
				if (_conditions == null)
				{
					_conditions = new List<CustomCondition>();
				}
				return _conditions;
			}
			set
			{
				_conditions = value;
			}
		}
	}
	public class CustomCondition
	{
		public BoosterCondition Condition { get; set; }

		public string PublicShortName { get; set; }

		public string PublicName { get; set; }

		public string Description { get; set; }
	}
	public class CustomEffect
	{
		public AgentModifier Effect { get; set; }

		public string PublicShortName { get; set; }

		public string PublicName { get; set; }

		public string Description { get; set; }

		public string DescriptionNegative { get; set; }

		public BoosterEffectCategory EffectCategory { get; set; }

		public float Value { get; set; }
	}
}
namespace BoosterPack.Manager
{
	public class DataBlockManager
	{
		private uint _templateIds = 306783378u;

		private uint _effectIds = 306783378u;

		private uint _conditionIds = 306783378u;

		private uint _itemId = 306783378u;

		private uint _id = 536870911u;

		public List<BoosterImplantInventoryItem> Basic { get; }

		public List<BoosterImplantInventoryItem> Advanced { get; }

		public List<BoosterImplantInventoryItem> Special { get; }

		public DataBlockManager()
		{
			Basic = new List<BoosterImplantInventoryItem>();
			Advanced = new List<BoosterImplantInventoryItem>();
			Special = new List<BoosterImplantInventoryItem>();
		}

		public void CreateDataBlocksForBooster(CustomBooster booster)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Expected O, but got Unknown
			//IL_005c: 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_0091: Unknown result type (might be due to invalid IL or missing references)
			//IL_0098: Expected O, but got Unknown
			//IL_00aa: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b9: Unknown result type (might be due to invalid IL or missing references)
			//IL_0131: Unknown result type (might be due to invalid IL or missing references)
			//IL_0138: Expected O, but got Unknown
			//IL_01b7: Unknown result type (might be due to invalid IL or missing references)
			//IL_01be: Expected O, but got Unknown
			//IL_01d0: Unknown result type (might be due to invalid IL or missing references)
			//IL_0275: Unknown result type (might be due to invalid IL or missing references)
			//IL_027b: Expected O, but got Unknown
			//IL_02cb: 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_0336: Unknown result type (might be due to invalid IL or missing references)
			//IL_033b: Unknown result type (might be due to invalid IL or missing references)
			//IL_033d: Unknown result type (might be due to invalid IL or missing references)
			//IL_033f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0341: Unknown result type (might be due to invalid IL or missing references)
			//IL_0354: Expected I4, but got Unknown
			BoosterImplantTemplateDataBlock val = new BoosterImplantTemplateDataBlock();
			((GameDataBlockBase<BoosterImplantTemplateDataBlock>)(object)val).name = GetUniqueName();
			((GameDataBlockBase<BoosterImplantTemplateDataBlock>)(object)val).persistentID = ++_templateIds;
			val.Deprecated = false;
			val.PublicName = GetTranslation(booster.PublicName);
			val.Description = GetTranslation(booster.Description);
			val.ImplantCategory = booster.ImplantCategory;
			val.MainEffectType = booster.MainEffectType;
			foreach (CustomEffect effect in booster.Effects)
			{
				BoosterImplantEffectDataBlock val2 = new BoosterImplantEffectDataBlock();
				((GameDataBlockBase<BoosterImplantEffectDataBlock>)(object)val2).name = GetUniqueName();
				val2.Effect = effect.Effect;
				val2.BoosterEffectCategory = effect.EffectCategory;
				val2.PublicShortName = GetTranslation(effect.PublicShortName);
				val2.PublicName = GetTranslation(effect.PublicName);
				val2.Description = GetTranslation(effect.Description);
				val2.DescriptionNegative = GetTranslation(effect.DescriptionNegative);
				((GameDataBlockBase<BoosterImplantEffectDataBlock>)(object)val2).persistentID = _effectIds++;
				BoosterImplantEffectInstance val3 = new BoosterImplantEffectInstance();
				val3.BoosterImplantEffect = ((GameDataBlockBase<BoosterImplantEffectDataBlock>)(object)val2).persistentID;
				val3.MinValue = effect.Value;
				val3.MaxValue = effect.Value;
				val.Effects.Add(val3);
				GameDataBlockBase<BoosterImplantEffectDataBlock>.AddBlock(val2, -1);
			}
			foreach (CustomCondition condition in booster.Conditions)
			{
				BoosterImplantConditionDataBlock val4 = new BoosterImplantConditionDataBlock();
				((GameDataBlockBase<BoosterImplantConditionDataBlock>)(object)val4).name = GetUniqueName();
				val4.Condition = condition.Condition;
				val4.PublicShortName = GetTranslation(condition.PublicShortName);
				val4.PublicName = GetTranslation(condition.PublicName);
				val4.Description = GetTranslation(condition.Description);
				((GameDataBlockBase<BoosterImplantConditionDataBlock>)(object)val4).persistentID = _conditionIds++;
				val.Conditions.Add(((GameDataBlockBase<BoosterImplantConditionDataBlock>)(object)val4).persistentID);
				GameDataBlockBase<BoosterImplantConditionDataBlock>.AddBlock(val4, -1);
			}
			GameDataBlockBase<BoosterImplantTemplateDataBlock>.AddBlock(val, -1);
			BoosterImplantInventoryItem val5 = new BoosterImplantInventoryItem();
			((BoosterImplantBase)val5).Id = _itemId++;
			((BoosterImplantBase)val5).TemplateId = ((GameDataBlockBase<BoosterImplantTemplateDataBlock>)(object)val).persistentID;
			((BoosterImplantBase)val5).UsesRemaining = 99;
			List<BoosterImplantEffect> list = new List<BoosterImplantEffect>();
			Enumerator<BoosterImplantEffectInstance> enumerator3 = val.Effects.GetEnumerator();
			while (enumerator3.MoveNext())
			{
				BoosterImplantEffectInstance current3 = enumerator3.Current;
				BoosterImplantEffect item = default(BoosterImplantEffect);
				item.Id = current3.BoosterImplantEffect;
				item.Param = current3.MaxValue;
				list.Add(item);
			}
			((BoosterImplantBase)val5).Effects = Il2CppStructArray<BoosterImplantEffect>.op_Implicit(list.ToArray());
			((BoosterImplantBase)val5).Conditions = new Il2CppStructArray<uint>(Il2CppArrayBase<uint>.op_Implicit(val.Conditions?.ToArray()));
			BoosterImplantCategory implantCategory = val.ImplantCategory;
			BoosterImplantCategory val6 = implantCategory;
			switch ((int)val6)
			{
			case 0:
				Basic.Add(val5);
				break;
			case 1:
				Advanced.Add(val5);
				break;
			case 2:
				Special.Add(val5);
				break;
			}
		}

		private LocalizedText GetTranslation(string booLocalization)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Expected O, but got Unknown
			LocalizedText val = new LocalizedText();
			val.UntranslatedText = booLocalization;
			return val;
		}

		private string GetUniqueName()
		{
			return $"CustomBoosters_{++_id}";
		}
	}
	public static class ScriptManager
	{
		private static bool _initialized;

		internal static void HotReaload()
		{
			_initialized = false;
			Initialize();
			PersistentInventoryManager.Current.UpdateBoosterImplants(ref CacheApiWrapper._inv);
		}

		public static void Initialize()
		{
			if (!_initialized)
			{
				_initialized = true;
				string text = Path.Combine(MTFOPathAPI.CustomPath, "CustomBoosters");
				if (!Directory.Exists(text))
				{
					Directory.CreateDirectory(text);
				}
				WriteEnumValues(text);
				text = Path.Combine(text, "CustomBoosters.json");
				WriteDefault(text);
				ActivateableBoosterData data = ReadData(text);
				PrepareForUseIngame(data);
			}
		}

		public static void PrepareForUseIngame(ActivateableBoosterData data)
		{
			//IL_0053: Unknown result type (might be due to invalid IL or missing references)
			//IL_0059: Expected O, but got Unknown
			//IL_0059: Unknown result type (might be due to invalid IL or missing references)
			//IL_005f: Expected O, but got Unknown
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0066: Expected O, but got Unknown
			//IL_00ac: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b3: Expected O, but got Unknown
			CacheApiWrapper.UseCustomData = data.UseCustomData;
			List<CustomBooster> customBoosters = data.CustomBoosters;
			DataBlockManager dataBlockManager = new DataBlockManager();
			foreach (CustomBooster item in customBoosters)
			{
				dataBlockManager.CreateDataBlocksForBooster(item);
			}
			Category val = new Category();
			Category val2 = new Category();
			Category val3 = new Category();
			val.Inventory = Il2CppReferenceArray<BoosterImplantInventoryItem>.op_Implicit(dataBlockManager.Basic.ToArray());
			val2.Inventory = Il2CppReferenceArray<BoosterImplantInventoryItem>.op_Implicit(dataBlockManager.Advanced.ToArray());
			val3.Inventory = Il2CppReferenceArray<BoosterImplantInventoryItem>.op_Implicit(dataBlockManager.Special.ToArray());
			BoosterImplantPlayerData val4 = new BoosterImplantPlayerData();
			val4.Basic = val;
			val4.Advanced = val2;
			val4.Specialized = val3;
			val4.New = Il2CppStructArray<uint>.op_Implicit(new uint[0]);
			CacheApiWrapper.Inventory = val4;
		}

		private static ActivateableBoosterData ReadData(string path)
		{
			JsonSerializerOptions jsonSerializerOptions = new JsonSerializerOptions
			{
				IncludeFields = false,
				ReadCommentHandling = JsonCommentHandling.Skip,
				PropertyNameCaseInsensitive = true,
				WriteIndented = true
			};
			jsonSerializerOptions.Converters.Add(new JsonStringEnumConverter());
			return JsonSerializer.Deserialize<ActivateableBoosterData>(File.ReadAllText(path), jsonSerializerOptions) ?? ParseExistingDataBlocks();
		}

		private static void WriteDefault(string path)
		{
			if (!File.Exists(path))
			{
				JsonSerializerOptions jsonSerializerOptions = new JsonSerializerOptions
				{
					IncludeFields = false,
					ReadCommentHandling = JsonCommentHandling.Skip,
					PropertyNameCaseInsensitive = true,
					WriteIndented = true
				};
				jsonSerializerOptions.Converters.Add(new JsonStringEnumConverter());
				File.WriteAllText(path, JsonSerializer.Serialize(ParseExistingDataBlocks(), jsonSerializerOptions));
			}
		}

		private static void WriteEnumValues(string dictionaryPath)
		{
			string path = Path.Combine(dictionaryPath, "MainEffectType.txt");
			if (!File.Exists(path))
			{
				File.WriteAllText(path, "==This file is auto-generated by CustomBoosters. It's not for editing==\n" + string.Join("\n", Enum.GetNames(typeof(BoosterEffectCategory))));
			}
			string path2 = Path.Combine(dictionaryPath, "EffectCategory.txt");
			if (!File.Exists(path2))
			{
				File.WriteAllText(path2, "==This file is auto-generated by CustomBoosters. It's not for editing==\n" + string.Join("\n", Enum.GetNames(typeof(BoosterEffectCategory))));
			}
			string path3 = Path.Combine(dictionaryPath, "ImplantCategory.txt");
			if (!File.Exists(path3))
			{
				File.WriteAllText(path3, "==This file is auto-generated by CustomBoosters. It's not for editing==\n" + string.Join("\n", Enum.GetNames(typeof(BoosterImplantCategory))));
			}
			string path4 = Path.Combine(dictionaryPath, "Effect.txt");
			if (!File.Exists(path4))
			{
				File.WriteAllText(path4, "==This file is auto-generated by CustomBoosters. It's not for editing==\n" + string.Join("\n", Enum.GetNames(typeof(AgentModifier))));
			}
			string path5 = Path.Combine(dictionaryPath, "Condition.txt");
			if (!File.Exists(path5))
			{
				File.WriteAllText(path5, "==This file is auto-generated by CustomBoosters. It's not for editing==\n" + string.Join("\n", Enum.GetNames(typeof(BoosterCondition))));
			}
		}

		private static ActivateableBoosterData ParseExistingDataBlocks()
		{
			//IL_00a0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b4: Unknown result type (might be due to invalid IL or missing references)
			ActivateableBoosterData activateableBoosterData = new ActivateableBoosterData();
			List<CustomBooster> list2 = (activateableBoosterData.CustomBoosters = new List<CustomBooster>());
			activateableBoosterData.UseCustomData = false;
			Il2CppArrayBase<BoosterImplantTemplateDataBlock> allBlocks = GameDataBlockBase<BoosterImplantTemplateDataBlock>.GetAllBlocks();
			Il2CppArrayBase<BoosterImplantEffectDataBlock> allBlocks2 = GameDataBlockBase<BoosterImplantEffectDataBlock>.GetAllBlocks();
			Il2CppArrayBase<BoosterImplantConditionDataBlock> allBlocks3 = GameDataBlockBase<BoosterImplantConditionDataBlock>.GetAllBlocks();
			foreach (BoosterImplantTemplateDataBlock temp in allBlocks)
			{
				CustomBooster customBooster = new CustomBooster();
				customBooster.PublicName = Text.Get(temp.PublicName.Id);
				customBooster.Description = Text.Get(temp.Description.Id);
				customBooster.MainEffectType = temp.MainEffectType;
				customBooster.ImplantCategory = temp.ImplantCategory;
				Enumerator<BoosterImplantEffectInstance> enumerator2 = temp.Effects.GetEnumerator();
				while (enumerator2.MoveNext())
				{
					BoosterImplantEffectInstance effect = enumerator2.Current;
					BoosterImplantEffectDataBlock effectDb2 = ((IEnumerable<BoosterImplantEffectDataBlock>)allBlocks2).First((BoosterImplantEffectDataBlock x) => ((GameDataBlockBase<BoosterImplantEffectDataBlock>)(object)x).persistentID == effect.BoosterImplantEffect);
					customBooster.Effects.Add(ParseEffect(effectDb2, effect.MaxValue));
				}
				if (temp.RandomEffects.Count > 0)
				{
					Enumerator<BoosterImplantEffectInstance> enumerator3 = temp.RandomEffects[0].GetEnumerator();
					while (enumerator3.MoveNext())
					{
						BoosterImplantEffectInstance effect2 = enumerator3.Current;
						BoosterImplantEffectDataBlock effectDb3 = ((IEnumerable<BoosterImplantEffectDataBlock>)allBlocks2).First((BoosterImplantEffectDataBlock x) => ((GameDataBlockBase<BoosterImplantEffectDataBlock>)(object)x).persistentID == effect2.BoosterImplantEffect);
						customBooster.Effects.Add(ParseEffect(effectDb3, effect2.MaxValue));
					}
				}
				Enumerator<uint> enumerator4 = temp.Conditions.GetEnumerator();
				while (enumerator4.MoveNext())
				{
					uint condition = enumerator4.Current;
					BoosterImplantConditionDataBlock conditionDb2 = ((IEnumerable<BoosterImplantConditionDataBlock>)allBlocks3).First((BoosterImplantConditionDataBlock x) => ((GameDataBlockBase<BoosterImplantConditionDataBlock>)(object)x).persistentID == condition);
					customBooster.Conditions.Add(ParseCondition(conditionDb2));
				}
				if (temp.RandomConditions.Count > 0)
				{
					BoosterImplantConditionDataBlock conditionDb3 = ((IEnumerable<BoosterImplantConditionDataBlock>)allBlocks3).First((BoosterImplantConditionDataBlock x) => ((GameDataBlockBase<BoosterImplantConditionDataBlock>)(object)x).persistentID == temp.RandomConditions[0]);
					customBooster.Conditions.Add(ParseCondition(conditionDb3));
				}
				list2.Add(customBooster);
			}
			return activateableBoosterData;
			static CustomCondition ParseCondition(BoosterImplantConditionDataBlock conditionDb)
			{
				//IL_004e: Unknown result type (might be due to invalid IL or missing references)
				return new CustomCondition
				{
					PublicShortName = Text.Get(conditionDb.PublicShortName.Id),
					PublicName = Text.Get(conditionDb.PublicName.Id),
					Description = Text.Get(conditionDb.Description.Id),
					Condition = conditionDb.Condition
				};
			}
			static CustomEffect ParseEffect(BoosterImplantEffectDataBlock effectDb, float value)
			{
				//IL_0065: Unknown result type (might be due to invalid IL or missing references)
				//IL_0072: Unknown result type (might be due to invalid IL or missing references)
				return new CustomEffect
				{
					PublicShortName = Text.Get(effectDb.PublicShortName.Id),
					PublicName = Text.Get(effectDb.PublicName.Id),
					Description = Text.Get(effectDb.Description.Id),
					DescriptionNegative = Text.Get(effectDb.DescriptionNegative.Id),
					Effect = effectDb.Effect,
					EffectCategory = effectDb.BoosterEffectCategory,
					Value = value
				};
			}
		}
	}
}

plugins/TrickyBall's Paradise/Custom/DesertCullingFix/DesertCullingFix.dll

Decompiled 8 months ago
using System;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using BepInEx;
using BepInEx.Unity.IL2CPP;
using CullingSystem;
using HarmonyLib;
using Il2CppInterop.Runtime.InteropTypes.Arrays;
using Microsoft.CodeAnalysis;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETCoreApp,Version=v6.0", FrameworkDisplayName = ".NET 6.0")]
[assembly: AssemblyCompany("DesertCullingFix")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0")]
[assembly: AssemblyProduct("DesertCullingFix")]
[assembly: AssemblyTitle("DesertCullingFix")]
[assembly: AssemblyVersion("1.0.0.0")]
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;
		}
	}
}
namespace DesertCullingFix
{
	[BepInPlugin("TheDoggyDoge.DesertCullingFix", "DesertCullingFix", "1.0.0")]
	public class EntryPoint : BasePlugin
	{
		public static EntryPoint e;

		public override void Load()
		{
			//IL_000b: Unknown result type (might be due to invalid IL or missing references)
			e = this;
			new Harmony("TheDoggyDoge.DesertCullingFix").PatchAll();
			Patch.culling_enabled = true;
		}

		public static void LogIt(object data)
		{
			((BasePlugin)e).Log.LogInfo(data);
		}

		public virtual bool Unload()
		{
			return ((BasePlugin)this).Unload();
		}
	}
	[HarmonyPatch]
	internal class Patch
	{
		public static bool culling_enabled = true;

		public static int cull_count = 0;

		[HarmonyPrefix]
		[HarmonyPatch(typeof(C_Camera), "RunVisibility")]
		public static bool Prefix_RunVisibility(C_Camera __instance)
		{
			//IL_001c: 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_003c: 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)
			if (C_Camera.RenderWithElevatorMask || __instance.m_cullAgent.CurrentNode == null)
			{
				return false;
			}
			C_Camera.Position = ((Component)__instance).transform.position;
			C_Camera.Forward = ((Component)__instance).transform.forward;
			C_Camera.Right = ((Component)__instance).transform.right;
			C_Camera.Up = ((Component)__instance).transform.up;
			C_CullingManager.SpotLights_WantsToShow.Clear();
			C_CullingManager.PointLights_WantsToShow.Clear();
			if (culling_enabled)
			{
				cull_count = 0;
				C_LightPropagationJob.ResetDynamics();
				__instance.PropagateFrustra();
				C_CullingManager.C_CameraUpdate();
			}
			C_CullingManager.SortAndUpdateLights();
			return false;
		}

		[HarmonyPrefix]
		[HarmonyPatch(typeof(C_CullingCluster), "Show")]
		public static void Prefix_Cluster_Show(C_CullingCluster __instance)
		{
			cull_count += ((Il2CppArrayBase<Renderer>)(object)__instance.Renderers).Count;
		}

		[HarmonyPrefix]
		[HarmonyPatch(typeof(C_CullBucket), "Show")]
		public static void Prefix_Bucket_Show(C_CullBucket __instance)
		{
			cull_count += __instance.Renderers.Count;
		}
	}
}

plugins/TrickyBall's Paradise/Custom/FloLib.dll

Decompiled 8 months ago
using System;
using System.CodeDom.Compiler;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Cryptography;
using System.Security.Permissions;
using System.Text;
using AIGraph;
using AK;
using Agents;
using AssetShards;
using BepInEx;
using BepInEx.Core.Logging.Interpolation;
using BepInEx.Logging;
using BepInEx.Unity.IL2CPP;
using BepInEx.Unity.IL2CPP.Hook;
using BepInEx.Unity.IL2CPP.Utils;
using BepInEx.Unity.IL2CPP.Utils.Collections;
using FloLib.Attributes;
using FloLib.Events;
using FloLib.Infos;
using FloLib.Infos.Comps;
using FloLib.Infos.Inject;
using FloLib.Networks;
using FloLib.Networks.Inject;
using FloLib.Networks.PayloadStructs;
using FloLib.Utils;
using FloLib.Utils.Comps;
using FloLib.Utils.Extensions;
using GTFO.API;
using GameData;
using HarmonyLib;
using Il2CppInterop.Runtime;
using Il2CppInterop.Runtime.Injection;
using Il2CppInterop.Runtime.InteropTypes;
using Il2CppInterop.Runtime.InteropTypes.Arrays;
using Il2CppInterop.Runtime.InteropTypes.Fields;
using Il2CppInterop.Runtime.Runtime;
using Il2CppSystem;
using Il2CppSystem.Collections.Generic;
using LevelGeneration;
using Microsoft.CodeAnalysis;
using Player;
using SNetwork;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETCoreApp,Version=v6.0", FrameworkDisplayName = ".NET 6.0")]
[assembly: AssemblyCompany("FloLib")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0+gitd7090d7-dirty-master")]
[assembly: AssemblyProduct("FloLib")]
[assembly: AssemblyTitle("FloLib")]
[assembly: TargetPlatform("Windows7.0")]
[assembly: SupportedOSPlatform("Windows7.0")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.0.0.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

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

		public NullableAttribute(byte[] P_0)
		{
			NullableFlags = P_0;
		}
	}
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class NativeIntegerAttribute : Attribute
	{
		public readonly bool[] TransformFlags;

		public NativeIntegerAttribute()
		{
			TransformFlags = new bool[1] { true };
		}

		public NativeIntegerAttribute(bool[] P_0)
		{
			TransformFlags = 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 FloLib
{
	public static class Automation
	{
		private const BindingFlags ALL = BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic;

		private static readonly Queue<(MethodInfo method, object[] args)> _InvokeWhenStartGame;

		private static readonly Queue<(MethodInfo method, object[] args)> _InvokeWhenStartupAssetLoaded;

		private static readonly Queue<(MethodInfo method, object[] args)> _InvokeWhenEnemyAssetLoaded;

		private static readonly Queue<(MethodInfo method, object[] args)> _InvokeWhenSharedAssetLoaded;

		private static readonly Queue<(MethodInfo method, object[] args)> _InvokeWhenAllAssetsLoaded;

		static Automation()
		{
			_InvokeWhenStartGame = new Queue<(MethodInfo, object[])>();
			_InvokeWhenStartupAssetLoaded = new Queue<(MethodInfo, object[])>();
			_InvokeWhenEnemyAssetLoaded = new Queue<(MethodInfo, object[])>();
			_InvokeWhenSharedAssetLoaded = new Queue<(MethodInfo, object[])>();
			_InvokeWhenAllAssetsLoaded = new Queue<(MethodInfo, object[])>();
			StartGameEvent.OnGameLoaded += delegate
			{
				(MethodInfo, object[]) result5;
				while (_InvokeWhenStartGame.TryDequeue(out result5))
				{
					RunMethod(result5.Item1, result5.Item2);
				}
			};
			AssetEvent.OnStartupAssetLoaded += delegate
			{
				(MethodInfo, object[]) result4;
				while (_InvokeWhenStartupAssetLoaded.TryDequeue(out result4))
				{
					RunMethod(result4.Item1, result4.Item2);
				}
			};
			AssetEvent.OnEnemyAssetLoaded += delegate
			{
				(MethodInfo, object[]) result3;
				while (_InvokeWhenEnemyAssetLoaded.TryDequeue(out result3))
				{
					RunMethod(result3.Item1, result3.Item2);
				}
			};
			AssetEvent.OnSharedAssetLoaded += delegate
			{
				(MethodInfo, object[]) result2;
				while (_InvokeWhenSharedAssetLoaded.TryDequeue(out result2))
				{
					RunMethod(result2.Item1, result2.Item2);
				}
			};
			AssetEvent.OnAllAssetsLoaded += delegate
			{
				(MethodInfo, object[]) result;
				while (_InvokeWhenAllAssetsLoaded.TryDequeue(out result))
				{
					RunMethod(result.Item1, result.Item2);
				}
			};
		}

		public static void RegisterTypes()
		{
			Assembly obj = new StackFrame(1).GetMethod()?.GetType()?.Assembly ?? null;
			if (obj == null)
			{
				throw new NullReferenceException("Caller Assembly was null");
			}
			RegisterTypes(obj);
		}

		public static void RegisterTypes(Type target)
		{
			if (target == null)
			{
				throw new ArgumentNullException("target");
			}
			RegisterTypes(target.Assembly);
		}

		public static void RegisterTypes(Assembly target)
		{
			if (target == null)
			{
				throw new ArgumentNullException("target");
			}
			InjectAll(target);
			AddAutoInvokes(target);
		}

		private static void InjectAll(Assembly assem)
		{
			//IL_0069: Unknown result type (might be due to invalid IL or missing references)
			//IL_006e: Unknown result type (might be due to invalid IL or missing references)
			//IL_007f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0094: Expected O, but got Unknown
			foreach (Type item in assem.GetTypes()?.Where((Type x) => Attribute.IsDefined(x, typeof(AutoInjectAttribute))) ?? Enumerable.Empty<Type>())
			{
				AutoInjectAttribute autoInjectAttribute = (AutoInjectAttribute)Attribute.GetCustomAttribute(item, typeof(AutoInjectAttribute));
				if (autoInjectAttribute.Interfaces.Length != 0)
				{
					RegisterTypeOptions val = new RegisterTypeOptions();
					val.set_Interfaces(Il2CppInterfaceCollection.op_Implicit(autoInjectAttribute.Interfaces));
					val.set_LogSuccess(RegisterTypeOptions.Default.LogSuccess);
					ClassInjector.RegisterTypeInIl2Cpp(item, val);
				}
				else
				{
					ClassInjector.RegisterTypeInIl2Cpp(item);
				}
			}
		}

		private static void AddAutoInvokes(Assembly assem)
		{
			foreach (MethodInfo item in assem.GetTypes()?.SelectMany((Type x) => x.GetMethods(BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic))?.Where((MethodInfo x) => x.IsStatic && Attribute.IsDefined(x, typeof(AutoInvokeAttribute))) ?? Enumerable.Empty<MethodInfo>())
			{
				AutoInvokeAttribute obj = (AutoInvokeAttribute)Attribute.GetCustomAttribute(item, typeof(AutoInvokeAttribute));
				object[] arguments = obj.Arguments;
				switch (obj.When)
				{
				case InvokeWhen.PluginLoaded:
					RunMethod(item, arguments);
					break;
				case InvokeWhen.StartGame:
					_InvokeWhenStartGame.Enqueue((item, arguments));
					break;
				case InvokeWhen.StartupAssetLoaded:
					_InvokeWhenStartupAssetLoaded.Enqueue((item, arguments));
					break;
				case InvokeWhen.EnemyAssetLoaded:
					_InvokeWhenEnemyAssetLoaded.Enqueue((item, arguments));
					break;
				case InvokeWhen.SharedAssetLoaded:
					_InvokeWhenSharedAssetLoaded.Enqueue((item, arguments));
					break;
				case InvokeWhen.AllAssetsLoaded:
					_InvokeWhenAllAssetsLoaded.Enqueue((item, arguments));
					break;
				}
			}
		}

		private static void RunMethod(MethodInfo method, params object[] args)
		{
			if (method.IsConstructor)
			{
				RuntimeHelpers.RunClassConstructor(method.DeclaringType.TypeHandle);
			}
			else
			{
				method.Invoke(null, args);
			}
		}
	}
	[BepInPlugin("GTFO.FloLib", "FloLib", "1.0.0")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	internal class EntryPoint : BasePlugin
	{
		private Harmony _Harmony;

		public override void Load()
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_0010: Expected O, but got Unknown
			_Harmony = new Harmony("FloLib.Harmony");
			_Harmony.PatchAll();
			Automation.RegisterTypes(((object)this).GetType());
		}

		public override bool Unload()
		{
			_Harmony.UnpatchSelf();
			return ((BasePlugin)this).Unload();
		}
	}
	internal static class Logger
	{
		internal static bool LogExceptionInDetail;

		private static readonly ManualLogSource _Logger;

		static Logger()
		{
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			//IL_000f: Expected O, but got Unknown
			_Logger = new ManualLogSource("FloLib");
			Logger.Sources.Add((ILogSource)(object)_Logger);
		}

		private static string Format(object msg)
		{
			return msg.ToString();
		}

		public static void Info(BepInExInfoLogInterpolatedStringHandler handler)
		{
			_Logger.LogInfo(handler);
		}

		public static void Info(string str)
		{
			_Logger.LogMessage((object)str);
		}

		public static void Info(object data)
		{
			_Logger.LogMessage((object)Format(data));
		}

		public static void Debug(BepInExDebugLogInterpolatedStringHandler handler)
		{
			_Logger.LogDebug(handler);
		}

		public static void Debug(string str)
		{
			_Logger.LogDebug((object)str);
		}

		public static void Debug(object data)
		{
			_Logger.LogDebug((object)Format(data));
		}

		public static void Error(BepInExErrorLogInterpolatedStringHandler handler)
		{
			_Logger.LogError(handler);
		}

		public static void Error(string str)
		{
			_Logger.LogError((object)str);
		}

		public static void Error(object data)
		{
			_Logger.LogError((object)Format(data));
		}

		public static void Fatal(BepInExFatalLogInterpolatedStringHandler handler)
		{
			_Logger.LogFatal(handler);
		}

		public static void Fatal(string str)
		{
			_Logger.LogFatal((object)str);
		}

		public static void Fatal(object data)
		{
			_Logger.LogFatal((object)Format(data));
		}

		public static void Warn(BepInExWarningLogInterpolatedStringHandler handler)
		{
			_Logger.LogWarning(handler);
		}

		public static void Warn(string str)
		{
			_Logger.LogWarning((object)str);
		}

		public static void Warn(object data)
		{
			_Logger.LogWarning((object)Format(data));
		}

		[Conditional("DEBUG")]
		public static void DebugOnly(object data)
		{
		}

		public static void Exception(Exception e)
		{
			//IL_001c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0022: Expected O, but got Unknown
			if (LogExceptionInDetail)
			{
				_Logger.LogError((object)e.ToString());
				return;
			}
			bool flag = default(bool);
			BepInExErrorLogInterpolatedStringHandler val = new BepInExErrorLogInterpolatedStringHandler(2, 2, ref flag);
			if (flag)
			{
				((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(e.GetType().Name);
				((BepInExLogInterpolatedStringHandler)val).AppendLiteral(": ");
				((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(e.Message);
			}
			_Logger.LogError(val);
		}
	}
	internal static class TaskQueue
	{
		public const float INTERVAL = 0.15f;

		private static readonly ConcurrentQueue<(Action action, string? name)> q;

		public static Coroutine mainCoroutine { get; private set; }

		private static IEnumerator MainLoop()
		{
			while (true)
			{
				if (q.TryDequeue(out (Action, string) result))
				{
					CoroutineManager.StartCoroutine(CollectionExtensions.WrapToIl2Cpp(ExecuteTask(result.Item1, (result.Item2 == null) ? "unnamed" : result.Item2)), (Action)null);
				}
				yield return (object)new WaitForSeconds(0.15f);
			}
		}

		private static IEnumerator ExecuteTask(Action task, string name)
		{
			try
			{
				task?.Invoke();
			}
			catch (Exception ex)
			{
				bool flag = default(bool);
				BepInExErrorLogInterpolatedStringHandler val = new BepInExErrorLogInterpolatedStringHandler(46, 2, ref flag);
				if (flag)
				{
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral("Exception occurred during execution of task ");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(name);
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral(": ");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<Exception>(ex);
				}
				Logger.Error(val);
			}
			yield break;
		}

		public static void AddTask(Action task, string name = null)
		{
			q.Enqueue((task, name));
		}

		static TaskQueue()
		{
			q = new ConcurrentQueue<(Action, string)>();
			Logger.Debug("TaskQueue: Coroutine started");
			mainCoroutine = CoroutineManager.StartPersistantCoroutine(CollectionExtensions.WrapToIl2Cpp(MainLoop()));
		}
	}
	[GeneratedCode("VersionInfoGenerator", "2.1.3+git35c0c2a-master")]
	[CompilerGenerated]
	internal static class VersionInfo
	{
		public const string RootNamespace = "FloLib";

		public const string Version = "1.0.0";

		public const string VersionPrerelease = null;

		public const string VersionMetadata = "gitd7090d7-dirty-master";

		public const string SemVer = "1.0.0+gitd7090d7-dirty-master";

		public const string GitRevShort = "d7090d7-dirty";

		public const string GitRevLong = "d7090d7625ec9ea5a37260ec10ba96729e107216-dirty";

		public const string GitBranch = "master";

		public const string GitTag = null;

		public const int GitCommitsSinceTag = 0;

		public const bool GitIsDirty = true;
	}
}
namespace FloLib.Utils
{
	public enum CoroutineLifeTime
	{
		Forever,
		Lobby,
		Level,
		BetweenRecall
	}
	public static class Coroutines
	{
		private static MonoBehaviour _Runner;

		private static readonly Queue<Coroutine> _Coroutines_Lobby = new Queue<Coroutine>();

		private static readonly Queue<Coroutine> _Coroutines_Level = new Queue<Coroutine>();

		private static readonly Queue<Coroutine> _Coroutines_CPLoad = new Queue<Coroutine>();

		[AutoInvoke(InvokeWhen.StartGame)]
		internal static void Init()
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			//IL_000b: Expected O, but got Unknown
			GameObject val = new GameObject();
			Object.DontDestroyOnLoad((Object)val);
			_Runner = (MonoBehaviour)(object)val.AddComponent<EmptyMB>();
			LevelAPI.OnLevelCleanup += LevelAPI_OnLevelCleanup;
			Inject_SNet_Capture.OnBufferRecalled += Inject_SNet_Capture_OnBufferRecalled;
		}

		private static void Inject_SNet_Capture_OnBufferRecalled(eBufferType obj)
		{
			StopAll(CoroutineLifeTime.BetweenRecall);
		}

		private static void LevelAPI_OnLevelCleanup()
		{
			StopAll();
			StopAll(CoroutineLifeTime.BetweenRecall);
		}

		public static void StopAll(CoroutineLifeTime lifeTime = CoroutineLifeTime.Level)
		{
			Queue<Coroutine> queue = lifeTime switch
			{
				CoroutineLifeTime.Lobby => _Coroutines_Lobby, 
				CoroutineLifeTime.Level => _Coroutines_Level, 
				CoroutineLifeTime.BetweenRecall => _Coroutines_CPLoad, 
				_ => throw new NotSupportedException($"{"CoroutineLifeTime"}: {lifeTime} is not supported!"), 
			};
			Coroutine result;
			while (queue.TryDequeue(out result))
			{
				_Runner.StopCoroutine(result);
			}
		}

		public static void Stop(Coroutine coroutine)
		{
			_Runner.StopCoroutine(coroutine);
		}

		public static Coroutine Start(IEnumerator coroutine, CoroutineLifeTime lifeTime = CoroutineLifeTime.Forever)
		{
			switch (lifeTime)
			{
			case CoroutineLifeTime.Forever:
				return MonoBehaviourExtensions.StartCoroutine(_Runner, coroutine);
			case CoroutineLifeTime.Lobby:
			{
				Coroutine val = MonoBehaviourExtensions.StartCoroutine(_Runner, coroutine);
				_Coroutines_Lobby.Enqueue(val);
				return val;
			}
			case CoroutineLifeTime.Level:
			{
				Coroutine val = MonoBehaviourExtensions.StartCoroutine(_Runner, coroutine);
				_Coroutines_Level.Enqueue(val);
				return val;
			}
			case CoroutineLifeTime.BetweenRecall:
			{
				Coroutine val = MonoBehaviourExtensions.StartCoroutine(_Runner, coroutine);
				_Coroutines_CPLoad.Enqueue(val);
				return val;
			}
			default:
				throw new NotSupportedException($"{"CoroutineLifeTime"}: {lifeTime} is not supported!!");
			}
		}

		public static Coroutine DoWait(float delay, Action onDone, CoroutineLifeTime lifeTime = CoroutineLifeTime.Forever)
		{
			return Start(Wait(delay, onDone), lifeTime);
		}

		public static Coroutine DoWaitRealtime(float delay, Action onDone, CoroutineLifeTime lifeTime = CoroutineLifeTime.Forever)
		{
			return Start(WaitRealtime(delay, onDone), lifeTime);
		}

		public static Coroutine DoBlink(BlinkInfo blinkInfo, Action<bool> onBlinkChanged, CoroutineLifeTime lifeTime = CoroutineLifeTime.Forever)
		{
			return Start(Blink(blinkInfo, onBlinkChanged), lifeTime);
		}

		public static Coroutine DoLerp(LerpInfo lerpInfo, Action<float> onValueChanged, CoroutineLifeTime lifeTime = CoroutineLifeTime.Forever)
		{
			return Start(Lerp(lerpInfo, onValueChanged), lifeTime);
		}

		public static IEnumerator Wait(float delay, Action onDone)
		{
			yield return (object)new WaitForSeconds(delay);
			onDone?.Invoke();
		}

		public static IEnumerator WaitRealtime(float delay, Action onDone)
		{
			yield return (object)new WaitForSecondsRealtime(delay);
			onDone?.Invoke();
		}

		public static IEnumerator Blink(BlinkInfo info, Action<bool> onBlinkChanged)
		{
			float time = 0f;
			bool lastCond = false;
			onBlinkChanged?.Invoke(obj: false);
			while (time < info.Duration)
			{
				bool flag = BlinkByProgress(Mathf.Repeat(time * info.Speed, 1f));
				if (flag != lastCond)
				{
					onBlinkChanged?.Invoke(flag);
					lastCond = flag;
				}
				time += Time.deltaTime;
				yield return null;
			}
			onBlinkChanged?.Invoke(info.EndBlinkState);
		}

		public static IEnumerator Lerp(LerpInfo info, Action<float> onValueChanged)
		{
			float time = 0f;
			onValueChanged?.Invoke(info.From);
			while (time < info.Duration)
			{
				float num = info.Easing.Evaluate(time / info.Duration);
				float obj = Mathf.Lerp(info.From, info.To, num);
				onValueChanged?.Invoke(obj);
				time += Time.deltaTime;
				yield return null;
			}
			onValueChanged?.Invoke(info.To);
		}

		private static bool BlinkByProgress(float progress)
		{
			return progress % 0.25f < 0.125f;
		}
	}
	public struct BlinkInfo
	{
		public bool EndBlinkState;

		public float Speed;

		public float Duration;

		public static readonly BlinkInfo InDefault = new BlinkInfo
		{
			Duration = 0.33f,
			Speed = 3f,
			EndBlinkState = true
		};

		public static readonly BlinkInfo OutDefault = new BlinkInfo
		{
			Duration = 0.33f,
			Speed = 3f,
			EndBlinkState = false
		};
	}
	public struct LerpInfo
	{
		public float From;

		public float To;

		public float Duration;

		public EaseFunc.Type Easing;

		public LerpInfo(float from, float to, float duration, EaseFunc.Type ease = EaseFunc.Type.Linear)
		{
			From = from;
			To = to;
			Duration = duration;
			Easing = ease;
		}
	}
	public static class EaseFunc
	{
		public enum Type : byte
		{
			Linear,
			Zero,
			One,
			InQuad,
			OutQuad,
			InOutQuad,
			InCubic,
			OutCubic,
			InOutCubic,
			InQuart,
			OutQuart,
			InOutQuart,
			InQuint,
			OutQuint,
			InOutQuint,
			InSine,
			OutSine,
			InOutSine,
			InExpo,
			OutExpo,
			InOutExpo,
			InCirc,
			OutCirc,
			InOutCirc,
			InElastic,
			OutElastic,
			InOutElastic,
			InBack,
			OutBack,
			InOutBack,
			InBounce,
			OutBounce,
			InOutBounce
		}

		public static float Evaluate(this Type type, float t)
		{
			t = Mathf.Clamp01(t);
			return type switch
			{
				Type.Linear => t, 
				Type.Zero => 0f, 
				Type.One => 1f, 
				Type.InQuad => InQuad(t), 
				Type.OutQuad => OutQuad(t), 
				Type.InOutQuad => InOutQuad(t), 
				Type.InCubic => InCubic(t), 
				Type.OutCubic => OutCubic(t), 
				Type.InOutCubic => InOutCubic(t), 
				Type.InQuart => InQuart(t), 
				Type.OutQuart => OutQuart(t), 
				Type.InOutQuart => InOutQuart(t), 
				Type.InQuint => InQuint(t), 
				Type.OutQuint => OutQuint(t), 
				Type.InOutQuint => InOutQuint(t), 
				Type.InSine => InSine(t), 
				Type.OutSine => OutSine(t), 
				Type.InOutSine => InOutSine(t), 
				Type.InExpo => InExpo(t), 
				Type.OutExpo => OutExpo(t), 
				Type.InOutExpo => InOutExpo(t), 
				Type.InCirc => InCirc(t), 
				Type.OutCirc => OutCirc(t), 
				Type.InOutCirc => InOutCirc(t), 
				Type.InElastic => InElastic(t), 
				Type.OutElastic => OutElastic(t), 
				Type.InOutElastic => InOutElastic(t), 
				Type.InBack => InBack(t), 
				Type.OutBack => OutBack(t), 
				Type.InOutBack => InOutBack(t), 
				Type.InBounce => InBounce(t), 
				Type.OutBounce => OutBounce(t), 
				Type.InOutBounce => InOutBounce(t), 
				_ => throw new ArgumentOutOfRangeException("type", "Given type was invalid!"), 
			};
		}

		public static float InQuad(float t)
		{
			return t * t;
		}

		public static float OutQuad(float t)
		{
			return 1f - InQuad(1f - t);
		}

		public static float InOutQuad(float t)
		{
			if ((double)t < 0.5)
			{
				return InQuad(t * 2f) / 2f;
			}
			return 1f - InQuad((1f - t) * 2f) / 2f;
		}

		public static float InCubic(float t)
		{
			return t * t * t;
		}

		public static float OutCubic(float t)
		{
			return 1f - InCubic(1f - t);
		}

		public static float InOutCubic(float t)
		{
			if ((double)t < 0.5)
			{
				return InCubic(t * 2f) / 2f;
			}
			return 1f - InCubic((1f - t) * 2f) / 2f;
		}

		public static float InQuart(float t)
		{
			return t * t * t * t;
		}

		public static float OutQuart(float t)
		{
			return 1f - InQuart(1f - t);
		}

		public static float InOutQuart(float t)
		{
			if ((double)t < 0.5)
			{
				return InQuart(t * 2f) / 2f;
			}
			return 1f - InQuart((1f - t) * 2f) / 2f;
		}

		public static float InQuint(float t)
		{
			return t * t * t * t * t;
		}

		public static float OutQuint(float t)
		{
			return 1f - InQuint(1f - t);
		}

		public static float InOutQuint(float t)
		{
			if ((double)t < 0.5)
			{
				return InQuint(t * 2f) / 2f;
			}
			return 1f - InQuint((1f - t) * 2f) / 2f;
		}

		public static float InSine(float t)
		{
			return (float)(0.0 - Math.Cos((double)t * Math.PI / 2.0));
		}

		public static float OutSine(float t)
		{
			return (float)Math.Sin((double)t * Math.PI / 2.0);
		}

		public static float InOutSine(float t)
		{
			return (float)(Math.Cos((double)t * Math.PI) - 1.0) / -2f;
		}

		public static float InExpo(float t)
		{
			return (float)Math.Pow(2.0, 10f * (t - 1f));
		}

		public static float OutExpo(float t)
		{
			return 1f - InExpo(1f - t);
		}

		public static float InOutExpo(float t)
		{
			if ((double)t < 0.5)
			{
				return InExpo(t * 2f) / 2f;
			}
			return 1f - InExpo((1f - t) * 2f) / 2f;
		}

		public static float InCirc(float t)
		{
			return 0f - ((float)Math.Sqrt(1f - t * t) - 1f);
		}

		public static float OutCirc(float t)
		{
			return 1f - InCirc(1f - t);
		}

		public static float InOutCirc(float t)
		{
			if ((double)t < 0.5)
			{
				return InCirc(t * 2f) / 2f;
			}
			return 1f - InCirc((1f - t) * 2f) / 2f;
		}

		public static float InElastic(float t)
		{
			return 1f - OutElastic(1f - t);
		}

		public static float OutElastic(float t)
		{
			float num = 0.3f;
			return (float)Math.Pow(2.0, -10f * t) * (float)Math.Sin((double)(t - num / 4f) * (Math.PI * 2.0) / (double)num) + 1f;
		}

		public static float InOutElastic(float t)
		{
			if ((double)t < 0.5)
			{
				return InElastic(t * 2f) / 2f;
			}
			return 1f - InElastic((1f - t) * 2f) / 2f;
		}

		public static float InBack(float t)
		{
			float num = 1.70158f;
			return t * t * ((num + 1f) * t - num);
		}

		public static float OutBack(float t)
		{
			return 1f - InBack(1f - t);
		}

		public static float InOutBack(float t)
		{
			if ((double)t < 0.5)
			{
				return InBack(t * 2f) / 2f;
			}
			return 1f - InBack((1f - t) * 2f) / 2f;
		}

		public static float InBounce(float t)
		{
			return 1f - OutBounce(1f - t);
		}

		public static float OutBounce(float t)
		{
			float num = 2.75f;
			float num2 = 7.5625f;
			if (t < 1f / num)
			{
				return num2 * t * t;
			}
			if (t < 2f / num)
			{
				t -= 1.5f / num;
				return num2 * t * t + 0.75f;
			}
			if ((double)t < 2.5 / (double)num)
			{
				t -= 2.25f / num;
				return num2 * t * t + 0.9375f;
			}
			t -= 2.625f / num;
			return num2 * t * t + 63f / 64f;
		}

		public static float InOutBounce(float t)
		{
			if ((double)t < 0.5)
			{
				return InBounce(t * 2f) / 2f;
			}
			return 1f - InBounce((1f - t) * 2f) / 2f;
		}
	}
	public static class EasyDetour
	{
		public unsafe delegate void StaticVoidDelegate(Il2CppMethodInfo* methodInfo);

		public unsafe delegate void InstanceVoidDelegate(IntPtr instancePtr, Il2CppMethodInfo* methodInfo);

		public static bool TryCreate<T>(DetourDescriptor descriptor, T to, out T originalCall, out INativeDetour detourInstance) where T : Delegate
		{
			try
			{
				nint methodPointer = descriptor.GetMethodPointer();
				detourInstance = INativeDetour.CreateAndApply<T>((IntPtr)methodPointer, to, ref originalCall);
				return detourInstance != null;
			}
			catch (Exception ex)
			{
				Logger.Error("Exception Thrown while creating Detour:");
				Logger.Error(ex.ToString());
			}
			originalCall = null;
			detourInstance = null;
			return false;
		}
	}
	public struct DetourDescriptor
	{
		public Type Type;

		public Type ReturnType;

		public Type[] ArgTypes;

		public string MethodName;

		public bool IsGeneric;

		public unsafe nint GetMethodPointer()
		{
			if (Type == null)
			{
				throw new MissingFieldException("Field Type is not set!");
			}
			if (ReturnType == null)
			{
				throw new MissingFieldException("Field ReturnType is not set! If you mean 'void' do typeof(void)");
			}
			if (string.IsNullOrEmpty(MethodName))
			{
				throw new MissingFieldException("Field MethodName is not set or valid!");
			}
			Il2CppType.From(Type, true);
			IntPtr nativeClassPointer = Il2CppClassPointerStore.GetNativeClassPointer(Type);
			string fullName = GetFullName(ReturnType);
			string[] array;
			if (ArgTypes == null || ArgTypes.Length == 0)
			{
				array = Array.Empty<string>();
			}
			else
			{
				int num = ArgTypes.Length;
				array = new string[num];
				for (int i = 0; i < num; i++)
				{
					Type type = ArgTypes[i];
					array[i] = GetFullName(type);
				}
			}
			void** ptr = (void**)IL2CPP.GetIl2CppMethod(nativeClassPointer, IsGeneric, MethodName, fullName, array).ToPointer();
			if (ptr == null)
			{
				return (nint)ptr;
			}
			return (nint)(*ptr);
		}

		private static string GetFullName(Type type)
		{
			bool isPointer = type.IsPointer;
			if (isPointer)
			{
				type = type.GetElementType();
			}
			if (type.IsPrimitive || type == typeof(string))
			{
				if (isPointer)
				{
					return type.MakePointerType().FullName;
				}
				return type.FullName;
			}
			Type val = Il2CppType.From(type, true);
			if (isPointer)
			{
				return val.MakePointerType().FullName;
			}
			return val.FullName;
		}
	}
	public struct HalfColor
	{
		public Half R;

		public Half G;

		public Half B;

		public Half A;

		public HalfColor()
		{
			R = (Half)0f;
			G = (Half)0f;
			B = (Half)0f;
			A = (Half)0f;
		}

		public HalfColor(float r, float g, float b, float a)
		{
			R = (Half)r;
			G = (Half)g;
			B = (Half)b;
			A = (Half)a;
		}

		public static implicit operator Color(HalfColor halfCol)
		{
			//IL_0030: Unknown result type (might be due to invalid IL or missing references)
			return new Color((float)halfCol.R, (float)halfCol.G, (float)halfCol.B, (float)halfCol.A);
		}

		public static implicit operator HalfColor(Color col)
		{
			//IL_0009: Unknown result type (might be due to invalid IL or missing references)
			//IL_001b: Unknown result type (might be due to invalid IL or missing references)
			//IL_002d: Unknown result type (might be due to invalid IL or missing references)
			//IL_003f: Unknown result type (might be due to invalid IL or missing references)
			HalfColor result = new HalfColor();
			result.R = (Half)col.r;
			result.G = (Half)col.g;
			result.B = (Half)col.b;
			result.A = (Half)col.a;
			return result;
		}
	}
	public struct HalfRGBColor
	{
		public Half R;

		public Half G;

		public Half B;

		public static implicit operator Color(HalfRGBColor halfCol)
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			return new Color((float)halfCol.R, (float)halfCol.G, (float)halfCol.B);
		}

		public static implicit operator HalfRGBColor(Color col)
		{
			//IL_000a: Unknown result type (might be due to invalid IL or missing references)
			//IL_001c: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Unknown result type (might be due to invalid IL or missing references)
			HalfRGBColor result = default(HalfRGBColor);
			result.R = (Half)col.r;
			result.G = (Half)col.g;
			result.B = (Half)col.b;
			return result;
		}
	}
	public class RNG
	{
		private const int Float01Precision = 2000000000;

		private const float Float01Inv = 5E-10f;

		private static uint _UniqueIDForRandomSeed = 0u;

		private Random _Rand;

		private int _Seed;

		public static GlobalRNG Global { get; private set; } = new GlobalRNG();


		public float Float01 => (float)_Rand.Next(0, 2000000001) * 5E-10f;

		public float FloatMinusOneToPlusOne => (float)_Rand.Next(-2000000000, 2000000001) * 5E-10f;

		public int Int0ToPositive => _Rand.Next(0, int.MaxValue);

		public int Int0ToNegative => _Rand.Next(int.MinValue, 1);

		public int Int => _Rand.Next(int.MinValue, int.MaxValue);

		public RNG()
		{
			if (_UniqueIDForRandomSeed == uint.MaxValue)
			{
				_UniqueIDForRandomSeed = 0u;
			}
			else
			{
				_UniqueIDForRandomSeed++;
			}
			_Seed = $"{_UniqueIDForRandomSeed} {Environment.TickCount64}".GetHashCode();
			_Rand = new Random(_Seed);
		}

		public RNG(int seed)
		{
			_Seed = seed;
			_Rand = new Random(seed);
		}

		public virtual void Reset(int? newSeed = null)
		{
			if (newSeed.HasValue)
			{
				_Seed = newSeed.Value;
			}
			_Rand = new Random(_Seed);
		}

		public bool Probability(float probability)
		{
			if (probability <= 0f)
			{
				return false;
			}
			if (probability >= 1f)
			{
				return true;
			}
			return Float01 < probability;
		}

		public bool OneIn(int cases)
		{
			//IL_0009: Unknown result type (might be due to invalid IL or missing references)
			//IL_000f: Expected O, but got Unknown
			if (cases <= 0)
			{
				bool flag = default(bool);
				BepInExWarningLogInterpolatedStringHandler val = new BepInExWarningLogInterpolatedStringHandler(46, 3, ref flag);
				if (flag)
				{
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>("RNG");
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral(".");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>("OneIn");
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" received ");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<int>(cases);
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" (0 or negative); fallback to false");
				}
				Logger.Warn(val);
				return false;
			}
			if (cases == 1)
			{
				return true;
			}
			return _Rand.Next(0, cases) == 0;
		}

		public T Choice<T>(params T[] items)
		{
			return Choice((IEnumerable<T>)items);
		}

		public T Choice<T>(IEnumerable<T> items)
		{
			if (IsChoiceHaveSimpleScenarioValue(items, out var value))
			{
				return value;
			}
			int maxValue = items.Count();
			int index = _Rand.Next(0, maxValue);
			return items.ElementAt(index);
		}

		public T[] Choice<T>(IEnumerable<T> items, int count)
		{
			if (IsChoiceHaveSimpleScenarioValue(items, out var value))
			{
				return new T[1] { value };
			}
			return items.OrderBy((T x) => _Rand.NextDouble()).Take(count).ToArray();
		}

		public T WeightedChoice<T>(IEnumerable<(T item, float weight)> itemTuples)
		{
			if (IsChoiceHaveSimpleScenarioValue<(T, float)>(itemTuples, out var value))
			{
				return value.Item1;
			}
			T[] array = itemTuples.Select(((T item, float weight) x) => x.item).ToArray();
			float[] array2 = itemTuples.Select(((T item, float weight) x) => x.weight).ToArray();
			float num = 0f;
			for (int i = 0; i < array2.Length; i++)
			{
				float num2 = array2[i];
				if (num2 <= 0f)
				{
					array2[i] = -1f;
				}
				else
				{
					num = (array2[i] = num + num2);
				}
			}
			if (num <= 0f)
			{
				return Choice(array);
			}
			float num3 = Float01 * num;
			for (int j = 0; j < array2.Length; j++)
			{
				if (j == array2.Length - 1 || num3 <= array2[j])
				{
					return array[j];
				}
			}
			throw new InvalidOperationException("What? this should never happen");
		}

		private static bool IsChoiceHaveSimpleScenarioValue<T>(IEnumerable<T> items, out T value)
		{
			int num = items.Count();
			if (num <= 0)
			{
				throw new ArgumentException("Argument Item Count is 0!", "items");
			}
			if (num == 1)
			{
				value = items.First();
				return true;
			}
			value = default(T);
			return false;
		}
	}
	public sealed class GlobalRNG : RNG
	{
		public sealed override void Reset(int? newSeed = null)
		{
			Logger.Warn("Resetting Seed Value is not allowed on RNG.Global");
		}
	}
}
namespace FloLib.Utils.Extensions
{
	public static class ColorExtension
	{
		public static string ToHex(this Color input)
		{
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			return "#" + ColorUtility.ToHtmlStringRGB(input);
		}

		public static string ToHexRGBA(this Color input)
		{
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			return "#" + ColorUtility.ToHtmlStringRGBA(input);
		}

		public static void GetColorInfo(this Color input, out Color baseColor, out float colorMultiplier)
		{
			//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_001a: 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)
			//IL_0072: 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)
			float num = 0f;
			float num2 = 0f;
			float r = input.r;
			float g = input.g;
			float b = input.b;
			float num3 = Mathf.Abs(r);
			float num4 = Mathf.Abs(g);
			float num5 = Mathf.Abs(b);
			if (num3 > num2)
			{
				num2 = num3;
				num = r;
			}
			if (num4 > num2)
			{
				num2 = num4;
				num = g;
			}
			if (num5 > num2)
			{
				num2 = num5;
				num = b;
			}
			if (num2 > 0f)
			{
				baseColor = new Color(r / num, g / num, b / num, 1f);
				colorMultiplier = num;
			}
			else
			{
				baseColor = Color.black;
				colorMultiplier = 1f;
			}
		}
	}
	public static class ComponentExtension
	{
		public static bool TryGetComp<T>(this Component comp, out T component)
		{
			component = comp.GetComponent<T>();
			return component != null;
		}

		public static bool TryGetVirtualScene(this Component comp, out GUIX_VirtualScene scene)
		{
			GUIX_VirtualSceneLink component = comp.GetComponent<GUIX_VirtualSceneLink>();
			if ((Object)(object)component == (Object)null)
			{
				scene = null;
				return false;
			}
			scene = component.m_virtualScene;
			return (Object)(object)scene != (Object)null;
		}

		public static string GetGameObjectPath(this Component comp)
		{
			return comp.gameObject.GetPath();
		}
	}
	public static class GameObjectExtension
	{
		public static bool TryGetComp<T>(this GameObject obj, out T component)
		{
			component = obj.GetComponent<T>();
			return component != null;
		}

		public static T GetCompInParentOrChild<T>(this GameObject obj)
		{
			T val = obj.GetComponentInParent<T>();
			if (val == null)
			{
				val = obj.GetComponentInChildren<T>();
				if (val == null)
				{
					obj.GetComponent<T>();
				}
			}
			return val;
		}

		public static string GetPath(this GameObject obj)
		{
			string text = "/" + ((Object)obj).name;
			while ((Object)(object)obj.transform.parent != (Object)null)
			{
				obj = ((Component)obj.transform.parent).gameObject;
				text = "/" + ((Object)obj).name + text;
			}
			return text;
		}
	}
	public static class Il2CppBoxingExtension
	{
		public static Object BoxToIl2CppObject(this bool value)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			Boolean val = default(Boolean);
			val.m_value = value;
			return ((Boolean)(ref val)).BoxIl2CppObject();
		}

		public static Object BoxToIl2CppObject(this byte value)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			Byte val = default(Byte);
			val.m_value = value;
			return ((Byte)(ref val)).BoxIl2CppObject();
		}

		public static Object BoxToIl2CppObject(this sbyte value)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			SByte val = default(SByte);
			val.m_value = value;
			return ((SByte)(ref val)).BoxIl2CppObject();
		}

		public static Object BoxToIl2CppObject(this char value)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			Char val = default(Char);
			val.m_value = value;
			return ((Char)(ref val)).BoxIl2CppObject();
		}

		public static Object BoxToIl2CppObject(this short value)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			Int16 val = default(Int16);
			val.m_value = value;
			return ((Int16)(ref val)).BoxIl2CppObject();
		}

		public static Object BoxToIl2CppObject(this ushort value)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			UInt16 val = default(UInt16);
			val.m_value = value;
			return ((UInt16)(ref val)).BoxIl2CppObject();
		}

		public static Object BoxToIl2CppObject(this int value)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			Int32 val = default(Int32);
			val.m_value = value;
			return ((Int32)(ref val)).BoxIl2CppObject();
		}

		public static Object BoxToIl2CppObject(this uint value)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			UInt32 val = default(UInt32);
			val.m_value = value;
			return ((UInt32)(ref val)).BoxIl2CppObject();
		}

		public static Object BoxToIl2CppObject(this long value)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			Int64 val = default(Int64);
			val.m_value = value;
			return ((Int64)(ref val)).BoxIl2CppObject();
		}

		public static Object BoxToIl2CppObject(this ulong value)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			UInt64 val = default(UInt64);
			val.m_value = value;
			return ((UInt64)(ref val)).BoxIl2CppObject();
		}

		public static Object BoxToIl2CppObject(this float value)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			Single val = default(Single);
			val.m_value = value;
			return ((Single)(ref val)).BoxIl2CppObject();
		}

		public static Object BoxToIl2CppObject(this double value)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			Double val = default(Double);
			val.m_value = value;
			return ((Double)(ref val)).BoxIl2CppObject();
		}

		public static Object BoxToIl2CppObject(this nint value)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			IntPtr val = default(IntPtr);
			val.m_value = value;
			return ((IntPtr)(ref val)).BoxIl2CppObject();
		}
	}
	public static class Il2CppObjectExtension
	{
		public static bool CanCastToType<T>(this Il2CppObjectBase obj) where T : Il2CppObjectBase
		{
			return obj.TryCast<T>() != null;
		}

		public static bool TryCastToType<T>(this Il2CppObjectBase obj, out T result) where T : Il2CppObjectBase
		{
			result = obj.TryCast<T>();
			return result != null;
		}
	}
	public static class LGLightExtension
	{
		public static void SetColor(this IEnumerable<LG_Light> lights, Color color)
		{
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			foreach (LG_Light light in lights)
			{
				light.ChangeColor(color);
			}
		}

		public static void SetEnabled(this IEnumerable<LG_Light> lights, bool enabled)
		{
			foreach (LG_Light light in lights)
			{
				light.SetEnabled(enabled);
			}
		}

		public static bool Is(this LG_Light light, LightCategory lightCategory)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Invalid comparison between Unknown and I4
			return (int)light.m_category == (int)lightCategory;
		}

		public static bool IsAny(this LG_Light light, params LightCategory[] categories)
		{
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			//IL_000d: Invalid comparison between Unknown and I4
			for (int i = 0; i < categories.Length; i++)
			{
				if ((int)light.m_category == (int)categories[i])
				{
					return true;
				}
			}
			return false;
		}
	}
	public enum LightCategory
	{
		General = 0,
		Special = 1,
		Independent = 3,
		Sign = 5,
		Door = 4,
		DoorImportant = 6,
		Emergency = 2
	}
	public static class TerminalExtension
	{
		public static void SetPowered(this LG_ComputerTerminal terminal, bool isPowered)
		{
			terminal.OnProximityExit();
			Interact_ComputerTerminal componentInChildren = ((Component)terminal).GetComponentInChildren<Interact_ComputerTerminal>(true);
			if ((Object)(object)componentInChildren != (Object)null)
			{
				((Behaviour)componentInChildren).enabled = isPowered;
				((Interact_Base)componentInChildren).SetActive(isPowered);
			}
			GUIX_VirtualSceneLink component = ((Component)terminal).GetComponent<GUIX_VirtualSceneLink>();
			if ((Object)(object)component != (Object)null && (Object)(object)component.m_virtualScene != (Object)null)
			{
				GUIX_VirtualCamera virtualCamera = component.m_virtualScene.virtualCamera;
				float num = (isPowered ? 0.3f : 0f);
				float num2 = (isPowered ? 1000f : 0f);
				virtualCamera.SetFovAndClip(virtualCamera.paramCamera.fieldOfView, num, num2);
			}
			if ((Object)(object)terminal.m_text != (Object)null)
			{
				((Behaviour)terminal.m_text).enabled = isPowered;
			}
			if (!isPowered)
			{
				PlayerAgent localInteractionSource = terminal.m_localInteractionSource;
				if ((Object)(object)localInteractionSource != (Object)null && localInteractionSource.FPItemHolder.InTerminalTrigger)
				{
					terminal.ExitFPSView();
				}
			}
		}
	}
	public static class VectorExtension
	{
		public static string ToFormattedString(this Vector2 vector)
		{
			//IL_0017: 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)
			return $"x: {vector.x:0.0000}, y: {vector.y:0.0000}";
		}

		public static string ToFormattedString(this Vector3 vector)
		{
			//IL_0018: Unknown result type (might be due to invalid IL or missing references)
			//IL_0036: 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)
			return $"x: {vector.x:0.0000}, y: {vector.y:0.0000} z: {vector.z:0.0000}";
		}

		public static string ToFormattedString(this Vector4 vector)
		{
			//IL_0018: Unknown result type (might be due to invalid IL or missing references)
			//IL_0036: 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_0072: Unknown result type (might be due to invalid IL or missing references)
			return $"x: {vector.x:0.0000}, y: {vector.y:0.0000} z: {vector.z:0.0000} w: {vector.w:0.0000}";
		}
	}
}
namespace FloLib.Utils.Comps
{
	[AutoInject]
	internal sealed class EmptyMB : MonoBehaviour
	{
	}
}
namespace FloLib.Networks
{
	public static class GlobalNetAction<P> where P : struct
	{
		private static string _EventName;

		private static bool _IsSetup;

		public static SNet_ChannelType SendChannel { get; set; }

		public static SNet_Player LastSender { get; private set; }

		public static ulong LastSenderID { get; private set; }

		public static event Action<ulong, P> OnReceive;

		public static event Action<ulong, P> OnReceiveLocally;

		static GlobalNetAction()
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			SendChannel = (SNet_ChannelType)2;
			_IsSetup = false;
			Setup();
		}

		public static void Setup()
		{
			if (!_IsSetup)
			{
				_EventName = UName.Get(typeof(P), "NA");
				NetworkAPI.RegisterEvent<P>(_EventName, (Action<ulong, P>)Received);
				_IsSetup = true;
			}
		}

		public static void Send(P payload)
		{
			if (!_IsSetup)
			{
				Logger.Error("Action Wasn't Setup!");
				return;
			}
			SendToLocal(payload);
			TaskQueue.AddTask(delegate
			{
				//IL_000b: Unknown result type (might be due to invalid IL or missing references)
				NetworkAPI.InvokeEvent<P>(_EventName, payload, SendChannel);
			}, "GlobalNetAction.Send");
		}

		public static void SendTo(P payload, SNet_Player target)
		{
			if (!_IsSetup)
			{
				Logger.Error("Action Wasn't Setup!");
				return;
			}
			if (target.IsLocal)
			{
				SendToLocal(payload);
				return;
			}
			TaskQueue.AddTask(delegate
			{
				//IL_000b: Unknown result type (might be due to invalid IL or missing references)
				NetworkAPI.InvokeEvent<P>(_EventName, payload, SendChannel);
			}, "GlobalNetAction.SendTo");
		}

		public static void SendTo(P payload, SNet_SendGroup group)
		{
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			if (!_IsSetup)
			{
				Logger.Error("Action Wasn't Setup!");
				return;
			}
			Enumerator<SNet_Player> enumerator = SNet_PlayerSendGroupManager.GetGroup(group).GetEnumerator();
			while (enumerator.MoveNext())
			{
				SNet_Player current = enumerator.Current;
				SendTo(payload, current);
			}
		}

		private static void SendToLocal(P payload)
		{
			if (!_IsSetup)
			{
				Logger.Error("Action Wasn't Setup!");
				return;
			}
			SNet_Player val = (LastSender = SNet.LocalPlayer);
			if ((Object)(object)val != (Object)null)
			{
				LastSenderID = val.Lookup;
			}
			GlobalNetAction<P>.OnReceive?.Invoke(LastSenderID, payload);
			GlobalNetAction<P>.OnReceiveLocally?.Invoke(LastSenderID, payload);
		}

		private static void Received(ulong sender, P payload)
		{
			if (!_IsSetup)
			{
				Logger.Error("Action Wasn't Setup!");
				return;
			}
			SNet_Player lastSender = default(SNet_Player);
			if (!SNet.Core.TryGetPlayer(sender, ref lastSender, false))
			{
				LastSender = null;
				LastSenderID = 0uL;
				Logger.Error("NetAction sender was invalid!");
			}
			LastSender = lastSender;
			LastSenderID = sender;
			GlobalNetAction<P>.OnReceive?.Invoke(sender, payload);
		}
	}
	public static class GlobalNetMasterAction<P> where P : struct
	{
		public static Func<ulong, P, bool> IsActionValid;

		private static string _AskEventName;

		private static string _EventName;

		private static bool _IsSetup;

		public static SNet_ChannelType SendChannel { get; set; }

		public static SNet_Player LastSender { get; private set; }

		public static ulong LastSenderID { get; private set; }

		public static event Action<ulong, P> OnReceive;

		public static event Action<ulong, P> OnMasterReceive;

		static GlobalNetMasterAction()
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			SendChannel = (SNet_ChannelType)2;
			IsActionValid = (ulong sender, P p) => true;
			_IsSetup = false;
			Setup();
		}

		public static void Setup()
		{
			if (!_IsSetup)
			{
				_AskEventName = UName.Get(typeof(P), "NMA0");
				_EventName = UName.Get(typeof(P), "NMA1");
				NetworkAPI.RegisterEvent<P>(_AskEventName, (Action<ulong, P>)ReceivedAsk);
				NetworkAPI.RegisterEvent<P>(_EventName, (Action<ulong, P>)Received);
				_IsSetup = true;
			}
		}

		public static void Ask(P payload)
		{
			if (!_IsSetup)
			{
				Logger.Error("Action Wasn't Setup!");
			}
			else
			{
				if (!SNet.HasMaster)
				{
					return;
				}
				if (SNet.IsMaster)
				{
					Func<ulong, P, bool> isActionValid = IsActionValid;
					if (isActionValid == null || isActionValid(SNet.LocalPlayer.Lookup, payload))
					{
						TaskQueue.AddTask(delegate
						{
							//IL_000b: Unknown result type (might be due to invalid IL or missing references)
							NetworkAPI.InvokeEvent<P>(_EventName, payload, SendChannel);
						}, "GlobalNetMasterAction.Master");
						GlobalNetMasterAction<P>.OnReceive?.Invoke(SNet.LocalPlayer.Lookup, payload);
						GlobalNetMasterAction<P>.OnMasterReceive?.Invoke(SNet.LocalPlayer.Lookup, payload);
					}
				}
				else
				{
					TaskQueue.AddTask(delegate
					{
						//IL_0010: Unknown result type (might be due to invalid IL or missing references)
						NetworkAPI.InvokeEvent<P>(_AskEventName, payload, SNet.Master, SendChannel);
					}, "GlobalNetMasterAction.Ask.Client");
				}
			}
		}

		private static void ReceivedAsk(ulong sender, P payload)
		{
			if (!_IsSetup)
			{
				Logger.Error("Action Wasn't Setup!");
				return;
			}
			if (!SNet.IsMaster)
			{
				Logger.Error("Non Master Received Ask Action!");
				return;
			}
			Func<ulong, P, bool> isActionValid = IsActionValid;
			if (isActionValid == null || isActionValid(sender, payload))
			{
				TaskQueue.AddTask(delegate
				{
					//IL_000b: Unknown result type (might be due to invalid IL or missing references)
					NetworkAPI.InvokeEvent<P>(_EventName, payload, SendChannel);
				}, "GlobalNetMasterAction.ReceivedAsk.Master");
				GlobalNetMasterAction<P>.OnReceive?.Invoke(SNet.LocalPlayer.Lookup, payload);
				GlobalNetMasterAction<P>.OnMasterReceive?.Invoke(sender, payload);
			}
		}

		private static void Received(ulong sender, P payload)
		{
			if (!_IsSetup)
			{
				Logger.Error("Action Wasn't Setup!");
				return;
			}
			SNet_Player lastSender = default(SNet_Player);
			if (!SNet.Core.TryGetPlayer(sender, ref lastSender, false))
			{
				LastSender = null;
				LastSenderID = 0uL;
				Logger.Error("NetMasterAction sender was invalid!");
				return;
			}
			LastSender = lastSender;
			LastSenderID = sender;
			if (!LastSender.IsMaster)
			{
				Logger.Error("Sender was not a master");
			}
			else
			{
				GlobalNetMasterAction<P>.OnReceive?.Invoke(sender, payload);
			}
		}
	}
	internal static class UName
	{
		private static readonly SHA1 SHA = SHA1.Create();

		public static string Get(Type type, string prefix)
		{
			return prefix + GetHash(type.FullName);
		}

		public static string GetHash(string text)
		{
			return Convert.ToBase64String(SHA.ComputeHash(Encoding.Unicode.GetBytes(text + "this is salt text, Awesome!")));
		}
	}
}
namespace FloLib.Networks.Replications
{
	public interface IStateReplicatorHolder<S> where S : struct
	{
		StateReplicator<S> Replicator { get; }

		void OnStateChange(S oldState, S state, bool isRecall);
	}
	public sealed class ReplicatorHandshake
	{
		public delegate void ClientRequestedSyncDel(SNet_Player requestedPlayer);

		public struct Packet
		{
			public uint replicatorID;

			public PacketAction action;
		}

		public enum PacketAction : byte
		{
			Created,
			Destroyed,
			SyncRequest
		}

		public sealed class Data
		{
			public bool SetupOnHost;

			public bool SetupOnClient;
		}

		private readonly Dictionary<uint, Data> _Lookup = new Dictionary<uint, Data>();

		public string EventName { get; private set; }

		public bool IsReadyToSync { get; private set; }

		public event ClientRequestedSyncDel OnClientSyncRequested;

		public static ReplicatorHandshake Create(string guid)
		{
			if (string.IsNullOrWhiteSpace(guid))
			{
				return null;
			}
			string text = "RHs" + guid;
			if (!NetworkAPI.IsEventRegistered(text))
			{
				return new ReplicatorHandshake(text);
			}
			return null;
		}

		private ReplicatorHandshake(string eventName)
		{
			EventName = eventName;
			NetworkAPI.RegisterEvent<Packet>(eventName, (Action<ulong, Packet>)OnSyncAction);
			Inject_OnRecallDone.OnRecallDone += delegate
			{
				Logger.Warn("ReplicatorHandshake: client sending sync request");
				ClientSyncRequest();
			};
		}

		private void ClientSyncRequest()
		{
			if (SNet.IsMaster)
			{
				return;
			}
			foreach (uint replicatorID in _Lookup.Keys)
			{
				TaskQueue.AddTask(delegate
				{
					NetworkAPI.InvokeEvent<Packet>(EventName, new Packet
					{
						replicatorID = replicatorID,
						action = PacketAction.SyncRequest
					}, SNet.Master, (SNet_ChannelType)2);
				}, $"SyncReplicatorID_{replicatorID}");
			}
		}

		public void Reset()
		{
			_Lookup.Clear();
		}

		private void OnSyncAction(ulong sender, Packet packet)
		{
			//IL_0090: Unknown result type (might be due to invalid IL or missing references)
			//IL_0096: Expected O, but got Unknown
			if (!SNet.IsMaster && sender == SNet.Master.Lookup)
			{
				if (packet.action == PacketAction.Created)
				{
					SetHostState(packet.replicatorID, isSetup: true);
				}
				else if (packet.action == PacketAction.Destroyed)
				{
					SetHostState(packet.replicatorID, isSetup: false);
				}
			}
			else
			{
				if (!SNet.IsMaster)
				{
					return;
				}
				if (packet.action == PacketAction.Created)
				{
					SetClientState(packet.replicatorID, isSetup: true);
				}
				else if (packet.action == PacketAction.Destroyed)
				{
					SetClientState(packet.replicatorID, isSetup: false);
				}
				else
				{
					if (packet.action != PacketAction.SyncRequest)
					{
						return;
					}
					SNet_Player requestedPlayer = default(SNet_Player);
					if (!SNet.TryGetPlayer(sender, ref requestedPlayer))
					{
						bool flag = default(bool);
						BepInExErrorLogInterpolatedStringHandler val = new BepInExErrorLogInterpolatedStringHandler(32, 1, ref flag);
						if (flag)
						{
							((BepInExLogInterpolatedStringHandler)val).AppendLiteral("Cannot find player from sender: ");
							((BepInExLogInterpolatedStringHandler)val).AppendFormatted<ulong>(sender);
						}
						Logger.Error(val);
					}
					else
					{
						this.OnClientSyncRequested?.Invoke(requestedPlayer);
					}
				}
			}
		}

		public void UpdateCreated(uint id)
		{
			if (SNet.IsInLobby)
			{
				if (SNet.IsMaster)
				{
					SetHostState(id, isSetup: true);
					TaskQueue.AddTask(delegate
					{
						NetworkAPI.InvokeEvent<Packet>(EventName, new Packet
						{
							replicatorID = id,
							action = PacketAction.Created
						}, (SNet_ChannelType)2);
					}, "UpdateCreated.Master");
				}
				else if (SNet.HasMaster)
				{
					SetClientState(id, isSetup: true);
					TaskQueue.AddTask(delegate
					{
						NetworkAPI.InvokeEvent<Packet>(EventName, new Packet
						{
							replicatorID = id,
							action = PacketAction.Created
						}, SNet.Master, (SNet_ChannelType)2);
					}, "UpdateCreated.Client");
				}
				else
				{
					Logger.Error("Handshake::MASTER is NULL in lobby; This should NOT happen!!!!!!!!!!!!");
				}
			}
			else
			{
				Logger.Error("Handshake::Session Type StateReplicator cannot be created without lobby!");
			}
		}

		public void UpdateDestroyed(uint id)
		{
			if (SNet.IsInLobby)
			{
				if (SNet.IsMaster)
				{
					SetHostState(id, isSetup: true);
					TaskQueue.AddTask(delegate
					{
						NetworkAPI.InvokeEvent<Packet>(EventName, new Packet
						{
							replicatorID = id,
							action = PacketAction.Destroyed
						}, (SNet_ChannelType)2);
					}, "UpdateDestroyed.Master");
				}
				else if (SNet.HasMaster)
				{
					SetClientState(id, isSetup: true);
					TaskQueue.AddTask(delegate
					{
						NetworkAPI.InvokeEvent<Packet>(EventName, new Packet
						{
							replicatorID = id,
							action = PacketAction.Destroyed
						}, SNet.Master, (SNet_ChannelType)2);
					}, "UpdateDestroyed.Client");
				}
				else
				{
					Logger.Error("Handshake::MASTER is NULL in lobby; This should NOT happen!!!!!!!!!!!!");
				}
			}
			else
			{
				Logger.Error("Handshake::Session Type StateReplicator cannot be created without lobby!");
			}
		}

		private void SetHostState(uint id, bool isSetup)
		{
			if (_Lookup.TryGetValue(id, out var value))
			{
				value.SetupOnHost = isSetup;
			}
			else
			{
				_Lookup[id] = new Data
				{
					SetupOnHost = isSetup
				};
			}
			UpdateSyncState(id);
		}

		private void SetClientState(uint id, bool isSetup)
		{
			if (_Lookup.TryGetValue(id, out var value))
			{
				value.SetupOnClient = isSetup;
			}
			else
			{
				_Lookup[id] = new Data
				{
					SetupOnClient = isSetup
				};
			}
			UpdateSyncState(id);
		}

		private void UpdateSyncState(uint id)
		{
			bool isReadyToSync = IsReadyToSync;
			if (_Lookup.TryGetValue(id, out var value))
			{
				IsReadyToSync = value.SetupOnHost && value.SetupOnClient;
			}
			else
			{
				IsReadyToSync = false;
			}
			if (IsReadyToSync && isReadyToSync != IsReadyToSync && SNet.HasMaster && !SNet.IsMaster)
			{
				TaskQueue.AddTask(delegate
				{
					NetworkAPI.InvokeEvent<Packet>(EventName, new Packet
					{
						replicatorID = id,
						action = PacketAction.SyncRequest
					}, SNet.Master, (SNet_ChannelType)2);
				}, "Client.UpdateSyncState.SyncRequest");
			}
		}
	}
	public delegate void OnReceiveDel<S>(ulong sender, uint replicatorID, S newState) where S : struct;
	public static class StatePayloads
	{
		public enum Size
		{
			State4Byte = 4,
			State8Byte = 8,
			State16Byte = 16,
			State32Byte = 32,
			State48Byte = 48,
			State64Byte = 64,
			State80Byte = 80,
			State96Byte = 96,
			State128Byte = 128,
			State196Byte = 196,
			State256Byte = 256
		}

		public static Size GetSizeType(int size)
		{
			Size size2 = Size.State8Byte;
			foreach (object value in Enum.GetValues(typeof(Size)))
			{
				if (size <= (int)value && (int)size2 < (int)value)
				{
					size2 = (Size)value;
					break;
				}
			}
			return size2;
		}

		public static IReplicatorEvent<S> CreateEvent<S>(Size size, string eventName, OnReceiveDel<S> onReceiveCallback) where S : struct
		{
			return size switch
			{
				Size.State4Byte => ReplicatorPayloadWrapper<S, StatePayload4Byte>.Create(eventName, onReceiveCallback), 
				Size.State8Byte => ReplicatorPayloadWrapper<S, StatePayload8Byte>.Create(eventName, onReceiveCallback), 
				Size.State16Byte => ReplicatorPayloadWrapper<S, StatePayload16Byte>.Create(eventName, onReceiveCallback), 
				Size.State32Byte => ReplicatorPayloadWrapper<S, StatePayload32Byte>.Create(eventName, onReceiveCallback), 
				Size.State48Byte => ReplicatorPayloadWrapper<S, StatePayload48Byte>.Create(eventName, onReceiveCallback), 
				Size.State64Byte => ReplicatorPayloadWrapper<S, StatePayload64Byte>.Create(eventName, onReceiveCallback), 
				Size.State80Byte => ReplicatorPayloadWrapper<S, StatePayload80Byte>.Create(eventName, onReceiveCallback), 
				Size.State96Byte => ReplicatorPayloadWrapper<S, StatePayload96Byte>.Create(eventName, onReceiveCallback), 
				Size.State128Byte => ReplicatorPayloadWrapper<S, StatePayload128Byte>.Create(eventName, onReceiveCallback), 
				Size.State196Byte => ReplicatorPayloadWrapper<S, StatePayload196Byte>.Create(eventName, onReceiveCallback), 
				Size.State256Byte => ReplicatorPayloadWrapper<S, StatePayload256Byte>.Create(eventName, onReceiveCallback), 
				_ => null, 
			};
		}

		public static S Get<S>(byte[] bytes, int bytesLength) where S : struct
		{
			int num = Marshal.SizeOf(typeof(S));
			if (num > bytesLength)
			{
				throw new ArgumentException($"StateData Exceed size of {bytesLength} : Unable to Deserialize", "S");
			}
			IntPtr intPtr = Marshal.AllocHGlobal(num);
			Marshal.Copy(bytes, 0, intPtr, num);
			S result = (S)Marshal.PtrToStructure(intPtr, typeof(S));
			Marshal.FreeHGlobal(intPtr);
			return result;
		}

		public static void Set<S>(S stateData, int size, ref byte[] payloadBytes) where S : struct
		{
			if (Marshal.SizeOf(stateData) > size)
			{
				throw new ArgumentException($"StateData Exceed size of {size} : Unable to Serialize", "S");
			}
			byte[] array = new byte[size];
			IntPtr intPtr = Marshal.AllocHGlobal(size);
			Marshal.StructureToPtr(stateData, intPtr, fDeleteOld: false);
			Marshal.Copy(intPtr, array, 0, size);
			Marshal.FreeHGlobal(intPtr);
			payloadBytes = array;
		}
	}
	public interface IReplicatorEvent<S> where S : struct
	{
		string Name { get; }

		bool IsRegistered { get; }

		void Invoke(uint replicatorID, S data);

		void Invoke(uint replicatorID, S data, SNet_ChannelType channelType);

		void Invoke(uint replicatorID, S data, SNet_Player target);

		void Invoke(uint replicatorID, S data, SNet_Player target, SNet_ChannelType channelType);
	}
	public class ReplicatorPayloadWrapper<S, P> : IReplicatorEvent<S> where S : struct where P : struct, IStatePayload
	{
		public string Name { get; private set; }

		public bool IsRegistered { get; private set; }

		public static IReplicatorEvent<S> Create(string eventName, OnReceiveDel<S> onReceiveCallback)
		{
			ReplicatorPayloadWrapper<S, P> replicatorPayloadWrapper = new ReplicatorPayloadWrapper<S, P>();
			replicatorPayloadWrapper.Register(eventName, onReceiveCallback);
			if (!replicatorPayloadWrapper.IsRegistered)
			{
				return null;
			}
			return replicatorPayloadWrapper;
		}

		public void Register(string eventName, OnReceiveDel<S> onReceiveCallback)
		{
			if (!IsRegistered && !NetworkAPI.IsEventRegistered(eventName))
			{
				NetworkAPI.RegisterEvent<P>(eventName, (Action<ulong, P>)delegate(ulong sender, P payload)
				{
					onReceiveCallback?.Invoke(sender, payload.ID, payload.Get<S>());
				});
				IsRegistered = true;
				Name = eventName;
			}
		}

		public void Invoke(uint replicatorID, S data)
		{
			P payload = new P
			{
				ID = replicatorID
			};
			payload.Set(data);
			TaskQueue.AddTask(delegate
			{
				NetworkAPI.InvokeEvent<P>(Name, payload, (SNet_ChannelType)2);
			}, "ReplicatorPayloadWrapper.Invoke(uint, S)");
		}

		public void Invoke(uint replicatorID, S data, SNet_ChannelType channelType)
		{
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			P payload = new P
			{
				ID = replicatorID
			};
			payload.Set(data);
			TaskQueue.AddTask(delegate
			{
				//IL_0012: Unknown result type (might be due to invalid IL or missing references)
				NetworkAPI.InvokeEvent<P>(Name, payload, channelType);
			}, "ReplicatorPayloadWrapper.Invoke(uint, S, SNet_ChannelType)");
		}

		public void Invoke(uint replicatorID, S data, SNet_Player target)
		{
			P payload = new P
			{
				ID = replicatorID
			};
			payload.Set(data);
			TaskQueue.AddTask(delegate
			{
				NetworkAPI.InvokeEvent<P>(Name, payload, target, (SNet_ChannelType)2);
			}, "ReplicatorPayloadWrapper.Invoke(uint, S, SNet_Player)");
		}

		public void Invoke(uint replicatorID, S data, SNet_Player target, SNet_ChannelType channelType)
		{
			//IL_0014: 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)
			P payload = new P
			{
				ID = replicatorID
			};
			payload.Set(data);
			TaskQueue.AddTask(delegate
			{
				//IL_0018: Unknown result type (might be due to invalid IL or missing references)
				NetworkAPI.InvokeEvent<P>(Name, payload, target, channelType);
			}, "ReplicatorPayloadWrapper.Invoke(uint, S, SNet_Player, SNet_ChannelType)");
		}
	}
	public interface IStatePayload
	{
		uint ID { get; set; }

		S Get<S>() where S : struct;

		void Set<S>(S stateData) where S : struct;
	}
	public struct StatePayload4Byte : IStatePayload
	{
		public const int Size = 4;

		private uint id;

		[MarshalAs(UnmanagedType.ByValArray, SizeConst = 4)]
		public byte[] PayloadBytes;

		public uint ID
		{
			get
			{
				return id;
			}
			set
			{
				id = value;
			}
		}

		public S Get<S>() where S : struct
		{
			return StatePayloads.Get<S>(PayloadBytes, 4);
		}

		public void Set<S>(S stateData) where S : struct
		{
			StatePayloads.Set(stateData, 4, ref PayloadBytes);
		}
	}
	public struct StatePayload8Byte : IStatePayload
	{
		public const int Size = 8;

		[MarshalAs(UnmanagedType.ByValArray, SizeConst = 8)]
		public byte[] PayloadBytes;

		[field: MarshalAs(UnmanagedType.U4)]
		public uint ID { get; set; }

		public S Get<S>() where S : struct
		{
			return StatePayloads.Get<S>(PayloadBytes, 8);
		}

		public void Set<S>(S stateData) where S : struct
		{
			StatePayloads.Set(stateData, 8, ref PayloadBytes);
		}
	}
	public struct StatePayload16Byte : IStatePayload
	{
		public const int Size = 16;

		[MarshalAs(UnmanagedType.ByValArray, SizeConst = 16)]
		public byte[] PayloadBytes;

		[field: MarshalAs(UnmanagedType.U4)]
		public uint ID { get; set; }

		public S Get<S>() where S : struct
		{
			return StatePayloads.Get<S>(PayloadBytes, 16);
		}

		public void Set<S>(S stateData) where S : struct
		{
			StatePayloads.Set(stateData, 16, ref PayloadBytes);
		}
	}
	public struct StatePayload32Byte : IStatePayload
	{
		public const int Size = 32;

		[MarshalAs(UnmanagedType.ByValArray, SizeConst = 32)]
		public byte[] PayloadBytes;

		[field: MarshalAs(UnmanagedType.U4)]
		public uint ID { get; set; }

		public S Get<S>() where S : struct
		{
			return StatePayloads.Get<S>(PayloadBytes, 32);
		}

		public void Set<S>(S stateData) where S : struct
		{
			StatePayloads.Set(stateData, 32, ref PayloadBytes);
		}
	}
	public struct StatePayload48Byte : IStatePayload
	{
		public const int Size = 48;

		[MarshalAs(UnmanagedType.ByValArray, SizeConst = 48)]
		public byte[] PayloadBytes;

		[field: MarshalAs(UnmanagedType.U4)]
		public uint ID { get; set; }

		public S Get<S>() where S : struct
		{
			return StatePayloads.Get<S>(PayloadBytes, 48);
		}

		public void Set<S>(S stateData) where S : struct
		{
			StatePayloads.Set(stateData, 48, ref PayloadBytes);
		}
	}
	public struct StatePayload64Byte : IStatePayload
	{
		public const int Size = 64;

		[MarshalAs(UnmanagedType.ByValArray, SizeConst = 64)]
		public byte[] PayloadBytes;

		[field: MarshalAs(UnmanagedType.U4)]
		public uint ID { get; set; }

		public S Get<S>() where S : struct
		{
			return StatePayloads.Get<S>(PayloadBytes, 64);
		}

		public void Set<S>(S stateData) where S : struct
		{
			StatePayloads.Set(stateData, 64, ref PayloadBytes);
		}
	}
	public struct StatePayload80Byte : IStatePayload
	{
		public const int Size = 80;

		[MarshalAs(UnmanagedType.ByValArray, SizeConst = 80)]
		public byte[] PayloadBytes;

		[field: MarshalAs(UnmanagedType.U4)]
		public uint ID { get; set; }

		public S Get<S>() where S : struct
		{
			return StatePayloads.Get<S>(PayloadBytes, 80);
		}

		public void Set<S>(S stateData) where S : struct
		{
			StatePayloads.Set(stateData, 80, ref PayloadBytes);
		}
	}
	public struct StatePayload96Byte : IStatePayload
	{
		public const int Size = 96;

		[MarshalAs(UnmanagedType.ByValArray, SizeConst = 96)]
		public byte[] PayloadBytes;

		[field: MarshalAs(UnmanagedType.U4)]
		public uint ID { get; set; }

		public S Get<S>() where S : struct
		{
			return StatePayloads.Get<S>(PayloadBytes, 96);
		}

		public void Set<S>(S stateData) where S : struct
		{
			StatePayloads.Set(stateData, 96, ref PayloadBytes);
		}
	}
	public struct StatePayload128Byte : IStatePayload
	{
		public const int Size = 128;

		[MarshalAs(UnmanagedType.ByValArray, SizeConst = 128)]
		public byte[] PayloadBytes;

		[field: MarshalAs(UnmanagedType.U4)]
		public uint ID { get; set; }

		public S Get<S>() where S : struct
		{
			return StatePayloads.Get<S>(PayloadBytes, 128);
		}

		public void Set<S>(S stateData) where S : struct
		{
			StatePayloads.Set(stateData, 128, ref PayloadBytes);
		}
	}
	public struct StatePayload196Byte : IStatePayload
	{
		public const int Size = 196;

		[MarshalAs(UnmanagedType.ByValArray, SizeConst = 196)]
		public byte[] PayloadBytes;

		[field: MarshalAs(UnmanagedType.U4)]
		public uint ID { get; set; }

		public S Get<S>() where S : struct
		{
			return StatePayloads.Get<S>(PayloadBytes, 196);
		}

		public void Set<S>(S stateData) where S : struct
		{
			StatePayloads.Set(stateData, 196, ref PayloadBytes);
		}
	}
	public struct StatePayload256Byte : IStatePayload
	{
		public const int Size = 256;

		[MarshalAs(UnmanagedType.ByValArray, SizeConst = 256)]
		public byte[] PayloadBytes;

		[field: MarshalAs(UnmanagedType.U4)]
		public uint ID { get; set; }

		public S Get<S>() where S : struct
		{
			return StatePayloads.Get<S>(PayloadBytes, 256);
		}

		public void Set<S>(S stateData) where S : struct
		{
			StatePayloads.Set(stateData, 256, ref PayloadBytes);
		}
	}
	public enum LifeTimeType
	{
		Forever,
		Level
	}
	public sealed class StateReplicator<S> where S : struct
	{
		private readonly Dictionary<eBufferType, S> _RecallStateSnapshots = new Dictionary<eBufferType, S>();

		public static readonly string Name;

		public static readonly string HashName;

		public static readonly string ClientRequestEventName;

		public static readonly string HostSetStateEventName;

		public static readonly string HostSetRecallStateEventName;

		public static readonly int StateSize;

		public static readonly StatePayloads.Size StateSizeType;

		private static readonly IReplicatorEvent<S> _C_RequestEvent;

		private static readonly IReplicatorEvent<S> _H_SetStateEvent;

		private static readonly IReplicatorEvent<S> _H_SetRecallStateEvent;

		private static readonly ReplicatorHandshake _Handshake;

		private static readonly Dictionary<uint, StateReplicator<S>> _Replicators;

		public bool IsValid => ID != 0;

		public bool IsInvalid => ID == 0;

		public uint ID { get; private set; }

		public LifeTimeType LifeTime { get; private set; }

		public IStateReplicatorHolder<S> Holder { get; private set; }

		public S State { get; private set; }

		public bool ClientSendStateAllowed { get; set; } = true;


		public bool CanSendToClient
		{
			get
			{
				if (SNet.IsInLobby)
				{
					return SNet.IsMaster;
				}
				return false;
			}
		}

		public bool CanSendToHost
		{
			get
			{
				if (SNet.IsInLobby && !SNet.IsMaster && SNet.HasMaster)
				{
					return ClientSendStateAllowed;
				}
				return false;
			}
		}

		public bool IsHandshakeSetup { get; private set; }

		public event Action<S, S, bool> OnStateChanged;

		public void SetupHandshake()
		{
			if (!IsInvalid && !IsHandshakeSetup)
			{
				_Handshake.UpdateCreated(ID);
				IsHandshakeSetup = true;
			}
		}

		public void SetState(S state)
		{
			if (!IsInvalid)
			{
				DoSync(state);
			}
		}

		public void SetStateUnsynced(S state)
		{
			if (!IsInvalid)
			{
				State = state;
			}
		}

		public void Unload()
		{
			if (IsValid)
			{
				_Replicators.Remove(ID);
				_RecallStateSnapshots.Clear();
				_Handshake.UpdateDestroyed(ID);
				IsHandshakeSetup = false;
				ID = 0u;
			}
		}

		private void DoSync(S newState)
		{
			if (!IsInvalid)
			{
				if (CanSendToClient)
				{
					_H_SetStateEvent.Invoke(ID, newState);
					Internal_ChangeState(newState, isRecall: false);
				}
				else if (CanSendToHost)
				{
					_C_RequestEvent.Invoke(ID, newState, SNet.Master);
				}
			}
		}

		private void Internal_ChangeState(S state, bool isRecall)
		{
			if (!IsInvalid)
			{
				S state2 = State;
				State = state;
				this.OnStateChanged?.Invoke(state2, state, isRecall);
				Holder?.OnStateChange(state2, state, isRecall);
			}
		}

		private void SendDropInState(SNet_Player target)
		{
			if (!IsInvalid)
			{
				if ((Object)(object)target == (Object)null)
				{
					Logger.Error("SendDropInState::Target was null??");
				}
				else
				{
					_H_SetRecallStateEvent.Invoke(ID, State, target);
				}
			}
		}

		public void ClearAllRecallSnapshot()
		{
			if (!IsInvalid)
			{
				_RecallStateSnapshots.Clear();
			}
		}

		private void SaveSnapshot(eBufferType type)
		{
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			if (!IsInvalid)
			{
				_RecallStateSnapshots[type] = State;
			}
		}

		private void RestoreSnapshot(eBufferType type)
		{
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			//IL_0040: Unknown result type (might be due to invalid IL or missing references)
			//IL_0046: Expected O, but got Unknown
			//IL_0060: Unknown result type (might be due to invalid IL or missing references)
			if (IsInvalid || !CanSendToClient)
			{
				return;
			}
			if (_RecallStateSnapshots.TryGetValue(type, out var value))
			{
				_H_SetRecallStateEvent.Invoke(ID, value);
				Internal_ChangeState(value, isRecall: true);
				return;
			}
			bool flag = default(bool);
			BepInExErrorLogInterpolatedStringHandler val = new BepInExErrorLogInterpolatedStringHandler(29, 2, ref flag);
			if (flag)
			{
				((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>("RestoreSnapshot");
				((BepInExLogInterpolatedStringHandler)val).AppendLiteral("::There was no snapshot for ");
				((BepInExLogInterpolatedStringHandler)val).AppendFormatted<eBufferType>(type);
				((BepInExLogInterpolatedStringHandler)val).AppendLiteral("?");
			}
			Logger.Error(val);
		}

		static StateReplicator()
		{
			_Replicators = new Dictionary<uint, StateReplicator<S>>();
			Name = typeof(S).Name;
			StateSize = Marshal.SizeOf(typeof(S));
			StateSizeType = StatePayloads.GetSizeType(StateSize);
			using (MD5.Create())
			{
				HashName = UName.GetHash(typeof(S).FullName);
				ClientRequestEventName = "SRs" + Name + "-" + HashName;
				HostSetStateEventName = "SRr" + Name + "-" + HashName;
				HostSetRecallStateEventName = "SRre" + Name + "-" + HashName;
				_C_RequestEvent = StatePayloads.CreateEvent<S>(StateSizeType, ClientRequestEventName, ClientRequestEventCallback);
				_H_SetStateEvent = StatePayloads.CreateEvent<S>(StateSizeType, HostSetStateEventName, HostSetStateEventCallback);
				_H_SetRecallStateEvent = StatePayloads.CreateEvent<S>(StateSizeType, HostSetRecallStateEventName, HostSetRecallStateEventCallback);
				_Handshake = ReplicatorHandshake.Create(Name + "-" + HashName);
				_Handshake.OnClientSyncRequested += ClientSyncRequested;
				Inject_SNet_Capture.OnBufferCapture += BufferStored;
				Inject_SNet_Capture.OnBufferRecalled += BufferRecalled;
				Inject_Builder.BeforeBuildStart += LevelCleanedUp;
				LevelAPI.OnLevelCleanup += LevelCleanedUp;
			}
		}

		public static void Setup()
		{
		}

		private static void ClientSyncRequested(SNet_Player requestedPlayer)
		{
			foreach (StateReplicator<S> value in _Replicators.Values)
			{
				if (value.IsValid)
				{
					value.SendDropInState(requestedPlayer);
				}
			}
		}

		private static void BufferStored(eBufferType type)
		{
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			foreach (StateReplicator<S> value in _Replicators.Values)
			{
				if (value.IsValid)
				{
					value.SaveSnapshot(type);
				}
			}
		}

		private static void BufferRecalled(eBufferType type)
		{
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			foreach (StateReplicator<S> value in _Replicators.Values)
			{
				if (value.IsValid)
				{
					value.RestoreSnapshot(type);
				}
			}
		}

		private static void LevelCleanedUp()
		{
			UnloadSessionReplicator();
		}

		private StateReplicator()
		{
		}

		public static StateReplicator<S> Create(uint replicatorID, S startState, LifeTimeType lifeTime, IStateReplicatorHolder<S> owner = null)
		{
			//IL_0067: Unknown result type (might be due to invalid IL or missing references)
			//IL_006d: Expected O, but got Unknown
			if (replicatorID == 0)
			{
				Logger.Error("Replicator ID 0 is reserved for empty!");
				return null;
			}
			if (_Replicators.ContainsKey(replicatorID))
			{
				Logger.Error("Replicator ID has already assigned!");
				return null;
			}
			StateReplicator<S> stateReplicator = new StateReplicator<S>
			{
				ID = replicatorID,
				LifeTime = lifeTime,
				Holder = owner,
				State = startState
			};
			switch (lifeTime)
			{
			case LifeTimeType.Forever:
				stateReplicator.IsHandshakeSetup = true;
				break;
			case LifeTimeType.Level:
				stateReplicator.SetupHandshake();
				break;
			default:
			{
				bool flag = default(bool);
				BepInExErrorLogInterpolatedStringHandler val = new BepInExErrorLogInterpolatedStringHandler(22, 1, ref flag);
				if (flag)
				{
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral("LifeTime is invalid!: ");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<LifeTimeType>(lifeTime);
				}
				Logger.Error(val);
				return null;
			}
			}
			_Replicators[replicatorID] = stateReplicator;
			return stateReplicator;
		}

		public static void UnloadSessionReplicator()
		{
			List<uint> list = new List<uint>();
			foreach (StateReplicator<S> value in _Replicators.Values)
			{
				if (value.LifeTime == LifeTimeType.Level)
				{
					list.Add(value.ID);
					value.Unload();
				}
			}
			foreach (uint item in list)
			{
				_Replicators.Remove(item);
			}
			_Handshake.Reset();
		}

		private static void ClientRequestEventCallback(ulong sender, uint replicatorID, S newState)
		{
			if (SNet.IsMaster && _Replicators.TryGetValue(replicatorID, out var value))
			{
				value.SetState(newState);
			}
		}

		private static void HostSetStateEventCallback(ulong sender, uint replicatorID, S newState)
		{
			if (SNet.HasMaster && SNet.Master.Lookup == sender && _Replicators.TryGetValue(replicatorID, out var value))
			{
				value.Internal_ChangeState(newState, isRecall: false);
			}
		}

		private static void HostSetRecallStateEventCallback(ulong sender, uint replicatorID, S newState)
		{
			if (SNet.HasMaster && SNet.Master.Lookup == sender && _Replicators.TryGetValue(replicatorID, out var value))
			{
				value.Internal_ChangeState(newState, isRecall: true);
			}
		}
	}
}
namespace FloLib.Networks.PayloadStructs
{
	public struct PL_Agent
	{
		public ushort AgentID;

		public PL_Agent()
		{
			AgentID = 0;
		}

		public PL_Agent(Agent agent)
		{
			AgentID = agent.GlobalID;
		}

		public void Set(Agent agent)
		{
			AgentID = agent.GlobalID;
		}

		public bool TryGet(out Agent agent)
		{
			IReplicator val = default(IReplicator);
			if (!SNet_Replication.TryGetReplicator(AgentID, ref val))
			{
				agent = null;
				return false;
			}
			if (val == null)
			{
				agent = null;
				return false;
			}
			if (val.ReplicatorSupplier == null)
			{
				agent = null;
				return false;
			}
			MonoBehaviour val2 = ((Il2CppObjectBase)val.ReplicatorSupplier).TryCast<MonoBehaviour>();
			if ((Object)(object)val2 == (Object)null)
			{
				agent = null;
				return false;
			}
			agent = ((Component)val2).GetComponent<Agent>();
			return (Object)(object)agent != (Object)null;
		}
	}
}
namespace FloLib.Networks.Inject
{
	[HarmonyPatch]
	internal class Inject_OnRecallDone
	{
		public static event Action OnRecallDone;

		[HarmonyPostfix]
		[HarmonyPatch(typeof(SNet_SyncManager), "OnRecallDone")]
		private static void Post_OnRecallDone(SNet_SyncManager __instance)
		{
			Inject_OnRecallDone.OnRecallDone?.Invoke();
		}
	}
	[HarmonyPatch(typeof(SNet_Capture))]
	internal static class Inject_SNet_Capture
	{
		public static event Action<eBufferType> OnBufferCapture;

		public static event Action<eBufferType> OnBufferRecalled;

		[HarmonyPatch("TriggerCapture")]
		[HarmonyPrefix]
		private static void Pre_TriggerCapture(SNet_Capture __instance)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			eBufferType primedBufferType = __instance.PrimedBufferType;
			Inject_SNet_Capture.OnBufferCapture?.Invoke(primedBufferType);
		}

		[HarmonyPatch("RecallBuffer")]
		[HarmonyPostfix]
		[HarmonyWrapSafe]
		private static void Post_RecallBuffer(SNet_Capture __instance, eBufferType bufferType)
		{
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			if (!__instance.IsRecalling)
			{
				Inject_SNet_Capture.OnBufferRecalled?.Invoke(bufferType);
			}
		}
	}
}
namespace FloLib.Infos
{
	public sealed class ComponentList<T> : IEnumerable<T>, IEnumerable where T : Component
	{
		private readonly List<T> _InternalList = new List<T>();

		private T[] _ArrayCache = Array.Empty<T>();

		public T[] Items => _ArrayCache;

		internal void Add(T itemToAdd)
		{
			int id = ((Object)(object)itemToAdd).GetInstanceID();
			if (!_InternalList.Any((T t) => ((Object)(object)t).GetInstanceID() == id))
			{
				_InternalList.Add(itemToAdd);
				_ArrayCache = _InternalList.ToArray();
			}
		}

		internal void AddRange(IEnumerable<T> itemsToAdd)
		{
			foreach (T item in itemsToAdd)
			{
				Add(item);
			}
		}

		internal void Remove(T itemToRemove)
		{
			int id = ((Object)(object)itemToRemove).GetInstanceID();
			int num = _InternalList.FindIndex((T i) => ((Object)(object)i).GetInstanceID() == id);
			if (num > -1)
			{
				_InternalList.RemoveAt(num);
				_ArrayCache = _InternalList.ToArray();
			}
		}

		internal void Clear()
		{
			_InternalList.Clear();
			_ArrayCache = Array.Empty<T>();
		}

		public IEnumerator<T> GetEnumerator()
		{
			return _InternalList.GetEnumerator();
		}

		IEnumerator IEnumerable.GetEnumerator()
		{
			return _InternalList.GetEnumerator();
		}
	}
	public static class LG_LightInfo
	{
		public struct Data
		{
			public float PrefabIntensity;

			public LightMode SpawnedMode;

			public float SpawnedIntensity;

			public Color SpawnedColor;
		}

		public static bool TryGetLightData(LG_Light light, out Data data)
		{
			if ((Object)(object)light == (Object)null)
			{
				data = default(Data);
				return false;
			}
			if (!((Component)(object)light).TryGetComp<LightData>(out var component))
			{
				data = default(Data);
				return false;
			}
			data = component.CreateData();
			return true;
		}

		public static void RevertToSpawnedState(LG_Light light)
		{
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			if (!((Object)(object)light == (Object)null) && ((Component)(object)light).TryGetComp<LightData>(out var component))
			{
				light.ChangeColor(component.SpawnedColor);
				light.ChangeIntensity(component.SpawnedIntensity);
			}
		}
	}
	public enum LightMode
	{
		Off,
		On,
		Broken_Flickering
	}
	public static class LG_Objects
	{
		public static ComponentList<LG_SecurityDoor> SecurityDoors { get; private set; } = new ComponentList<LG_SecurityDoor>();


		public static ComponentList<LG_WeakDoor> WeakDoors { get; private set; } = new ComponentList<LG_WeakDoor>();


		public static ComponentList<LG_Light> Lights { get; private set; } = new ComponentList<LG_Light>();


		public static ComponentList<LG_ComputerTerminal> Terminals { get; private set; } = new ComponentList<LG_ComputerTerminal>();


		public static ComponentList<LG_LabDisplay> LabDisplays { get; private set; } = new ComponentList<LG_LabDisplay>();


		public static ComponentList<LG_DoorButton> DoorButtons { get; private set; } = new ComponentList<LG_DoorButton>();


		public static ComponentList<LG_WeakLock> WeakLocks { get; private set; } = new ComponentList<LG_WeakLock>();


		public static ComponentList<LG_HSUActivator_Core> HSUActivators { get; private set; } = new ComponentList<LG_HSUActivator_Core>();


		public static ComponentList<CarryItemPickup_Core> CarryItems { get; private set; } = new ComponentList<CarryItemPickup_Core>();


		public static ComponentList<GenericSmallPickupItem_Core> PickupItems { get; private set; } = new ComponentList<GenericSmallPickupItem_Core>();


		public static ComponentList<LG_Ladder> Ladders { get; private set; } = new ComponentList<LG_Ladder>();


		public static ComponentList<LG_WardenObjective_Reactor> Reactors { get; private set; } = new ComponentList<LG_WardenObjective_Reactor>();


		public static ComponentList<LG_PowerGeneratorCluster> GeneratorClusters { get; private set; } = new ComponentList<LG_PowerGeneratorCluster>();


		public static ComponentList<LG_PowerGenerator_Core> Generators { get; private set; } = new ComponentList<LG_PowerGenerator_Core>();


		[AutoInvoke(InvokeWhen.PluginLoaded)]
		internal static void Init()
		{
			LevelAPI.OnLevelCleanup += OnLevelCleanup;
		}

		private static void OnLevelCleanup()
		{
			SecurityDoors.Clear();
			WeakDoors.Clear();
			Lights.Clear();
			Terminals.Clear();
			LabDisplays.Clear();
			DoorButtons.Clear();
			WeakLocks.Clear();
			HSUActivators.Clear();
			CarryItems.Clear();
			PickupItems.Clear();
			Ladders.Clear();
			Reactors.Clear();
			GeneratorClusters.Clear();
			Generators.Clear();
		}

		public static O FindObjectInLevel<O>(bool includeInactive = false) where O : Object
		{
			return ((Component)Builder.CurrentFloor).GetComponentInChildren<O>(includeInactive);
		}

		public static IEnumerable<O> FindObjectsInLevel<O>(bool includeInactive = false) where O : Object
		{
			return (IEnumerable<O>)((Component)Builder.CurrentFloor).GetComponentsInChildren<O>(includeInactive);
		}

		public static LG_SecurityDoor FindSecurityDoor(LG_LayerType layer, eLocalZoneIndex localindex)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			return FindSecurityDoor((eDimensionIndex)0, layer, localindex);
		}

		public static LG_SecurityDoor FindSecurityDoor(eDimensionIndex dim, LG_LayerType layer, eLocalZoneIndex localindex)
		{
			//IL_0005: 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_0007: Unknown result type (might be due to invalid IL or missing references)
			LG_Zone val = default(LG_Zone);
			Builder.CurrentFloor.TryGetZoneByLocalIndex(dim, layer, localindex, ref val);
			if ((Object)(object)val == (Object)null)
			{
				return null;
			}
			if ((Object)(object)val.m_sourceGate == (Object)null)
			{
				return null;
			}
			if (val.m_sourceGate.SpawnedDoor == null)
			{
				return null;
			}
			return ((Il2CppObjectBase)val.m_sourceGate.SpawnedDoor).TryCast<LG_SecurityDoor>();
		}
	}
	public static class LocalPlayer
	{
		private static int? _InstanceID;

		public static bool HasAgent { get; private set; }

		public static PlayerAgent Agent { get; private set; }

		public static LocalPlayerAgent LocalAgent { get; private set; }

		public static bool TryGetAgent(out PlayerAgent agent)
		{
			agent = Agent;
			return HasAgent;
		}

		public static bool TryGetLocalAgent(out LocalPlayerAgent agent)
		{
			agent = LocalAgent;
			return HasAgent;
		}

		public static Vector3 GetPosition()
		{
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			if (HasAgent)
			{
				return ((Agent)Agent).Position;
			}
			return Vector3.zero;
		}

		public static Vector3 GetPosition(Vector3 fallback)
		{
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			if (HasAgent)
			{
				return ((Agent)Agent).Position;
			}
			return fallback;
		}

		public static Vector3 GetEyePosition()
		{
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			if (HasAgent)
			{
				return ((Agent)Agent).EyePosition;
			}
			return Vector3.zero;
		}

		public static Vector3 GetEyePosition(Vector3 fallback)
		{
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			if (HasAgent)
			{
				return ((Agent)Agent).EyePosition;
			}
			return fallback;
		}

		[AutoInvoke(InvokeWhen.StartupAssetLoaded)]
		internal static void Init()
		{
			Coroutines.Start(UpdatePlayerInfo());
		}

		private static IEnumerator UpdatePlayerInfo()
		{
			while (true)
			{
				if (PlayerManager.HasLocalPlayerAgent())
				{
					PlayerAgent localPlayerAgent = PlayerManager.GetLocalPlayerAgent();
					int instanceID = ((Object)localPlayerAgent).GetInstanceID();
					if (!_InstanceID.HasValue || _InstanceID.Value != instanceID)
					{
						Agent = localPlayerAgent;
						LocalAgent = ((Il2CppObjectBase)localPlayerAgent).Cast<LocalPlayerAgent>();
						_InstanceID = ((Object)localPlayerAgent).GetInstanceID();
						HasAgent = true;
					}
				}
				else
				{
					Agent = null;
					LocalAgent = null;
					_InstanceID = null;
					HasAgent = false;
				}
				yield return null;
			}
		}
	}
}
namespace FloLib.Infos.Inject
{
	[HarmonyPatch]
	internal static class Inject_Builder
	{
		internal static event Action BeforeBuildStart;

		[HarmonyPostfix]
		[HarmonyPatch(typeof(Builder), "BuildDone")]
		[HarmonyPriority(800)]
		private static void Post_BuildDone()
		{
			LG_Objects.Terminals.AddRange(Find<LG_ComputerTerminal>());
			LG_Objects.LabDisplays.AddRange(Find<LG_LabDisplay>());
			LG_Objects.DoorButtons.AddRange(Find<LG_DoorButton>());
			LG_Objects.WeakLocks.AddRange(Find<LG_WeakLock>());
			LG_Objects.HSUActivators.AddRange(Find<LG_HSUActivator_Core>());
			LG_Objects.CarryItems.AddRange(Find<CarryItemPickup_Core>());
			LG_Objects.PickupItems.AddRange(Find<GenericSmallPickupItem_Core>());
			LG_Objects.Ladders.AddRange(Find<LG_Ladder>());
			LG_Objects.Reactors.AddRange(Find<LG_WardenObjective_Reactor>());
			LG_Objects.GeneratorClusters.AddRange(Find<LG_PowerGeneratorCluster>());
			LG_Objects.Generators.AddRange(Find<LG_PowerGenerator_Core>());
		}

		[HarmonyPrefix]
		[HarmonyPatch(typeof(Builder), "Build")]
		private static void Pre_Build()
		{
			Inject_Builder.BeforeBuildStart?.Invoke();
		}

		private static IEnumerable<T> Find<T>() where T : Object
		{
			return LG_Objects.FindObjectsInLevel<T>();
		}
	}
	[HarmonyPatch(typeof(LG_BuildZoneLightsJob), "Build")]
	internal static class Inject_LG_LightBuild
	{
		[HarmonyPriority(0)]
		private static void Prefix(LG_BuildZoneLightsJob __instance, out List<LG_Light> __state)
		{
			__state = new List<LG_Light>();
			Enumerator<AIG_CourseNode> enumerator = __instance.m_zone.m_courseNodes.GetEnumerator();
			while (enumerator.MoveNext())
			{
				foreach (LG_Light componentsInChild in ((Component)enumerator.Current.m_area).GetComponentsInChildren<LG_Light>())
				{
					LightData lightData = ((Component)componentsInChild).gameObject.AddComponent<LightData>();
					LG_PointLight result2;
					if (((Il2CppObjectBase)(object)componentsInChild).TryCastToType<LG_SpotLight>(out LG_SpotLight result))
					{
						lightData.PrefabIntensity.Set(result.m_spotLight.intensity);
					}
					else if (((Il2CppObjectBase)(object)componentsInChild).TryCastToType<LG_PointLight>(out result2))
					{
						lightData.PrefabIntensity.Set(result2.m_pointLight.intensity);
					}
					else
					{
						if (!((Il2CppObjectBase)(object)componentsInChild).TryCastToType<LG_SpotLightAmbient>(out LG_SpotLightAmbient result3))
						{
							continue;
						}
						lightData.PrefabIntensity.Set(result3.m_spotLight.intensity);
					}
					__state.Add(componentsInChild);
				}
			}
			LG_Objects.Lights.AddRange(__state);
		}

		[HarmonyPriority(0)]
		private static void Postfix(List<LG_Light> __state)
		{
			//IL_0076: Unknown result type (might be due to invalid IL or missing references)
			//IL_007b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0029: Unknown result type (might be due to invalid IL or missing references)
			//IL_002f: Expected O, but got Unknown
			bool flag = default(bool);
			foreach (LG_Light item in __state)
			{
				LightData component = ((Component)item).GetComponent<LightData>();
				if ((Object)(object)component == (Object)null)
				{
					BepInExErrorLogInterpolatedStringHandler val = new BepInExErrorLogInterpolatedStringHandler(32, 2, ref flag);
					if (flag)
					{
						((BepInExLogInterpolatedStringHandler)val).AppendLiteral("Found Light without ");
						((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>("LightData");
						((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" Component! ");
						((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(((Component)(object)item).GetGameObjectPath());
					}
					Logger.Error(val);
				}
				else
				{
					component.SpawnedIntensity = item.m_intensity;
					component.SpawnedColor = item.m_color;
					component.SpawnedMode = GetLightMode(item);
				}
			}
			__state.Clear();
		}

		private static LightMode GetLightMode(LG_Light light)
		{
			if (light.GetC_Light().LightUpdator != null)
			{
				return LightMode.Broken_Flickering;
			}
			if (((Component)light).gameObject.active)
			{
				return LightMode.On;
			}
			return LightMode.Off;
		}
	}
	[HarmonyPatch(typeof(LG_SecurityDoor), "Setup")]
	internal static class Inject_LG_SecDoor
	{
		private static void Postfix(LG_SecurityDoor __instance)
		{
			LG_Objects.SecurityDoors.Add(__instance);
		}
	}
	[HarmonyPatch(typeof(LG_WeakDoor), "Setup")]
	internal static class Inject_LG_WeakDoor
	{
		private static void Postfix(LG_WeakDoor __instance)
		{
			LG_Objects.WeakDoors.Add(__instance);
		}
	}
}
namespace FloLib.Infos.Comps
{
	[AutoInject]
	internal sealed class LightData : MonoBehaviour
	{
		public Il2CppValueField<float> PrefabIntensity;

		public LightMode SpawnedMode;

		public float SpawnedIntensity;

		public Color SpawnedColor;

		public LG_LightInfo.Data CreateData()
		{
			//IL_0037: 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)
			LG_LightInfo.Data result = default(LG_LightInfo.Data);
			result.PrefabIntensity = Il2CppValueField<float>.op_Implicit(PrefabIntensity);
			result.SpawnedMode = SpawnedMode;
			result.SpawnedIntensity = SpawnedIntensity;
			result.SpawnedColor = SpawnedColor;
			return result;
		}
	}
}
namespace FloLib.Game.ScreenShakes
{
	public sealed class ScreenShake
	{
		[AutoInvoke(InvokeWhen.StartupAssetLoaded)]
		internal static void Init()
		{
			GlobalNetAction<ScreenShakeDescriptor>.OnReceive += OnReceive;
		}

		public static void Trigger(ScreenShakeDescriptor data)
		{
			GlobalNetAction<ScreenShakeDescriptor>.Send(data);
		}

		private static void OnReceive(ulong sender, ScreenShakeDescriptor data)
		{
			if (LocalPlayer.TryGetAgent(out var agent))
			{
				FPSCamera fPSCamera = agent.FPSCamera;
				MonoBehaviourExtensions.StartCoroutine((MonoBehaviour)(object)fPSCamera, DoShake(fPSCamera, data));
			}
		}

		private static IEnumerator DoShake(FPSCamera camera, ScreenShakeDescriptor data)
		{
			float time = 0f;
			while (time < data.Duration)
			{
				float num = 1f;
				if (data.Mode == ScreenShakeMode.PositionFalloff)
				{
					float num2 = Vector3.Distance(data.Position, camera.Position);
					num = Mathf.InverseLerp(data.FalloffEnd, data.FalloffStart, num2);
				}
				float t = data.Modifier switch
				{
					ScreenShakeModifier.PingPong => Mathf.PingPong(Mathf.InverseLerp(data.Duration, 0f, time) * 2f, 1f), 
					ScreenShakeModifier.Increase => Mathf.InverseLerp(0f, data.Duration, time), 
					ScreenShakeModifier.Decrease => Mathf.InverseLerp(data.Duration, 0f, time), 
					_ => 1f, 
				};
				t = data.IntensityEasing.Evaluate(t);
				float constantCameraShakeAmount = num * t * data.Intensity;
				camera.SetConstantCameraShakeAmount(constantCameraShakeAmount);
				time += Time.deltaTime;
				yield return null;
			}
			camera.SetConstantCameraShakeAmount(0f);
		}
	}
	public struct ScreenShakeDescriptor
	{
		public ScreenShakeMode Mode;

		public ScreenShakeModifier Modifier;

		public Vector3 Position;

		public float Intensity;

		public float Duration;

		public float FalloffStart;

		public float FalloffEnd;

		public EaseFunc.Type IntensityEasing;
	}
	public enum ScreenShakeMode : byte
	{
		Global,
		PositionFalloff
	}
	public enum ScreenShakeModifier : byte
	{
		PingPong,
		Increase,
		Decrease,
		Constant
	}
}
namespace FloLib.Game.Projectiles
{
	public class Projectile : MonoBehaviour
	{
	}
}
namespace FloLib.Game.Explosions
{
	public sealed class Explosion
	{
		public static readonly Color DefaultFlashColor = new Color(1f, 0.2f, 0f, 1f);

		[AutoInvoke(InvokeWhen.StartupAssetLoaded)]
		internal static void Init()
		{
			ExplosionEffectPooling.Initialize();
			GlobalNetAction<ExplosionDescriptor>.OnReceive += OnReceive;
		}

		private static void OnReceive(ulong sender, ExplosionDescriptor data)
		{
			Internal_TriggerExplosion(data);
		}

		public static void Trigger(ExplosionDescriptor data)
		{
			GlobalNetAction<ExplosionDescriptor>.Send(data);
		}

		internal static void Internal_TriggerExplosion(ExplosionDescriptor data)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			//IL_0036: Unknown result type (might be due to invalid IL or missing references)
			CellSound.Post(EVENTS.STICKYMINEEXPLODE, data.Position);
			LightFlash(data.Position, data.MaxDamageRange, data.LightColor);
			if (!SNet.IsMaster)
			{
				return;
			}
			Il2CppReferenceArray<Collider> val = Physics.OverlapSphere(data.Position, data.MaxDamageRange, LayerManager.MASK_EXPLOSION_TARGETS);
			if (((Il2CppArrayBase<Collider>)(object)val).Count < 1)
			{
				return;
			}
			DamageUtil.IncrementSearchID();
			uint searchID = DamageUtil.SearchID;
			foreach (Collider item in (Il2CppArrayBase<Collider>)(object)val)
			{
				ProcessExplosion(data, item, searchID);
			}
		}

		private static void ProcessExplosion(ExplosionDescriptor data, Collider target, uint searchID)
		{
			//IL_003f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0044: Unknown result type (might be due to invalid IL or missing references)
			//IL_004d: 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_005a: Unknown result type (might be due to invalid IL or missing references)
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0103: Unknown result type (might be due to invalid IL or missing references)
			//IL_0108: Unknown result type (might be due to invalid IL or missing references)
			//IL_0112: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)target == (Object)null || (Object)(object)((Component)target).gameObject == (Object)null || !((Component)target).gameObject.TryGetComp<IDamageable>(out var component))
			{
				return;
			}
			component = component.GetBaseDamagable();
			if (component == null || component.TempSearchID == searchID)
			{
				return;
			}
			Vector3 damagablePosition = GetDamagablePosition(component);
			component.TempSearchID = searchID;
			float distance = Vector3.Distance(data.Position, damagablePosition);
			if (!IsExplosionBlocked(data.Position, damagablePosition, target))
			{
				float num = CalcBaseRangeDamage(data.MaxDamage, distance, data.MaxDamageRange, data.MinDamageRange);
				if ((Object)(object)((Il2CppObjectBase)component).TryCast<Dam_EnemyDamageBase>() != (Object)null)
				{
					num *= (float)data.DamageMultiplierToEnemy;
				}
				else if ((Object)(object)((Il2CppObjectBase)component).TryCast<Dam_PlayerDamageBase>() != (Object)null)
				{
					num *= (float)data.DamageMultiplierToPlayer;
				}
				Agent baseAgent = component.GetBaseAgent();
				if ((Object)(object)baseAgent != (Object)null && baseAgent.GlobalID == data.Inflictor.AgentID)
				{
					num *= (float)data.DamageMultiplierToInflictor;
				}
				if (Mathf.Abs(num) > float.Epsilon)
				{
					component.ExplosionDamage(num, data.Position, Vector3.up * 1000f, 0u);
				}
			}
		}

		private static Vector3 GetDamagablePosition(IDamageable damagable)
		{
			//IL_0018: Unknown result type (might be due to invalid IL or missing references)
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			Agent baseAgent = damagable.GetBaseAgent();
			if ((Object)(object)baseAgent != (Object)null)
			{
				return baseAgent.EyePosition;
			}
			return damagable.DamageTargetPos;
		}

		private static bool IsExplosionBlocked(Vector3 pos1, Vector3 pos2, Collider targetCollider)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			RaycastHit val = default(RaycastHit);
			if (Physics.Linecast(pos1, pos2, ref val, LayerManager.MASK_EXPLOSION_BLOCKERS))
			{
				if 

plugins/TrickyBall's Paradise/Custom/ForLegacy/net6/custombooster.dll

Decompiled 8 months ago
using System;
using System.CodeDom.Compiler;
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 System.Text.Json;
using System.Text.Json.Serialization;
using BepInEx;
using BepInEx.Logging;
using BepInEx.Unity.IL2CPP;
using BoosterImplants;
using BoosterPack.Manager;
using BoosterPack.Models;
using BoosterPack.Patches;
using CellMenu;
using DropServer.BoosterImplants;
using GameData;
using HarmonyLib;
using Il2CppInterop.Runtime.InteropTypes.Arrays;
using Il2CppSystem;
using Il2CppSystem.Collections.Generic;
using Il2CppSystem.Threading.Tasks;
using Localization;
using MTFO.API;
using Microsoft.CodeAnalysis;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: TargetFramework(".NETCoreApp,Version=v6.0", FrameworkDisplayName = "")]
[assembly: AssemblyCompany("BoosterPack")]
[assembly: AssemblyConfiguration("Debug")]
[assembly: AssemblyFileVersion("1.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0+git465baee-dirty-master")]
[assembly: AssemblyProduct("BoosterPack")]
[assembly: AssemblyTitle("BoosterPack")]
[assembly: AssemblyVersion("1.0.0.0")]
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;
		}
	}
}
namespace BoosterPack
{
	[BepInPlugin("Endskill.CustomBoosters", "CustomBoosters", "1.0.0")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	public class BepinExLoader : BasePlugin
	{
		public const string MODNAME = "CustomBoosters";

		public const string AUTHOR = "Endskill";

		public const string GUID = "Endskill.CustomBoosters";

		public const string VERSION = "1.0.0";

		public override void Load()
		{
			//IL_0037: Unknown result type (might be due to invalid IL or missing references)
			//IL_003d: Expected O, but got Unknown
			LogManager.SetLogger(((BasePlugin)this).Log);
			LogManager._debugMessagesActive = ((BasePlugin)this).Config.Bind<bool>("Dev Settings", "DebugMessages", false, "This settings activates/deactivates debug messages in the console for this specific plugin.").Value;
			Harmony val = new Harmony("Endskill.CustomBoosters");
			val.PatchAll(typeof(PersistentInventoryManagerPatches));
			val.PatchAll(typeof(DropServerPatches));
			val.PatchAll(typeof(BoosterImplantInventoryItemPatches));
			val.PatchAll(typeof(CmPageLoadoutPatches));
			MTFOHotReloadAPI.OnHotReload += ScriptManager.HotReaload;
		}
	}
	public static class CacheApiWrapper
	{
		internal static BoosterImplantPlayerData _inv;

		public static bool UseCustomData { get; set; }

		public static BoosterImplantPlayerData Inventory
		{
			get
			{
				return _inv;
			}
			set
			{
				_inv = value;
			}
		}
	}
	internal static class LogManager
	{
		private static ManualLogSource logger;

		internal static bool _debugMessagesActive;

		internal static void SetLogger(ManualLogSource log)
		{
			logger = log;
		}

		public static void Verbose(object msg)
		{
			if (_debugMessagesActive)
			{
				logger.LogInfo(msg);
			}
		}

		public static void Debug(object msg)
		{
			if (_debugMessagesActive)
			{
				logger.LogDebug(msg);
			}
		}

		public static void Message(object msg)
		{
			if (_debugMessagesActive)
			{
				logger.LogMessage(msg);
			}
		}

		public static void Error(object msg)
		{
			logger.LogError(msg);
		}

		public static void Warn(object msg)
		{
			logger.LogWarning(msg);
		}
	}
	[GeneratedCode("VersionInfoGenerator", "2.0.0+git50a4b1a-master")]
	[CompilerGenerated]
	internal static class VersionInfo
	{
		public const string RootNamespace = "BoosterPack";

		public const string Version = "1.0.0";

		public const string VersionPrerelease = null;

		public const string VersionMetadata = "git465baee-dirty-master";

		public const string SemVer = "1.0.0+git465baee-dirty-master";

		public const string GitRevShort = "465baee-dirty";

		public const string GitRevLong = "465baeed0cd33374f3d2e30104b8e8fe99e66f59-dirty";

		public const string GitBranch = "master";

		public const string GitTag = null;

		public const bool GitIsDirty = true;
	}
}
namespace BoosterPack.Patches
{
	[HarmonyPatch(typeof(BoosterImplantInventoryItem))]
	public class BoosterImplantInventoryItemPatches
	{
		[HarmonyPatch(/*Could not decode attribute arguments.*/)]
		[HarmonyPrefix]
		public static bool Prefix(ref bool __result)
		{
			__result = true;
			return false;
		}
	}
	[HarmonyPatch(typeof(CM_PageLoadout))]
	public static class CmPageLoadoutPatches
	{
		[HarmonyPatch("ProcessBoosterImplantEvents")]
		[HarmonyPrefix]
		public static bool ProcessBoosterImplantEventsPrefix()
		{
			return false;
		}
	}
	[HarmonyPatch(typeof(DropServerManager))]
	public static class DropServerManagerPatches
	{
		private static PlayerInventoryData _cachedInventory;

		[HarmonyPatch("GetBoosterImplantPlayerDataAsync")]
		[HarmonyPrefix]
		public static bool GetBoosterImplantPlayerDataAsyncPrefix(ref Task<PlayerInventoryData> __result)
		{
			LogManager.Debug("Booster Patch");
			__result = GetInventory();
			return false;
		}

		[HarmonyPatch("GetInventoryPlayerDataAsync")]
		[HarmonyPrefix]
		public static bool GetInventoryPlayerDataAsyncPrefix(ref Task<PlayerInventoryData> __result)
		{
			LogManager.Debug("Inventar Patch");
			__result = GetInventory();
			return false;
		}

		private static Task<PlayerInventoryData> GetInventory()
		{
			//IL_001b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0025: Expected O, but got Unknown
			//IL_002a: 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_0030: Unknown result type (might be due to invalid IL or missing references)
			//IL_003a: Expected O, but got Unknown
			//IL_003b: Unknown result type (might be due to invalid IL or missing references)
			//IL_003c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0046: Expected O, but got Unknown
			//IL_0047: Unknown result type (might be due to invalid IL or missing references)
			//IL_0048: Unknown result type (might be due to invalid IL or missing references)
			//IL_0052: Expected O, but got Unknown
			//IL_0058: Expected O, but got Unknown
			if (_cachedInventory != null)
			{
				return Task.FromResult<PlayerInventoryData>(_cachedInventory);
			}
			_cachedInventory = new PlayerInventoryData();
			_cachedInventory.BoosterData = new Nullable<BoosterImplantPlayerData>(new BoosterImplantPlayerData
			{
				Basic = new Category(),
				Advanced = new Category(),
				Specialized = new Category()
			});
			return Task.FromResult<PlayerInventoryData>(_cachedInventory);
		}
	}
	[HarmonyPatch(typeof(DropServerGameSession))]
	internal class DropServerPatches
	{
		[HarmonyPatch("ConsumeBoosters")]
		[HarmonyPrefix]
		public static bool ConsumeBoostersPrefix()
		{
			return false;
		}
	}
	[HarmonyPatch(typeof(PersistentInventoryManager))]
	public class PersistentInventoryManagerPatches
	{
		private static uint _id = 9599u;

		[HarmonyPatch("UpdateBoosterImplants")]
		[HarmonyPrefix]
		[HarmonyWrapSafe]
		public static bool UpdateBoosterImplantsPrefix(PersistentInventoryManager __instance)
		{
			//IL_0050: Unknown result type (might be due to invalid IL or missing references)
			//IL_0056: Invalid comparison between Unknown and I4
			ScriptManager.Initialize();
			if (!CacheApiWrapper.UseCustomData)
			{
				CreateData();
			}
			BoosterImplant[] array = ((IEnumerable<BoosterImplantCategory>)BoosterImplantConstants.Categories).Select((BoosterImplantCategory c) => PersistentInventoryManager.GetActiveBoosterImplant((BoosterImplantCategory)c)).ToArray();
			UpdateBoosterImplantInventoryModelMock(__instance);
			if ((int)__instance.m_boosterImplantDirtyState == 0)
			{
				__instance.ClearPendingBoosterImplantTransactions();
			}
			else
			{
				PersistentInventoryManager.CleanupPendingBoosterImplantTransactions(__instance.m_boosterImplantPendingTransactions, __instance.m_boosterImplantInventory);
				PersistentInventoryManager.ApplyPendingBoosterImplantTransactionsToModel(__instance.m_boosterImplantInventory, __instance.m_boosterImplantPendingTransactions);
			}
			for (int i = 0; i < array.Length; i++)
			{
				if (PersistentInventoryManager.GetActiveBoosterImplant((BoosterImplantCategory)i) != array[i])
				{
					Action onActiveBoosterImplantsChanged = __instance.OnActiveBoosterImplantsChanged;
					if (onActiveBoosterImplantsChanged != null)
					{
						onActiveBoosterImplantsChanged.Invoke();
					}
					break;
				}
			}
			Action onBoosterImplantInventoryChanged = __instance.OnBoosterImplantInventoryChanged;
			if ((Delegate)(object)onBoosterImplantInventoryChanged == (Delegate)null)
			{
				return false;
			}
			onBoosterImplantInventoryChanged.Invoke();
			return false;
		}

		private static void CreateData()
		{
			//IL_003f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0046: Expected O, but got Unknown
			//IL_0384: Unknown result type (might be due to invalid IL or missing references)
			//IL_038b: Expected O, but got Unknown
			//IL_038b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0392: Expected O, but got Unknown
			//IL_0392: Unknown result type (might be due to invalid IL or missing references)
			//IL_0399: Expected O, but got Unknown
			//IL_03d4: Unknown result type (might be due to invalid IL or missing references)
			//IL_03db: Expected O, but got Unknown
			//IL_00d5: Unknown result type (might be due to invalid IL or missing references)
			//IL_0110: Unknown result type (might be due to invalid IL or missing references)
			//IL_013e: Unknown result type (might be due to invalid IL or missing references)
			//IL_01dc: Unknown result type (might be due to invalid IL or missing references)
			//IL_0217: Unknown result type (might be due to invalid IL or missing references)
			//IL_0245: Unknown result type (might be due to invalid IL or missing references)
			//IL_028e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0293: Unknown result type (might be due to invalid IL or missing references)
			//IL_02af: Unknown result type (might be due to invalid IL or missing references)
			//IL_02cb: Unknown result type (might be due to invalid IL or missing references)
			//IL_0325: Unknown result type (might be due to invalid IL or missing references)
			//IL_032a: Unknown result type (might be due to invalid IL or missing references)
			//IL_032c: Unknown result type (might be due to invalid IL or missing references)
			//IL_032e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0330: Unknown result type (might be due to invalid IL or missing references)
			//IL_0343: Expected I4, but got Unknown
			Il2CppArrayBase<BoosterImplantTemplateDataBlock> allBlocks = GameDataBlockBase<BoosterImplantTemplateDataBlock>.GetAllBlocks();
			Il2CppArrayBase<BoosterImplantEffectDataBlock> allBlocks2 = GameDataBlockBase<BoosterImplantEffectDataBlock>.GetAllBlocks();
			Il2CppArrayBase<BoosterImplantConditionDataBlock> allBlocks3 = GameDataBlockBase<BoosterImplantConditionDataBlock>.GetAllBlocks();
			List<BoosterImplantInventoryItem> list = new List<BoosterImplantInventoryItem>();
			List<BoosterImplantInventoryItem> list2 = new List<BoosterImplantInventoryItem>();
			List<BoosterImplantInventoryItem> list3 = new List<BoosterImplantInventoryItem>();
			foreach (BoosterImplantTemplateDataBlock item3 in allBlocks)
			{
				BoosterImplantInventoryItem val = new BoosterImplantInventoryItem();
				((BoosterImplantBase)val).Id = _id++;
				((BoosterImplantBase)val).TemplateId = ((GameDataBlockBase<BoosterImplantTemplateDataBlock>)(object)item3).persistentID;
				((BoosterImplantBase)val).UsesRemaining = 88;
				List<BoosterImplantEffect> list4 = new List<BoosterImplantEffect>();
				Enumerator<BoosterImplantEffectInstance> enumerator2 = item3.Effects.GetEnumerator();
				while (enumerator2.MoveNext())
				{
					BoosterImplantEffectInstance effect2 = enumerator2.Current;
					BoosterImplantEffectDataBlock val2 = ((IEnumerable<BoosterImplantEffectDataBlock>)allBlocks2).First((BoosterImplantEffectDataBlock x) => ((GameDataBlockBase<BoosterImplantEffectDataBlock>)(object)x).persistentID == effect2.BoosterImplantEffect);
					LogManager.Debug($"Effect has: {val2.BoosterEffectCategory}, Param: {effect2.MaxValue}");
					BoosterImplantEffect item = default(BoosterImplantEffect);
					item.Id = effect2.BoosterImplantEffect;
					item.Param = effect2.MaxValue;
					list4.Add(item);
				}
				bool flag = true;
				Enumerator<List<BoosterImplantEffectInstance>> enumerator3 = item3.RandomEffects.GetEnumerator();
				while (enumerator3.MoveNext())
				{
					List<BoosterImplantEffectInstance> current2 = enumerator3.Current;
					if (!flag)
					{
						continue;
					}
					flag = false;
					Enumerator<BoosterImplantEffectInstance> enumerator4 = current2.GetEnumerator();
					while (enumerator4.MoveNext())
					{
						BoosterImplantEffectInstance effect = enumerator4.Current;
						BoosterImplantEffectDataBlock val3 = ((IEnumerable<BoosterImplantEffectDataBlock>)allBlocks2).First((BoosterImplantEffectDataBlock x) => ((GameDataBlockBase<BoosterImplantEffectDataBlock>)(object)x).persistentID == effect.BoosterImplantEffect);
						LogManager.Debug($"Effect has: {val3.BoosterEffectCategory}, Param: {effect.MaxValue}");
						BoosterImplantEffect item2 = default(BoosterImplantEffect);
						item2.Id = effect.BoosterImplantEffect;
						item2.Param = effect.MaxValue;
						list4.Add(item2);
					}
				}
				((BoosterImplantBase)val).Effects = Il2CppStructArray<BoosterImplantEffect>.op_Implicit(list4.ToArray());
				foreach (BoosterImplantEffect item4 in (Il2CppArrayBase<BoosterImplantEffect>)(object)((BoosterImplantBase)val).Effects)
				{
					LogManager.Debug($"Effect2 has: {item4.Id}, Param: {item4.Param}");
				}
				((BoosterImplantBase)val).Conditions = new Il2CppStructArray<uint>(Il2CppArrayBase<uint>.op_Implicit(item3.Conditions?.ToArray()));
				BoosterImplantCategory implantCategory = item3.ImplantCategory;
				BoosterImplantCategory val4 = implantCategory;
				switch ((int)val4)
				{
				case 0:
					list.Add(val);
					break;
				case 1:
					list2.Add(val);
					break;
				case 2:
					list3.Add(val);
					break;
				}
			}
			Category val5 = new Category();
			Category val6 = new Category();
			Category val7 = new Category();
			val5.Inventory = new Il2CppReferenceArray<BoosterImplantInventoryItem>(list.ToArray());
			val6.Inventory = new Il2CppReferenceArray<BoosterImplantInventoryItem>(list2.ToArray());
			val7.Inventory = new Il2CppReferenceArray<BoosterImplantInventoryItem>(list3.ToArray());
			BoosterImplantPlayerData val8 = new BoosterImplantPlayerData();
			val8.Basic = val5;
			val8.Advanced = val6;
			val8.Specialized = val7;
			val8.New = Il2CppStructArray<uint>.op_Implicit(new uint[0]);
			CacheApiWrapper.Inventory = val8;
		}

		private static void UpdateBoosterImplantInventoryModelMock(PersistentInventoryManager instance)
		{
			//IL_0119: Unknown result type (might be due to invalid IL or missing references)
			//IL_011e: Unknown result type (might be due to invalid IL or missing references)
			//IL_013a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0156: Unknown result type (might be due to invalid IL or missing references)
			//IL_0197: Unknown result type (might be due to invalid IL or missing references)
			//IL_019e: Expected O, but got Unknown
			BoosterImplantPlayerData inventory = CacheApiWrapper.Inventory;
			BoosterImplantInventoryModel boosterImplantInventory = instance.m_boosterImplantInventory;
			boosterImplantInventory.New.Clear();
			int num = 0;
			while (true)
			{
				int num2 = num;
				uint[] array = Il2CppArrayBase<uint>.op_Implicit((Il2CppArrayBase<uint>)(object)inventory.New);
				int num3 = ((array != null) ? array.Length : 0);
				if (num2 < num3)
				{
					boosterImplantInventory.New.Add(((Il2CppArrayBase<uint>)(object)inventory.New)[num]);
					num++;
					continue;
				}
				break;
			}
			Category[] array2 = (Category[])(object)new Category[3] { inventory.Basic, inventory.Advanced, inventory.Specialized };
			int num4 = default(int);
			for (int i = 0; i < array2.Length; i++)
			{
				Category val = array2[i];
				Category val2 = ((Il2CppArrayBase<Category>)(object)boosterImplantInventory.Categories)[i];
				uint num5 = (boosterImplantInventory.FindPrepared((BoosterImplantCategory)i, ref num4) ? ((Il2CppArrayBase<Category>)(object)boosterImplantInventory.Categories)[i].Inventory[num4].InstanceId : uint.MaxValue);
				val2.Inventory.Clear();
				for (int j = 0; j < ((Il2CppArrayBase<BoosterImplantInventoryItem>)(object)val.Inventory).Length; j++)
				{
					try
					{
						BoosterImplantInventoryItem val3 = ((Il2CppArrayBase<BoosterImplantInventoryItem>)(object)val.Inventory)[j];
						foreach (BoosterImplantEffect item in (Il2CppArrayBase<BoosterImplantEffect>)(object)((BoosterImplantBase)val3).Effects)
						{
							LogManager.Debug($"testItem has: {item.Id} {item.Param}");
						}
						BoosterImplantInventoryItem val4 = new BoosterImplantInventoryItem(((Il2CppArrayBase<BoosterImplantInventoryItem>)(object)val.Inventory)[j]);
						val4.Prepared = val4.InstanceId == num5;
						val2.Inventory.Add(val4);
					}
					catch (Exception ex)
					{
						PersistentInventoryManager.LogError(ex.Message);
					}
				}
				val2.Currency = val.Currency;
				val2.Missed = val.Missed;
				val2.MissedAcknowledged = Mathf.Clamp(val2.MissedAcknowledged, val.MissedAck, val.Missed);
			}
		}
	}
}
namespace BoosterPack.Models
{
	public class ActivateableBoosterData
	{
		public bool UseCustomData { get; set; }

		public List<CustomBooster> CustomBoosters { get; set; }
	}
	public class CustomBooster
	{
		private List<CustomEffect> _effects;

		private List<CustomCondition> _conditions;

		public string PublicName { get; set; }

		public string Description { get; set; }

		public BoosterEffectCategory MainEffectType { get; set; }

		public BoosterImplantCategory ImplantCategory { get; set; }

		public List<CustomEffect> Effects
		{
			get
			{
				if (_effects == null)
				{
					_effects = new List<CustomEffect>();
				}
				return _effects;
			}
			set
			{
				_effects = value;
			}
		}

		public List<CustomCondition> Conditions
		{
			get
			{
				if (_conditions == null)
				{
					_conditions = new List<CustomCondition>();
				}
				return _conditions;
			}
			set
			{
				_conditions = value;
			}
		}
	}
	public class CustomCondition
	{
		public BoosterCondition Condition { get; set; }

		public string PublicShortName { get; set; }

		public string PublicName { get; set; }

		public string Description { get; set; }
	}
	public class CustomEffect
	{
		public AgentModifier Effect { get; set; }

		public string PublicShortName { get; set; }

		public string PublicName { get; set; }

		public string Description { get; set; }

		public string DescriptionNegative { get; set; }

		public BoosterEffectCategory EffectCategory { get; set; }

		public float Value { get; set; }
	}
}
namespace BoosterPack.Manager
{
	public class DataBlockManager
	{
		private uint _templateIds = 306783378u;

		private uint _effectIds = 306783378u;

		private uint _conditionIds = 306783378u;

		private uint _itemId = 306783378u;

		private uint _id = 536870911u;

		public List<BoosterImplantInventoryItem> Basic { get; }

		public List<BoosterImplantInventoryItem> Advanced { get; }

		public List<BoosterImplantInventoryItem> Special { get; }

		public DataBlockManager()
		{
			Basic = new List<BoosterImplantInventoryItem>();
			Advanced = new List<BoosterImplantInventoryItem>();
			Special = new List<BoosterImplantInventoryItem>();
		}

		public void CreateDataBlocksForBooster(CustomBooster booster)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Expected O, but got Unknown
			//IL_005c: 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_0091: Unknown result type (might be due to invalid IL or missing references)
			//IL_0098: Expected O, but got Unknown
			//IL_00aa: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b9: Unknown result type (might be due to invalid IL or missing references)
			//IL_0131: Unknown result type (might be due to invalid IL or missing references)
			//IL_0138: Expected O, but got Unknown
			//IL_01b7: Unknown result type (might be due to invalid IL or missing references)
			//IL_01be: Expected O, but got Unknown
			//IL_01d0: Unknown result type (might be due to invalid IL or missing references)
			//IL_0275: Unknown result type (might be due to invalid IL or missing references)
			//IL_027b: Expected O, but got Unknown
			//IL_02cb: 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_0336: Unknown result type (might be due to invalid IL or missing references)
			//IL_033b: Unknown result type (might be due to invalid IL or missing references)
			//IL_033d: Unknown result type (might be due to invalid IL or missing references)
			//IL_033f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0341: Unknown result type (might be due to invalid IL or missing references)
			//IL_0354: Expected I4, but got Unknown
			BoosterImplantTemplateDataBlock val = new BoosterImplantTemplateDataBlock();
			((GameDataBlockBase<BoosterImplantTemplateDataBlock>)(object)val).name = GetUniqueName();
			((GameDataBlockBase<BoosterImplantTemplateDataBlock>)(object)val).persistentID = ++_templateIds;
			val.Deprecated = false;
			val.PublicName = GetTranslation(booster.PublicName);
			val.Description = GetTranslation(booster.Description);
			val.ImplantCategory = booster.ImplantCategory;
			val.MainEffectType = booster.MainEffectType;
			foreach (CustomEffect effect in booster.Effects)
			{
				BoosterImplantEffectDataBlock val2 = new BoosterImplantEffectDataBlock();
				((GameDataBlockBase<BoosterImplantEffectDataBlock>)(object)val2).name = GetUniqueName();
				val2.Effect = effect.Effect;
				val2.BoosterEffectCategory = effect.EffectCategory;
				val2.PublicShortName = GetTranslation(effect.PublicShortName);
				val2.PublicName = GetTranslation(effect.PublicName);
				val2.Description = GetTranslation(effect.Description);
				val2.DescriptionNegative = GetTranslation(effect.DescriptionNegative);
				((GameDataBlockBase<BoosterImplantEffectDataBlock>)(object)val2).persistentID = _effectIds++;
				BoosterImplantEffectInstance val3 = new BoosterImplantEffectInstance();
				val3.BoosterImplantEffect = ((GameDataBlockBase<BoosterImplantEffectDataBlock>)(object)val2).persistentID;
				val3.MinValue = effect.Value;
				val3.MaxValue = effect.Value;
				val.Effects.Add(val3);
				GameDataBlockBase<BoosterImplantEffectDataBlock>.AddBlock(val2, -1);
			}
			foreach (CustomCondition condition in booster.Conditions)
			{
				BoosterImplantConditionDataBlock val4 = new BoosterImplantConditionDataBlock();
				((GameDataBlockBase<BoosterImplantConditionDataBlock>)(object)val4).name = GetUniqueName();
				val4.Condition = condition.Condition;
				val4.PublicShortName = GetTranslation(condition.PublicShortName);
				val4.PublicName = GetTranslation(condition.PublicName);
				val4.Description = GetTranslation(condition.Description);
				((GameDataBlockBase<BoosterImplantConditionDataBlock>)(object)val4).persistentID = _conditionIds++;
				val.Conditions.Add(((GameDataBlockBase<BoosterImplantConditionDataBlock>)(object)val4).persistentID);
				GameDataBlockBase<BoosterImplantConditionDataBlock>.AddBlock(val4, -1);
			}
			GameDataBlockBase<BoosterImplantTemplateDataBlock>.AddBlock(val, -1);
			BoosterImplantInventoryItem val5 = new BoosterImplantInventoryItem();
			((BoosterImplantBase)val5).Id = _itemId++;
			((BoosterImplantBase)val5).TemplateId = ((GameDataBlockBase<BoosterImplantTemplateDataBlock>)(object)val).persistentID;
			((BoosterImplantBase)val5).UsesRemaining = 99;
			List<BoosterImplantEffect> list = new List<BoosterImplantEffect>();
			Enumerator<BoosterImplantEffectInstance> enumerator3 = val.Effects.GetEnumerator();
			while (enumerator3.MoveNext())
			{
				BoosterImplantEffectInstance current3 = enumerator3.Current;
				BoosterImplantEffect item = default(BoosterImplantEffect);
				item.Id = current3.BoosterImplantEffect;
				item.Param = current3.MaxValue;
				list.Add(item);
			}
			((BoosterImplantBase)val5).Effects = Il2CppStructArray<BoosterImplantEffect>.op_Implicit(list.ToArray());
			((BoosterImplantBase)val5).Conditions = new Il2CppStructArray<uint>(Il2CppArrayBase<uint>.op_Implicit(val.Conditions?.ToArray()));
			BoosterImplantCategory implantCategory = val.ImplantCategory;
			BoosterImplantCategory val6 = implantCategory;
			switch ((int)val6)
			{
			case 0:
				Basic.Add(val5);
				break;
			case 1:
				Advanced.Add(val5);
				break;
			case 2:
				Special.Add(val5);
				break;
			}
		}

		private LocalizedText GetTranslation(string booLocalization)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Expected O, but got Unknown
			LocalizedText val = new LocalizedText();
			val.UntranslatedText = booLocalization;
			return val;
		}

		private string GetUniqueName()
		{
			return $"CustomBoosters_{++_id}";
		}
	}
	public static class ScriptManager
	{
		private static bool _initialized;

		internal static void HotReaload()
		{
			_initialized = false;
			Initialize();
			PersistentInventoryManager.Current.UpdateBoosterImplants(ref CacheApiWrapper._inv);
		}

		public static void Initialize()
		{
			if (!_initialized)
			{
				_initialized = true;
				string text = Path.Combine(MTFOPathAPI.CustomPath, "CustomBoosters");
				if (!Directory.Exists(text))
				{
					Directory.CreateDirectory(text);
				}
				WriteEnumValues(text);
				text = Path.Combine(text, "CustomBoosters.json");
				WriteDefault(text);
				ActivateableBoosterData data = ReadData(text);
				PrepareForUseIngame(data);
			}
		}

		public static void PrepareForUseIngame(ActivateableBoosterData data)
		{
			//IL_0053: Unknown result type (might be due to invalid IL or missing references)
			//IL_0059: Expected O, but got Unknown
			//IL_0059: Unknown result type (might be due to invalid IL or missing references)
			//IL_005f: Expected O, but got Unknown
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0066: Expected O, but got Unknown
			//IL_00ac: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b3: Expected O, but got Unknown
			CacheApiWrapper.UseCustomData = data.UseCustomData;
			List<CustomBooster> customBoosters = data.CustomBoosters;
			DataBlockManager dataBlockManager = new DataBlockManager();
			foreach (CustomBooster item in customBoosters)
			{
				dataBlockManager.CreateDataBlocksForBooster(item);
			}
			Category val = new Category();
			Category val2 = new Category();
			Category val3 = new Category();
			val.Inventory = Il2CppReferenceArray<BoosterImplantInventoryItem>.op_Implicit(dataBlockManager.Basic.ToArray());
			val2.Inventory = Il2CppReferenceArray<BoosterImplantInventoryItem>.op_Implicit(dataBlockManager.Advanced.ToArray());
			val3.Inventory = Il2CppReferenceArray<BoosterImplantInventoryItem>.op_Implicit(dataBlockManager.Special.ToArray());
			BoosterImplantPlayerData val4 = new BoosterImplantPlayerData();
			val4.Basic = val;
			val4.Advanced = val2;
			val4.Specialized = val3;
			val4.New = Il2CppStructArray<uint>.op_Implicit(new uint[0]);
			CacheApiWrapper.Inventory = val4;
		}

		private static ActivateableBoosterData ReadData(string path)
		{
			JsonSerializerOptions jsonSerializerOptions = new JsonSerializerOptions
			{
				IncludeFields = false,
				ReadCommentHandling = JsonCommentHandling.Skip,
				PropertyNameCaseInsensitive = true,
				WriteIndented = true
			};
			jsonSerializerOptions.Converters.Add(new JsonStringEnumConverter());
			return JsonSerializer.Deserialize<ActivateableBoosterData>(File.ReadAllText(path), jsonSerializerOptions) ?? ParseExistingDataBlocks();
		}

		private static void WriteDefault(string path)
		{
			if (!File.Exists(path))
			{
				JsonSerializerOptions jsonSerializerOptions = new JsonSerializerOptions
				{
					IncludeFields = false,
					ReadCommentHandling = JsonCommentHandling.Skip,
					PropertyNameCaseInsensitive = true,
					WriteIndented = true
				};
				jsonSerializerOptions.Converters.Add(new JsonStringEnumConverter());
				File.WriteAllText(path, JsonSerializer.Serialize(ParseExistingDataBlocks(), jsonSerializerOptions));
			}
		}

		private static void WriteEnumValues(string dictionaryPath)
		{
			string path = Path.Combine(dictionaryPath, "MainEffectType.txt");
			if (!File.Exists(path))
			{
				File.WriteAllText(path, "==This file is auto-generated by CustomBoosters. It's not for editing==\n" + string.Join("\n", Enum.GetNames(typeof(BoosterEffectCategory))));
			}
			string path2 = Path.Combine(dictionaryPath, "EffectCategory.txt");
			if (!File.Exists(path2))
			{
				File.WriteAllText(path2, "==This file is auto-generated by CustomBoosters. It's not for editing==\n" + string.Join("\n", Enum.GetNames(typeof(BoosterEffectCategory))));
			}
			string path3 = Path.Combine(dictionaryPath, "ImplantCategory.txt");
			if (!File.Exists(path3))
			{
				File.WriteAllText(path3, "==This file is auto-generated by CustomBoosters. It's not for editing==\n" + string.Join("\n", Enum.GetNames(typeof(BoosterImplantCategory))));
			}
			string path4 = Path.Combine(dictionaryPath, "Effect.txt");
			if (!File.Exists(path4))
			{
				File.WriteAllText(path4, "==This file is auto-generated by CustomBoosters. It's not for editing==\n" + string.Join("\n", Enum.GetNames(typeof(AgentModifier))));
			}
			string path5 = Path.Combine(dictionaryPath, "Condition.txt");
			if (!File.Exists(path5))
			{
				File.WriteAllText(path5, "==This file is auto-generated by CustomBoosters. It's not for editing==\n" + string.Join("\n", Enum.GetNames(typeof(BoosterCondition))));
			}
		}

		private static ActivateableBoosterData ParseExistingDataBlocks()
		{
			//IL_00a0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b4: Unknown result type (might be due to invalid IL or missing references)
			ActivateableBoosterData activateableBoosterData = new ActivateableBoosterData();
			List<CustomBooster> list2 = (activateableBoosterData.CustomBoosters = new List<CustomBooster>());
			activateableBoosterData.UseCustomData = false;
			Il2CppArrayBase<BoosterImplantTemplateDataBlock> allBlocks = GameDataBlockBase<BoosterImplantTemplateDataBlock>.GetAllBlocks();
			Il2CppArrayBase<BoosterImplantEffectDataBlock> allBlocks2 = GameDataBlockBase<BoosterImplantEffectDataBlock>.GetAllBlocks();
			Il2CppArrayBase<BoosterImplantConditionDataBlock> allBlocks3 = GameDataBlockBase<BoosterImplantConditionDataBlock>.GetAllBlocks();
			foreach (BoosterImplantTemplateDataBlock temp in allBlocks)
			{
				CustomBooster customBooster = new CustomBooster();
				customBooster.PublicName = Text.Get(temp.PublicName.Id);
				customBooster.Description = Text.Get(temp.Description.Id);
				customBooster.MainEffectType = temp.MainEffectType;
				customBooster.ImplantCategory = temp.ImplantCategory;
				Enumerator<BoosterImplantEffectInstance> enumerator2 = temp.Effects.GetEnumerator();
				while (enumerator2.MoveNext())
				{
					BoosterImplantEffectInstance effect = enumerator2.Current;
					BoosterImplantEffectDataBlock effectDb2 = ((IEnumerable<BoosterImplantEffectDataBlock>)allBlocks2).First((BoosterImplantEffectDataBlock x) => ((GameDataBlockBase<BoosterImplantEffectDataBlock>)(object)x).persistentID == effect.BoosterImplantEffect);
					customBooster.Effects.Add(ParseEffect(effectDb2, effect.MaxValue));
				}
				if (temp.RandomEffects.Count > 0)
				{
					Enumerator<BoosterImplantEffectInstance> enumerator3 = temp.RandomEffects[0].GetEnumerator();
					while (enumerator3.MoveNext())
					{
						BoosterImplantEffectInstance effect2 = enumerator3.Current;
						BoosterImplantEffectDataBlock effectDb3 = ((IEnumerable<BoosterImplantEffectDataBlock>)allBlocks2).First((BoosterImplantEffectDataBlock x) => ((GameDataBlockBase<BoosterImplantEffectDataBlock>)(object)x).persistentID == effect2.BoosterImplantEffect);
						customBooster.Effects.Add(ParseEffect(effectDb3, effect2.MaxValue));
					}
				}
				Enumerator<uint> enumerator4 = temp.Conditions.GetEnumerator();
				while (enumerator4.MoveNext())
				{
					uint condition = enumerator4.Current;
					BoosterImplantConditionDataBlock conditionDb2 = ((IEnumerable<BoosterImplantConditionDataBlock>)allBlocks3).First((BoosterImplantConditionDataBlock x) => ((GameDataBlockBase<BoosterImplantConditionDataBlock>)(object)x).persistentID == condition);
					customBooster.Conditions.Add(ParseCondition(conditionDb2));
				}
				if (temp.RandomConditions.Count > 0)
				{
					BoosterImplantConditionDataBlock conditionDb3 = ((IEnumerable<BoosterImplantConditionDataBlock>)allBlocks3).First((BoosterImplantConditionDataBlock x) => ((GameDataBlockBase<BoosterImplantConditionDataBlock>)(object)x).persistentID == temp.RandomConditions[0]);
					customBooster.Conditions.Add(ParseCondition(conditionDb3));
				}
				list2.Add(customBooster);
			}
			return activateableBoosterData;
			static CustomCondition ParseCondition(BoosterImplantConditionDataBlock conditionDb)
			{
				//IL_004e: Unknown result type (might be due to invalid IL or missing references)
				return new CustomCondition
				{
					PublicShortName = Text.Get(conditionDb.PublicShortName.Id),
					PublicName = Text.Get(conditionDb.PublicName.Id),
					Description = Text.Get(conditionDb.Description.Id),
					Condition = conditionDb.Condition
				};
			}
			static CustomEffect ParseEffect(BoosterImplantEffectDataBlock effectDb, float value)
			{
				//IL_0065: Unknown result type (might be due to invalid IL or missing references)
				//IL_0072: Unknown result type (might be due to invalid IL or missing references)
				return new CustomEffect
				{
					PublicShortName = Text.Get(effectDb.PublicShortName.Id),
					PublicName = Text.Get(effectDb.PublicName.Id),
					Description = Text.Get(effectDb.Description.Id),
					DescriptionNegative = Text.Get(effectDb.DescriptionNegative.Id),
					Effect = effectDb.Effect,
					EffectCategory = effectDb.BoosterEffectCategory,
					Value = value
				};
			}
		}
	}
}

plugins/TrickyBall's Paradise/Custom/ForLegacy/net6/Inas07.EOSExt.EnvTemperature.dll

Decompiled 8 months ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using Agents;
using BepInEx;
using BepInEx.Unity.IL2CPP;
using EOSExt.EnvTemperature.Components;
using EOSExt.EnvTemperature.Definitions;
using EOSExt.EnvTemperature.Patches;
using ExtraObjectiveSetup.BaseClasses;
using ExtraObjectiveSetup.Utils;
using FloLib.Infos;
using GTFO.API;
using GTFO.API.Utilities;
using GameData;
using GameEvent;
using Gear;
using HarmonyLib;
using Il2CppInterop.Runtime.Injection;
using Il2CppSystem.Collections.Generic;
using LevelGeneration;
using Localization;
using Microsoft.CodeAnalysis;
using Player;
using SNetwork;
using TMPro;
using UnityEngine;
using UnityEngine.UI;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETCoreApp,Version=v6.0", FrameworkDisplayName = ".NET 6.0")]
[assembly: AssemblyCompany("Inas07.EOSExt.EnvTemperature")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0+8ea4fc529bf4c30b0880418d9bd567d7c57ce903")]
[assembly: AssemblyProduct("Inas07.EOSExt.EnvTemperature")]
[assembly: AssemblyTitle("Inas07.EOSExt.EnvTemperature")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.0.0.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

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

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

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

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace EOSExt.EnvTemperature
{
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInPlugin("Inas.EOSExt.EnvTemperature", "EOSExt.EnvTemperature", "1.0.1")]
	public class EntryPoint : BasePlugin
	{
		public const string AUTHOR = "Inas";

		public const string PLUGIN_NAME = "EOSExt.EnvTemperature";

		public const string VERSION = "1.0.1";

		private Harmony m_Harmony;

		public override void Load()
		{
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0016: Expected O, but got Unknown
			SetupManagers();
			m_Harmony = new Harmony("EOSExt.EnvTemperature");
			m_Harmony.PatchAll();
			EOSLogger.Log("ExtraObjectiveSetup.EnvTemperature loaded.");
		}

		private void SetupManagers()
		{
			((GenericDefinitionManager<TemperatureDefinition>)TemperatureDefinitionManager.Current).Init();
		}
	}
	public class TemperatureDefinitionManager : GenericDefinitionManager<TemperatureDefinition>
	{
		public static readonly TemperatureZoneDefinition DEFAULT_ZONE_DEF;

		public static TemperatureDefinitionManager Current { get; }

		protected override string DEFINITION_NAME => "EnvTemperature";

		private Dictionary<(eDimensionIndex dimensionIndex, LG_LayerType layerType, eLocalZoneIndex localIndex), TemperatureZoneDefinition> zoneDefs { get; } = new Dictionary<(eDimensionIndex, LG_LayerType, eLocalZoneIndex), TemperatureZoneDefinition>();


		protected override void AddDefinitions(GenericDefinition<TemperatureDefinition> definition)
		{
			List<TemperatureSetting> settings = definition.Definition.Settings;
			if (settings.Count > 0)
			{
				settings.Sort((TemperatureSetting t1, TemperatureSetting t2) => t1.Temperature.CompareTo(t2.Temperature));
				bool flag = true;
				if (settings[0].Temperature < 0f)
				{
					EOSLogger.Error($"Found negative temperature: '{settings[0].Temperature}'");
					flag = false;
				}
				if (settings[settings.Count - 1].Temperature > 1f)
				{
					EOSLogger.Error($"Found temperature greater than 1: '{settings[settings.Count - 1].Temperature}'");
					flag = false;
				}
				if (!flag)
				{
					EOSLogger.Error($"Found invalid temperature for MainLevelLayout '{definition.ID}'. Correct it first to make it effective");
					return;
				}
				if (settings[0].Temperature != 0f)
				{
					List<TemperatureSetting> list = new List<TemperatureSetting>();
					TemperatureSetting item = new TemperatureSetting(settings[0])
					{
						Temperature = 0f
					};
					list.Add(item);
					list.AddRange(settings);
					definition.Definition.Settings = list;
					settings.Clear();
					settings = list;
				}
			}
			foreach (TemperatureZoneDefinition zone in definition.Definition.Zones)
			{
				zone.DecreaseRate = Math.Abs(zone.DecreaseRate);
			}
			base.AddDefinitions(definition);
		}

		protected override void FileChanged(LiveEditEventArgs e)
		{
			base.FileChanged(e);
			Clear();
			OnBuildDone();
			if (PlayerTemperatureManager.TryGetCurrentManager(out var mgr) && base.definitions.TryGetValue(RundownManager.ActiveExpedition.LevelLayoutData, out var value))
			{
				mgr.UpdateTemperatureDefinition(value.Definition);
				mgr.UpdateGUIText();
			}
		}

		private void OnBuildDone()
		{
			if (!base.definitions.TryGetValue(RundownManager.ActiveExpedition.LevelLayoutData, out var value))
			{
				return;
			}
			value.Definition.Zones.ForEach(delegate(TemperatureZoneDefinition def)
			{
				//IL_0007: Unknown result type (might be due to invalid IL or missing references)
				//IL_000d: Unknown result type (might be due to invalid IL or missing references)
				//IL_0013: Unknown result type (might be due to invalid IL or missing references)
				//IL_006b: Unknown result type (might be due to invalid IL or missing references)
				//IL_0071: 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_003d: Unknown result type (might be due to invalid IL or missing references)
				//IL_0043: Unknown result type (might be due to invalid IL or missing references)
				//IL_0049: Unknown result type (might be due to invalid IL or missing references)
				if (zoneDefs.ContainsKey((((GlobalZoneIndex)def).DimensionIndex, ((GlobalZoneIndex)def).LayerType, ((GlobalZoneIndex)def).LocalIndex)))
				{
					EOSLogger.Warning($"TemperatureDefinitionManager: duplicate definition found: {(((GlobalZoneIndex)def).DimensionIndex, ((GlobalZoneIndex)def).LayerType, ((GlobalZoneIndex)def).LocalIndex)}");
				}
				zoneDefs[(((GlobalZoneIndex)def).DimensionIndex, ((GlobalZoneIndex)def).LayerType, ((GlobalZoneIndex)def).LocalIndex)] = def;
			});
		}

		private void Clear()
		{
			zoneDefs.Clear();
		}

		public bool TryGetZoneDefinition(eDimensionIndex dimensionIndex, LG_LayerType layerType, eLocalZoneIndex localIndex, out TemperatureZoneDefinition def)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			return zoneDefs.TryGetValue((dimensionIndex, layerType, localIndex), out def);
		}

		public bool TryGetLevelTemperatureSettings(out List<TemperatureSetting> settings)
		{
			if (base.definitions.TryGetValue(RundownManager.ActiveExpedition.LevelLayoutData, out var value))
			{
				settings = value.Definition.Settings;
				if (settings != null)
				{
					return settings.Count > 0;
				}
				return false;
			}
			settings = null;
			return false;
		}

		private TemperatureDefinitionManager()
		{
			LevelAPI.OnBuildDone += OnBuildDone;
			LevelAPI.OnBuildStart += Clear;
			LevelAPI.OnLevelCleanup += Clear;
		}

		static TemperatureDefinitionManager()
		{
			Current = new TemperatureDefinitionManager();
			DEFAULT_ZONE_DEF = new TemperatureZoneDefinition
			{
				DecreaseRate = 0f
			};
		}
	}
}
namespace EOSExt.EnvTemperature.Patches
{
	[HarmonyPatch]
	internal static class Patch_BulletWeapon
	{
		private static TemperatureSetting? m_curSetting;

		private static Dictionary<uint, float> DefaultReloadTimes;

		[HarmonyPostfix]
		[HarmonyWrapSafe]
		[HarmonyPatch(typeof(BulletWeaponArchetype), "OnWield")]
		public static void Post_OnWield(BulletWeaponArchetype __instance)
		{
			uint persistentID = ((GameDataBlockBase<ArchetypeDataBlock>)(object)__instance.m_archetypeData).persistentID;
			if (!DefaultReloadTimes.ContainsKey(persistentID))
			{
				DefaultReloadTimes[persistentID] = __instance.m_archetypeData.DefaultReloadTime;
			}
			TemperatureSetting curSetting = m_curSetting;
			if (curSetting != null && curSetting.SlowDownMultiplier_Reload > 0f)
			{
				__instance.m_archetypeData.DefaultReloadTime = DefaultReloadTimes[persistentID] * curSetting.SlowDownMultiplier_Reload;
				EOSLogger.Debug("Temperature: Slowing down reload!");
			}
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(BulletWeaponArchetype), "Update")]
		private static void Post_Update(BulletWeaponArchetype __instance)
		{
			TemperatureSetting currentTemperatureSetting = PlayerTemperatureManager.GetCurrentTemperatureSetting();
			if (m_curSetting == currentTemperatureSetting)
			{
				return;
			}
			uint persistentID = ((GameDataBlockBase<ArchetypeDataBlock>)(object)__instance.m_archetypeData).persistentID;
			if (DefaultReloadTimes.ContainsKey(persistentID))
			{
				float num = DefaultReloadTimes[persistentID];
				if (currentTemperatureSetting == null || currentTemperatureSetting.SlowDownMultiplier_Reload <= 0f)
				{
					__instance.m_archetypeData.DefaultReloadTime = num;
				}
				else
				{
					__instance.m_archetypeData.DefaultReloadTime = num * currentTemperatureSetting.SlowDownMultiplier_Reload;
				}
			}
			m_curSetting = currentTemperatureSetting;
		}

		[HarmonyPrefix]
		[HarmonyWrapSafe]
		[HarmonyPatch(typeof(BulletWeaponArchetype), "OnUnWield")]
		private static void Pre_OnUnWield(BulletWeaponArchetype __instance)
		{
			uint persistentID = ((GameDataBlockBase<ArchetypeDataBlock>)(object)__instance.m_archetypeData).persistentID;
			if (DefaultReloadTimes.ContainsKey(persistentID))
			{
				float defaultReloadTime = DefaultReloadTimes[persistentID];
				__instance.m_archetypeData.DefaultReloadTime = defaultReloadTime;
			}
		}

		private static void Clear()
		{
			DefaultReloadTimes.Clear();
		}

		static Patch_BulletWeapon()
		{
			m_curSetting = null;
			DefaultReloadTimes = new Dictionary<uint, float>();
			LevelAPI.OnBuildStart += Clear;
			LevelAPI.OnLevelCleanup += Clear;
		}
	}
	[HarmonyPatch]
	internal static class Patch_MWS_ChargeUp_Enter
	{
		private static float DefaultChargeTime = 1f;

		[HarmonyPostfix]
		[HarmonyPatch(typeof(MWS_ChargeUp), "Enter")]
		private static void Postfix_Enter(MWS_ChargeUp __instance)
		{
			DefaultChargeTime = __instance.m_maxDamageTime;
			TemperatureSetting currentTemperatureSetting = PlayerTemperatureManager.GetCurrentTemperatureSetting();
			if (currentTemperatureSetting != null && currentTemperatureSetting.SlowDownMultiplier_Melee > 0f)
			{
				__instance.m_maxDamageTime *= currentTemperatureSetting.SlowDownMultiplier_Melee;
			}
		}

		[HarmonyPrefix]
		[HarmonyWrapSafe]
		[HarmonyPatch(typeof(MWS_ChargeUp), "Exit")]
		private static void Pre_Exit(MWS_ChargeUp __instance)
		{
			__instance.m_maxDamageTime = DefaultChargeTime;
		}
	}
	[HarmonyPatch]
	internal static class Patch_Dam_PlayerDamageBase
	{
		internal static bool s_disableDialog;

		[HarmonyPrefix]
		[HarmonyWrapSafe]
		[HarmonyPatch(typeof(Dam_PlayerDamageLocal), "ReceiveFallDamage")]
		private static bool Pre_ReceiveFallDamage(Dam_PlayerDamageLocal __instance, pMiniDamageData data)
		{
			//IL_00aa: Unknown result type (might be due to invalid IL or missing references)
			float num = ((UFloat16)(ref data.damage)).Get(((Dam_SyncedDamageBase)__instance).HealthMax);
			((Dam_PlayerDamageBase)__instance).m_nextRegen = Clock.Time + ((Dam_PlayerDamageBase)__instance).Owner.PlayerData.healthRegenStartDelayAfterDamage;
			if (((Agent)((Dam_PlayerDamageBase)__instance).Owner).IsLocallyOwned)
			{
				DramaManager.CurrentState.OnLocalDamage(num);
				GameEventManager.PostEvent((eGameEvent)13, ((Dam_PlayerDamageBase)__instance).Owner, num, "", (Dictionary<string, string>)null);
			}
			else
			{
				DramaManager.CurrentState.OnTeammatesDamage(num);
			}
			if (((Dam_PlayerDamageBase)__instance).IgnoreAllDamage)
			{
				return false;
			}
			if (SNet.IsMaster)
			{
				if (((Dam_SyncedDamageBase)__instance).RegisterDamage(num))
				{
					((Dam_SyncedDamageBase)__instance).SendSetDead(true);
				}
				else
				{
					((Dam_SyncedDamageBase)__instance).SendSetHealth(((Dam_SyncedDamageBase)__instance).Health);
				}
			}
			__instance.Hitreact(((UFloat16)(ref data.damage)).Get(((Dam_SyncedDamageBase)__instance).HealthMax), Vector3.zero, true, !s_disableDialog, false);
			return false;
		}
	}
	[HarmonyPatch]
	internal static class Patch_PlayerAgent
	{
		[HarmonyPostfix]
		[HarmonyWrapSafe]
		[HarmonyPatch(typeof(PlayerAgent), "Setup")]
		private static void Post_Setup(PlayerAgent __instance)
		{
			if (((Agent)__instance).IsLocallyOwned && !((Object)(object)((Component)__instance).gameObject.GetComponent<PlayerTemperatureManager>() != (Object)null))
			{
				((Component)__instance).gameObject.AddComponent<PlayerTemperatureManager>().Setup();
			}
		}
	}
	[HarmonyPatch]
	internal static class Patches_PLOC
	{
		private const float MIN_MOD = 0.1f;

		private static float s_moveSpeedMult = 1f;

		[HarmonyPrefix]
		[HarmonyPatch(typeof(PLOC_Base), "GetHorizontalVelocityFromInput")]
		private static void Pre_GetHorizontalVelocityFromInput(ref float moveSpeed)
		{
			moveSpeed *= s_moveSpeedMult;
		}

		internal static void SetMoveSpeedModifier(float m)
		{
			s_moveSpeedMult = Math.Max(0.1f, m);
		}

		internal static void ResetMoveSpeedModifier()
		{
			s_moveSpeedMult = 1f;
		}
	}
}
namespace EOSExt.EnvTemperature.Definitions
{
	public class TemperatureSetting
	{
		public float Temperature { get; set; } = 1f;


		public float Damage { get; set; } = -1f;


		public float DamageTick { get; set; }

		public float SlowDownMultiplier_Reload { get; set; } = -1f;


		public float SlowDownMultiplier_Melee { get; set; } = -1f;


		public float SlowDownMultiplier_Move { get; set; } = -1f;


		public TemperatureSetting()
		{
		}

		public TemperatureSetting(TemperatureSetting o)
		{
			Temperature = o.Temperature;
			Damage = o.Damage;
			DamageTick = o.DamageTick;
			SlowDownMultiplier_Reload = o.SlowDownMultiplier_Reload;
			SlowDownMultiplier_Melee = o.SlowDownMultiplier_Melee;
			SlowDownMultiplier_Move = o.SlowDownMultiplier_Move;
		}
	}
	public class TemperatureZoneDefinition : GlobalZoneIndex
	{
		public float Temperature { get; set; } = 0.5f;


		public float DecreaseRate { get; set; }
	}
	public class TemperatureDefinition
	{
		public float StartTemperature { get; set; } = 0.5f;


		public float JumpActionHeatGained { get; set; }

		public float SprintActionHeatGained { get; set; }

		public float CrouchActionHeatGained { get; set; }

		public float StandingActionHeatGained { get; set; }

		public float LadderClimbingActionHeatGained { get; set; }

		public List<TemperatureZoneDefinition> Zones { get; set; } = new List<TemperatureZoneDefinition>
		{
			new TemperatureZoneDefinition()
		};


		public List<TemperatureSetting> Settings { get; set; } = new List<TemperatureSetting>
		{
			new TemperatureSetting()
		};

	}
}
namespace EOSExt.EnvTemperature.Components
{
	public class PlayerTemperatureManager : MonoBehaviour
	{
		public const float DEFAULT_PLAYER_TEMPERATURE = 0.5f;

		public const float TEMPERATURE_SETTING_UPDATE_TIME = 1f;

		public const float TEMPERATURE_FLUCTUATE_TIME = 1f;

		private float m_tempSettingLastUpdateTime;

		private float m_lastDamageTime;

		private float m_tempFluctuateTime;

		private bool m_ShowDamageWarning = true;

		private TextMeshPro m_TemperatureText;

		private const string DEFAULT_GUI_TEXT = "SUIT TEMP: <color=orange>{0}</color>";

		private string m_GUIText = "SUIT TEMP: <color=orange>{0}</color>";

		private readonly Color m_lowTempColor = new Color(0f, 0.5f, 0.5f);

		private readonly Color m_midTempColor = new Color(1f, 0.64f, 0f);

		private readonly Color m_highTempColor = new Color(1f, 0.07f, 0.576f);

		public PlayerAgent PlayerAgent { get; private set; }

		public TemperatureDefinition? TemperatureDef { get; private set; }

		public TemperatureSetting? TemperatureSetting { get; private set; }

		public float PlayerTemperature { get; private set; } = 0.5f;


		internal void Setup()
		{
			TemperatureDef = null;
			PlayerAgent = ((Component)this).gameObject.GetComponent<PlayerAgent>();
			LevelAPI.OnBuildDone += OnBuildDone;
			LevelAPI.OnEnterLevel += OnEnterLevel;
		}

		private void OnDestroy()
		{
			Object.Destroy((Object)(object)m_TemperatureText);
			LevelAPI.OnBuildDone -= OnBuildDone;
			LevelAPI.OnEnterLevel -= OnEnterLevel;
		}

		private void SetupGUI()
		{
			//IL_0065: Unknown result type (might be due to invalid IL or missing references)
			//IL_008e: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b7: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)m_TemperatureText == (Object)null)
			{
				m_TemperatureText = Object.Instantiate<TextMeshPro>(GuiManager.PlayerLayer.m_objectiveTimer.m_titleText);
				m_TemperatureText.transform.SetParent(((Component)GuiManager.PlayerLayer.m_playerStatus).gameObject.transform, false);
				((Component)m_TemperatureText).GetComponent<RectTransform>().anchoredPosition = new Vector2(-5f, 8f);
				((Component)m_TemperatureText).gameObject.transform.localPosition = new Vector3(268.2203f, 25.3799f, 0f);
				((Component)m_TemperatureText).gameObject.transform.localScale = new Vector3(0.75f, 0.75f, 0.75f);
			}
			((Component)m_TemperatureText).gameObject.SetActive(TemperatureDef != null);
		}

		internal void UpdateGUIText()
		{
			TextDataBlock block = GameDataBlockBase<TextDataBlock>.GetBlock("EnvTemperature.Text");
			m_GUIText = ((block != null) ? Text.Get(((GameDataBlockBase<TextDataBlock>)(object)block).persistentID) : "SUIT TEMP: <color=orange>{0}</color>");
		}

		private void UpdateGui()
		{
			//IL_0090: Unknown result type (might be due to invalid IL or missing references)
			//IL_0096: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a7: Unknown result type (might be due to invalid IL or missing references)
			//IL_0060: Unknown result type (might be due to invalid IL or missing references)
			//IL_0066: Unknown result type (might be due to invalid IL or missing references)
			//IL_007d: Unknown result type (might be due to invalid IL or missing references)
			if (TemperatureDef != null)
			{
				((Component)m_TemperatureText).gameObject.SetActive(true);
				((TMP_Text)m_TemperatureText).SetText(string.Format(m_GUIText, (PlayerTemperature * 100f).ToString("N0")), true);
				if (PlayerTemperature > 0.5f)
				{
					((Graphic)m_TemperatureText).color = Color.Lerp(m_midTempColor, m_highTempColor, (PlayerTemperature - 0.5f) * 2f);
				}
				else
				{
					((Graphic)m_TemperatureText).color = Color.Lerp(m_lowTempColor, m_midTempColor, PlayerTemperature * 2f);
				}
				((TMP_Text)m_TemperatureText).ForceMeshUpdate(false, false);
			}
			else
			{
				((Component)m_TemperatureText).gameObject.SetActive(false);
			}
		}

		private void UpdateMoveSpeed()
		{
			if (TemperatureSetting == null || TemperatureSetting.SlowDownMultiplier_Move <= 0f)
			{
				Patches_PLOC.ResetMoveSpeedModifier();
			}
			else
			{
				Patches_PLOC.SetMoveSpeedModifier(TemperatureSetting.SlowDownMultiplier_Move);
			}
		}

		private void ResetMoveSpeed()
		{
			Patches_PLOC.ResetMoveSpeedModifier();
		}

		public void UpdateTemperatureDefinition(TemperatureDefinition def)
		{
			TemperatureDef = def;
			TemperatureSetting = null;
			PlayerTemperature = def?.StartTemperature ?? 0.5f;
		}

		private void OnBuildDone()
		{
			UpdateTemperatureDefinition(((GenericDefinitionManager<TemperatureDefinition>)TemperatureDefinitionManager.Current).GetDefinition(RundownManager.ActiveExpedition.LevelLayoutData)?.Definition ?? null);
		}

		private void OnEnterLevel()
		{
			PlayerTemperature = ((TemperatureDef != null) ? TemperatureDef.StartTemperature : 0.5f);
			UpdateGUIText();
			SetupGUI();
			ResetMoveSpeed();
		}

		private void DealDamage()
		{
			if (TemperatureSetting != null && !(TemperatureSetting.Damage < 0f) && !(Time.time - m_lastDamageTime < TemperatureSetting.DamageTick))
			{
				Patch_Dam_PlayerDamageBase.s_disableDialog = true;
				((Dam_SyncedDamageBase)PlayerAgent.Damage).FallDamage(TemperatureSetting.Damage);
				Patch_Dam_PlayerDamageBase.s_disableDialog = false;
				m_lastDamageTime = Time.time;
			}
		}

		private void UpdateTemperatureSettings()
		{
			if (Time.time - m_tempSettingLastUpdateTime < 1f)
			{
				return;
			}
			if (!TemperatureDefinitionManager.Current.TryGetLevelTemperatureSettings(out var settings))
			{
				TemperatureSetting = null;
				return;
			}
			int num = 0;
			int num2 = settings.Count - 1;
			float playerTemperature = PlayerTemperature;
			while (num < num2)
			{
				int num3 = (num + num2) / 2;
				float temperature = settings[num3].Temperature;
				float num4 = ((num3 + 1 < settings.Count) ? settings[num3 + 1].Temperature : 1f);
				if (temperature <= playerTemperature && playerTemperature < num4)
				{
					break;
				}
				if (playerTemperature < temperature)
				{
					num2 = num3 - 1;
				}
				else
				{
					num = num3 + 1;
				}
			}
			TemperatureSetting = settings[Math.Clamp((num + num2) / 2, 0, settings.Count - 1)];
			m_tempSettingLastUpdateTime = Time.time;
		}

		private void Update()
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Invalid comparison between Unknown and I4
			//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_0078: Unknown result type (might be due to invalid IL or missing references)
			//IL_007d: Unknown result type (might be due to invalid IL or missing references)
			//IL_007f: Unknown result type (might be due to invalid IL or missing references)
			//IL_00aa: Expected I4, but got Unknown
			//IL_01b3: Unknown result type (might be due to invalid IL or missing references)
			//IL_01bf: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c6: Unknown result type (might be due to invalid IL or missing references)
			if ((int)GameStateManager.CurrentStateName != 10 || TemperatureDef == null || (Object)(object)PlayerAgent == (Object)null)
			{
				return;
			}
			Vector3 lastMoveDelta = PlayerAgent.Locomotion.LastMoveDelta;
			float num = ((Vector3)(ref lastMoveDelta)).magnitude / Clock.FixedDelta;
			float num2 = (PlayerAgent.PlayerData.walkMoveSpeed + PlayerAgent.PlayerData.runMoveSpeed) * 0.5f;
			float num3 = 0f;
			PLOC_State currentStateEnum = PlayerAgent.Locomotion.m_currentStateEnum;
			switch ((int)currentStateEnum)
			{
			case 0:
				num3 = TemperatureDef.StandingActionHeatGained * Time.deltaTime;
				break;
			case 1:
				num3 = ((!(num <= num2)) ? ((TemperatureDef.CrouchActionHeatGained + TemperatureDef.SprintActionHeatGained) * Time.deltaTime) : (TemperatureDef.CrouchActionHeatGained * Time.deltaTime));
				break;
			case 2:
				num3 = TemperatureDef.SprintActionHeatGained * Time.deltaTime;
				break;
			case 3:
				num3 = ((!(num <= num2)) ? ((TemperatureDef.JumpActionHeatGained + TemperatureDef.SprintActionHeatGained) * Time.deltaTime) : (TemperatureDef.JumpActionHeatGained * Time.deltaTime));
				break;
			case 7:
				num3 = 0f;
				break;
			case 8:
				num3 = TemperatureDef.LadderClimbingActionHeatGained * Time.deltaTime;
				break;
			}
			if ((double)num3 < 1E-05)
			{
				if (Time.time - m_tempFluctuateTime > 1f)
				{
					float num4 = TemperatureDef.StartTemperature;
					LG_Zone zone = ((Agent)PlayerAgent).CourseNode.m_zone;
					if (TemperatureDefinitionManager.Current.TryGetZoneDefinition(zone.DimensionIndex, zone.Layer.m_type, zone.LocalIndex, out var def))
					{
						num4 = def.Temperature;
					}
					float num5 = def.DecreaseRate * Random.RandomRange(0f, 1f);
					if (PlayerTemperature > num4)
					{
						PlayerTemperature -= num5;
					}
					else
					{
						PlayerTemperature += num5;
					}
					m_tempFluctuateTime = Time.time;
				}
			}
			else
			{
				m_tempFluctuateTime = Time.time;
			}
			PlayerTemperature += num3;
			UpdateTemperatureSettings();
			TemperatureSetting? temperatureSetting = TemperatureSetting;
			if (temperatureSetting != null && temperatureSetting.Damage > 0f)
			{
				DealDamage();
			}
			UpdateGui();
			UpdateMoveSpeed();
		}

		public static bool TryGetCurrentManager(out PlayerTemperatureManager mgr)
		{
			mgr = null;
			LocalPlayerAgent val = default(LocalPlayerAgent);
			if (!LocalPlayer.TryGetLocalAgent(ref val))
			{
				EOSLogger.Debug("Temperature: cannot get localplayeragent");
				return false;
			}
			mgr = ((Component)val).gameObject.GetComponent<PlayerTemperatureManager>();
			if ((Object)(object)val == (Object)null)
			{
				EOSLogger.Error("LocalPlayerAgent does not have `PlayerTemperatureManager`!");
				return false;
			}
			return true;
		}

		public static TemperatureSetting? GetCurrentTemperatureSetting()
		{
			if (!TryGetCurrentManager(out var mgr))
			{
				return null;
			}
			return mgr.TemperatureSetting;
		}

		static PlayerTemperatureManager()
		{
			ClassInjector.RegisterTypeInIl2Cpp<PlayerTemperatureManager>();
		}
	}
}

plugins/TrickyBall's Paradise/Custom/ForLegacy/net6/Inas07.ThermalSights.dll

Decompiled 8 months ago
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using System.Text.Json.Serialization;
using AssetShards;
using BepInEx;
using BepInEx.Unity.IL2CPP;
using ChainedPuzzles;
using ExtraObjectiveSetup.BaseClasses;
using ExtraObjectiveSetup.Expedition.Gears;
using ExtraObjectiveSetup.Utils;
using FirstPersonItem;
using GTFO.API;
using GTFO.API.Utilities;
using GameData;
using HarmonyLib;
using Il2CppInterop.Runtime.InteropTypes.Arrays;
using Il2CppSystem;
using Microsoft.CodeAnalysis;
using ThermalSights.Definition;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETCoreApp,Version=v6.0", FrameworkDisplayName = ".NET 6.0")]
[assembly: AssemblyCompany("Inas07.ThermalSights")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0")]
[assembly: AssemblyProduct("Inas07.ThermalSights")]
[assembly: AssemblyTitle("Inas07.ThermalSights")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.0.0.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace ThermalSights
{
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInPlugin("Inas.ThermalSights", "ThermalSights", "1.0.0")]
	public class EntryPoint : BasePlugin
	{
		public const string AUTHOR = "Inas";

		public const string PLUGIN_NAME = "ThermalSights";

		public const string VERSION = "1.0.0";

		private Harmony m_Harmony;

		public override void Load()
		{
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0016: Expected O, but got Unknown
			SetupManagers();
			m_Harmony = new Harmony("ThermalSights");
			m_Harmony.PatchAll();
			EOSLogger.Log("ThermalSights loaded.");
		}

		private void SetupManagers()
		{
			AssetShardManager.OnStartupAssetsLoaded += Action.op_Implicit((Action)delegate
			{
				((GenericDefinitionManager<TSADefinition>)TSAManager.Current).Init();
			});
		}
	}
	public class TSAManager : GenericDefinitionManager<TSADefinition>
	{
		public class PuzzleVisualWrapper
		{
			public GameObject GO { get; set; }

			public Renderer Renderer { get; set; }

			public float Intensity { get; set; }

			public float BehindWallIntensity { get; set; }

			public void SetIntensity(float t)
			{
				if (GO.active)
				{
					if (Intensity > 0f)
					{
						Renderer.material.SetFloat("_Intensity", Intensity * t);
					}
					if (BehindWallIntensity > 0f)
					{
						Renderer.material.SetFloat("_BehindWallIntensity", BehindWallIntensity * t);
					}
				}
			}
		}

		private const bool OUTPUT_THERMAL_SHADER_SETTINGS_ON_WIELD = false;

		public static TSAManager Current { get; }

		protected override string DEFINITION_NAME => "ThermalSight";

		private Dictionary<uint, Renderer[]> InLevelGearThermals { get; } = new Dictionary<uint, Renderer[]>();


		private HashSet<uint> ModifiedInLevelGearThermals { get; } = new HashSet<uint>();


		private HashSet<uint> ThermalOfflineGears { get; } = new HashSet<uint>();


		public uint CurrentGearPID { get; private set; }

		private List<PuzzleVisualWrapper> PuzzleVisuals { get; } = new List<PuzzleVisualWrapper>();


		protected override void FileChanged(LiveEditEventArgs e)
		{
			base.FileChanged(e);
			InitThermalOfflineGears();
			CleanupInLevelGearThermals(keepCurrentGear: true);
			TrySetThermalSightRenderer(CurrentGearPID);
		}

		public override void Init()
		{
			InitThermalOfflineGears();
		}

		private void InitThermalOfflineGears()
		{
			ThermalOfflineGears.Clear();
			foreach (PlayerOfflineGearDataBlock allBlock in GameDataBlockBase<PlayerOfflineGearDataBlock>.GetAllBlocks())
			{
				if (((GameDataBlockBase<PlayerOfflineGearDataBlock>)(object)allBlock).name.ToLowerInvariant().EndsWith("_t"))
				{
					ThermalOfflineGears.Add(((GameDataBlockBase<PlayerOfflineGearDataBlock>)(object)allBlock).persistentID);
				}
			}
			EOSLogger.Debug($"Found OfflineGear with thermal sight, count: {ThermalOfflineGears.Count}");
		}

		private bool TryGetInLevelGearThermalRenderersFromItem(ItemEquippable item, uint gearPID, out Renderer[] renderers)
		{
			//IL_0058: Unknown result type (might be due to invalid IL or missing references)
			renderers = null;
			if (item.GearIDRange == null)
			{
				return false;
			}
			if (gearPID == 0)
			{
				gearPID = ExpeditionGearManager.GetOfflineGearPID(item.GearIDRange);
			}
			if (gearPID == 0 || !IsGearWithThermal(gearPID))
			{
				return false;
			}
			bool flag = false;
			if (!InLevelGearThermals.ContainsKey(gearPID))
			{
				flag = true;
			}
			else
			{
				try
				{
					_ = ((Component)InLevelGearThermals[gearPID][0]).gameObject.transform.position;
					flag = false;
				}
				catch
				{
					ModifiedInLevelGearThermals.Remove(gearPID);
					flag = true;
				}
			}
			if (flag)
			{
				renderers = (from x in ((IEnumerable<Renderer>)((Component)item).GetComponentsInChildren<Renderer>(true))?.Where((Renderer x) => (Object)(object)x.sharedMaterial != (Object)null && (Object)(object)x.sharedMaterial.shader != (Object)null)
					where ((Object)x.sharedMaterial.shader).name.ToLower().Contains("Thermal".ToLower())
					select x).ToArray() ?? null;
				if (renderers != null)
				{
					if (renderers.Length != 1)
					{
						EOSLogger.Warning(((Item)item).PublicName + " contains more than 1 thermal renderers!");
					}
					InLevelGearThermals[gearPID] = renderers;
					return true;
				}
				EOSLogger.Debug(((Item)item).PublicName + ": thermal renderer not found");
				return false;
			}
			renderers = InLevelGearThermals[gearPID];
			return true;
		}

		internal bool TrySetThermalSightRenderer(uint gearPID = 0u)
		{
			//IL_00fe: Unknown result type (might be due to invalid IL or missing references)
			//IL_0105: Expected O, but got Unknown
			//IL_0110: Unknown result type (might be due to invalid IL or missing references)
			//IL_0115: Unknown result type (might be due to invalid IL or missing references)
			//IL_017e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0185: Expected O, but got Unknown
			//IL_0190: Unknown result type (might be due to invalid IL or missing references)
			if (gearPID == 0)
			{
				gearPID = CurrentGearPID;
			}
			if (!IsGearWithThermal(gearPID))
			{
				return false;
			}
			if (ModifiedInLevelGearThermals.Contains(gearPID))
			{
				return true;
			}
			if (base.definitions.TryGetValue(gearPID, out var value) && InLevelGearThermals.TryGetValue(gearPID, out var value2))
			{
				TSShader shader = value.Definition.Shader;
				Renderer[] array = value2;
				foreach (Renderer val in array)
				{
					PropertyInfo[] properties = shader.GetType().GetProperties();
					foreach (PropertyInfo propertyInfo in properties)
					{
						Type type = Nullable.GetUnderlyingType(propertyInfo.PropertyType) ?? propertyInfo.PropertyType;
						string text = "_" + propertyInfo.Name;
						if (type == typeof(float))
						{
							val.material.SetFloat(text, (float)propertyInfo.GetValue(shader));
						}
						else if (type == typeof(EOSColor))
						{
							EOSColor val2 = (EOSColor)propertyInfo.GetValue(shader);
							val.material.SetVector(text, Color.op_Implicit(val2.ToUnityColor()));
						}
						else if (type == typeof(bool))
						{
							bool flag = (bool)propertyInfo.GetValue(shader);
							val.material.SetFloat(text, flag ? 1f : 0f);
						}
						else if (type == typeof(Vec4))
						{
							Vec4 val3 = (Vec4)propertyInfo.GetValue(shader);
							val.material.SetVector(text, val3.ToVector4());
						}
					}
				}
				ModifiedInLevelGearThermals.Add(gearPID);
				return true;
			}
			return false;
		}

		internal void OnPlayerItemWielded(FirstPersonItemHolder fpsItemHolder, ItemEquippable item)
		{
			if (item.GearIDRange == null)
			{
				CurrentGearPID = 0u;
				return;
			}
			CurrentGearPID = ExpeditionGearManager.GetOfflineGearPID(item.GearIDRange);
			TryGetInLevelGearThermalRenderersFromItem(item, CurrentGearPID, out var _);
			TrySetThermalSightRenderer(CurrentGearPID);
		}

		public bool IsGearWithThermal(uint gearPID)
		{
			return ThermalOfflineGears.Contains(gearPID);
		}

		private void CleanupInLevelGearThermals(bool keepCurrentGear = false)
		{
			if (!keepCurrentGear || !InLevelGearThermals.ContainsKey(CurrentGearPID))
			{
				InLevelGearThermals.Clear();
			}
			else
			{
				Renderer[] value = InLevelGearThermals[CurrentGearPID];
				InLevelGearThermals.Clear();
				InLevelGearThermals[CurrentGearPID] = value;
			}
			ModifiedInLevelGearThermals.Clear();
		}

		internal void SetCurrentThermalSightSettings(float t)
		{
			if (InLevelGearThermals.TryGetValue(CurrentGearPID, out var value) && base.definitions.TryGetValue(CurrentGearPID, out var value2))
			{
				Renderer[] array = value;
				foreach (Renderer obj in array)
				{
					float zoom = value2.Definition.Shader.Zoom;
					float offAimPixelZoom = value2.Definition.OffAimPixelZoom;
					float num = Mathf.Lerp(zoom, offAimPixelZoom, t);
					obj.material.SetFloat("_Zoom", num);
				}
			}
		}

		private void Clear()
		{
			CurrentGearPID = 0u;
			CleanupInLevelGearThermals();
			CleanupPuzzleVisuals();
		}

		private TSAManager()
		{
			LevelAPI.OnBuildStart += Clear;
			LevelAPI.OnLevelCleanup += Clear;
		}

		static TSAManager()
		{
			Current = new TSAManager();
		}

		public void RegisterPuzzleVisual(CP_Bioscan_Core core)
		{
			Il2CppArrayBase<Renderer> componentsInChildren = ((Component)core).gameObject.GetComponentsInChildren<Renderer>(true);
			if (componentsInChildren == null)
			{
				return;
			}
			foreach (Renderer item2 in ((IEnumerable<Renderer>)componentsInChildren).Where((Renderer comp) => ((Object)((Component)comp).gameObject).name.Equals("Zone")).ToList())
			{
				GameObject gameObject = ((Component)item2).gameObject;
				float @float = item2.material.GetFloat("_Intensity");
				float float2 = item2.material.GetFloat("_BehindWallIntensity");
				PuzzleVisualWrapper item = new PuzzleVisualWrapper
				{
					GO = gameObject,
					Renderer = item2,
					Intensity = @float,
					BehindWallIntensity = float2
				};
				PuzzleVisuals.Add(item);
			}
		}

		public void RegisterPuzzleVisual(PuzzleVisualWrapper wrapper)
		{
			PuzzleVisuals.Add(wrapper);
		}

		internal void SetPuzzleVisualsIntensity(float t)
		{
			PuzzleVisuals.ForEach(delegate(PuzzleVisualWrapper v)
			{
				v.SetIntensity(t);
			});
		}

		private void CleanupPuzzleVisuals()
		{
			PuzzleVisuals.Clear();
		}
	}
}
namespace ThermalSights.Patches
{
	internal static class CP_Bioscan_Core_Setup
	{
		[HarmonyPostfix]
		[HarmonyPatch(typeof(CP_Bioscan_Core), "Setup")]
		private static void Post_CaptureBioscanVisual(CP_Bioscan_Core __instance)
		{
			TSAManager.Current.RegisterPuzzleVisual(__instance);
		}
	}
	[HarmonyPatch]
	internal static class FirstPersonItemHolder_SetWieldedItem
	{
		public static event Action<FirstPersonItemHolder, ItemEquippable> OnItemWielded;

		[HarmonyPostfix]
		[HarmonyPatch(typeof(FirstPersonItemHolder), "SetWieldedItem")]
		private static void Post_SetWieldedItem(FirstPersonItemHolder __instance, ItemEquippable item)
		{
			TSAManager.Current.OnPlayerItemWielded(__instance, item);
			TSAManager.Current.SetPuzzleVisualsIntensity(1f);
			TSAManager.Current.SetCurrentThermalSightSettings(1f);
			FirstPersonItemHolder_SetWieldedItem.OnItemWielded?.Invoke(__instance, item);
		}
	}
	[HarmonyPatch]
	internal static class FPIS_Aim_Update
	{
		public static event Action<FPIS_Aim, float> OnAimUpdate;

		[HarmonyPostfix]
		[HarmonyPatch(typeof(FPIS_Aim), "Update")]
		private static void Post_Aim_Update(FPIS_Aim __instance)
		{
			if (!((Object)(object)((FPItemState)__instance).Holder.WieldedItem == (Object)null))
			{
				float num = 1f - FirstPersonItemHolder.m_transitionDelta;
				if (!TSAManager.Current.IsGearWithThermal(TSAManager.Current.CurrentGearPID))
				{
					num = Math.Max(0.05f, num);
				}
				else
				{
					TSAManager.Current.SetCurrentThermalSightSettings(num);
				}
				TSAManager.Current.SetPuzzleVisualsIntensity(num);
				FPIS_Aim_Update.OnAimUpdate?.Invoke(__instance, num);
			}
		}
	}
}
namespace ThermalSights.Definition
{
	public class TSADefinition
	{
		public float OffAimPixelZoom { get; set; } = 1f;


		public TSShader Shader { get; set; } = new TSShader();

	}
	public class TSShader
	{
		[JsonPropertyName("DistanceFalloff")]
		[Range(0.0, 1.0)]
		public float HeatFalloff { get; set; } = 0.01f;


		[Range(0.0, 1.0)]
		public float FogFalloff { get; set; } = 0.1f;


		[JsonPropertyName("PixelZoom")]
		[Range(0.0, 1.0)]
		public float Zoom { get; set; } = 0.8f;


		[JsonPropertyName("AspectRatioAdjust")]
		[Range(0.0, 2.0)]
		public float RatioAdjust { get; set; } = 1f;


		[Range(0.0, 1.0)]
		public float DistortionCenter { get; set; } = 0.5f;


		public float DistortionScale { get; set; } = 1f;


		public float DistortionSpeed { get; set; } = 1f;


		public float DistortionSignalSpeed { get; set; } = 0.025f;


		[Range(0.0, 1.0)]
		public float DistortionMin { get; set; } = 0.01f;


		[Range(0.0, 1.0)]
		public float DistortionMax { get; set; } = 0.4f;


		[JsonPropertyName("AmbientTemperature")]
		[Range(0.0, 1.0)]
		public float AmbientTemp { get; set; } = 0.15f;


		[JsonPropertyName("BackgroundTemperature")]
		[Range(0.0, 1.0)]
		public float BackgroundTemp { get; set; } = 0.05f;


		[Range(0.0, 10.0)]
		public float AlbedoColorFactor { get; set; } = 0.5f;


		[Range(0.0, 10.0)]
		public float AmbientColorFactor { get; set; } = 5f;


		public float OcclusionHeat { get; set; } = 0.5f;


		public float BodyOcclusionHeat { get; set; } = 2.5f;


		[Range(0.0, 1.0)]
		public float ScreenIntensity { get; set; } = 0.2f;


		[Range(0.0, 1.0)]
		public float OffAngleFade { get; set; } = 0.95f;


		[Range(0.0, 1.0)]
		public float Noise { get; set; } = 0.1f;


		[JsonPropertyName("MinShadowEnemyDistortion")]
		[Range(0.0, 1.0)]
		public float DistortionMinShadowEnemies { get; set; } = 0.2f;


		[JsonPropertyName("MaxShadowEnemyDistortion")]
		[Range(0.0, 1.0)]
		public float DistortionMaxShadowEnemies { get; set; } = 1f;


		[Range(0.0, 1.0)]
		public float DistortionSignalSpeedShadowEnemies { get; set; } = 1f;


		public float ShadowEnemyFresnel { get; set; } = 10f;


		[Range(0.0, 1.0)]
		public float ShadowEnemyHeat { get; set; } = 0.1f;


		public EOSColor ReticuleColorA { get; set; } = new EOSColor
		{
			r = 1f,
			g = 1f,
			b = 1f,
			a = 1f
		};


		public EOSColor ReticuleColorB { get; set; } = new EOSColor
		{
			r = 1f,
			g = 1f,
			b = 1f,
			a = 1f
		};


		public EOSColor ReticuleColorC { get; set; } = new EOSColor
		{
			r = 1f,
			g = 1f,
			b = 1f,
			a = 1f
		};


		[Range(0.0, 20.0)]
		public float SightDirt { get; set; }

		public bool LitGlass { get; set; }

		public bool ClipBorders { get; set; } = true;


		public Vec4 AxisX { get; set; } = new Vec4();


		public Vec4 AxisY { get; set; } = new Vec4();


		public Vec4 AxisZ { get; set; } = new Vec4();


		public bool Flip { get; set; } = true;


		[JsonPropertyName("Distance1")]
		[Range(0.0, 100.0)]
		public float ProjDist1 { get; set; } = 100f;


		[JsonPropertyName("Distance2")]
		[Range(0.0, 100.0)]
		public float ProjDist2 { get; set; } = 66f;


		[JsonPropertyName("Distance3")]
		[Range(0.0, 100.0)]
		public float ProjDist3 { get; set; } = 33f;


		[JsonPropertyName("Size1")]
		[Range(0.0, 3.0)]
		public float ProjSize1 { get; set; } = 1f;


		[JsonPropertyName("Size2")]
		[Range(0.0, 3.0)]
		public float ProjSize2 { get; set; } = 1f;


		[JsonPropertyName("Size3")]
		[Range(0.0, 3.0)]
		public float ProjSize3 { get; set; } = 1f;


		[JsonPropertyName("Zeroing")]
		[Range(-1.0, 1.0)]
		public float ZeroOffset { get; set; }
	}
}

plugins/TrickyBall's Paradise/Custom/ForLegacy/net6/LEGACY.dll

Decompiled 8 months ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using System.Text;
using AIGraph;
using AK;
using Agents;
using AssetShards;
using BepInEx;
using BepInEx.Logging;
using BepInEx.Unity.IL2CPP;
using BepInEx.Unity.IL2CPP.Utils.Collections;
using BoosterImplants;
using CellMenu;
using ChainedPuzzles;
using EOSExt.Reactor.Managers;
using Enemies;
using ExtraObjectiveSetup;
using ExtraObjectiveSetup.BaseClasses;
using ExtraObjectiveSetup.ExtendedWardenEvents;
using ExtraObjectiveSetup.Instances;
using ExtraObjectiveSetup.JSON;
using ExtraObjectiveSetup.Utils;
using FloLib.Infos;
using FloLib.Networks.Replications;
using GTFO.API;
using GTFO.API.Utilities;
using GameData;
using GameEvent;
using Gear;
using HarmonyLib;
using Il2CppInterop.Runtime.Injection;
using Il2CppInterop.Runtime.InteropTypes;
using Il2CppInterop.Runtime.InteropTypes.Arrays;
using Il2CppSystem;
using Il2CppSystem.Collections.Generic;
using LEGACY.ExtraEvents;
using LEGACY.ExtraEvents.Patches;
using LEGACY.LegacyOverride;
using LEGACY.LegacyOverride.DummyVisual;
using LEGACY.LegacyOverride.DummyVisual.VisualGOAnimation;
using LEGACY.LegacyOverride.DummyVisual.VisualGOAnimation.AnimationConfig;
using LEGACY.LegacyOverride.DummyVisual.VisualSequenceType;
using LEGACY.LegacyOverride.ElevatorCargo;
using LEGACY.LegacyOverride.EnemyTagger;
using LEGACY.LegacyOverride.EventScan;
using LEGACY.LegacyOverride.ExpeditionIntelNotification;
using LEGACY.LegacyOverride.ExpeditionSuccessPage;
using LEGACY.LegacyOverride.FogBeacon;
using LEGACY.LegacyOverride.ForceFail;
using LEGACY.LegacyOverride.Music;
using LEGACY.LegacyOverride.ResourceStations;
using LEGACY.LegacyOverride.Restart;
using LEGACY.Utils;
using LEGACY.VanillaFix;
using LevelGeneration;
using Localization;
using MTFO.API;
using Microsoft.CodeAnalysis;
using Player;
using SNetwork;
using ScanPosOverride.Managers;
using StateMachines;
using TMPro;
using ThermalSights;
using UnityEngine;
using UnityEngine.UI;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: TargetFramework(".NETCoreApp,Version=v6.0", FrameworkDisplayName = ".NET 6.0")]
[assembly: AssemblyCompany("LEGACY")]
[assembly: AssemblyConfiguration("Debug")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0")]
[assembly: AssemblyProduct("LEGACY")]
[assembly: AssemblyTitle("LEGACY")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.0.0.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
[HarmonyPatch(typeof(PUI_Watermark), "UpdateWatermark")]
internal static class Patch_WatermarkUpdateWatermark
{
	private static void Postfix(PUI_Watermark __instance)
	{
		string text = "4.6.2+git44e73d7-dirty-main".Remove("x.x.x".Length);
		((TMP_Text)__instance.m_watermarkText).SetText("<color=red>MODDED</color> <color=orange>" + text + "</color>\n<color=red>NOT</color> <#ff3919>criscriscris</color>", true);
	}
}
namespace LEGACY
{
	internal static class Assets
	{
		public static GameObject CircleSensor { get; private set; }

		public static GameObject MovableSensor { get; private set; }

		public static GameObject OBSVisual { get; private set; }

		public static GameObject ObjectiveMarker { get; private set; }

		public static GameObject EventScan { get; private set; }

		internal static GameObject DummyScan { get; private set; }

		internal static GameObject DummySensor { get; private set; }

		internal static GameObject AmmoStation { get; private set; }

		internal static GameObject MediStation { get; private set; }

		internal static GameObject ToolStation { get; private set; }

		internal static GameObject RestartPage { get; private set; }

		public static void Init()
		{
			CircleSensor = AssetAPI.GetLoadedAsset<GameObject>("Assets/SecuritySensor/CircleSensor.prefab");
			MovableSensor = AssetAPI.GetLoadedAsset<GameObject>("Assets/SecuritySensor/MovableSensor.prefab");
			OBSVisual = AssetAPI.GetLoadedAsset<GameObject>("Assets/SecuritySensor/OBSVisual.prefab");
			ObjectiveMarker = AssetAPI.GetLoadedAsset<GameObject>("Assets/SecuritySensor/ObjectiveMarker.prefab");
			EventScan = AssetAPI.GetLoadedAsset<GameObject>("Assets/EventObjects/EventScan.prefab");
			DummyScan = AssetAPI.GetLoadedAsset<GameObject>("Assets/DummyVisual/DummyScan.prefab");
			DummySensor = AssetAPI.GetLoadedAsset<GameObject>("Assets/DummyVisual/DummySensor.prefab");
			AmmoStation = AssetAPI.GetLoadedAsset<GameObject>("Assets/Misc/AmmoStation.prefab");
			MediStation = AssetAPI.GetLoadedAsset<GameObject>("Assets/Misc/MediStation.prefab");
			ToolStation = AssetAPI.GetLoadedAsset<GameObject>("Assets/Misc/ToolStation.prefab");
			RestartPage = AssetAPI.GetLoadedAsset<GameObject>("Assets/Misc/CM_PageRestart_CellUI.prefab");
		}
	}
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInPlugin("Inas.LEGACY", "LEGACY", "4.4.4")]
	public class EntryPoint : BasePlugin
	{
		public const string AUTHOR = "Inas";

		public const string RUNDOWN_NAME = "LEGACY";

		public const string VERSION = "4.4.4";

		public const bool TESTING = false;

		public const string TEST_STRING = "TESTING";

		private Harmony m_Harmony;

		public override void Load()
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_0011: Expected O, but got Unknown
			m_Harmony = new Harmony("LEGACY");
			m_Harmony.PatchAll();
			LegacyOverrideManagers.Init();
			LegacyExtraEvents.Init();
			LEGACY.VanillaFix.Debugger.Current.Init();
			AssetAPI.OnAssetBundlesLoaded += Assets.Init;
			EventAPI.OnManagersSetup += delegate
			{
				AssetShardManager.OnStartupAssetsLoaded += Action.op_Implicit((Action)MainMenuGuiLayer.Current.PageRundownNew.SetupCustomTutorialButton);
			};
		}
	}
}
namespace LEGACY.Reactor
{
	[HarmonyPatch]
	internal class Patch_ReactorShutdown
	{
		[HarmonyPostfix]
		[HarmonyPatch(typeof(LG_WardenObjective_Reactor), "OnStateChange")]
		private static void Post_OnStateChange(LG_WardenObjective_Reactor __instance, pReactorState oldState, pReactorState newState)
		{
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			//IL_0018: 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_006c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0072: Invalid comparison between Unknown and I4
			//IL_008e: 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_0090: Unknown result type (might be due to invalid IL or missing references)
			//IL_0095: Unknown result type (might be due to invalid IL or missing references)
			//IL_0097: Unknown result type (might be due to invalid IL or missing references)
			//IL_0099: Unknown result type (might be due to invalid IL or missing references)
			//IL_009b: Unknown result type (might be due to invalid IL or missing references)
			//IL_009e: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b0: Expected I4, but got Unknown
			//IL_00b3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bb: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cb: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d2: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)__instance == (Object)null || oldState.status == newState.status)
			{
				return;
			}
			WardenObjectiveDataBlock val = null;
			if (!WardenObjectiveManager.Current.TryGetActiveWardenObjectiveData(__instance.SpawnNode.LayerType, ref val) || val == null)
			{
				LegacyLogger.Error("Patch_ReactorShutdown: ");
				LegacyLogger.Error("Failed to get warden objective");
			}
			else if ((int)val.Type == 2 && !val.OnActivateOnSolveItem)
			{
				eWardenObjectiveEventTrigger val2 = (eWardenObjectiveEventTrigger)0;
				eReactorStatus status = newState.status;
				eReactorStatus val3 = status;
				switch (val3 - 7)
				{
				default:
					return;
				case 0:
					val2 = (eWardenObjectiveEventTrigger)1;
					break;
				case 1:
					val2 = (eWardenObjectiveEventTrigger)2;
					break;
				case 2:
					val2 = (eWardenObjectiveEventTrigger)3;
					break;
				}
				LG_LayerType layerType = __instance.SpawnNode.LayerType;
				WardenObjectiveManager.CheckAndExecuteEventsOnTrigger(val.EventsOnActivate, val2, false, 0f, (Il2CppStructArray<eWardenObjectiveEventType>)null);
			}
		}

		[HarmonyPrefix]
		[HarmonyPatch(typeof(LG_WardenObjective_Reactor), "OnBuildDone")]
		private static void Pre_OnBuildDone_ChainedPuzzleMidObjectiveFix(LG_WardenObjective_Reactor __instance)
		{
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			WardenObjectiveDataBlock val = null;
			if (!WardenObjectiveManager.Current.TryGetActiveWardenObjectiveData(__instance.SpawnNode.LayerType, ref val) || val == null)
			{
				LegacyLogger.Error("Patch_ReactorShutdown: Failed to get warden objective");
			}
			else if (val.ChainedPuzzleMidObjective != 0)
			{
				__instance.m_chainedPuzzleAlignMidObjective = __instance.m_chainedPuzzleAlign;
			}
		}

		[HarmonyPrefix]
		[HarmonyPatch(typeof(LG_WardenObjective_Reactor), "Update")]
		private static bool Pre_Update(LG_WardenObjective_Reactor __instance)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_000d: Invalid comparison between Unknown and I4
			if ((int)__instance.m_currentState.status != 7)
			{
				return true;
			}
			if (!__instance.m_currentWaveData.HasVerificationTerminal)
			{
				return true;
			}
			__instance.SetGUIMessage(true, Text.Format(3000u, (Object[])(object)new Object[1] { Object.op_Implicit("<color=orange>" + __instance.m_currentWaveData.VerificationTerminalSerial + "</color>") }), (ePUIMessageStyle)3, false, "", "");
			return false;
		}
	}
	[HarmonyPatch]
	internal class Patch_ReactorStartup_ExtraEventsExecution
	{
		[HarmonyPostfix]
		[HarmonyPatch(typeof(LG_WardenObjective_Reactor), "OnStateChange")]
		private static void Post_ExecuteOnNoneEventsOnDefenseStart(LG_WardenObjective_Reactor __instance, pReactorState oldState, pReactorState newState)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			//IL_001c: Invalid comparison between Unknown and I4
			if (oldState.status != newState.status && (int)newState.status == 3)
			{
				WardenObjectiveManager.CheckAndExecuteEventsOnTrigger(__instance.m_currentWaveData.Events, (eWardenObjectiveEventTrigger)0, false, 0f, (Il2CppStructArray<eWardenObjectiveEventType>)null);
			}
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(LG_WardenObjective_Reactor), "OnBuildDone")]
		private static void Post_OnBuildDone(LG_WardenObjective_Reactor __instance)
		{
			//IL_0012: 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: Invalid comparison between Unknown and I4
			WardenObjectiveDataBlock db = default(WardenObjectiveDataBlock);
			if (!WardenObjectiveManager.Current.TryGetActiveWardenObjectiveData(__instance.SpawnNode.LayerType, ref db) || db == null)
			{
				LegacyLogger.Error("Patch_ReactorStartup_ExtraEventsExecution: ");
				LegacyLogger.Error("Failed to get warden objective");
			}
			else if ((int)db.Type == 1 && !db.OnActivateOnSolveItem)
			{
				ChainedPuzzleInstance chainedPuzzleToStartSequence = __instance.m_chainedPuzzleToStartSequence;
				chainedPuzzleToStartSequence.OnPuzzleSolved += Action.op_Implicit((Action)delegate
				{
					WardenObjectiveManager.CheckAndExecuteEventsOnTrigger(db.EventsOnActivate, (eWardenObjectiveEventTrigger)0, true, 0f, (Il2CppStructArray<eWardenObjectiveEventType>)null);
				});
			}
		}
	}
	[HarmonyPatch]
	internal class Patch_ReactorStartup_OverwriteGUIBehaviour
	{
		private static HashSet<uint> ForceDisableLevels;

		[HarmonyPrefix]
		[HarmonyPatch(typeof(LG_WardenObjective_Reactor), "OnStateChange")]
		private static bool Pre_HideReactorMessageForInfiniteWave(LG_WardenObjective_Reactor __instance, pReactorState oldState, pReactorState newState)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			//IL_001a: Unknown result type (might be due to invalid IL or missing references)
			//IL_001b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0021: Invalid comparison between Unknown and I4
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002a: Invalid comparison between Unknown and I4
			//IL_002c: Unknown result type (might be due to invalid IL or missing references)
			//IL_002d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0033: Invalid comparison between Unknown and I4
			//IL_0053: Unknown result type (might be due to invalid IL or missing references)
			//IL_0059: 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_007d: Unknown result type (might be due to invalid IL or missing references)
			//IL_006b: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ab: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ad: Unknown result type (might be due to invalid IL or missing references)
			//IL_00af: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c4: Expected I4, but got Unknown
			//IL_008f: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d7: Unknown result type (might be due to invalid IL or missing references)
			//IL_02ce: Unknown result type (might be due to invalid IL or missing references)
			//IL_0310: Unknown result type (might be due to invalid IL or missing references)
			//IL_0158: Unknown result type (might be due to invalid IL or missing references)
			//IL_0215: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d9: Unknown result type (might be due to invalid IL or missing references)
			if (oldState.status == newState.status)
			{
				return true;
			}
			if ((int)newState.status != 2 && (int)newState.status != 3 && (int)newState.status != 4)
			{
				return true;
			}
			if (ForceDisable())
			{
				if (oldState.stateCount != newState.stateCount)
				{
					__instance.OnStateCountUpdate(newState.stateCount);
				}
				if (oldState.stateProgress != newState.stateProgress)
				{
					__instance.OnStateProgressUpdate(newState.stateProgress);
				}
				__instance.ReadyForVerification = false;
				eReactorStatus status = newState.status;
				eReactorStatus val = status;
				switch (val - 2)
				{
				case 0:
				{
					WardenObjectiveDataBlock val2 = null;
					if (!WardenObjectiveManager.Current.TryGetActiveWardenObjectiveData(__instance.SpawnNode.LayerType, ref val2) || val2 == null)
					{
						LegacyLogger.Error("Patch_ReactorStartup_OverwriteGUIBehaviour: ");
						LegacyLogger.Error("Failed to get warden objective datablock");
						break;
					}
					__instance.m_lightCollection.SetMode(val2.LightsOnDuringIntro);
					__instance.m_lightCollection.ResetUpdateValues(true);
					__instance.lcReset = true;
					__instance.m_lightsBlinking = false;
					__instance.m_spawnEnemies = false;
					__instance.m_progressUpdateEnabled = true;
					__instance.m_alarmCountdownPlayed = false;
					__instance.m_currentDuration = ((!newState.verifyFailed) ? __instance.m_currentWaveData.Warmup : __instance.m_currentWaveData.WarmupFail);
					WardenObjectiveManager.CheckAndExecuteEventsOnTrigger(__instance.m_currentWaveData.Events, (eWardenObjectiveEventTrigger)1, false, 0f, (Il2CppStructArray<eWardenObjectiveEventType>)null);
					if (__instance.m_currentWaveCount == 1)
					{
						Debug.LogError(Object.op_Implicit("Reactor IDLE START"));
						__instance.m_sound.Post(EVENTS.REACTOR_POWER_LEVEL_1_LOOP, true);
						__instance.m_sound.SetRTPCValue(GAME_PARAMETERS.REACTOR_POWER, 0f);
					}
					else
					{
						Debug.LogError(Object.op_Implicit("Reactor REACTOR_POWER_DOWN"));
						__instance.m_sound.Post(EVENTS.REACTOR_POWER_LEVEL_2_TO_1_TRANSITION, true);
						__instance.m_sound.SetRTPCValue(GAME_PARAMETERS.REACTOR_POWER, 0f);
					}
					break;
				}
				case 1:
					__instance.m_lightCollection.ResetUpdateValues(true);
					__instance.lcReset = true;
					__instance.m_spawnEnemies = true;
					__instance.m_currentEnemyWaveIndex = 0;
					__instance.m_alarmCountdownPlayed = false;
					__instance.m_progressUpdateEnabled = true;
					__instance.m_currentDuration = __instance.m_currentWaveData.Wave;
					__instance.m_sound.Post(EVENTS.REACTOR_POWER_LEVEL_1_TO_3_TRANSITION, true);
					break;
				case 2:
					__instance.m_lightCollection.ResetUpdateValues(false);
					__instance.lcReset = true;
					__instance.m_spawnEnemies = false;
					__instance.m_progressUpdateEnabled = true;
					__instance.ReadyForVerification = true;
					Debug.Log(Object.op_Implicit("Wait for verify! newState.verifyFailed? " + newState.verifyFailed));
					__instance.m_currentDuration = ((!newState.verifyFailed) ? __instance.m_currentWaveData.Verify : __instance.m_currentWaveData.VerifyFail);
					WardenObjectiveManager.CheckAndExecuteEventsOnTrigger(__instance.m_currentWaveData.Events, (eWardenObjectiveEventTrigger)2, false, 0f, (Il2CppStructArray<eWardenObjectiveEventType>)null);
					break;
				}
				__instance.m_currentState = newState;
				return false;
			}
			return true;
		}

		private static bool ForceDisable()
		{
			return ForceDisableLevels.Contains(RundownManager.ActiveExpedition.LevelLayoutData);
		}

		static Patch_ReactorStartup_OverwriteGUIBehaviour()
		{
			ForceDisableLevels = new HashSet<uint>();
			LevelLayoutDataBlock block = GameDataBlockBase<LevelLayoutDataBlock>.GetBlock("Legacy_L3E2_L1");
			if (block != null)
			{
				ForceDisableLevels.Add(((GameDataBlockBase<LevelLayoutDataBlock>)(object)block).persistentID);
			}
			block = GameDataBlockBase<LevelLayoutDataBlock>.GetBlock("Legacy_L1E1_L1");
			if (block != null)
			{
				ForceDisableLevels.Add(((GameDataBlockBase<LevelLayoutDataBlock>)(object)block).persistentID);
			}
		}
	}
}
namespace LEGACY.HardcodedBehaviours
{
	[HarmonyPatch]
	internal class Patch_PickupItem_Hardcoded
	{
		[HarmonyPrefix]
		[HarmonyPatch(typeof(LG_Distribute_PickupItemsPerZone), "Build")]
		private static void Pre_LG_Distribute_PickupItemsPerZone(LG_Distribute_PickupItemsPerZone __instance)
		{
			//IL_0036: Unknown result type (might be due to invalid IL or missing references)
			//IL_003b: Unknown result type (might be due to invalid IL or missing references)
			//IL_003c: Unknown result type (might be due to invalid IL or missing references)
			//IL_003d: Unknown result type (might be due to invalid IL or missing references)
			//IL_003e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0040: Invalid comparison between Unknown and I4
			//IL_004b: 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_0052: 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_0056: Unknown result type (might be due to invalid IL or missing references)
			//IL_0059: Invalid comparison between Unknown and I4
			//IL_0044: Unknown result type (might be due to invalid IL or missing references)
			//IL_0046: Invalid comparison between Unknown and I4
			LevelLayoutDataBlock block = GameDataBlockBase<LevelLayoutDataBlock>.GetBlock("LAYOUT_O4_1_L1");
			if (block == null || RundownManager.ActiveExpedition.LevelLayoutData != ((GameDataBlockBase<LevelLayoutDataBlock>)(object)block).persistentID)
			{
				return;
			}
			eLocalZoneIndex localIndex = __instance.m_zone.LocalIndex;
			eLocalZoneIndex val = localIndex;
			if ((int)val != 1)
			{
				if ((int)val == 5)
				{
					__instance.m_zonePlacementWeights.Start = 0f;
					__instance.m_zonePlacementWeights.Middle = 0f;
					__instance.m_zonePlacementWeights.End = 100000f;
				}
				return;
			}
			ePickupItemType pickupType = __instance.m_pickupType;
			ePickupItemType val2 = pickupType;
			if ((int)val2 == 1)
			{
				__instance.m_zonePlacementWeights.Start = 100000f;
				__instance.m_zonePlacementWeights.Middle = 0f;
				__instance.m_zonePlacementWeights.End = 0f;
			}
		}
	}
}
namespace LEGACY.VanillaFix
{
	[HarmonyPatch]
	internal class Patch_FixScoutFreeze
	{
		[HarmonyPrefix]
		[HarmonyPatch(typeof(ES_ScoutScream), "CommonUpdate")]
		private static bool Prefix_Debug(ES_ScoutScream __instance)
		{
			if (((AgentAI)((ES_Base)__instance).m_ai).Target == null)
			{
				return false;
			}
			return true;
		}
	}
	[HarmonyPatch]
	internal class Patch_LG_SecurityDoor_Fix_EventsOnUnlockDoor_Powergenerator
	{
		[HarmonyPrefix]
		[HarmonyPatch(typeof(LG_SecurityDoor), "OnSyncDoorStatusChange")]
		private static void Pre_OnSyncDoorStatusChange(LG_SecurityDoor __instance, pDoorState state, bool isRecall)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_0008: 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_000a: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_000e: Invalid comparison between Unknown and I4
			//IL_001a: Unknown result type (might be due to invalid IL or missing references)
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0025: Invalid comparison between Unknown and I4
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			//IL_0015: Invalid comparison between Unknown and I4
			eDoorStatus status = state.status;
			eDoorStatus val = status;
			if ((val - 4 <= 1 || (int)val == 9) && (int)__instance.m_lastState.status == 6 && !isRecall)
			{
				WardenObjectiveManager.CheckAndExecuteEventsOnTrigger(__instance.LinkedToZoneData.EventsOnUnlockDoor, (eWardenObjectiveEventTrigger)0, true, 0f, (Il2CppStructArray<eWardenObjectiveEventType>)null);
			}
		}
	}
	[HarmonyPatch]
	internal class Patch_LockSecurityDoor_FixCustomText
	{
		[HarmonyPostfix]
		[HarmonyPatch(typeof(LG_SecurityDoor_Locks), "Setup", new Type[] { typeof(LG_SecurityDoor) })]
		private static void Post_LG_SecurityDoor_Locks_Setup(LG_SecurityDoor door, LG_SecurityDoor_Locks __instance)
		{
			LocalizedText customText = door.LinkedToZoneData.ProgressionPuzzleToEnter.CustomText;
			__instance.m_lockedWithNoKeyInteractionText = customText;
		}
	}
	[HarmonyPatch]
	internal class Debugger
	{
		public static Debugger Current { get; private set; } = new Debugger();


		public bool DEBUGGING { get; private set; } = false;


		private Debugger()
		{
		}

		internal void Init()
		{
			if (DEBUGGING)
			{
			}
		}

		private void f1(int k, out string v)
		{
			if (k < 2)
			{
				v = "2";
			}
			v = null;
		}

		private void f2(int k, ref string v)
		{
			if (k < 2)
			{
				v = "2";
			}
		}
	}
}
namespace LEGACY.Utils
{
	public delegate float EasingFunction(float t, float b, float c, float d);
	public delegate bool BoolCheck();
	internal static class CoroutineEase
	{
		private static IEnumerator DoEaseLocalScale(Transform trans, Vector3 startScale, Vector3 targetScale, float startTime, float duration, EasingFunction ease, Action onDone, BoolCheck checkAbort)
		{
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			bool doAbort = false;
			while (Clock.Time < startTime + duration && !doAbort)
			{
				doAbort = checkAbort?.Invoke() ?? false;
				float t = ease(Clock.Time - startTime, 0f, 1f, duration);
				trans.localScale = Vector3.Lerp(startScale, targetScale, t);
				yield return null;
			}
			trans.localScale = targetScale;
			if (!doAbort && onDone != null)
			{
				onDone();
			}
		}

		private static IEnumerator DoEaseLocalPos(Transform trans, Vector3 sourcePos, Vector3 targetPos, float startTime, float duration, EasingFunction ease, Action onDone, BoolCheck checkAbort)
		{
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			bool doAbort = false;
			while (Clock.Time < startTime + duration && !doAbort)
			{
				doAbort = checkAbort?.Invoke() ?? false;
				float t = ease(Clock.Time - startTime, 0f, 1f, duration);
				trans.localPosition = Vector3.Lerp(sourcePos, targetPos, t);
				yield return null;
			}
			trans.localPosition = targetPos;
			if (!doAbort && onDone != null)
			{
				onDone();
			}
		}

		private static IEnumerator DoEaseLocalRot(Transform trans, Vector3 sourceEuler, Vector3 targetEuler, float startTime, float duration, EasingFunction ease, Action onDone, BoolCheck checkAbort)
		{
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			bool doAbort = false;
			while (Clock.Time < startTime + duration && !doAbort)
			{
				doAbort = checkAbort?.Invoke() ?? false;
				float t = ease(Clock.Time - startTime, 0f, 1f, duration);
				trans.localEulerAngles = Vector3.Lerp(sourceEuler, targetEuler, t);
				yield return null;
			}
			trans.localEulerAngles = targetEuler;
			if (!doAbort && onDone != null)
			{
				onDone();
			}
		}

		internal static Coroutine EaseLocalScale(Transform trans, Vector3 startScale, Vector3 targetScale, float duration, EasingFunction ease = null, Action onDone = null, BoolCheck checkAbort = null)
		{
			//IL_0015: 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)
			EasingFunction ease2 = ease ?? new EasingFunction(Easing.EaseOutExpo);
			return CoroutineManager.StartCoroutine(CollectionExtensions.WrapToIl2Cpp(DoEaseLocalScale(trans, startScale, targetScale, Clock.Time, duration, ease2, onDone, checkAbort)), (Action)null);
		}

		internal static Coroutine EaseLocalPos(Transform trans, Vector3 sourcePos, Vector3 targetPos, float duration, EasingFunction ease = null, Action onDone = null, BoolCheck checkAbort = null)
		{
			//IL_0015: 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)
			EasingFunction ease2 = ease ?? new EasingFunction(Easing.EaseOutExpo);
			return CoroutineManager.StartCoroutine(CollectionExtensions.WrapToIl2Cpp(DoEaseLocalPos(trans, sourcePos, targetPos, Clock.Time, duration, ease2, onDone, checkAbort)), (Action)null);
		}

		internal static Coroutine EaseLocalRot(Transform trans, Vector3 sourceEuler, Vector3 targetEuler, float duration, EasingFunction ease = null, Action onDone = null, BoolCheck checkAbort = null)
		{
			//IL_0015: 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)
			EasingFunction ease2 = ease ?? new EasingFunction(Easing.EaseOutExpo);
			return CoroutineManager.StartCoroutine(CollectionExtensions.WrapToIl2Cpp(DoEaseLocalRot(trans, sourceEuler, targetEuler, Clock.Time, duration, ease2, onDone, checkAbort)), (Action)null);
		}
	}
	public static class GOExtensions
	{
		public static GameObject GetChild(this GameObject go, string childName, bool substrSearch = false, bool recursiveSearch = true)
		{
			if (((Object)go).name.Equals(childName) || (substrSearch && ((Object)go).name.Contains(childName)))
			{
				return go;
			}
			for (int i = 0; i < go.transform.childCount; i++)
			{
				GameObject gameObject = ((Component)go.transform.GetChild(i)).gameObject;
				GameObject val = null;
				if (recursiveSearch)
				{
					val = gameObject.GetChild(childName, substrSearch);
				}
				else if (((Object)gameObject).name.Equals(childName) || (substrSearch && ((Object)gameObject).name.Contains(childName)))
				{
					val = gameObject;
				}
				if ((Object)(object)val != (Object)null)
				{
					return val;
				}
			}
			return null;
		}
	}
	public static class Helper
	{
		private static void ResetChild(iChainedPuzzleCore ICore)
		{
			CP_Bioscan_Core val = ((Il2CppObjectBase)ICore).TryCast<CP_Bioscan_Core>();
			if ((Object)(object)val != (Object)null)
			{
				CP_Holopath_Spline val2 = ((Il2CppObjectBase)val.m_spline).Cast<CP_Holopath_Spline>();
				CP_PlayerScanner val3 = ((Il2CppObjectBase)val.PlayerScanner).Cast<CP_PlayerScanner>();
				val3.ResetScanProgression(0f);
				val.Deactivate();
				return;
			}
			CP_Cluster_Core val4 = ((Il2CppObjectBase)ICore).TryCast<CP_Cluster_Core>();
			if ((Object)(object)val4 == (Object)null)
			{
				LegacyLogger.Error("ResetChild: found iChainedPuzzleCore that is neither CP_Bioscan_Core nor CP_Cluster_Core...");
				return;
			}
			CP_Holopath_Spline val5 = ((Il2CppObjectBase)val4.m_spline).Cast<CP_Holopath_Spline>();
			foreach (iChainedPuzzleCore item in (Il2CppArrayBase<iChainedPuzzleCore>)(object)val4.m_childCores)
			{
				ResetChild(item);
			}
			val4.Deactivate();
		}

		public static void ResetChainedPuzzle(ChainedPuzzleInstance chainedPuzzleInstance)
		{
			//IL_0018: Unknown result type (might be due to invalid IL or missing references)
			//IL_001d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0027: Expected O, but got Unknown
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0072: 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_007f: 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)
			//IL_00a2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ac: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00be: Unknown result type (might be due to invalid IL or missing references)
			if (chainedPuzzleInstance.Data.DisableSurvivalWaveOnComplete)
			{
				chainedPuzzleInstance.m_sound = new CellSoundPlayer(chainedPuzzleInstance.m_parent.position);
			}
			foreach (iChainedPuzzleCore item in (Il2CppArrayBase<iChainedPuzzleCore>)(object)chainedPuzzleInstance.m_chainedPuzzleCores)
			{
				ResetChild(item);
			}
			if (SNet.IsMaster)
			{
				pChainedPuzzleState state = chainedPuzzleInstance.m_stateReplicator.State;
				pChainedPuzzleState val = default(pChainedPuzzleState);
				val.status = (eChainedPuzzleStatus)0;
				val.currentSurvivalWave_EventID = state.currentSurvivalWave_EventID;
				val.isSolved = false;
				val.isActive = false;
				pChainedPuzzleState val2 = val;
				chainedPuzzleInstance.m_stateReplicator.InteractWithState(val2, new pChainedPuzzleInteraction
				{
					type = (eChainedPuzzleInteraction)2
				});
			}
		}

		public static List<T> ToManagedList<T>(this List<T> il2cppList)
		{
			List<T> list = new List<T>();
			Enumerator<T> enumerator = il2cppList.GetEnumerator();
			while (enumerator.MoveNext())
			{
				T current = enumerator.Current;
				list.Add(current);
			}
			return list;
		}

		public static bool TryGetComponent<T>(this GameObject obj, out T comp)
		{
			comp = obj.GetComponent<T>();
			return comp != null;
		}

		public static bool IsPlayerInLevel(PlayerAgent player)
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0013: Invalid comparison between Unknown and I4
			return (int)player.Owner.Load<pGameState>().gameState == 10;
		}

		public static ChainedPuzzleInstance GetChainedPuzzleForCommandOnTerminal(LG_ComputerTerminal terminal, string command)
		{
			//IL_0020: 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_0027: 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_002b: Unknown result type (might be due to invalid IL or missing references)
			//IL_003e: Expected I4, but got Unknown
			//IL_00d7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e7: Unknown result type (might be due to invalid IL or missing references)
			//IL_0184: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f6: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f9: Invalid comparison between Unknown and I4
			//IL_020c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0210: Invalid comparison between Unknown and I4
			//IL_0212: Unknown result type (might be due to invalid IL or missing references)
			//IL_0216: Invalid comparison between Unknown and I4
			//IL_0218: Unknown result type (might be due to invalid IL or missing references)
			//IL_021c: Invalid comparison between Unknown and I4
			//IL_021e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0222: Invalid comparison between Unknown and I4
			//IL_0224: Unknown result type (might be due to invalid IL or missing references)
			//IL_0228: Invalid comparison between Unknown and I4
			//IL_025f: Unknown result type (might be due to invalid IL or missing references)
			uint num = 0u;
			if (terminal.SpawnNode.m_dimension.IsMainDimension)
			{
				LG_LayerType layerType = terminal.SpawnNode.LayerType;
				LG_LayerType val = layerType;
				switch ((int)val)
				{
				case 0:
					num = RundownManager.ActiveExpedition.LevelLayoutData;
					break;
				case 1:
					num = RundownManager.ActiveExpedition.SecondaryLayout;
					break;
				case 2:
					num = RundownManager.ActiveExpedition.ThirdLayout;
					break;
				default:
					LegacyLogger.Error("Unimplemented layer type.");
					return null;
				}
			}
			else
			{
				num = terminal.SpawnNode.m_dimension.DimensionData.LevelLayoutData;
			}
			LevelLayoutDataBlock block = GameDataBlockBase<LevelLayoutDataBlock>.GetBlock(num);
			List<CustomTerminalCommand> val2 = null;
			List<LG_ComputerTerminal> terminalsSpawnedInZone = terminal.SpawnNode.m_zone.TerminalsSpawnedInZone;
			int num2 = terminalsSpawnedInZone.IndexOf(terminal);
			ExpeditionZoneData val3 = null;
			Enumerator<ExpeditionZoneData> enumerator = block.Zones.GetEnumerator();
			while (enumerator.MoveNext())
			{
				ExpeditionZoneData current = enumerator.Current;
				if (current.LocalIndex == terminal.SpawnNode.m_zone.LocalIndex)
				{
					val3 = current;
					break;
				}
			}
			if (val3 == null)
			{
				LegacyLogger.Error("Cannot find target zone data.");
				return null;
			}
			if (val3.TerminalPlacements.Count != terminalsSpawnedInZone.Count)
			{
				LegacyLogger.Error("The numbers of terminal placement and spawn, skipped for the zone terminal.");
				return null;
			}
			val2 = val3.TerminalPlacements[num2].UniqueCommands;
			if (val2.Count == 0)
			{
				return null;
			}
			List<WardenObjectiveEventData> val4 = null;
			TERM_Command val5 = (TERM_Command)0;
			Enumerator<CustomTerminalCommand> enumerator2 = val2.GetEnumerator();
			string text = default(string);
			string text2 = default(string);
			while (enumerator2.MoveNext())
			{
				CustomTerminalCommand current2 = enumerator2.Current;
				if (current2.Command == command)
				{
					val4 = current2.CommandEvents;
					if (!terminal.m_command.TryGetCommand(current2.Command, ref val5, ref text, ref text2))
					{
						LegacyLogger.Error("Cannot get TERM_COMMAND for command {0} on the specified terminal.");
					}
					break;
				}
			}
			if (val4 == null || (int)val5 == 0)
			{
				return null;
			}
			if ((int)val5 != 38 && (int)val5 != 39 && (int)val5 != 40 && (int)val5 != 41 && (int)val5 != 42)
			{
				return null;
			}
			ChainedPuzzleInstance val6 = null;
			for (int i = 0; i < val4.Count && (val4[i].ChainPuzzle == 0 || !terminal.TryGetChainPuzzleForCommand(val5, i, ref val6) || !((Object)(object)val6 != (Object)null)); i++)
			{
			}
			return val6;
		}

		public static bool TryGetZoneEntranceSecDoor(LG_Zone zone, out LG_SecurityDoor door)
		{
			if ((Object)(object)zone == (Object)null)
			{
				door = null;
				return false;
			}
			if ((Object)(object)zone.m_sourceGate == (Object)null)
			{
				door = null;
				return false;
			}
			if (zone.m_sourceGate.SpawnedDoor == null)
			{
				door = null;
				return false;
			}
			door = ((Il2CppObjectBase)zone.m_sourceGate.SpawnedDoor).TryCast<LG_SecurityDoor>();
			return (Object)(object)door != (Object)null;
		}

		internal static bool isSecDoorToZoneOpened(LG_Zone zone14)
		{
			//IL_0025: 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_0031: Invalid comparison between Unknown and I4
			LG_SecurityDoor door = null;
			if (!TryGetZoneEntranceSecDoor(zone14, out door) || (Object)(object)door == (Object)null)
			{
				return false;
			}
			return (int)door.m_sync.GetCurrentSyncState().status == 10;
		}

		public static List<T> cast<T>(List<T> list)
		{
			List<T> list2 = new List<T>();
			Enumerator<T> enumerator = list.GetEnumerator();
			while (enumerator.MoveNext())
			{
				T current = enumerator.Current;
				list2.Add(current);
			}
			return list2;
		}

		private static eDimensionIndex GetCurrentDimensionIndex()
		{
			//IL_002c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0031: Unknown result type (might be due to invalid IL or missing references)
			//IL_0034: Unknown result type (might be due to invalid IL or missing references)
			if (PlayerManager.PlayerAgentsInLevel.Count <= 0)
			{
				throw new Exception("? You don't have any player agent in level? How could that happen?");
			}
			return ((Agent)PlayerManager.PlayerAgentsInLevel[0]).DimensionIndex;
		}

		public static void GetMinLayerAndLocalIndex(out LG_LayerType MinLayer, out eLocalZoneIndex MinLocalIndex)
		{
			//IL_0035: Unknown result type (might be due to invalid IL or missing references)
			//IL_003a: Invalid comparison between I4 and Unknown
			//IL_0060: Unknown result type (might be due to invalid IL or missing references)
			//IL_0065: Invalid comparison between I4 and Unknown
			//IL_0048: Unknown result type (might be due to invalid IL or missing references)
			//IL_004e: Expected I4, but got Unknown
			//IL_007d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0083: Expected I4, but got Unknown
			MinLayer = (LG_LayerType)2;
			MinLocalIndex = (eLocalZoneIndex)20;
			Enumerator<PlayerAgent> enumerator = PlayerManager.PlayerAgentsInLevel.GetEnumerator();
			while (enumerator.MoveNext())
			{
				PlayerAgent current = enumerator.Current;
				if (IsPlayerInLevel(current))
				{
					if ((int)MinLayer > (int)current.m_courseNode.LayerType)
					{
						MinLayer = (LG_LayerType)(int)current.m_courseNode.LayerType;
						MinLocalIndex = (eLocalZoneIndex)20;
					}
					if ((int)MinLocalIndex >= (int)current.m_courseNode.m_zone.LocalIndex)
					{
						MinLocalIndex = (eLocalZoneIndex)(int)current.m_courseNode.m_zone.LocalIndex;
					}
				}
			}
		}

		public static void GetMaxLayerAndLocalIndex(out LG_LayerType MaxLayer, out eLocalZoneIndex MaxLocalIndex)
		{
			//IL_0034: Unknown result type (might be due to invalid IL or missing references)
			//IL_0039: Invalid comparison between I4 and Unknown
			//IL_005e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0063: Invalid comparison between I4 and Unknown
			//IL_0047: Unknown result type (might be due to invalid IL or missing references)
			//IL_004d: Expected I4, but got Unknown
			//IL_0078: Unknown result type (might be due to invalid IL or missing references)
			//IL_007e: Expected I4, but got Unknown
			MaxLayer = (LG_LayerType)0;
			MaxLocalIndex = (eLocalZoneIndex)0;
			Enumerator<PlayerAgent> enumerator = PlayerManager.PlayerAgentsInLevel.GetEnumerator();
			while (enumerator.MoveNext())
			{
				PlayerAgent current = enumerator.Current;
				if (IsPlayerInLevel(current))
				{
					if ((int)MaxLayer < (int)current.m_courseNode.LayerType)
					{
						MaxLayer = (LG_LayerType)(int)current.m_courseNode.LayerType;
						MaxLocalIndex = (eLocalZoneIndex)0;
					}
					if ((int)MaxLocalIndex < (int)current.m_courseNode.m_zone.LocalIndex)
					{
						MaxLocalIndex = (eLocalZoneIndex)(int)current.m_courseNode.m_zone.LocalIndex;
					}
				}
			}
		}

		public static int GetMinAreaIndex(LG_Zone zone)
		{
			//IL_001c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0021: Unknown result type (might be due to invalid IL or missing references)
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			//IL_0028: 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_002e: Unknown result type (might be due to invalid IL or missing references)
			//IL_005e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0063: Unknown result type (might be due to invalid IL or missing references)
			//IL_0072: 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)
			if ((Object)(object)zone == (Object)null)
			{
				return -1;
			}
			LG_LayerType type = zone.m_layer.m_type;
			eLocalZoneIndex localIndex = zone.LocalIndex;
			eDimensionIndex currentDimensionIndex = GetCurrentDimensionIndex();
			int num = zone.m_areas.Count;
			Enumerator<PlayerAgent> enumerator = PlayerManager.PlayerAgentsInLevel.GetEnumerator();
			while (enumerator.MoveNext())
			{
				PlayerAgent current = enumerator.Current;
				if (current.m_courseNode.LayerType != type || current.m_courseNode.m_zone.LocalIndex != localIndex)
				{
					continue;
				}
				int i = 0;
				for (List<LG_Area> areas = zone.m_areas; i < areas.Count; i++)
				{
					if (((Object)((Component)areas[i]).gameObject).GetInstanceID() == ((Object)((Component)current.m_courseNode.m_area).gameObject).GetInstanceID())
					{
						if (num > i)
						{
							num = i;
						}
						break;
					}
				}
			}
			return num;
		}

		public static LG_ComputerTerminal FindTerminal(eDimensionIndex dimensionIndex, LG_LayerType layerType, eLocalZoneIndex localIndex, int terminalIndex)
		{
			//IL_0008: 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_000a: 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_0052: Unknown result type (might be due to invalid IL or missing references)
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			//IL_0103: Unknown result type (might be due to invalid IL or missing references)
			//IL_0119: Unknown result type (might be due to invalid IL or missing references)
			//IL_012f: Unknown result type (might be due to invalid IL or missing references)
			LG_Zone val = null;
			if (!Builder.CurrentFloor.TryGetZoneByLocalIndex(dimensionIndex, layerType, localIndex, ref val) || (Object)(object)val == (Object)null)
			{
				LegacyLogger.Error($"FindTerminal: Didn't find LG_Zone {dimensionIndex}, {layerType}, {localIndex}");
				return null;
			}
			if (val.TerminalsSpawnedInZone == null || terminalIndex >= val.TerminalsSpawnedInZone.Count)
			{
				LegacyLogger.Error($"FindTerminal: Invalid terminal index {terminalIndex} - {((val.TerminalsSpawnedInZone != null) ? val.TerminalsSpawnedInZone.Count : 0)} terminals are spawned in {dimensionIndex}, {layerType}, {localIndex}");
				return null;
			}
			return (terminalIndex < 0) ? null : val.TerminalsSpawnedInZone[terminalIndex];
		}

		public static AIG_NodeCluster GetNodeFromDimensionPosition(eDimensionIndex dimensionIndex, Vector3 position)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0003: 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_001e: Unknown result type (might be due to invalid IL or missing references)
			AIG_GeomorphNodeVolume val = default(AIG_GeomorphNodeVolume);
			AIG_VoxelNodePillar val2 = default(AIG_VoxelNodePillar);
			AIG_INode val3 = default(AIG_INode);
			AIG_NodeCluster result = default(AIG_NodeCluster);
			if (!AIG_GeomorphNodeVolume.TryGetGeomorphVolume(0, dimensionIndex, position, ref val) || !((AIG_NodeVolume)val).m_voxelNodeVolume.TryGetPillar(position, ref val2) || !val2.TryGetVoxelNode(position.y, ref val3) || !AIG_NodeCluster.TryGetNodeCluster(val3.ClusterID, ref result))
			{
				LegacyLogger.Error("TryWarpTo : Position is not valid, try again inside an area.");
				return null;
			}
			return result;
		}
	}
	internal static class Json
	{
		static Json()
		{
		}

		public static T Deserialize<T>(string json)
		{
			return EOSJson.Deserialize<T>(json);
		}

		public static object Deserialize(Type type, string json)
		{
			return EOSJson.Deserialize(type, json);
		}

		public static string Serialize<T>(T value)
		{
			return EOSJson.Serialize<T>(value);
		}

		public static void Load<T>(string filePath, out T config) where T : new()
		{
			config = Deserialize<T>(File.ReadAllText(filePath));
		}
	}
	internal static class LegacyLogger
	{
		private static ManualLogSource logger = Logger.CreateLogSource("LEGACYCore");

		public static void Log(string format, params object[] args)
		{
			Log(string.Format(format, args));
		}

		public static void Log(string str)
		{
			if (logger != null)
			{
				logger.Log((LogLevel)8, (object)str);
			}
		}

		public static void Warning(string format, params object[] args)
		{
			Warning(string.Format(format, args));
		}

		public static void Warning(string str)
		{
			if (logger != null)
			{
				logger.Log((LogLevel)4, (object)str);
			}
		}

		public static void Error(string format, params object[] args)
		{
			Error(string.Format(format, args));
		}

		public static void Error(string str)
		{
			if (logger != null)
			{
				logger.Log((LogLevel)2, (object)str);
			}
		}

		public static void Debug(string format, params object[] args)
		{
			Debug(string.Format(format, args));
		}

		public static void Debug(string str)
		{
			if (logger != null)
			{
				logger.Log((LogLevel)32, (object)str);
			}
		}
	}
	public class SpawnHibernateEnemiesEvent
	{
		public eWardenObjectiveEventTrigger Trigger { get; set; } = (eWardenObjectiveEventTrigger)0;


		public int Type { get; set; } = 170;


		public eDimensionIndex DimensionIndex { get; set; } = (eDimensionIndex)0;


		public LG_LayerType Layer { get; set; } = (LG_LayerType)0;


		public eLocalZoneIndex LocalIndex { get; set; } = (eLocalZoneIndex)0;


		public string WorldEventObjectFilter { get; set; } = "RANDOM";


		public uint EnemyID { get; set; }

		public int Count { get; set; } = 1;


		public float Delay { get; set; } = 0f;


		public float Duration { get; set; } = 2f;

	}
	public class WeightedAreaSelector
	{
		private static readonly Dictionary<LG_Zone, WeightedAreaSelector> dict;

		private WeightedRandomBag<LG_Area> weightedRandomBag;

		public static WeightedAreaSelector Get(LG_Zone zone)
		{
			//IL_003f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0044: 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_0048: Unknown result type (might be due to invalid IL or missing references)
			//IL_004a: Unknown result type (might be due to invalid IL or missing references)
			//IL_004d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0067: Expected I4, but got Unknown
			//IL_00b0: Unknown result type (might be due to invalid IL or missing references)
			if (!dict.ContainsKey(zone))
			{
				WeightedAreaSelector weightedAreaSelector = new WeightedAreaSelector();
				Enumerator<LG_Area> enumerator = zone.m_areas.GetEnumerator();
				while (enumerator.MoveNext())
				{
					LG_Area current = enumerator.Current;
					float num = 0f;
					LG_AreaSize size = current.m_size;
					LG_AreaSize val = size;
					switch (val - 1)
					{
					case 4:
						num = 7f;
						break;
					case 0:
						num = 20f;
						break;
					case 1:
						num = 30f;
						break;
					case 2:
						num = 35f;
						break;
					case 3:
						num = 45f;
						break;
					default:
						LegacyLogger.Error($"Unhandled LG_AreaSize: {current.m_size}. Won't build.");
						return null;
					}
					weightedAreaSelector.AddEntry(current, num);
				}
				dict.Add(zone, weightedAreaSelector);
			}
			return dict[zone];
		}

		public static WeightedAreaSelector Get(eDimensionIndex eDimensionIndex, LG_LayerType layerType, eLocalZoneIndex localIndex)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			LG_Zone val = default(LG_Zone);
			if (!Builder.CurrentFloor.TryGetZoneByLocalIndex(eDimensionIndex, layerType, localIndex, ref val) || !Object.op_Implicit((Object)(object)val))
			{
				return null;
			}
			return Get(val);
		}

		private WeightedAreaSelector()
		{
			weightedRandomBag = new WeightedRandomBag<LG_Area>();
		}

		private void AddEntry(LG_Area area, float weight)
		{
			weightedRandomBag.AddEntry(area, weight);
		}

		public LG_Area GetRandom()
		{
			return weightedRandomBag.GetRandom();
		}

		private static void OnBuildDone()
		{
		}

		private static void Clear()
		{
			dict.Clear();
		}

		static WeightedAreaSelector()
		{
			dict = new Dictionary<LG_Zone, WeightedAreaSelector>();
			LevelAPI.OnLevelCleanup += dict.Clear;
		}
	}
	public class WeightedRandomBag<T>
	{
		private struct Entry
		{
			public double accumulatedWeight;

			public T item;
		}

		private List<Entry> entries = new List<Entry>();

		private double accumulatedWeight;

		private Random rand = new Random();

		public void AddEntry(T item, double weight)
		{
			if (weight <= 0.0)
			{
				LegacyLogger.Error("AddEntry: no non-positive weight pls.");
				return;
			}
			accumulatedWeight += weight;
			entries.Add(new Entry
			{
				item = item,
				accumulatedWeight = accumulatedWeight
			});
		}

		public T GetRandom()
		{
			double num = rand.NextDouble() * accumulatedWeight;
			foreach (Entry entry in entries)
			{
				if (entry.accumulatedWeight >= num)
				{
					return entry.item;
				}
			}
			return default(T);
		}
	}
}
namespace LEGACY.LegacyOverride
{
	internal class NavMarkerManager
	{
		private Dictionary<string, GameObject> markerVisuals = new Dictionary<string, GameObject>();

		private Dictionary<string, NavMarker> navMarkers = new Dictionary<string, NavMarker>();

		private List<GameObject> arbitraryNavMarkers = new List<GameObject>();

		public static NavMarkerManager Current { get; private set; } = new NavMarkerManager();


		private GameObject InstantiateMarkerVisual()
		{
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			//IL_001e: Unknown result type (might be due to invalid IL or missing references)
			//IL_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)
			GameObject val = Object.Instantiate<GameObject>(Assets.ObjectiveMarker);
			float num = 0.16216217f;
			Transform transform = val.transform;
			transform.localPosition += Vector3.up * num;
			return val;
		}

		public void EnableMarkerAt(string markerName, GameObject target, float scale)
		{
			//IL_0051: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00de: Unknown result type (might be due to invalid IL or missing references)
			if (navMarkers.ContainsKey(markerName))
			{
				navMarkers[markerName].SetVisible(true);
			}
			else
			{
				NavMarker val = GuiManager.NavMarkerLayer.PrepareGenericMarker(target);
				if ((Object)(object)val != (Object)null)
				{
					val.SetColor(new Color(0.855f, 0.482f, 0.976f));
					val.SetStyle((eNavMarkerStyle)14);
					val.SetVisible(true);
					navMarkers[markerName] = val;
				}
				else
				{
					LegacyLogger.Error("EnableMarkerAt: got null nav marker");
				}
			}
			GameObject val2 = null;
			if (markerVisuals.ContainsKey(markerName))
			{
				val2 = markerVisuals[markerName];
			}
			else
			{
				val2 = InstantiateMarkerVisual();
				val2.transform.localScale = new Vector3(scale, scale, scale);
				val2.transform.SetPositionAndRotation(target.transform.position, Quaternion.identity);
				markerVisuals[markerName] = val2;
			}
			CoroutineManager.BlinkIn(val2, 0f);
			LegacyLogger.Debug("EnableMarker: marker " + markerName + " enabled");
		}

		public void EnableArbitraryMarkerAt(string markerName, Vector3 Position)
		{
			//IL_002d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0033: Expected O, but got Unknown
			//IL_0039: Unknown result type (might be due to invalid IL or missing references)
			//IL_003a: Unknown result type (might be due to invalid IL or missing references)
			//IL_007a: Unknown result type (might be due to invalid IL or missing references)
			if (navMarkers.ContainsKey(markerName))
			{
				navMarkers[markerName].SetVisible(true);
			}
			else
			{
				GameObject val = new GameObject(markerName);
				val.transform.SetPositionAndRotation(Position, Quaternion.identity);
				arbitraryNavMarkers.Add(val);
				NavMarker val2 = GuiManager.NavMarkerLayer.PrepareGenericMarker(val);
				if ((Object)(object)val2 != (Object)null)
				{
					val2.SetColor(new Color(0.855f, 0.482f, 0.976f));
					val2.SetStyle((eNavMarkerStyle)14);
					val2.SetVisible(true);
					navMarkers[markerName] = val2;
				}
				else
				{
					LegacyLogger.Error("EnableMarkerAt: got null nav marker");
				}
			}
			LegacyLogger.Debug("EnableMarker: marker " + markerName + " enabled");
		}

		internal (GameObject markerVisual, NavMarker navMakrer) GetMarkerVisuals(string markerName)
		{
			GameObject value;
			NavMarker value2;
			return (markerVisuals.TryGetValue(markerName, out value) && navMarkers.TryGetValue(markerName, out value2)) ? (value, value2) : (null, null);
		}

		public void DisableMakrer(string markerName)
		{
			if (navMarkers.ContainsKey(markerName))
			{
				navMarkers[markerName].SetVisible(false);
			}
			if (markerVisuals.ContainsKey(markerName))
			{
				GameObject val = markerVisuals[markerName];
				if (val.active)
				{
					CoroutineManager.BlinkOut(val, 0f);
				}
				LegacyLogger.Debug("DisableMakrer: marker " + markerName + " disabled");
			}
		}

		public void Clear()
		{
			foreach (GameObject value in markerVisuals.Values)
			{
				Object.Destroy((Object)(object)value);
			}
			arbitraryNavMarkers.ForEach((Action<GameObject>)Object.Destroy);
			markerVisuals.Clear();
			navMarkers.Clear();
			arbitraryNavMarkers.Clear();
		}

		private NavMarkerManager()
		{
			LevelAPI.OnBuildStart += Clear;
			LevelAPI.OnLevelCleanup += Clear;
		}
	}
	internal static class LegacyOverrideManagers
	{
		internal static readonly string LEGACY_CONFIG_PATH = Path.Combine(MTFOPathAPI.CustomPath, "LegacyOverride");

		internal static void Init()
		{
			ElevatorCargoOverrideManager.Current.Init();
			BigPickupFogBeaconSettingManager.Current.Init();
			EnemyTaggerSettingManager.Current.Init();
			ForceFailManager.Current.Init();
			((GenericExpeditionDefinitionManager<ExpeditionIntel>)ExpeditionIntelNotifier.Current).Init();
			((GenericExpeditionDefinitionManager<EventScanDefinition>)EventScanManager.Current).Init();
			((GenericExpeditionDefinitionManager<VisualGroupDefinition>)VisualManager.Current).Init();
			((GenericExpeditionDefinitionManager<MusicOverride>)MusicStateOverrider.Current).Init();
			((ZoneDefinitionManager<LevelSpawnedFogBeaconDefinition>)LevelSpawnedFogBeaconManager.Current).Init();
			((GenericExpeditionDefinitionManager<SuccessPageCustomization>)SuccessPageCustomizationManager.Current).Init();
			((GenericExpeditionDefinitionManager<ResourceStationDefinition>)ResourceStationManager.Current).Init();
		}
	}
}
namespace LEGACY.LegacyOverride.Restart
{
	public static class CM_PageRestart
	{
		internal static TextMeshPro Text { get; private set; }

		internal static GameObject Reconnecting { get; private set; }

		public static GameObject Page { get; private set; }

		internal static void Setup()
		{
			//IL_0053: Unknown result type (might be due to invalid IL or missing references)
			//IL_0059: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ef: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)Page != (Object)null)
			{
				LegacyLogger.Warning("Duplicate setup for CM_PageRestart!");
				try
				{
					Object.Destroy((Object)(object)Page);
				}
				finally
				{
					Page = null;
				}
			}
			Transform transform = ((Component)((GuiLayer)GuiManager.Current.m_mainMenuLayer).GuiLayerBase).transform;
			Page = Object.Instantiate<GameObject>(Assets.RestartPage, transform.position, transform.rotation, transform);
			CM_PageBase component = Page.GetComponent<CM_PageBase>();
			GameObject gameObject = ((Component)component.m_movingContentHolder).gameObject;
			Reconnecting = gameObject.GetChild("Reconnecting");
			GameObject gameObject2 = ((Component)GuiManager.Current.m_mainMenuLayer.PageMap.m_mapDisconnected.transform.GetChild(0)).gameObject;
			gameObject2 = Object.Instantiate<GameObject>(gameObject2, Reconnecting.transform);
			Text = gameObject2.GetComponent<TextMeshPro>();
			((Graphic)Text).color = new Color(0f, 1f, 72f / 85f, 1f);
			((TMP_Text)Text).SetText("RECONNECTING", true);
			((TMP_Text)Text).ForceMeshUpdate(false, false);
			Page.GetComponent<CM_PageBase>().Setup(GuiManager.Current.m_mainMenuLayer);
		}

		public static void SetPageActive(bool active)
		{
			Page.GetComponent<CM_PageBase>().SetPageActive(active);
		}
	}
}
namespace LEGACY.LegacyOverride.ResourceStations
{
	public sealed class ToolStation : ResourceStation
	{
		public override string ItemKey => $"Tool_Station_{base.SerialNumber}";

		protected override void SetupInteraction()
		{
			base.SetupInteraction();
			TextDataBlock block = GameDataBlockBase<TextDataBlock>.GetBlock("InGame.InteractionPrompt.ToolStation");
			Interact.InteractionMessage = ((block == null) ? "TOOL STATION" : Text.Get(((GameDataBlockBase<TextDataBlock>)(object)block).persistentID));
		}

		protected override void Replenish(PlayerAgent player)
		{
			PlayerBackpack backpack = PlayerBackpackManager.GetBackpack(player.Owner);
			PlayerAmmoStorage ammoStorage = backpack.AmmoStorage;
			float num = Math.Max(0f, Math.Min(def.SupplyUplimit.Tool - ammoStorage.ClassAmmo.RelInPack, def.SupplyEfficiency.Tool));
			player.GiveAmmoRel((PlayerAgent)null, 0f, 0f, num);
			player.Sound.Post(EVENTS.AMMOPACK_APPLY, true);
		}

		public static ToolStation Instantiate(ResourceStationDefinition def)
		{
			if (def.StationType != StationType.TOOL)
			{
				LegacyLogger.Error($"Trying to instantiate MediStation with def with 'StationType': {def.StationType}!");
				return null;
			}
			GameObject gO = Object.Instantiate<GameObject>(Assets.ToolStation);
			return new ToolStation(def, gO);
		}

		private ToolStation(ResourceStationDefinition def, GameObject GO)
			: base(def, GO)
		{
		}

		static ToolStation()
		{
		}
	}
	public sealed class MediStation : ResourceStation
	{
		public const float VANILLA_MAX_HEALTH = 25f;

		public override string ItemKey => $"Health_Station_{base.SerialNumber}";

		protected override void SetupInteraction()
		{
			base.SetupInteraction();
			TextDataBlock block = GameDataBlockBase<TextDataBlock>.GetBlock("InGame.InteractionPrompt.MediStation");
			Interact.InteractionMessage = ((block == null) ? "HEALTH STATION" : Text.Get(((GameDataBlockBase<TextDataBlock>)(object)block).persistentID));
		}

		protected override void Replenish(PlayerAgent player)
		{
			float health = ((Dam_SyncedDamageBase)player.Damage).Health;
			float num = def.SupplyUplimit.Medi * 25f;
			if (!(health >= num))
			{
				player.GiveHealth((PlayerAgent)null, Math.Min(def.SupplyEfficiency.Medi, (num - health) / 25f));
				player.Sound.Post(EVENTS.MEDPACK_APPLY, true);
			}
		}

		public static MediStation Instantiate(ResourceStationDefinition def)
		{
			if (def.StationType != 0)
			{
				LegacyLogger.Error($"Trying to instantiate MediStation with def with 'StationType': {def.StationType}!");
				return null;
			}
			GameObject gO = Object.Instantiate<GameObject>(Assets.MediStation);
			return new MediStation(def, gO);
		}

		private MediStation(ResourceStationDefinition def, GameObject GO)
			: base(def, GO)
		{
		}

		static MediStation()
		{
		}
	}
	public abstract class ResourceStation
	{
		public const int UNLIMITED_USE_TIME = int.MaxValue;

		private Coroutine m_blinkMarkerCoroutine = null;

		public virtual GameObject GameObject { get; protected set; }

		public GameObject InteractGO
		{
			get
			{
				GameObject gameObject = GameObject;
				return ((gameObject != null) ? ((Component)gameObject.transform.GetChild(3)).gameObject : null) ?? null;
			}
		}

		public GameObject StationMarkerGO
		{
			get
			{
				GameObject gameObject = GameObject;
				return ((gameObject != null) ? ((Component)gameObject.transform.GetChild(2)).gameObject : null) ?? null;
			}
		}

		public virtual Interact_Timed Interact { get; protected set; }

		public virtual ResourceStationDefinition def { get; protected set; }

		public RSTimer Timer { get; protected set; }

		public StateReplicator<RSStateStruct> StateReplicator { get; protected set; }

		public RSStateStruct State => StateReplicator?.State ?? new RSStateStruct();

		public LG_GenericTerminalItem TerminalItem { get; protected set; }

		public AIG_CourseNode SpawnNode
		{
			get
			{
				return TerminalItem.SpawnNode;
			}
			set
			{
				TerminalItem.SpawnNode = value;
			}
		}

		protected int SerialNumber { get; private set; }

		public virtual string ItemKey => $"Resource_Station_{SerialNumber}";

		public bool Enabled => State.Enabled;

		protected virtual bool InCooldown => State.RemainingUseTime <= 0 && State.CurrentCooldownTime > 0f;

		public virtual bool HasUnlimitedUseTime => def.AllowedUseTimePerCooldown == int.MaxValue;

		public virtual void Destroy()
		{
			if (m_blinkMarkerCoroutine != null)
			{
				CoroutineManager.StopCoroutine(m_blinkMarkerCoroutine);
				m_blinkMarkerCoroutine = null;
			}
			Object.Destroy((Object)(object)GameObject);
			StateReplicator?.Unload();
			Interact = null;
			def = null;
			StateReplicator = null;
		}

		protected virtual bool CanInteract()
		{
			return Enabled && !InCooldown;
		}

		protected abstract void Replenish(PlayerAgent player);

		protected virtual void SetInteractionText()
		{
			//IL_0014: Unknown result type (might be due to invalid IL or missing references)
			string text = Text.Format(827u, (Object[])(object)new Object[1] { Object.op_Implicit(InputMapper.GetBindingName(((Interact_Base)Interact).InputAction)) });
			TextDataBlock block = GameDataBlockBase<TextDataBlock>.GetBlock("InGame.OnAdditionalInteractionText.ResourceStation");
			string text2 = ((block == null) ? "TO REPLENISH" : Text.Get(((GameDataBlockBase<TextDataBlock>)(object)block).persistentID));
			string text3 = (HasUnlimitedUseTime ? string.Empty : $"({State.RemainingUseTime}/{def.AllowedUseTimePerCooldown})");
			GuiManager.InteractionLayer.SetInteractPrompt(Interact.InteractionMessage, text + text2 + text3, (ePUIMessageStyle)0);
		}

		protected virtual void OnTriggerInteraction(PlayerAgent player)
		{
			RSStateStruct state = State;
			int num = (HasUnlimitedUseTime ? int.MaxValue : Math.Max(state.RemainingUseTime - 1, 0));
			int num2 = player.Owner.PlayerSlotIndex();
			if (num2 < 0 || num2 >= ((Il2CppArrayBase<SNet_Slot>)(object)SNet.Slots.PlayerSlots).Count)
			{
				LegacyLogger.Error($"ResourceStation_OnTriggerInteraction: player {player.PlayerName} has invalid slot index: {num2}");
			}
			else
			{
				StateReplicator?.SetState(new RSStateStruct
				{
					LastInteractedPlayer = num2,
					RemainingUseTime = num,
					CurrentCooldownTime = ((num == 0) ? def.CooldownTime : 0f),
					Enabled = true
				});
			}
		}

		protected virtual void OnInteractionSelected(PlayerAgent agent, bool selected)
		{
			if (selected)
			{
				SetInteractionText();
			}
		}

		protected virtual void SetupInteraction()
		{
			Interact.InteractDuration = def.InteractDuration;
			Interact_Timed interact = Interact;
			interact.ExternalPlayerCanInteract += Func<PlayerAgent, bool>.op_Implicit((Func<PlayerAgent, bool>)((PlayerAgent _) => CanInteract()));
			Interact_Timed interact2 = Interact;
			interact2.OnInteractionSelected += Action<PlayerAgent, bool>.op_Implicit((Action<PlayerAgent, bool>)OnInteractionSelected);
			Interact_Timed interact3 = Interact;
			interact3.OnInteractionTriggered += Action<PlayerAgent>.op_Implicit((Action<PlayerAgent>)OnTriggerInteraction);
		}

		protected virtual void SetupTerminalItem()
		{
			//IL_000c: 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_0022: Unknown result type (might be due to invalid IL or missing references)
			LG_Zone val = default(LG_Zone);
			if (!Builder.CurrentFloor.TryGetZoneByLocalIndex(((GlobalZoneIndex)def).DimensionIndex, ((GlobalZoneIndex)def).LayerType, ((GlobalZoneIndex)def).LocalIndex, ref val) || (Object)(object)val == (Object)null)
			{
				LegacyLogger.Error("ResourceStation: Cannot find spawn node!");
				return;
			}
			if (def.AreaIndex < 0 || def.AreaIndex >= val.m_areas.Count)
			{
				LegacyLogger.Error("ResourceStation: Cannot find spawn node - Area index is invalid!");
				return;
			}
			TerminalItem.Setup(ItemKey, val.m_areas[def.AreaIndex].m_courseNode);
			if (SpawnNode != null)
			{
				TerminalItem.FloorItemLocation = SpawnNode.m_zone.NavInfo.GetFormattedText((LG_NavInfoFormat)7);
			}
			TerminalItem.FloorItemStatus = (eFloorInventoryObjectStatus)0;
		}

		protected virtual void OnStateChanged(RSStateStruct oldState, RSStateStruct newState, bool isRecall)
		{
			if (isRecall)
			{
				return;
			}
			int lastInteractedPlayer = newState.LastInteractedPlayer;
			if (lastInteractedPlayer < 0 || lastInteractedPlayer >= ((Il2CppArrayBase<SNet_Slot>)(object)SNet.Slots.PlayerSlots).Count)
			{
				return;
			}
			if (((Interact_Base)Interact).IsSelected)
			{
				SetInteractionText();
			}
			if (!SNet.IsMaster)
			{
				return;
			}
			if (oldState.RemainingUseTime == newState.RemainingUseTime)
			{
				LegacyLogger.Warning("ResourceStation OnStateChanged: RemainingUseTime does not change, won't replenish");
				return;
			}
			LegacyLogger.Warning($"ResourceStation OnStateChanged: replenish for player {lastInteractedPlayer}, remaining use time: {newState.RemainingUseTime}");
			if (oldState.RemainingUseTime > 0)
			{
				SNet_Player playerInSlot = SNet.Slots.GetPlayerInSlot(lastInteractedPlayer);
				if ((Object)(object)playerInSlot != (Object)null)
				{
					Replenish(((Il2CppObjectBase)playerInSlot.m_playerAgent).Cast<PlayerAgent>());
				}
				else
				{
					LegacyLogger.Error($"playerSlot_{lastInteractedPlayer} has no player agent!");
				}
			}
			if (newState.RemainingUseTime == 0)
			{
				LegacyLogger.Warning("ResourceStation OnStateChanged: cooldown timer starts!");
				OnCoolDownStart();
			}
		}

		protected virtual void OnCoolDownStart()
		{
			Timer.StartTimer(def.CooldownTime);
			if (m_blinkMarkerCoroutine == null)
			{
				m_blinkMarkerCoroutine = CoroutineManager.StartCoroutine(CollectionExtensions.WrapToIl2Cpp(BlinkMarker()), (Action)null);
			}
		}

		protected virtual void OnCoolDownTimerProgress(float progress)
		{
		}

		protected virtual void OnCoolDownEnd()
		{
			LegacyLogger.Warning("ResourceStation OnCoolDownEnd");
			if (m_blinkMarkerCoroutine != null)
			{
				CoroutineManager.StopCoroutine(m_blinkMarkerCoroutine);
				m_blinkMarkerCoroutine = null;
				StationMarkerGO.SetActive(true);
			}
			if (SNet.IsMaster)
			{
				LegacyLogger.Warning("ResourceStation OnCoolDownEnd: master reset state!");
				StateReplicator.SetState(new RSStateStruct
				{
					LastInteractedPlayer = -1,
					RemainingUseTime = def.AllowedUseTimePerCooldown,
					CurrentCooldownTime = 0f,
					Enabled = true
				});
			}
		}

		protected virtual void SetupReplicator()
		{
			if (StateReplicator == null)
			{
				uint num = EOSNetworking.AllotReplicatorID();
				if (num == 0)
				{
					LegacyLogger.Error("ResourceStation: replicatorID depleted, cannot setup replicator!");
					return;
				}
				StateReplicator = StateReplicator<RSStateStruct>.Create(num, new RSStateStruct
				{
					RemainingUseTime = def.AllowedUseTimePerCooldown,
					CurrentCooldownTime = -1f,
					Enabled = true
				}, (LifeTimeType)1, (IStateReplicatorHolder<RSStateStruct>)null);
				StateReplicator.OnStateChanged += OnStateChanged;
			}
		}

		protected virtual void SetupRSTimer()
		{
			if ((Object)(object)Timer == (Object)null)
			{
				Timer = RSTimer.Instantiate(OnCoolDownTimerProgress, OnCoolDownEnd);
			}
		}

		private IEnumerator BlinkMarker()
		{
			while (true)
			{
				StationMarkerGO.SetActive(!StationMarkerGO.active);
				yield return (object)new WaitForSeconds(0.5f);
			}
		}

		protected ResourceStation(ResourceStationDefinition def, GameObject GO)
		{
			//IL_0030: 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)
			this.def = def;
			GameObject = GO;
			GameObject.transform.SetPositionAndRotation(def.Position.ToVector3(), def.Rotation.ToQuaternion());
			Interact = InteractGO.GetComponent<Interact_Timed>();
			SerialNumber = SerialGenerator.GetUniqueSerialNo();
			if ((Object)(object)Interact == (Object)null)
			{
				LegacyLogger.Error("ResourceStation: Interact Comp not found!");
			}
			else
			{
				SetupInteraction();
			}
			TerminalItem = GO.GetComponent<LG_GenericTerminalItem>();
			if ((Object)(object)TerminalItem == (Object)null)
			{
				LegacyLogger.Error("ResourceStation: TerminalItem not found!");
			}
			else
			{
				SetupTerminalItem();
			}
			SetupReplicator();
			SetupRSTimer();
		}

		static ResourceStation()
		{
		}
	}
	public sealed class AmmoStation : ResourceStation
	{
		public override string ItemKey => $"Ammunition_Station_{base.SerialNumber}";

		protected override void SetupInteraction()
		{
			base.SetupInteraction();
			TextDataBlock block = GameDataBlockBase<TextDataBlock>.GetBlock("InGame.InteractionPrompt.AmmoStation");
			Interact.InteractionMessage = ((block == null) ? "AMMUNITION STATION" : Text.Get(((GameDataBlockBase<TextDataBlock>)(object)block).persistentID));
		}

		public static AmmoStation Instantiate(ResourceStationDefinition def)
		{
			if (def.StationType != StationType.AMMO)
			{
				LegacyLogger.Error($"Trying to instantiate AmmoStation with def with 'StationType': {def.StationType}!");
				return null;
			}
			GameObject gO = Object.Instantiate<GameObject>(Assets.AmmoStation);
			return new AmmoStation(def, gO);
		}

		protected override void Replenish(PlayerAgent player)
		{
			PlayerBackpack backpack = PlayerBackpackManager.GetBackpack(player.Owner);
			PlayerAmmoStorage ammoStorage = backpack.AmmoStorage;
			float num = Math.Max(0f, Math.Min(def.SupplyUplimit.AmmoStandard - ammoStorage.StandardAmmo.RelInPack, def.SupplyEfficiency.AmmoStandard));
			float num2 = Math.Max(0f, Math.Min(def.SupplyUplimit.AmmoSpecial - ammoStorage.SpecialAmmo.RelInPack, def.SupplyEfficiency.AmmoSpecial));
			player.GiveAmmoRel((PlayerAgent)null, num, num2, 0f);
			player.Sound.Post(EVENTS.AMMOPACK_APPLY, true);
		}

		private AmmoStation(ResourceStationDefinition def, GameObject GO)
			: base(def, GO)
		{
		}

		static AmmoStation()
		{
		}
	}
	public enum StationType
	{
		MEDI,
		AMMO,
		TOOL
	}
	public class SupplyUplimit
	{
		public float Medi { get; set; } = 0.6f;


		public float AmmoStandard { get; set; } = 1f;


		public float AmmoSpecial { get; set; } = 1f;


		public float Tool { get; set; } = 0f;

	}
	public class SupplyEfficiency
	{
		public float Medi { get; set; } = 0.2f;


		public float AmmoStandard { get; set; } = 0.15f;


		public float AmmoSpecial { get; set; } = 0.15f;


		public float Tool { get; set; } = 0f;

	}
	public class ResourceStationDefinition : GlobalZoneIndex
	{
		public int AreaIndex { get; set; } = 0;


		public string WorldEventObjectFilter { get; set; } = string.Empty;


		public StationType StationType { get; set; } = StationType.AMMO;


		public Vec3 Position { get; set; } = new Vec3();


		public Vec3 Rotation { get; set; } = new Vec3();


		public float InteractDuration { get; set; } = 2.5f;


		public SupplyEfficiency SupplyEfficiency { get; set; } = new SupplyEfficiency();


		public SupplyUplimit SupplyUplimit { get; set; } = new SupplyUplimit();


		public int AllowedUseTimePerCooldown { get; set; } = int.MaxValue;


		public float CooldownTime { get; set; } = 3f;

	}
	public class ResourceStationManager : GenericExpeditionDefinitionManager<ResourceStationDefinition>
	{
		public static ResourceStationManager Current { get; private set; }

		protected override string DEFINITION_NAME => "ResourceStation";

		private Dictionary<string, ResourceStation> Stations { get; } = new Dictionary<string, ResourceStation>();


		private void Build(ResourceStationDefinition def)
		{
			if (Stations.ContainsKey(def.WorldEventObjectFilter))
			{
				LegacyLogger.Error("ResourceStationManager: WorldEventObjectFilter '" + def.WorldEventObjectFilter + "' is already used");
				return;
			}
			ResourceStation resourceStation = null;
			switch (def.StationType)
			{
			case StationType.MEDI:
				resourceStation = MediStation.Instantiate(def);
				break;
			case StationType.AMMO:
				resourceStation = AmmoStation.Instantiate(def);
				break;
			case StationType.TOOL:
				resourceStation = ToolStation.Instantiate(def);
				break;
			default:
				LegacyLogger.Error($"ResourceStation {def.StationType} is unimplemented");
				return;
			}
			if (resourceStation != null)
			{
				Stations[def.WorldEventObjectFilter] = resourceStation;
				LegacyLogger.Debug("ResourceStation '" + def.WorldEventObjectFilter + "' instantiated");
			}
		}

		private void BuildStations()
		{
			if (base.definitions.TryGetValue(base.CurrentMainLevelLayout, out var value))
			{
				value.Definitions.ForEach(Build);
			}
		}

		private void Clear()
		{
			foreach (ResourceStation value in Stations.Values)
			{
				value.Destroy();
			}
			Stations.Clear();
		}

		private ResourceStationManager()
		{
			LevelAPI.OnBuildStart += delegate
			{
				Clear();
			};
			LevelAPI.OnLevelCleanup += Clear;
			LevelAPI.OnBuildDone += BuildStations;
		}

		static ResourceStationManager()
		{
			Current = new ResourceStationManager();
		}
	}
	public struct RSStateStruct
	{
		public int LastInteractedPlayer;

		public int RemainingUseTime;

		public float CurrentCooldownTime;

		public bool Enabled;

		public RSStateStruct()
		{
			LastInteractedPlayer = 0;
			RemainingUseTime = 0;
			CurrentCooldownTime = 0f;
			Enabled = false;
		}
	}
	public class RSTimer : MonoBehaviour
	{
		private float startTime = 0f;

		private float endTime = 0f;

		private bool hasOnGoingTimer = false;

		private Action<float> OnProgress;

		private Action OnTimerEnd;

		public float RemainingTime => hasOnGoingTimer ? Math.Max(endTime - Clock.Time, 0f) : 0f;

		private static List<GameObject> TimerGOs { get; }

		private void Update()
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0008: Invalid comparison between Unknown and I4
			if ((int)GameStateManager.CurrentStateName == 10 && hasOnGoingTimer)
			{
				float time = Clock.Time;
				if (OnProgress != null)
				{
					OnProgress((time - startTime) / (endTime - startTime));
				}
				if (!(time < endTime))
				{
					endTime = 0f;
					hasOnGoingTimer = false;
					OnTimerEnd?.Invoke();
				}
			}
		}

		public void StartTimer(float time)
		{
			if (time <= 0f)
			{
				LegacyLogger.Error("StartTimer: time is not positive!");
				return;
			}
			if (hasOnGoingTimer)
			{
				LegacyLogger.Error("StartTimer: this timer is yet ended!");
				return;
			}
			startTime = Clock.Time;
			endTime = startTime + time;
			hasOnGoingTimer = true;
		}

		private void OnDestroy()
		{
			endTime = 0f;
			hasOnGoingTimer = false;
			OnTimerEnd = null;
		}

		public static RSTimer Instantiate(Action<float> onProgress, Action actionOnEnd)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Expected O, but got Unknown
			GameObject val = new GameObject();
			RSTimer rSTimer = val.AddComponent<RSTimer>();
			rSTimer.OnProgress = onProgress;
			rSTimer.OnTimerEnd = actionOnEnd;
			TimerGOs.Add(val);
			return rSTimer;
		}

		public static void DestroyAll()
		{
			TimerGOs.ForEach((Action<GameObject>)Object.Destroy);
			TimerGOs.Clear();
		}

		private RSTimer()
		{
		}

		static RSTimer()
		{
			TimerGOs = new List<GameObject>();
			ClassInjector.RegisterTypeInIl2Cpp<RSTimer>();
			LevelAPI.OnBuildStart += DestroyAll;
			LevelAPI.OnLevelCleanup += DestroyAll;
		}
	}
}
namespace LEGACY.LegacyOverride.EnemyTargeting
{
	internal class EnemyTargetingPrioritizer : MonoBehaviour
	{
		public const float UPDATE_INTERVAL = 3f;

		private float nextUpdateTime = float.NaN;

		internal EnemyAgent enemy = null;

		private Dam_EnemyDamageBase damage
		{
			get
			{
				EnemyAgent obj = enemy;
				return (obj != null) ? obj.Damage : null;
			}
		}

		private AgentTarget target
		{
			get
			{
				EnemyAgent obj = enemy;
				return (obj != null) ? ((AgentAI)obj.AI).Target : null;
			}
		}

		private void Update()
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0008: Invalid comparison between Unknown and I4
			//IL_008e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0094: Invalid comparison between Unknown and I4
			//IL_00ec: Unknown result type (might be due to invalid IL or missing references)
			//IL_0101: Unknown result type (might be due to invalid IL or missing references)
			if ((int)GameStateManager.CurrentStateName != 10 || !SNet.IsMaster)
			{
				return;
			}
			if (float.IsNaN(nextUpdateTime))
			{
				nextUpdateTime = Clock.Time + 3f;
			}
			else if (!(Clock.Time < nextUpdateTime) && !((Object)(object)enemy == (Object)null))
			{
				nextUpdateTime = Clock.Time + 3f;
				if ((int)((AgentAI)enemy.AI).Mode == 1 && target != null && !(((Il2CppObjectBase)target.m_agent.CourseNode).Pointer == ((Il2CppObjectBase)((Agent)enemy).CourseNode).Pointer) && PlayerManager.PlayerAgentsInLevel.Count > 1 && ((Agent)PlayerManager.PlayerAgentsInLevel[0]).CourseNode.m_dimension.DimensionIndex == ((Agent)enemy).CourseNode.m_dimension.DimensionIndex)
				{
					TryPrioritizeCloserTarget();
				}
			}
		}

		internal void TryPrioritizeCloserTarget()
		{
			AgentTarget val = target;
			Agent val2 = null;
			Enumerator<PlayerAgent> enumerator = PlayerManager.PlayerAgentsInLevel.GetEnumerator();
			while (enumerator.MoveNext())
			{
				PlayerAgent current = enumerator.Current;
				if (!((Agent)current).Alive || !(((Il2CppObjectBase)((Agent)current).CourseNode).Pointer == ((Il2CppObjectBase)((Agent)enemy).CourseNode).Pointer))
				{
					continue;
				}
				val2 = (Agent)(object)current;
				break;
			}
			if ((Object)(object)val2 == (Object)null)
			{
				Enumerator<PlayerAgent> enumerator2 = PlayerManager.PlayerAgentsInLevel.GetEnumerator();
				while (enumerator2.MoveNext())
				{
					PlayerAgent current2 = enumerator2.Current;
					if (!((Agent)current2).Alive || !(((Il2CppObjectBase)((Agent)current2).CourseNode.m_zone).Pointer == ((Il2CppObjectBase)((Agent)enemy).CourseNode.m_zone).Pointer))
					{
						continue;
					}
					val2 = (Agent)(object)current2;
					break;
				}
			}
			if ((Object)(object)val2 != (Object)null)
			{
				((AgentAI)enemy.AI).SetTarget(val2);
			}
		}

		private void OnDestroy()
		{
			enemy = null;
		}

		static EnemyTargetingPrioritizer()
		{
			ClassInjector.RegisterTypeInIl2Cpp<EnemyTargetingPrioritizer>();
		}
	}
}
namespace LEGACY.LegacyOverride.Patches
{
	[HarmonyPatch]
	internal static class ExpeditionSuccessPage
	{
		[HarmonyPostfix]
		[HarmonyPatch(typeof(CM_PageExpeditionSuccess), "OnEnable")]
		private static void Post_CM_PageExpeditionSuccess_OnEnable(CM_PageExpeditionSuccess __instance)
		{
			if (!((Object)(object)__instance == (Object)null))
			{
				SuccessPageCustomization currentCustomization = SuccessPageCustomizationManager.Current.CurrentCustomization;
				if (currentCustomization != null)
				{
					((TMP_Text)__instance.m_header).SetText(LocalizedText.op_Implicit(currentCustomization.PageHeader), true);
					__instance.m_overrideSuccessMusic = currentCustomization.OverrideSuccessMusic;
					LegacyLogger.Warning("Post_CM_PageExpeditionSuccess_OnEnable: " + ((Object)currentCustomization.PageHeader).ToString());
				}
			}
		}
	}
	[HarmonyPatch]
	internal class GUIManager_RestartPage
	{
		[HarmonyPostfix]
		[HarmonyWrapSafe]
		[HarmonyPatch(typeof(GuiManager), "Setup")]
		private static void Post_Setup(GuiManager __instance)
		{
			LevelAPI.OnBuildStart += delegate
			{
				CM_PageRestart.Setup();
			};
		}
	}
	[HarmonyPatch]
	internal static class LevelSpawnFogBeacon_BugFix
	{
		[HarmonyPostfix]
		[HarmonyPatch(typeof(HeavyFogRepellerGlobalState), "AttemptInteract")]
		private static void Post_HeavyFogRepellerGlobalState_AttemptInteract(HeavyFogRepellerGlobalState __instance)
		{
			LevelSpawnedFogBeaconSettings lSFBDef = LevelSpawnedFogBeaconManager.Current.GetLSFBDef(__instance);
			if (lSFBDef != null)
			{
				__instance.m_repellerSphere.Range = lSFBDef.Range;
			}
		}
	}
	[HarmonyPatch]
	internal class PrioritizeEnemyTargeting
	{
		private static bool s_patch = true;

		[HarmonyPostfix]
		[HarmonyPatch(typeof(EnemyCourseNavigation), "UpdateTracking")]
		private static void UpdateTracking(EnemyCourseNavigation __instance)
		{
			//IL_004f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0056: Invalid comparison between Unknown and I4
			if (!s_patch)
			{
				return;
			}
			int count = PlayerManager.PlayerAgentsInLevel.Count;
			if (!SNet.IsMaster || count <= 1)
			{
				return;
			}
			EnemyAgent owner = __instance.m_owner;
			if ((int)((StateMachine<ES_Base>)(object)owner.Locomotion).m_currentState.m_stateEnum == 14)
			{
				return;
			}
			Agent agent = __instance.m_targetRef.m_agent;
			if (((Il2CppObjectBase)agent.CourseNode).Pointer == ((Il2CppObjectBase)((Agent)owner).CourseNode).Pointer)
			{
				return;
			}
			PlayerAgent val = null;
			int num = Random.RandomRangeInt(0, count);
			for (int i = 0; i < count; i++)
			{
				PlayerAgent val2 = PlayerManager.PlayerAgentsInLevel[num];
				if (((Agent)val2).Alive && ((Il2CppObjectBase)((Agent)val2).CourseNode).Pointer == ((Il2CppObjectBase)((Agent)owner).CourseNode).Pointer)
				{
					val = val2;
					break;
				}
				num = (num + 1) % count;
			}
			if ((Object)(object)val != (Object)null)
			{
				s_patch = false;
				((AgentAI)owner.AI).SetTarget((Agent)(object)val);
				s_patch = true;
			}
		}
	}
	[HarmonyPatch]
	internal class RundownSelectionCustomization
	{
		private static uint r1TitleID;

		private static uint r2TitleID;

		[HarmonyPostfix]
		[HarmonyPatch(typeof(CM_PageRundown_New), "Setup")]
		private static void Post_CM_PageRundown_New(CM_PageRundown_New __instance)
		{
			//IL_0055: 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)
			//IL_009f: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ad: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00be: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f5: Unknown result type (might be due to invalid IL or missing references)
			//IL_0101: Unknown result type (might be due to invalid IL or missing references)
			//IL_010c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0112: Unknown result type (might be due to invalid IL or missing references)
			GameSetupDataBlock block = GameDataBlockBase<GameSetupDataBlock>.GetBlock(1u);
			if (block.RundownIdsToLoad.Count <= 1)
			{
				return;
			}
			int count = block.RundownIdsToLoad.Count;
			int num = count;
			if (num == 2)
			{
				((Il2CppArrayBase<Vector3>)(object)__instance.m_rundownSelectionPositions)[0] = new Vector3(-320f, 75f, 0f);
				((Il2CppArrayBase<Vector3>)(object)__instance.m_rundownSelectionPositions)[1] = new Vector3(320f, 0f, 0f);
				Vector3 zero = Vector3.zero;
				for (int i = block.RundownIdsToLoad.Count; i < ((Il2CppArrayBase<Vector3>)(object)__instance.m_rundownSelectionPositions).Count; i++)
				{
					zero = ((Il2CppArrayBase<Vector3>)(object)__instance.m_rundownSelectionPositions)[i];
					((Il2CppArrayBase<Vector3>)(object)__instance.m_rundownSelectionPositions)[i] = new Vector3(zero.x, -10000f, zero.z);
				}
				zero = __instance.m_textRundownHeaderTop.transform.position;
				__instance.m_textRundownHeaderTop.transform.position = new Vector3(zero.x, -350f, zero.z);
			}
		}

		private static void SetSelectionScale(CM_PageRundown_New p)
		{
			//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_0096: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cb: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ec: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fb: Unknown result type (might be due to invalid IL or missing references)
			//IL_0105: Unknown result type (might be due to invalid IL or missing references)
			//IL_010a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0120: Unknown result type (might be due to invalid IL or missing references)
			//IL_012a: Unknown result type (might be due to invalid IL or missing references)
			//IL_012f: 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_013e: Unknown result type (might be due to invalid IL or missing references)
			//IL_015a: Unknown result type (might be due to invalid IL or missing references)
			//IL_015f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0164: Unknown result type (might be due to invalid IL or missing references)
			//IL_0165: Unknown result type (might be due to invalid IL or missing references)
			//IL_016d: Unknown result type (might be due to invalid IL or missing references)
			GameSetupDataBlock block = GameDataBlockBase<GameSetupDataBlock>.GetBlock(1u);
			if (block.RundownIdsToLoad.Count > 1)
			{
				int count = block.RundownIdsToLoad.Count;
				int num = count;
				if (num == 2)
				{
					CM_RundownSelection val = p.m_rundownSelections[0];
					CM_RundownSelection val2 = p.m_rundownSelections[1];
					((Component)val).transform.localScale = new Vector3(2f, 2f, 2f) * 1.625f;
					((Component)val2).transform.localScale = new Vector3(1.25f, 1.25f, 1.25f) * 1.5f;
					Transform transform = val.m_rundownText.transform;
					Quaternion localRotation = (val2.m_rundownText.transform.localRotation = Quaternion.AngleAxis(45f, Vector3.right));
					transform.localRotation = localRotation;
					val.m_rundownText.transform.localPosition = Vector3.up * 60f + Vector3.right * 20f;
					val2.m_rundownText.transform.localPosition = Vector3.up * 85f + Vector3.left * 25f;
					Transform transform2 = ((Component)val).transform;
					localRotation = (((Component)val2).transform.localRotation = Quaternion.AngleAxis(-45f, Vector3.right));
					transform2.localRotation = localRotation;
					((TMP_Text)val.m_rundownText).text = ((r1TitleID != 0) ? Text.Get(r1TitleID) : "<size=50%><color=#00ae9d>[ LEGACY ]</color></size>");
					((TMP_Text)val2.m_rundownText).text = ((r2TitleID != 0) ? Text.Get(r2TitleID) : "<size=80%><color=#009ad6>[ L-OMNI ]</color></size>");
					DestroyAltText(val);
					DestroyAltText(val2);
				}
			}
			static void DestroyAltText(CM_RundownSelection s)
			{
				if ((Object)(object)s.m_altText != (Object)null)
				{
					Object.Destroy((Object)(object)((Component)s.m_altText).gameObject);
					s.m_altText = null;
				}
			}
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(CM_PageRundown_New), "UpdateRundownSelectionButton")]
		private static void Post_UpdateRundownSelectionButton(CM_PageRundown_New __instance)
		{
			InitTitle();
			SetSelectionScale(__instance);
		}

		private static void InitTitle()
		{
			if (r1TitleID == 0)
			{
				TextDataBlock block = GameDataBlockBase<TextDataBlock>.GetBlock("LEGACY_Title");
				if (block != null)
				{
					r1TitleID = ((GameDataBlockBase<TextDataBlock>)(object)block).persistentID;
				}
				block = GameDataBlockBase<TextDataBlock>.GetBlock("LEGACY-Omni_Title");
				if (block != null)
				{
					r2TitleID = ((GameDataBlockBase<TextDataBlock>)(object)block).persistentID;
				}
			}
		}

		private static IEnumerator reverseReveal(CM_PageRundown_New p, bool hosting, Transform guixSurfaceTransform)
		{
			float arrowScale = p.m_tierSpacing * 5f * p.m_tierSpaceToArrowScale;
			if (hosting)
			{
				CoroutineManager.BlinkIn(p.m_buttonConnect, 0f, (Transform)null);
				yield return (object)new WaitForSeconds(0.1f);
				yield return (object)new WaitForSeconds(0.24f);
				((RectTransformComp)p.m_buttonConnect).SetVisible(false);
			}
			CM_PageBase.PostSound(EVENTS.MENU_SURFACE_LEVEL_MOVE_UP, "");
			yield return CoroutineEase.EaseLocalPos(guixSurfaceTransform, Vector3.zero, new Vector3(0f, 650f, 0f), 0.5f, (EasingFunction)Easing.LinearTween, (Action)null, (BoolCheck)null);
			yield return (object)new WaitForSeconds(0.1f);
			CM_PageBase.PostSound(EVENTS.MENU_SURFACE_LEVEL_SHRINK, "");
			CoroutineEase.EaseLocalScale(p.m_textRundownHeader.transform, Vector3.one, new Vector3(0.6f, 0.6f, 0.6f), 0.2f, (EasingFunction)Easing.LinearTween, (Action)null, (BoolCheck)null);
			yield return CoroutineEase.EaseLocalScale(guixSurfaceTransform, Vector3.one, new Vector3(0.2f, 0.2f, 0.2f), 0.2f, (EasingFunction)Easing.LinearTween, (Action)null, (BoolCheck)null);
			yield return (object)new WaitForSeconds(0.1f);
			CoroutineEase.EaseLocalPos(p.m_textRundownHeader.transform, p.m_textRundownHeader.transform.localPosition, p.m_rundownHeaderPos, 0.2f, (EasingFunction)Easing.LinearTween, (Action)null, (BoolCheck)null);
			CoroutineManager.BlinkIn(p.m_rundownIntelButton, 0f, (Transform)null);
			yield return (object)new WaitForSeconds(0.2f);
			CM_PageBase.PostSound(EVENTS.MENU_SURFACE_LEVEL_TURN, "");
			yield return CoroutineEase.EaseLocalRot(guixSurfaceTransform, Vector3.zero, new Vector3(70f, 0f, 0f), 0.3f, (EasingFunction)Easing.LinearTween, (Action)null, (BoolCheck)null);
			p.m_verticalArrow.SetActive(true);
			yield return (object)new WaitForSeconds(0.5f);
			CoroutineManager.BlinkIn(((Component)p.m_tierMarkerSectorSummary).gameObject, 0f);
			CM_PageBase.PostSound(EVENTS.MENU_RUNDOWN_DISC_APPEAR_5, "");
			yield return (object)new WaitForSeconds(0.5f);
			CM_PageBase.PostSound(EVENTS.MENU_RUNDOWN_SPINE_START, "");
			CoroutineEase.EaseLocalScale(p.m_verticalArrow.transform, new Vector3(1f, 0f, 1f), new Vector3(1f, arrowScale, 1f), 4.3f, (EasingFunction)Easing.LinearTween, (Action)delegate
			{
				CM_PageBase.PostSound(EVENTS.MENU_RUNDOWN_SPINE_STOP, "");
			}, (BoolCheck)null);
			float tierMarkerDelay = 0.6f;
			yield return (object)new WaitForSeconds(0.2f);
			CM_PageBase.PostSound(EVENTS.MENU_RUNDOWN_DISC_APPEAR_3, "");
			((Component)p.m_guix_Tier3).gameObject.SetActive(true);
			for (int k = 0; k < p.m_expIconsTier3.Count; k++)
			{
				CoroutineManager.BlinkIn(((Component)p.m_expIconsTier3[k]).gameObject, (float)k * 0.1f);
			}
			if (p.m_expIconsTier3.Count > 0)
			{
				p.m_tierMarker3.SetVisible(true, tierMarkerDelay);
			}
			yield return (object)new WaitForSeconds(1f);
			CM_PageBase.PostSound(EVENTS.MENU_RUNDOWN_DISC_APPEAR_5, "");
			((Component)p.m_guix_Tier5).gameObject.SetActive(true);
			for (int m = 0; m < p.m_expIconsTier5.Count; m++)
			{
				CoroutineManager.BlinkIn(((Component)p.m_expIconsTier5[m]).gameObject, (float)m * 0.1f);
			}
			if (p.m_expIconsTier5.Count > 0)
			{
				p.m_tierMarker5.SetVisible(true, tierMarkerDelay);
			}
			yield return (object)new WaitForSeconds(1f);
			CM_PageBase.PostSound(EVENTS.MENU_RUNDOWN_DISC_APPEAR_4, "");
			((Component)p.m_guix_Tier4).gameObject.SetActive(true);
			for (int l = 0; l < p.m_expIconsTier4.Count; l++)
			{
				CoroutineManager.BlinkIn(((Component)p.m_expIconsTier4[l]).gameObject, (float)l * 0.1f);
			}
			if (p.m_expIconsTier4.Count > 0)
			{
				p.m_tierMarker4.SetVisible(true, tierMarkerDelay);
			}
			yield return (object)new WaitForSeconds(1f);
			CM_PageBase.PostSound(EVENTS.MENU_RUNDOWN_DISC_APPEAR_2, "");
			((Component)p.m_guix_Tier2).gameObject.SetActive(true);
			for (int j = 0; j < p.m_expIconsTier2.Count; j++)
			{
				CoroutineManager.BlinkIn(((Component)p.m_expIconsTier2[j]).gameObject, (float)j * 0.1f);
			}
			if (p.m_expIconsTier2.Count > 0)
			{
				p.m_tierMarker2.SetVisible(true, tierMarkerDelay);
			}
			yield return (object)new WaitForSeconds(1f);
			CM_PageBase.PostSound(EVENTS.MENU_RUNDOWN_DISC_APPEAR_1, "");
			((Component)p.m_guix_Tier1).gameObject.SetActive(true);
			for (int i = 0; i < p.m_expIconsTier1.Count; i++)
			{
				CoroutineManager.BlinkIn(((Component)p.m_expIconsTier1[i]).gameObject, (float)i * 0.1f);
			}
			if (p.m_expIconsTier1.Count > 0)
			{
				p.m_tierMarker1.SetVisible(true, tierMarkerDelay);
			}
			yield return (object)new WaitForSeconds(1f);
			((Component)p.m_joinOnServerIdText).gameObject.SetActive(true);
			CoroutineManager.BlinkIn(p.m_aboutTheRundownButton, 0f, (Transform)null);
			CoroutineManager.BlinkIn(p.m_discordButton, 0.1f, (Transform)null);
			if (SNet.IsMaster || !SNet.IsInLobby)
			{
				CoroutineManager.BlinkIn(p.m_matchmakeAllButton, 0.2f, (Transform)null);
			}
			p.m_selectionIsRevealed = true;
			p.CheckClipboard();
		}
	}
	[HarmonyPatch]
	internal class DisableExpeditionFailPageArtifactDisplay
	{
		private class CustomExpeditionFailedSequence
		{
			private CM_PageExpeditionFail page;

			public CustomExpeditionFailedSequence(CM_PageExpeditionFail page)
			{
				this.page = page;
			}

			public IEnumerator CustomFailedSequence()
			{
				yield return (object)new WaitForSeconds(0.5f);
				((Component)page.m_bgCortex_text).gameObject.SetActive(false);
				page.m_bgCortex_textBoxSmall.SetActive(false);
				page.m_bgCortex_textBoxLarge.SetActive(false);
				((Component)page.m_returnToLobby_text).gameObject.SetActive(false);
				CM_PageBase.PostSound(EVENTS.PLAY_01_FIRST_TEXT_APPEAR, "");
				yield return CoroutineManager.BlinkIn(page.m_bgCortex_logo, 0f);
				yield return (object)new WaitForSeconds(0.3f);
				CM_PageBase.PostSound(EVENTS.PLAY_01_FIRST_TEXT_APPEAR, "");
				yield return CoroutineManager.BlinkIn(page.m_bgCortex_text, 0f, (Transform)null);
				yield return (object)new WaitForSeconds(0.4f);
				CoroutineManager.BlinkIn(page.m_bgCortex_textBoxSmall, 0f);
				CoroutineManager.BlinkIn(page.m_bgCortex_textBoxLarge, 0.15f);
				yield return (object)new WaitForSeconds(0.5f);
				yield return Co

plugins/TrickyBall's Paradise/Custom/ForLegacy/x64/Release/netstandard2.1/Oxygen.dll

Decompiled 8 months ago
using System;
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 System.Text.Json;
using System.Text.Json.Serialization;
using AK;
using Agents;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Logging;
using BepInEx.Unity.IL2CPP;
using GTFO.API;
using GTFO.API.Utilities;
using GameData;
using GameEvent;
using HarmonyLib;
using Il2CppInterop.Runtime.Injection;
using Il2CppInterop.Runtime.InteropTypes.Arrays;
using Il2CppSystem.Collections.Generic;
using LevelGeneration;
using Localization;
using MTFO.Managers;
using Microsoft.CodeAnalysis;
using Oxygen.Components;
using Oxygen.Config;
using Oxygen.Utils;
using Oxygen.Utils.PartialData;
using Player;
using SNetwork;
using TMPro;
using UnityEngine;
using UnityEngine.UI;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("Oxygen")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0")]
[assembly: AssemblyProduct("Oxygen")]
[assembly: AssemblyTitle("Oxygen")]
[assembly: AssemblyVersion("1.0.0.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.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace Oxygen
{
	[BepInPlugin("Inas.Oxygen", "Oxygen", "1.3.2")]
	[BepInProcess("GTFO.exe")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	public class Plugin : BasePlugin
	{
		[CompilerGenerated]
		private static class <>O
		{
			public static Action <0>__OnBuildDone;

			public static Action <1>__OnLevelCleanup;

			public static Action <2>__Setup;

			public static Action <3>__OnLevelCleanup;

			public static Action <4>__OnBuildStart;

			public static Action <5>__OnLevelCleanup;

			public static LiveEditEventHandler <6>__Listener_FileChanged1;
		}

		public const string MODNAME = "Oxygen";

		public const string AUTHOR = "Inas";

		public const string GUID = "Inas.Oxygen";

		public const string VERSION = "1.3.2";

		public static readonly string OXYGEN_CONFIG_PATH = Path.Combine(ConfigManager.CustomPath, "Oxygen");

		public static Dictionary<uint, OxygenBlock> lookup = new Dictionary<uint, OxygenBlock>();

		private static LiveEditListener listener = null;

		public override void Load()
		{
			//IL_011a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0208: Unknown result type (might be due to invalid IL or missing references)
			//IL_020d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0213: Expected O, but got Unknown
			if (!Directory.Exists(OXYGEN_CONFIG_PATH))
			{
				Directory.CreateDirectory(OXYGEN_CONFIG_PATH);
				StreamWriter streamWriter = File.CreateText(Path.Combine(OXYGEN_CONFIG_PATH, "Template.json"));
				streamWriter.WriteLine(ConfigManager.Serialize(new OxygenConfig()));
				streamWriter.Flush();
				streamWriter.Close();
			}
			ClassInjector.RegisterTypeInIl2Cpp<AirManager>();
			LevelAPI.OnBuildDone += AirManager.OnBuildDone;
			LevelAPI.OnLevelCleanup += AirManager.OnLevelCleanup;
			ClassInjector.RegisterTypeInIl2Cpp<AirBar>();
			LevelAPI.OnBuildStart += AirBar.Setup;
			LevelAPI.OnLevelCleanup += AirBar.OnLevelCleanup;
			ClassInjector.RegisterTypeInIl2Cpp<AirPlane>();
			LevelAPI.OnBuildStart += AirPlane.OnBuildStart;
			LevelAPI.OnLevelCleanup += AirPlane.OnLevelCleanup;
			new Harmony("Inas.Oxygen").PatchAll();
			foreach (string item in Directory.EnumerateFiles(OXYGEN_CONFIG_PATH, "*.json", SearchOption.AllDirectories))
			{
				ConfigManager.Load<OxygenConfig>(item, out var config);
				foreach (OxygenBlock block in config.Blocks)
				{
					foreach (uint fogSetting in block.FogSettings)
					{
						if (!lookup.ContainsKey(fogSetting))
						{
							lookup.Add(fogSetting, block);
						}
					}
				}
			}
			listener = LiveEdit.CreateListener(OXYGEN_CONFIG_PATH, "*.json", true);
			LiveEditListener obj = listener;
			object obj2 = <>O.<6>__Listener_FileChanged1;
			if (obj2 == null)
			{
				LiveEditEventHandler val = Listener_FileChanged1;
				<>O.<6>__Listener_FileChanged1 = val;
				obj2 = (object)val;
			}
			obj.FileChanged += (LiveEditEventHandler)obj2;
		}

		private static void Listener_FileChanged1(LiveEditEventArgs e)
		{
			Log.Warning("LiveEdit File Changed: " + e.FullPath + ".");
			LiveEdit.TryReadFileContent(e.FullPath, (Action<string>)delegate(string content)
			{
				foreach (OxygenBlock block in ConfigManager.Deserialize<OxygenConfig>(content).Blocks)
				{
					foreach (uint fogSetting in block.FogSettings)
					{
						if (lookup.ContainsKey(fogSetting))
						{
							lookup.Remove(fogSetting);
						}
						lookup.Add(fogSetting, block);
						Log.Warning($"Replaced OxygenConfig for FogSetting: {fogSetting}.");
					}
				}
				if (GameStateManager.IsInExpedition)
				{
					AirManager.Current.UpdateAirConfig(AirManager.Current.FogSetting(), LiveEditForceUpdate: true);
				}
			});
		}
	}
}
namespace Oxygen.Utils
{
	internal static class Extension
	{
		public static T Instantiate<T>(this GameObject gameObject, string name) where T : Component
		{
			GameObject obj = Object.Instantiate<GameObject>(gameObject, gameObject.transform.parent, false);
			((Object)obj).name = name;
			return obj.GetComponent<T>();
		}
	}
	internal class LocalizedTextConverter : JsonConverter<LocalizedText>
	{
		public override bool HandleNull => false;

		public override LocalizedText Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
		{
			//IL_0018: Unknown result type (might be due to invalid IL or missing references)
			//IL_001d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002c: Expected O, but got Unknown
			//IL_002c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0031: 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_0045: Expected O, but got Unknown
			switch (reader.TokenType)
			{
			case JsonTokenType.String:
			{
				string @string = reader.GetString();
				return new LocalizedText
				{
					Id = 0u,
					UntranslatedText = @string
				};
			}
			case JsonTokenType.Number:
				return new LocalizedText
				{
					Id = reader.GetUInt32(),
					UntranslatedText = null
				};
			default:
				throw new JsonException($"LocalizedTextJson type: {reader.TokenType} is not implemented!");
			}
		}

		public override void Write(Utf8JsonWriter writer, LocalizedText value, JsonSerializerOptions options)
		{
			JsonSerializer.Serialize<LocalizedText>(writer, value, options);
		}
	}
	internal static class Log
	{
		private static ManualLogSource source;

		static Log()
		{
			source = Logger.CreateLogSource("Oxygen");
		}

		public static void Debug(object msg)
		{
			source.LogDebug(msg);
		}

		public static void Error(object msg)
		{
			source.LogError(msg);
		}

		public static void Fatal(object msg)
		{
			source.LogFatal(msg);
		}

		public static void Info(object msg)
		{
			source.LogInfo(msg);
		}

		public static void Message(object msg)
		{
			source.LogMessage(msg);
		}

		public static void Warning(object msg)
		{
			source.LogWarning(msg);
		}
	}
}
namespace Oxygen.Utils.PartialData
{
	public static class MTFOPartialDataUtil
	{
		public const string PLUGIN_GUID = "MTFO.Extension.PartialBlocks";

		public static JsonConverter PersistentIDConverter { get; private set; }

		public static JsonConverter LocalizedTextConverter { get; private set; }

		public static bool IsLoaded { get; private set; }

		public static bool Initialized { get; private set; }

		public static string PartialDataPath { get; private set; }

		public static string ConfigPath { get; private set; }

		static MTFOPartialDataUtil()
		{
			PersistentIDConverter = null;
			LocalizedTextConverter = null;
			IsLoaded = false;
			Initialized = false;
			PartialDataPath = string.Empty;
			ConfigPath = string.Empty;
			if (!((BaseChainloader<BasePlugin>)(object)IL2CPPChainloader.Instance).Plugins.TryGetValue("MTFO.Extension.PartialBlocks", out var value))
			{
				return;
			}
			try
			{
				Assembly obj = ((value == null) ? null : value.Instance?.GetType()?.Assembly) ?? null;
				if ((object)obj == null)
				{
					throw new Exception("Assembly is Missing!");
				}
				Type[] types = obj.GetTypes();
				Type type = types.First((Type t) => t.Name == "PersistentIDConverter");
				if ((object)type == null)
				{
					throw new Exception("Unable to Find PersistentIDConverter Class");
				}
				Type type2 = types.First((Type t) => t.Name == "LocalizedTextConverter");
				if ((object)type2 == null)
				{
					throw new Exception("Unable to Find LocalizedTextConverter Class");
				}
				Type obj2 = types.First((Type t) => t.Name == "PartialDataManager") ?? throw new Exception("Unable to Find PartialDataManager Class");
				PropertyInfo property = obj2.GetProperty("Initialized", BindingFlags.Static | BindingFlags.Public);
				PropertyInfo property2 = obj2.GetProperty("PartialDataPath", BindingFlags.Static | BindingFlags.Public);
				PropertyInfo? property3 = obj2.GetProperty("ConfigPath", BindingFlags.Static | BindingFlags.Public);
				if ((object)property == null)
				{
					throw new Exception("Unable to Find Property: Initialized");
				}
				if ((object)property2 == null)
				{
					throw new Exception("Unable to Find Property: PartialDataPath");
				}
				if ((object)property3 == null)
				{
					throw new Exception("Unable to Find Field: ConfigPath");
				}
				Initialized = (bool)property.GetValue(null);
				PartialDataPath = (string)property2.GetValue(null);
				ConfigPath = (string)property3.GetValue(null);
				PersistentIDConverter = (JsonConverter)Activator.CreateInstance(type);
				LocalizedTextConverter = (JsonConverter)Activator.CreateInstance(type2);
				IsLoaded = true;
			}
			catch (Exception value2)
			{
				Log.Error($"Exception thrown while reading data from MTFO_Extension_PartialData:\n{value2}");
			}
		}
	}
	public static class MTFOUtil
	{
		public const string PLUGIN_GUID = "com.dak.MTFO";

		public const BindingFlags PUBLIC_STATIC = BindingFlags.Static | BindingFlags.Public;

		public static string GameDataPath { get; private set; }

		public static string CustomPath { get; private set; }

		public static bool HasCustomContent { get; private set; }

		public static bool IsLoaded { get; private set; }

		static MTFOUtil()
		{
			GameDataPath = string.Empty;
			CustomPath = string.Empty;
			HasCustomContent = false;
			IsLoaded = false;
			if (!((BaseChainloader<BasePlugin>)(object)IL2CPPChainloader.Instance).Plugins.TryGetValue("com.dak.MTFO", out var value))
			{
				return;
			}
			try
			{
				Assembly obj = ((value == null) ? null : value.Instance?.GetType()?.Assembly) ?? null;
				if ((object)obj == null)
				{
					throw new Exception("Assembly is Missing!");
				}
				Type obj2 = obj.GetTypes().First((Type t) => t.Name == "ConfigManager") ?? throw new Exception("Unable to Find ConfigManager Class");
				FieldInfo field = obj2.GetField("GameDataPath", BindingFlags.Static | BindingFlags.Public);
				FieldInfo field2 = obj2.GetField("CustomPath", BindingFlags.Static | BindingFlags.Public);
				FieldInfo? field3 = obj2.GetField("HasCustomContent", BindingFlags.Static | BindingFlags.Public);
				if ((object)field == null)
				{
					throw new Exception("Unable to Find Field: GameDataPath");
				}
				if ((object)field2 == null)
				{
					throw new Exception("Unable to Find Field: CustomPath");
				}
				if ((object)field3 == null)
				{
					throw new Exception("Unable to Find Field: HasCustomContent");
				}
				GameDataPath = (string)field.GetValue(null);
				CustomPath = (string)field2.GetValue(null);
				HasCustomContent = (bool)field3.GetValue(null);
				IsLoaded = true;
			}
			catch (Exception value2)
			{
				Log.Error($"Exception thrown while reading path from DataDumper (MTFO): \n{value2}");
			}
		}
	}
}
namespace Oxygen.Patches
{
	[HarmonyPatch]
	internal class Patches_Dam_PlayerDamageLocal
	{
		[HarmonyPrefix]
		[HarmonyPatch(typeof(Dam_PlayerDamageLocal), "ReceiveNoAirDamage")]
		public static bool Pre_ReceiveNoAirDamage(Dam_PlayerDamageLocal __instance, pMiniDamageData data)
		{
			//IL_00a1: Unknown result type (might be due to invalid IL or missing references)
			float num = ((UFloat16)(ref data.damage)).Get(((Dam_SyncedDamageBase)__instance).HealthMax);
			((Dam_PlayerDamageBase)__instance).m_nextRegen = Clock.Time + ((Dam_PlayerDamageBase)__instance).Owner.PlayerData.healthRegenStartDelayAfterDamage;
			if (((Agent)((Dam_PlayerDamageBase)__instance).Owner).IsLocallyOwned)
			{
				DramaManager.CurrentState.OnLocalDamage(num);
				GameEventManager.PostEvent((eGameEvent)13, ((Dam_PlayerDamageBase)__instance).Owner, num, "", (Dictionary<string, string>)null);
			}
			else
			{
				DramaManager.CurrentState.OnTeammatesDamage(num);
			}
			if (((Dam_PlayerDamageBase)__instance).IgnoreAllDamage)
			{
				return false;
			}
			if (SNet.IsMaster && !((Dam_SyncedDamageBase)__instance).RegisterDamage(num))
			{
				((Dam_SyncedDamageBase)__instance).SendSetHealth(((Dam_SyncedDamageBase)__instance).Health);
			}
			__instance.Hitreact(((UFloat16)(ref data.damage)).Get(((Dam_SyncedDamageBase)__instance).HealthMax), Vector3.zero, true, false, false);
			return false;
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(Dam_PlayerDamageLocal), "ReceiveBulletDamage")]
		public static void Post_ReceiveBulletDamage()
		{
			AirManager.Current.ResetHealthToRegen();
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(Dam_PlayerDamageLocal), "ReceiveMeleeDamage")]
		public static void Post_ReceiveMeleeDamage()
		{
			AirManager.Current.ResetHealthToRegen();
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(Dam_PlayerDamageLocal), "ReceiveFireDamage")]
		public static void Post_ReceiveFireDamage()
		{
			AirManager.Current.ResetHealthToRegen();
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(Dam_PlayerDamageLocal), "ReceiveShooterProjectileDamage")]
		public static void Post_ReceiveShooterProjectileDamage()
		{
			AirManager.Current.ResetHealthToRegen();
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(Dam_PlayerDamageLocal), "ReceiveTentacleAttackDamage")]
		public static void Post_ReceiveTentacleAttackDamage()
		{
			AirManager.Current.ResetHealthToRegen();
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(Dam_PlayerDamageLocal), "ReceivePushDamage")]
		public static void Post_ReceivePushDamage()
		{
			AirManager.Current.ResetHealthToRegen();
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(Dam_PlayerDamageLocal), "ReceiveSetDead")]
		public static void Post_ReceiveSetDead()
		{
			AirManager.Current.ResetHealthToRegen();
		}
	}
	[HarmonyPatch(typeof(EnvironmentStateManager), "UpdateFog")]
	internal class EnvironmentStateManager_UpdateFog
	{
		public static void Prefix(EnvironmentStateManager __instance)
		{
			//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_002a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0039: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)AirManager.Current == (Object)null)
			{
				return;
			}
			FogState val = ((Il2CppArrayBase<FogState>)(object)__instance.m_stateReplicator.State.FogStates)[__instance.m_latestKnownLocalDimensionCreationIndex];
			if (val.FogDataID != 0)
			{
				AirManager.Current.UpdateAirConfig(val.FogDataID);
				if (!AirManager.Current.HasAirConfig())
				{
					AirManager.Current.StopInfectionLoop();
				}
			}
		}
	}
	[HarmonyPatch(typeof(FogRepeller_Sphere), "StartRepelling")]
	internal class FogRepeller_Sphere_StartRepelling
	{
		public static void Postfix(ref FogRepeller_Sphere __instance)
		{
			if (__instance.m_infectionShield != null)
			{
				EffectVolumeManager.UnregisterVolume((EffectVolume)(object)__instance.m_infectionShield);
				((EffectVolume)__instance.m_infectionShield).contents = (eEffectVolumeContents)0;
				EffectVolumeManager.RegisterVolume((EffectVolume)(object)__instance.m_infectionShield);
			}
		}
	}
	[HarmonyPatch(typeof(LocalPlayerAgentSettings), "UpdateBlendTowardsTargetFogSetting")]
	internal class LocalPlayerAgentSettings_UpdateBlendTowardsTargetFogSetting
	{
		public static void Postfix(LocalPlayerAgentSettings __instance, float amount)
		{
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			if (!AirManager.Current.HasAirConfig())
			{
				AirPlane.Current.Unregister();
			}
			else
			{
				if (__instance.m_targetFogSettings == null || !SNet.LocalPlayer.HasPlayerAgent)
				{
					return;
				}
				PlayerAgent localPlayerAgent = PlayerManager.GetLocalPlayerAgent();
				if ((Object)(object)localPlayerAgent.FPSCamera == (Object)null)
				{
					return;
				}
				AirPlane current = AirPlane.Current;
				if (!((Object)(object)current == (Object)null) && RundownManager.ExpeditionIsStarted)
				{
					float num = 0f;
					Dimension val = default(Dimension);
					if (Dimension.GetDimension(((Agent)localPlayerAgent).DimensionIndex, ref val))
					{
						num = val.GroundY;
					}
					PreLitVolume prelitVolume = localPlayerAgent.FPSCamera.PrelitVolume;
					((EffectVolume)current.airPlane).invert = (double)prelitVolume.m_densityHeightMaxBoost > (double)prelitVolume.m_fogDensity;
					((EffectVolume)current.airPlane).contents = (eEffectVolumeContents)1;
					((EffectVolume)current.airPlane).modification = (eEffectVolumeModification)0;
					((EffectVolume)current.airPlane).modificationScale = AirManager.Current.AirLoss();
					current.airPlane.lowestAltitude = prelitVolume.m_densityHeightAltitude + num;
					current.airPlane.highestAltitude = prelitVolume.m_densityHeightAltitude + prelitVolume.m_densityHeightRange + num;
					AirPlane.Current.Register();
				}
			}
		}
	}
	[HarmonyPatch]
	internal class Patch_PlayerAgent
	{
		[HarmonyPrefix]
		[HarmonyPatch(typeof(PlayerAgent), "ReceiveModification")]
		public static void ReceiveModification(PlayerAgent __instance, ref EV_ModificationData data)
		{
			if (AirManager.Current.HasAirConfig())
			{
				if ((double)data.health != 0.0)
				{
					AirManager.Current.RemoveAir(data.health);
				}
				else
				{
					AirManager.Current.AddAir();
				}
				data.health = 0f;
			}
		}

		[HarmonyPostfix]
		[HarmonyWrapSafe]
		[HarmonyPatch(typeof(PlayerAgent), "Setup")]
		internal static void Post_Setup(PlayerAgent __instance)
		{
			if (((Agent)__instance).IsLocallyOwned)
			{
				AirManager.Setup(__instance);
			}
		}
	}
}
namespace Oxygen.Config
{
	public class ConfigManager
	{
		private static readonly JsonSerializerOptions s_SerializerOptions;

		public static T Deserialize<T>(string json)
		{
			return JsonSerializer.Deserialize<T>(json, s_SerializerOptions);
		}

		public static string Serialize<T>(T value)
		{
			return JsonSerializer.Serialize(value, s_SerializerOptions);
		}

		static ConfigManager()
		{
			s_SerializerOptions = new JsonSerializerOptions
			{
				AllowTrailingCommas = true,
				ReadCommentHandling = JsonCommentHandling.Skip,
				PropertyNameCaseInsensitive = true,
				WriteIndented = true
			};
			s_SerializerOptions.Converters.Add(new JsonStringEnumConverter());
			if (MTFOPartialDataUtil.IsLoaded && MTFOPartialDataUtil.Initialized)
			{
				s_SerializerOptions.Converters.Add(MTFOPartialDataUtil.PersistentIDConverter);
				s_SerializerOptions.Converters.Add(MTFOPartialDataUtil.LocalizedTextConverter);
				Log.Message("PartialData Support Found!");
			}
			else
			{
				s_SerializerOptions.Converters.Add(new LocalizedTextConverter());
			}
		}

		public static void Load<T>(string file, out T config) where T : new()
		{
			if (file.Length < ".json".Length)
			{
				config = default(T);
				return;
			}
			if (file.Substring(file.Length - ".json".Length) != ".json")
			{
				file += ".json";
			}
			file = File.ReadAllText(Path.Combine(ConfigManager.CustomPath, "Oxygen", file));
			config = Deserialize<T>(file);
		}
	}
	public class AirText
	{
		public float x { get; set; }

		public float y { get; set; }

		public LocalizedText Text { get; set; }
	}
	public class OxygenConfig
	{
		public List<OxygenBlock> Blocks { get; set; } = new List<OxygenBlock>
		{
			new OxygenBlock()
		};

	}
	public class OxygenBlock
	{
		public float AirLoss { get; set; }

		public float AirGain { get; set; } = 1f;


		public float DamageTime { get; set; } = 1f;


		public float DamageAmount { get; set; }

		public bool ShatterGlass { get; set; }

		public float ShatterAmount { get; set; }

		public float DamageThreshold { get; set; } = 0.1f;


		public bool AlwaysDisplayAirBar { get; set; }

		public float HealthRegenProportion { get; set; } = 1f;


		public float TimeToStartHealthRegen { get; set; } = 3f;


		public float TimeToCompleteHealthRegen { get; set; } = 5f;


		public AirText AirText { get; set; }

		public List<uint> FogSettings { get; set; } = new List<uint> { 0u };

	}
}
namespace Oxygen.Components
{
	public class AirBar : MonoBehaviour
	{
		public static AirBar Current;

		private TextMeshPro m_airText;

		private TextMeshPro m_airTextLocalization;

		private float m_airTextX;

		private float m_airTextY;

		private float m_airTextZ;

		private RectTransform m_air1;

		private RectTransform m_air2;

		private SpriteRenderer m_airBar1;

		private SpriteRenderer m_airBar2;

		private float m_airWidth = 100f;

		private float m_barHeightMin = 3f;

		private float m_barHeightMax = 9f;

		private Color m_airLow = new Color(0f, 0.5f, 0.5f);

		private Color m_airHigh = new Color(0f, 0.3f, 0.8f);

		public AirBar(IntPtr value)
			: base(value)
		{
		}//IL_0031: Unknown result type (might be due to invalid IL or missing references)
		//IL_0036: 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_0050: Unknown result type (might be due to invalid IL or missing references)


		public static void Setup()
		{
			if ((Object)(object)Current == (Object)null)
			{
				Current = ((Component)GuiManager.Current.m_playerLayer.m_playerStatus).gameObject.AddComponent<AirBar>();
				Current.Init();
			}
		}

		private void Init()
		{
			//IL_00e5: Unknown result type (might be due to invalid IL or missing references)
			//IL_0100: Unknown result type (might be due to invalid IL or missing references)
			//IL_011b: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ac: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b6: Unknown result type (might be due to invalid IL or missing references)
			//IL_0270: Unknown result type (might be due to invalid IL or missing references)
			//IL_027a: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)m_airText == (Object)null)
			{
				m_airText = ((Component)GuiManager.Current.m_playerLayer.m_playerStatus.m_healthText).gameObject.Instantiate<TextMeshPro>("AirText");
				TextMeshPro airText = m_airText;
				((TMP_Text)airText).fontSize = ((TMP_Text)airText).fontSize / 1.25f;
				m_airText.transform.Translate(0f, -30f, 0f);
			}
			if ((Object)(object)m_airTextLocalization == (Object)null)
			{
				m_airTextLocalization = ((Component)GuiManager.Current.m_playerLayer.m_playerStatus.m_pulseText).gameObject.Instantiate<TextMeshPro>("AirText Localization");
				((Behaviour)m_airTextLocalization).enabled = true;
				m_airTextLocalization.transform.Translate(300f - m_airWidth, -45f, 0f);
				m_airTextX = m_airTextLocalization.transform.position.x;
				m_airTextY = m_airTextLocalization.transform.position.y;
				m_airTextZ = m_airTextLocalization.transform.position.z;
			}
			if ((Object)(object)m_air1 == (Object)null)
			{
				m_air1 = ((Component)((Component)GuiManager.Current.m_playerLayer.m_playerStatus.m_health1).gameObject.transform.parent).gameObject.Instantiate<RectTransform>("AirFill Right");
				((Component)m_air1).transform.Translate(0f, -30f, 0f);
				SpriteRenderer component = ((Component)((Transform)m_air1).GetChild(0)).GetComponent<SpriteRenderer>();
				component.size = new Vector2(m_airWidth, component.size.y);
				m_airBar1 = ((Component)((Transform)m_air1).GetChild(1)).GetComponent<SpriteRenderer>();
				((Renderer)((Component)((Transform)m_air1).GetChild(2)).GetComponent<SpriteRenderer>()).enabled = false;
			}
			if ((Object)(object)m_air2 == (Object)null)
			{
				m_air2 = ((Component)((Component)GuiManager.Current.m_playerLayer.m_playerStatus.m_health2).gameObject.transform.parent).gameObject.Instantiate<RectTransform>("AirFill Left");
				((Component)m_air2).transform.Translate(0f, 30f, 0f);
				SpriteRenderer component2 = ((Component)((Transform)m_air2).GetChild(0)).GetComponent<SpriteRenderer>();
				component2.size = new Vector2(m_airWidth, component2.size.y);
				m_airBar2 = ((Component)((Transform)m_air2).GetChild(1)).GetComponent<SpriteRenderer>();
				((Renderer)((Component)((Transform)m_air2).GetChild(2)).GetComponent<SpriteRenderer>()).enabled = false;
			}
			UpdateAirBar(1f);
			SetVisible(vis: false);
		}

		public void UpdateAirBar(float air)
		{
			SetAirPercentageText(air);
			SetAirBar(m_airBar1, air);
			SetAirBar(m_airBar2, air);
		}

		private void SetAirBar(SpriteRenderer bar, float val)
		{
			//IL_001b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			//IL_002d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0033: Unknown result type (might be due to invalid IL or missing references)
			bar.size = new Vector2(val * m_airWidth, Mathf.Lerp(m_barHeightMin, m_barHeightMax, val));
			bar.color = Color.Lerp(m_airLow, m_airHigh, val);
		}

		private void SetAirPercentageText(float val)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0012: 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_0042: Unknown result type (might be due to invalid IL or missing references)
			Color color = Color.Lerp(m_airLow, m_airHigh, val);
			((TMP_Text)m_airText).text = "O<size=75%>2</size>";
			((Graphic)m_airText).color = color;
			((TMP_Text)m_airText).ForceMeshUpdate(true, false);
			((Graphic)m_airTextLocalization).color = color;
			((TMP_Text)m_airTextLocalization).ForceMeshUpdate(true, false);
		}

		public void UpdateAirText(OxygenBlock config)
		{
			//IL_007d: Unknown result type (might be due to invalid IL or missing references)
			//IL_008d: Unknown result type (might be due to invalid IL or missing references)
			if (config != null)
			{
				string text = LocalizedText.op_Implicit(config.AirText.Text);
				float x = config.AirText.x;
				float y = config.AirText.y;
				((TMP_Text)m_airTextLocalization).text = text;
				((TMP_Text)m_airTextLocalization).ForceMeshUpdate(true, false);
				CoroutineManager.BlinkIn(((Component)m_airTextLocalization).gameObject, 0f);
				m_airTextLocalization.transform.SetPositionAndRotation(new Vector3(m_airTextX + x, m_airTextY + y, m_airTextZ), m_airTextLocalization.transform.rotation);
			}
		}

		public void SetVisible(bool vis)
		{
			((Component)m_airText).gameObject.SetActive(vis);
			((Component)m_airTextLocalization).gameObject.SetActive(vis);
			((Component)m_air1).gameObject.SetActive(vis);
			((Component)m_air2).gameObject.SetActive(vis);
		}

		public static void OnLevelCleanup()
		{
			if (!((Object)(object)Current == (Object)null))
			{
				Current.SetVisible(vis: false);
			}
		}
	}
	public class AirManager : MonoBehaviour
	{
		public static AirManager Current;

		public PlayerAgent m_playerAgent;

		private HUDGlassShatter m_hudGlass;

		private Dam_PlayerDamageBase Damage;

		public OxygenBlock config;

		private uint fogSetting;

		private FogSettingsDataBlock fogSettingDB;

		private float airAmount = 1f;

		private float damageTick;

		private float glassShatterAmount;

		private bool m_isInInfectionLoop;

		private bool isRegeningHealth;

		private float healthToRegen;

		private float healthRegenTick;

		private float tickUntilHealthRegenHealthStart;

		private readonly float regenHealthTickInterval = 0.25f;

		private float healthRegenAmountPerInterval;

		internal bool PlayerShouldCough;

		private readonly float CoughPerLoss = 0.1f;

		private float CoughLoss;

		public AirManager(IntPtr value)
			: base(value)
		{
		}

		public static void Setup(PlayerAgent playerAgent)
		{
			Current = ((Component)playerAgent).gameObject.AddComponent<AirManager>();
		}

		public static void OnBuildDone()
		{
			if (!((Object)(object)Current == (Object)null))
			{
				Current.m_playerAgent = PlayerManager.GetLocalPlayerAgent();
				Current.m_hudGlass = ((Component)Current.m_playerAgent.FPSCamera).GetComponent<HUDGlassShatter>();
				Current.Damage = ((Component)Current.m_playerAgent).gameObject.GetComponent<Dam_PlayerDamageBase>();
				Current.UpdateAirConfig(RundownManager.ActiveExpedition.Expedition.FogSettings);
				AirBar.Current.UpdateAirText(Current.config);
			}
		}

		public static void OnLevelCleanup()
		{
			if (!((Object)(object)Current == (Object)null))
			{
				if (Current.m_isInInfectionLoop)
				{
					Current.StopInfectionLoop();
				}
				Current.config = null;
				Current.fogSetting = 0u;
				Current.fogSettingDB = null;
				Current.airAmount = 0f;
				Current.damageTick = 0f;
				Current.glassShatterAmount = 0f;
				Current.healthToRegen = 0f;
				Current.m_playerAgent = null;
				Current.m_hudGlass = null;
				Current.Damage = null;
			}
		}

		private void Update()
		{
			if (!RundownManager.ExpeditionIsStarted)
			{
				return;
			}
			if (!HasAirConfig())
			{
				AirBar.Current.SetVisible(vis: false);
				return;
			}
			if (airAmount == 1f)
			{
				if (config.AlwaysDisplayAirBar)
				{
					AirBar.Current.SetVisible(vis: true);
				}
				else
				{
					AirBar.Current.SetVisible(vis: false);
				}
			}
			else
			{
				AirBar.Current.SetVisible(vis: true);
			}
			if (airAmount <= config.DamageThreshold)
			{
				damageTick += Time.deltaTime;
				if (damageTick > config.DamageTime && ((Agent)m_playerAgent).Alive)
				{
					AirDamage();
				}
				isRegeningHealth = false;
			}
			else if (healthToRegen > 0f)
			{
				tickUntilHealthRegenHealthStart += Time.deltaTime;
				if (tickUntilHealthRegenHealthStart > config.TimeToStartHealthRegen)
				{
					if (healthRegenAmountPerInterval == 0f)
					{
						healthRegenAmountPerInterval = healthToRegen * (regenHealthTickInterval / config.TimeToCompleteHealthRegen);
					}
					RegenHealth();
					if (!isRegeningHealth)
					{
						Damage.m_nextRegen = Clock.Time + config.TimeToStartHealthRegen + config.TimeToCompleteHealthRegen;
						isRegeningHealth = true;
					}
				}
			}
			else
			{
				isRegeningHealth = false;
			}
		}

		public void AddAir()
		{
			if (HasAirConfig())
			{
				float airGain = config.AirGain;
				airAmount = Mathf.Clamp01(airAmount + airGain);
				AirBar.Current.UpdateAirBar(airAmount);
				if (fogSettingDB.Infection <= 0f && m_isInInfectionLoop)
				{
					StopInfectionLoop();
				}
			}
		}

		public void RemoveAir(float amount)
		{
			if (HasAirConfig())
			{
				amount = config.AirLoss;
				airAmount = Mathf.Clamp01(airAmount - amount);
				AirBar.Current.UpdateAirBar(airAmount);
				if (fogSettingDB.Infection <= 0f && amount > 0f)
				{
					StartInfectionLoop();
				}
			}
		}

		public void AirDamage()
		{
			float health = ((Dam_SyncedDamageBase)Damage).Health;
			float damageAmount = config.DamageAmount;
			Damage.m_nextRegen = Clock.Time + config.TimeToStartHealthRegen;
			if (!(health <= 1f))
			{
				((Dam_SyncedDamageBase)Damage).NoAirDamage(damageAmount);
				if (config.ShatterGlass)
				{
					glassShatterAmount += config.ShatterAmount;
					m_hudGlass.SetGlassShatterProgression(glassShatterAmount);
				}
				damageTick = 0f;
				tickUntilHealthRegenHealthStart = 0f;
				healthRegenAmountPerInterval = 0f;
				healthToRegen += damageAmount * config.HealthRegenProportion;
				CoughLoss += damageAmount;
				if (CoughLoss > CoughPerLoss)
				{
					PlayerShouldCough = true;
					CoughLoss = 0f;
				}
			}
		}

		public void RegenHealth()
		{
			if (healthToRegen <= 0f)
			{
				return;
			}
			tickUntilHealthRegenHealthStart = config.TimeToStartHealthRegen;
			healthRegenTick += Time.deltaTime;
			if (healthRegenTick > regenHealthTickInterval)
			{
				float num = healthRegenAmountPerInterval;
				if (num >= healthToRegen)
				{
					num = healthToRegen;
					healthToRegen = 0f;
					tickUntilHealthRegenHealthStart = 0f;
					healthRegenAmountPerInterval = 0f;
					isRegeningHealth = false;
				}
				else
				{
					healthToRegen -= num;
				}
				((Dam_SyncedDamageBase)Damage).AddHealth(num, (Agent)(object)m_playerAgent);
				healthRegenTick = 0f;
			}
		}

		public void UpdateAirConfig(uint fogsetting, bool LiveEditForceUpdate = false)
		{
			if (fogsetting != 0 && (fogsetting != fogSetting || LiveEditForceUpdate))
			{
				if (Plugin.lookup.ContainsKey(fogsetting))
				{
					config = Plugin.lookup[fogsetting];
				}
				else if (Plugin.lookup.ContainsKey(0u))
				{
					config = Plugin.lookup[0u];
				}
				else
				{
					config = null;
					airAmount = 1f;
				}
				fogSetting = fogsetting;
				fogSettingDB = GameDataBlockBase<FogSettingsDataBlock>.GetBlock(fogsetting);
				if (GameStateManager.IsInExpedition)
				{
					AirBar.Current.UpdateAirText(config);
				}
			}
		}

		public void ResetHealthToRegen()
		{
			healthRegenTick = 0f;
			healthToRegen = 0f;
			tickUntilHealthRegenHealthStart = 0f;
		}

		public float AirLoss()
		{
			if (config != null)
			{
				return config.AirLoss;
			}
			return 0f;
		}

		public bool AlwaysDisplayAirBar()
		{
			if (config != null)
			{
				return config.AlwaysDisplayAirBar;
			}
			return false;
		}

		public uint FogSetting()
		{
			return fogSetting;
		}

		public float HealthToRegen()
		{
			return healthToRegen;
		}

		public string AirText()
		{
			return LocalizedText.op_Implicit((config == null) ? null : config.AirText.Text);
		}

		public float AirTextX()
		{
			if (config != null)
			{
				return config.AirText.x;
			}
			return 0f;
		}

		public float AirTextY()
		{
			if (config != null)
			{
				return config.AirText.y;
			}
			return 0f;
		}

		public bool HasAirConfig()
		{
			return config != null;
		}

		public void StartInfectionLoop()
		{
			if (!m_isInInfectionLoop)
			{
				m_playerAgent.Sound.Post(EVENTS.INFECTION_EFFECT_LOOP_START, true);
				m_isInInfectionLoop = true;
			}
		}

		public void StopInfectionLoop()
		{
			if (m_isInInfectionLoop)
			{
				if ((Object)(object)m_playerAgent != (Object)null && m_playerAgent.Sound != null)
				{
					m_playerAgent.Sound.Post(EVENTS.INFECTION_EFFECT_LOOP_STOP, true);
				}
				m_isInInfectionLoop = false;
			}
		}
	}
	public class AirPlane : MonoBehaviour
	{
		public static AirPlane Current;

		public EV_Plane airPlane;

		private bool isAirPlaneRegistered;

		public AirPlane(IntPtr value)
			: base(value)
		{
		}

		public static void OnBuildStart()
		{
			//IL_0026: Unknown result type (might be due to invalid IL or missing references)
			//IL_0030: Expected O, but got Unknown
			if ((Object)(object)Current == (Object)null)
			{
				Current = ((Component)LocalPlayerAgentSettings.Current).gameObject.AddComponent<AirPlane>();
			}
			Current.airPlane = new EV_Plane();
			uint num = RundownManager.ActiveExpedition.Expedition.FogSettings;
			if (num == 0)
			{
				num = 21u;
			}
			OxygenBlock oxygenBlock = (Plugin.lookup.ContainsKey(num) ? Plugin.lookup[num] : ((!Plugin.lookup.ContainsKey(0u)) ? null : Plugin.lookup[0u]));
			FogSettingsDataBlock block = GameDataBlockBase<FogSettingsDataBlock>.GetBlock(num);
			((EffectVolume)Current.airPlane).invert = block.DensityHeightMaxBoost > block.FogDensity;
			((EffectVolume)Current.airPlane).contents = (eEffectVolumeContents)1;
			((EffectVolume)Current.airPlane).modification = (eEffectVolumeModification)0;
			Current.airPlane.lowestAltitude = block.DensityHeightAltitude;
			Current.airPlane.highestAltitude = block.DensityHeightAltitude + block.DensityHeightRange;
			if (oxygenBlock != null)
			{
				((EffectVolume)Current.airPlane).modificationScale = oxygenBlock.AirLoss;
				Current.Register();
			}
		}

		public static void OnLevelCleanup()
		{
			if (!((Object)(object)Current == (Object)null))
			{
				Current.Unregister();
				Current.isAirPlaneRegistered = false;
				Current.airPlane = null;
			}
		}

		public void Register()
		{
			if (airPlane != null && !isAirPlaneRegistered)
			{
				EffectVolumeManager.RegisterVolume((EffectVolume)(object)airPlane);
				isAirPlaneRegistered = true;
			}
		}

		public void Unregister()
		{
			if (airPlane != null && isAirPlaneRegistered)
			{
				EffectVolumeManager.UnregisterVolume((EffectVolume)(object)airPlane);
				isAirPlaneRegistered = false;
			}
		}
	}
}

plugins/TrickyBall's Paradise/Custom/Inas07.EOSExt.EMP.dll

Decompiled 8 months ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using AIGraph;
using AK;
using AWO.Modules.WEE.Replicators;
using Agents;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Unity.IL2CPP;
using CellMenu;
using EOSExt.EMP.Definition;
using EOSExt.EMP.EMPComponent;
using EOSExt.EMP.Impl;
using EOSExt.EMP.Impl.Handlers;
using EOSExt.EMP.Impl.PersistentEMP;
using ExtraObjectiveSetup;
using ExtraObjectiveSetup.BaseClasses;
using ExtraObjectiveSetup.ExtendedWardenEvents;
using ExtraObjectiveSetup.Utils;
using FloLib.Networks.Replications;
using GTFO.API;
using GTFO.API.Utilities;
using GameData;
using Gear;
using HarmonyLib;
using Il2CppInterop.Runtime.Attributes;
using Il2CppInterop.Runtime.Injection;
using Il2CppInterop.Runtime.InteropTypes;
using Il2CppInterop.Runtime.InteropTypes.Arrays;
using Il2CppSystem.Collections.Generic;
using LevelGeneration;
using Microsoft.CodeAnalysis;
using Player;
using SNetwork;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETCoreApp,Version=v6.0", FrameworkDisplayName = ".NET 6.0")]
[assembly: AssemblyCompany("Inas07.EOSExt.EMP")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0+ddd2035f35992c9bbb9b48fa0cdce1d8a583a3b2")]
[assembly: AssemblyProduct("Inas07.EOSExt.EMP")]
[assembly: AssemblyTitle("Inas07.EOSExt.EMP")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.0.0.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace EOSExt.EMP
{
	public static class AWOUtil
	{
		public const string PLUGIN_GUID = "GTFO.AWO";

		public static bool IsLoaded { get; private set; }

		static AWOUtil()
		{
			IsLoaded = ((BaseChainloader<BasePlugin>)(object)IL2CPPChainloader.Instance).Plugins.TryGetValue("GTFO.AWO", out var _);
			EOSLogger.Debug("=============================================");
			EOSLogger.Debug($"EOSExt.EMP: AWO Loaded? {IsLoaded}");
			EOSLogger.Debug("=============================================");
		}

		internal static void SetupZoneLightReplicator(LG_Zone zone)
		{
			ZoneLightReplicator zoneReplicator = ((Component)zone).gameObject.GetComponent<ZoneLightReplicator>();
			if ((Object)(object)zoneReplicator == (Object)null)
			{
				EOSLogger.Error($"For Zone_{zone.Alias}: AWO is loaded but we cannot find its ZoneLightReplicator");
				return;
			}
			zoneReplicator.OnLightsChanged += delegate
			{
				//IL_0025: Unknown result type (might be due to invalid IL or missing references)
				LightWorker[] lightsInZone = zoneReplicator.LightsInZone;
				for (int i = 0; i < lightsInZone.Length; i++)
				{
					LG_Light light = lightsInZone[i].Light;
					EMPLightHandler handler = EMPLightHandler.GetHandler(light);
					if (handler != null)
					{
						handler.SetOriginalColor(light.m_color);
						handler.SetOriginalIntensity(light.m_intensity);
					}
				}
			};
		}
	}
	public class EMPManager : GenericExpeditionDefinitionManager<pEMPDefinition>
	{
		private Dictionary<uint, pEMP> _pEMPs { get; } = new Dictionary<uint, pEMP>();


		public IEnumerable<pEMP> pEMPs => _pEMPs.Values;

		protected override string DEFINITION_NAME => "PersistentEMP";

		public static EMPManager Current { get; }

		public PlayerAgent Player
		{
			get
			{
				if (!SNet.HasLocalPlayer || !SNet.LocalPlayer.HasPlayerAgent)
				{
					return null;
				}
				return ((Il2CppObjectBase)SNet.LocalPlayer.PlayerAgent).Cast<PlayerAgent>();
			}
		}

		internal List<EMPShock> ActiveEMPs { get; } = new List<EMPShock>();


		internal void SetupHUDAndFlashlight()
		{
			if ((Object)(object)Player == (Object)null)
			{
				EOSLogger.Error($"{"SetupHUDAndFlashlight": LocalPlayerAgent is not set!}");
				return;
			}
			if (EMPPlayerHudHandler.Instance == null)
			{
				((Component)Player).gameObject.AddComponent<EMPController>().AssignHandler(new EMPPlayerHudHandler());
				EOSLogger.Log("pEMP: PlayerHud setup completed");
			}
			if (EMPPlayerFlashLightHandler.Instance == null)
			{
				((Component)Player).gameObject.AddComponent<EMPController>().AssignHandler(new EMPPlayerFlashLightHandler());
				EOSLogger.Log("pEMP: PlayerFlashlight setup completed");
			}
		}

		internal void SetupAmmoWeaponHandlers(InventorySlot slot)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0004: Invalid comparison between Unknown and I4
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			if (slot - 1 <= 1)
			{
				SetupAmmoWeaponHandlerForSlot(slot);
			}
			static void SetupAmmoWeaponHandlerForSlot(InventorySlot slot)
			{
				//IL_0005: Unknown result type (might be due to invalid IL or missing references)
				//IL_0091: 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)
				BackpackItem val = default(BackpackItem);
				if (PlayerBackpackManager.LocalBackpack.TryGetBackpackItem(slot, ref val))
				{
					if (!((Object)(object)((Component)val.Instance).gameObject.GetComponent<EMPController>() != (Object)null))
					{
						((Component)val.Instance).gameObject.AddComponent<EMPController>().AssignHandler(new EMPGunSightHandler());
						EOSLogger.Log($"pEMP: Backpack {slot} setup completed");
					}
				}
				else
				{
					EOSLogger.Warning($"Couldn't get item for slot {slot}!");
				}
			}
		}

		internal void SetupToolHandler()
		{
			BackpackItem val = default(BackpackItem);
			if (PlayerBackpackManager.LocalBackpack.TryGetBackpackItem((InventorySlot)3, ref val))
			{
				if (!((Object)(object)((Component)val.Instance).gameObject.GetComponent<EMPController>() != (Object)null) && (Object)(object)((Component)val.Instance).GetComponent<EnemyScanner>() != (Object)null)
				{
					((Component)val.Instance).gameObject.AddComponent<EMPController>().AssignHandler(new EMPBioTrackerHandler());
					EOSLogger.Log($"pEMP: Backpack {3} setup completed");
				}
			}
			else
			{
				EOSLogger.Warning($"Couldn't get item for slot {3}!");
			}
		}

		public void TogglepEMPState(uint pEMPIndex, bool enabled)
		{
			if (!_pEMPs.ContainsKey(pEMPIndex))
			{
				EOSLogger.Error($"TogglepEMPState: pEMPIndex {pEMPIndex} not defined");
			}
			else
			{
				ActiveState newState = (enabled ? ActiveState.ENABLED : ActiveState.DISABLED);
				_pEMPs[pEMPIndex].ChangeToState(newState);
			}
		}

		public void TogglepEMPState(WardenObjectiveEventData e)
		{
			uint count = (uint)e.Count;
			bool enabled = e.Enabled;
			TogglepEMPState(count, enabled);
		}

		private void pEMPInit()
		{
			LevelAPI.OnBuildStart += delegate
			{
				pEMPClear();
				InitializepEMPs();
			};
			LevelAPI.OnLevelCleanup += pEMPClear;
		}

		private void pEMPClear()
		{
			foreach (pEMP value in _pEMPs.Values)
			{
				value.Destroy();
			}
			_pEMPs.Clear();
		}

		private void InitializepEMPs()
		{
			if (!base.definitions.ContainsKey(base.CurrentMainLevelLayout))
			{
				return;
			}
			GenericExpeditionDefinition<pEMPDefinition> val = base.definitions[base.CurrentMainLevelLayout];
			if (val == null || val.Definitions.Count < 1)
			{
				return;
			}
			foreach (pEMPDefinition definition in val.Definitions)
			{
				pEMP pEMP = new pEMP(definition);
				_pEMPs[definition.pEMPIndex] = pEMP;
				uint num = EOSNetworking.AllotReplicatorID();
				if (num == 0)
				{
					EOSLogger.Error("SetuppEMPReplicators: replicator ID depleted, cannot set up!");
					continue;
				}
				pEMP.SetupReplicator(num);
				EOSLogger.Debug($"pEMP_{definition.pEMPIndex} initialized");
			}
		}

		internal void SetLocalPlayerAgent(PlayerAgent localPlayerAgent)
		{
			if ((Object)(object)PlayerpEMPComponent.Current == (Object)null)
			{
				((Component)localPlayerAgent).gameObject.AddComponent<PlayerpEMPComponent>();
			}
		}

		public void ActivateEMPShock(Vector3 position, float range, float duration)
		{
			//IL_001a: 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_0039: Unknown result type (might be due to invalid IL or missing references)
			if (!GameStateManager.IsInExpedition)
			{
				EOSLogger.Error("Tried to activate an EMP when not in level, this shouldn't happen!");
				return;
			}
			float endTime = Clock.Time + duration;
			EMPShock eMPShock = new EMPShock(position, range, endTime);
			foreach (EMPHandler allHandler in EMPHandler.AllHandlers)
			{
				if (Vector3.Distance(position, allHandler.position) < range)
				{
					allHandler.AddAffectedBy(eMPShock);
				}
			}
			ActiveEMPs.Add(eMPShock);
		}

		internal void RemoveInactiveEMPs()
		{
			float time = Clock.Time;
			ActiveEMPs.RemoveAll((EMPShock emp) => emp.endTime < time);
		}

		public bool IsPlayerMapEMPD()
		{
			//IL_001d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0022: Unknown result type (might be due to invalid IL or missing references)
			//IL_0039: 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_009d: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a0: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)Player == (Object)null || !GameStateManager.IsInExpedition)
			{
				return false;
			}
			Vector3 position = ((Agent)Player).Position;
			foreach (EMPShock activeEMP in ActiveEMPs)
			{
				if (Vector3.Distance(position, activeEMP.position) < activeEMP.range)
				{
					return true;
				}
			}
			foreach (pEMP pEMP in pEMPs)
			{
				if (pEMP.State == ActiveState.ENABLED && pEMP.ItemToDisable.Map && Vector3.Distance(position, pEMP.position) < pEMP.range)
				{
					EOSLogger.Warning("MapEMPD: by pEMP");
					return true;
				}
			}
			return false;
		}

		protected override void FileChanged(LiveEditEventArgs e)
		{
			base.FileChanged(e);
			if (!base.definitions.TryGetValue(base.CurrentMainLevelLayout, out var value))
			{
				return;
			}
			foreach (pEMPDefinition definition in value.Definitions)
			{
				EOSLogger.Warning(definition.ItemToDisable.ToString());
			}
		}

		public override void Init()
		{
			EMPWardenEvents.Init();
			Events.InventoryWielded = (Action<InventorySlot>)Delegate.Combine(Events.InventoryWielded, new Action<InventorySlot>(SetupAmmoWeaponHandlers));
			pEMPInit();
		}

		private EMPManager()
		{
		}

		static EMPManager()
		{
			Current = new EMPManager();
			ClassInjector.RegisterTypeInIl2Cpp<EMPController>();
			ClassInjector.RegisterTypeInIl2Cpp<PlayerpEMPComponent>();
		}
	}
	internal static class EMPWardenEvents
	{
		public enum EMPEvents
		{
			Instant_Shock = 300,
			Toggle_PEMP_State
		}

		internal static void InstantShock(WardenObjectiveEventData e)
		{
			//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_001a: Unknown result type (might be due to invalid IL or missing references)
			Vector3 position = e.Position;
			float fogTransitionDuration = e.FogTransitionDuration;
			float duration = e.Duration;
			EMPManager.Current.ActivateEMPShock(position, fogTransitionDuration, duration);
		}

		internal static void TogglepEMPState(WardenObjectiveEventData e)
		{
			EMPManager.Current.TogglepEMPState(e);
		}

		internal static void Init()
		{
			EOSWardenEventManager.Current.AddEventDefinition(EMPEvents.Instant_Shock.ToString(), 300u, (Action<WardenObjectiveEventData>)InstantShock);
			EOSWardenEventManager.Current.AddEventDefinition(EMPEvents.Toggle_PEMP_State.ToString(), 301u, (Action<WardenObjectiveEventData>)TogglepEMPState);
		}
	}
	public static class Events
	{
		public static Action<GearPartFlashlight> FlashLightWielded;

		public static Action<InventorySlot> InventoryWielded;

		public static Action EnterGSInLevel;
	}
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInPlugin("Inas.EOSExt.EMP", "EOSExt.EMP", "1.1.7")]
	public class EntryPoint : BasePlugin
	{
		public const string AUTHOR = "Inas";

		public const string PLUGIN_NAME = "EOSExt.EMP";

		public const string VERSION = "1.1.7";

		private Harmony m_Harmony;

		public override void Load()
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_0010: Expected O, but got Unknown
			m_Harmony = new Harmony("EOSExt.EMP");
			m_Harmony.PatchAll();
			SetupManagers();
		}

		private void SetupManagers()
		{
			((GenericExpeditionDefinitionManager<pEMPDefinition>)EMPManager.Current).Init();
		}
	}
}
namespace EOSExt.EMP.Patches
{
	[HarmonyPatch]
	[HarmonyWrapSafe]
	internal class Inject_CM_PageMap
	{
		[HarmonyPostfix]
		[HarmonyPatch(typeof(CM_PageMap), "UpdatePlayerData")]
		private static void Post_CM_PageMap_OnEnable()
		{
			//IL_001b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0022: Invalid comparison between Unknown and I4
			CM_PageMap pageMap = MainMenuGuiLayer.Current.PageMap;
			if (!((Object)(object)pageMap == (Object)null) && RundownManager.ActiveExpedition != null && (int)GameStateManager.CurrentStateName == 10 && EMPManager.Current.IsPlayerMapEMPD())
			{
				pageMap.SetMapVisualsIsActive(false);
				pageMap.SetMapDisconnetedTextIsActive(true);
			}
		}
	}
	[HarmonyPatch(typeof(EnemyScanner))]
	internal static class Inject_EnemyScanner
	{
		[HarmonyPrefix]
		[HarmonyWrapSafe]
		[HarmonyPatch("UpdateDetectedEnemies")]
		internal static bool Pre_UpdateDetectedEnemies()
		{
			EMPBioTrackerHandler instance = EMPBioTrackerHandler.Instance;
			if (instance == null)
			{
				return true;
			}
			return !instance.IsEMPed();
		}

		[HarmonyPrefix]
		[HarmonyWrapSafe]
		[HarmonyPatch("UpdateTagProgress")]
		internal static bool Pre_UpdateTagProgress(EnemyScanner __instance)
		{
			//IL_006f: Unknown result type (might be due to invalid IL or missing references)
			//IL_004d: Unknown result type (might be due to invalid IL or missing references)
			if (EMPBioTrackerHandler.Instance == null)
			{
				return true;
			}
			if (EMPBioTrackerHandler.Instance.IsEMPed())
			{
				((ItemEquippable)__instance).Sound.Post(EVENTS.BIOTRACKER_TOOL_LOOP_STOP, true);
				__instance.m_screen.SetStatusText("ERROR");
				((ProgressBarBase)__instance.m_progressBar).SetProgress(1f);
				__instance.m_screen.SetGuixColor(Color.yellow);
				return false;
			}
			__instance.m_screen.SetStatusText("Ready to tag");
			__instance.m_screen.SetGuixColor(Color.red);
			return true;
		}
	}
	[HarmonyPatch]
	internal static class Inject_LG_Light
	{
		[HarmonyPrefix]
		[HarmonyWrapSafe]
		[HarmonyPatch(typeof(LG_Light), "Start")]
		internal static void Pre_Start(LG_Light __instance)
		{
			((Component)__instance).gameObject.AddComponent<EMPController>().AssignHandler(new EMPLightHandler());
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(LG_BuildZoneLightsJob), "Build")]
		private static void Post_ApplyColorScheme(bool __result, LG_BuildZoneLightsJob __instance)
		{
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			if (!__result)
			{
				return;
			}
			LG_Zone zone = __instance.m_zone;
			if ((Object)(object)zone == (Object)null)
			{
				return;
			}
			if (AWOUtil.IsLoaded)
			{
				AWOUtil.SetupZoneLightReplicator(zone);
			}
			Enumerator<AIG_CourseNode> enumerator = zone.m_courseNodes.GetEnumerator();
			while (enumerator.MoveNext())
			{
				foreach (LG_Light componentsInChild in ((Component)enumerator.Current.m_area).GetComponentsInChildren<LG_Light>(false))
				{
					EMPLightHandler handler = EMPLightHandler.GetHandler(componentsInChild);
					if (handler != null)
					{
						handler.SetOriginalColor(componentsInChild.m_color);
						handler.SetOriginalIntensity(componentsInChild.m_intensity);
					}
				}
			}
		}
	}
	[HarmonyPatch]
	internal static class Inject_PlayerAgent
	{
		[HarmonyPostfix]
		[HarmonyWrapSafe]
		[HarmonyPatch(typeof(PlayerAgent), "Setup")]
		internal static void Post_Setup(PlayerAgent __instance)
		{
			if (((Agent)__instance).IsLocallyOwned)
			{
				EMPManager.Current.SetLocalPlayerAgent(__instance);
			}
		}
	}
	[HarmonyPatch]
	internal static class Inject_PlayerHUD
	{
		[HarmonyPrefix]
		[HarmonyWrapSafe]
		[HarmonyPatch(typeof(PlayerGuiLayer), "UpdateGUIElementsVisibility")]
		private static bool Pre_UpdateGUIElementsVisibility()
		{
			if (EMPPlayerHudHandler.Instance != null && EMPPlayerHudHandler.Instance.IsEMPed())
			{
				return false;
			}
			return true;
		}

		[HarmonyPrefix]
		[HarmonyWrapSafe]
		[HarmonyPatch(typeof(CellSettingsApply), "ApplyPlayerGhostOpacity")]
		private static void Pre_ApplyPlayerGhostOpacity(ref float value)
		{
			if (EMPPlayerHudHandler.Instance != null && EMPPlayerHudHandler.Instance.IsEMPed())
			{
				value = 0f;
			}
		}

		[HarmonyPrefix]
		[HarmonyWrapSafe]
		[HarmonyPatch(typeof(CellSettingsApply), "ApplyHUDAlwaysShowTeammateInfo")]
		private static void Pre_ApplyHUDAlwaysShowTeammateInfo(ref bool value)
		{
			if (EMPPlayerHudHandler.Instance != null && EMPPlayerHudHandler.Instance.IsEMPed())
			{
				value = false;
			}
		}
	}
	[HarmonyPatch]
	internal static class Inject_Events
	{
		[HarmonyPostfix]
		[HarmonyWrapSafe]
		[HarmonyPatch(typeof(PlayerInventoryBase), "OnItemEquippableFlashlightWielded")]
		internal static void Post_OnItemEquippableFlashlightWielded(GearPartFlashlight flashlight)
		{
			Events.FlashLightWielded?.Invoke(flashlight);
		}

		[HarmonyPostfix]
		[HarmonyWrapSafe]
		[HarmonyPatch(typeof(PlayerInventoryLocal), "DoWieldItem")]
		internal static void Post_DoWieldItem(PlayerInventoryLocal __instance)
		{
			//IL_000b: Unknown result type (might be due to invalid IL or missing references)
			Events.InventoryWielded?.Invoke(((PlayerInventoryBase)__instance).WieldedSlot);
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(GS_InLevel), "Enter")]
		private static void Post_SetupGear(GS_InLevel __instance)
		{
			Events.EnterGSInLevel?.Invoke();
		}
	}
	[HarmonyPatch(typeof(PlayerSync))]
	internal static class Inject_PlayerSync
	{
		[HarmonyPrefix]
		[HarmonyWrapSafe]
		[HarmonyPatch("WantsToSetFlashlightEnabled")]
		internal static void Pre_WantsToSetFlashlightEnabled(PlayerSync __instance, ref bool enable)
		{
			if (EMPPlayerFlashLightHandler.Instance != null && EMPPlayerFlashLightHandler.Instance.IsEMPed())
			{
				enable = false;
			}
		}
	}
	[HarmonyPatch(typeof(SentryGunInstance))]
	internal static class Inject_SentryGunInstance
	{
		[HarmonyPostfix]
		[HarmonyWrapSafe]
		[HarmonyPatch("Setup")]
		internal static void Post_Setup(SentryGunInstance __instance)
		{
			((Component)__instance).gameObject.AddComponent<EMPController>().AssignHandler(new EMPSentryHandler());
		}
	}
}
namespace EOSExt.EMP.EMPComponent
{
	public class PlayerpEMPComponent : MonoBehaviour
	{
		private float nextUpdateTime = float.NaN;

		public const float UPDATE_INTERVAL = 0.2f;

		public static PlayerpEMPComponent Current
		{
			get
			{
				if (!SNet.HasLocalPlayer || !SNet.LocalPlayer.HasPlayerAgent)
				{
					return null;
				}
				return ((Component)((Il2CppObjectBase)SNet.LocalPlayer.PlayerAgent).Cast<PlayerAgent>()).GetComponent<PlayerpEMPComponent>();
			}
		}

		public PlayerAgent player => ((Component)this).gameObject.GetComponent<PlayerAgent>();

		private void CheckSetup()
		{
			if (!((Object)(object)EMPManager.Current.Player == (Object)null))
			{
				EMPManager.Current.SetupHUDAndFlashlight();
				EMPManager.Current.SetupToolHandler();
			}
		}

		private void Update()
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Invalid comparison between Unknown and I4
			//IL_008b: Unknown result type (might be due to invalid IL or missing references)
			if ((int)GameStateManager.CurrentStateName != 10 || (!float.IsNaN(nextUpdateTime) && Clock.Time < nextUpdateTime))
			{
				return;
			}
			nextUpdateTime = Clock.Time + 0.2f;
			CheckSetup();
			EMPManager.Current.RemoveInactiveEMPs();
			if ((Object)(object)player == (Object)null)
			{
				return;
			}
			foreach (pEMP pEMP in EMPManager.Current.pEMPs)
			{
				ItemToDisable itemToDisable = pEMP.ItemToDisable;
				if (pEMP.State == ActiveState.ENABLED && pEMP.InRange(((Agent)player).Position))
				{
					if (itemToDisable.BioTracker)
					{
						EMPBioTrackerHandler.Instance?.AddAffectedBy(pEMP);
					}
					if (itemToDisable.PlayerFlashLight)
					{
						EMPPlayerFlashLightHandler.Instance?.AddAffectedBy(pEMP);
					}
					if (itemToDisable.PlayerHUD)
					{
						EMPPlayerHudHandler.Instance?.AddAffectedBy(pEMP);
					}
					if (itemToDisable.Sentry)
					{
						EMPSentryHandler.Instance?.AddAffectedBy(pEMP);
					}
					if (!itemToDisable.GunSight)
					{
						continue;
					}
					foreach (EMPGunSightHandler instance in EMPGunSightHandler.Instances)
					{
						instance.AddAffectedBy(pEMP);
					}
					continue;
				}
				EMPBioTrackerHandler.Instance?.RemoveAffectedBy(pEMP);
				EMPPlayerFlashLightHandler.Instance?.RemoveAffectedBy(pEMP);
				EMPPlayerHudHandler.Instance?.RemoveAffectedBy(pEMP);
				EMPSentryHandler.Instance?.RemoveAffectedBy(pEMP);
				foreach (EMPGunSightHandler instance2 in EMPGunSightHandler.Instances)
				{
					instance2.RemoveAffectedBy(pEMP);
				}
			}
		}

		private void OnDestroy()
		{
		}

		static PlayerpEMPComponent()
		{
		}
	}
}
namespace EOSExt.EMP.Impl
{
	public sealed class EMPController : MonoBehaviour
	{
		private bool _hasHandler;

		private bool _setup;

		private float next_remove_time = float.NaN;

		private const float UPDATE_INTERVAL = 1f;

		public EMPHandler Handler { get; private set; }

		public float endTime { get; private set; }

		public Vector3 Position => ((Component)this).transform.position;

		private void Update()
		{
			if (_hasHandler)
			{
				float time = Clock.Time;
				Handler.Tick();
				if (float.IsNaN(next_remove_time) || next_remove_time < time)
				{
					Handler.RemoveEndedEMPs();
					next_remove_time = time + 1f;
				}
			}
		}

		[HideFromIl2Cpp]
		public void AssignHandler(EMPHandler handler)
		{
			if (Handler != null)
			{
				EOSLogger.Warning("Tried to assign a handler to a controller that already had one!");
				return;
			}
			Handler = handler;
			Handler.Setup(((Component)this).gameObject, this);
			_hasHandler = true;
			_setup = true;
		}

		[HideFromIl2Cpp]
		public void ForceState(EMPState state)
		{
			if (Handler != null)
			{
				Handler.ForceState(state);
			}
		}

		private void OnDestroy()
		{
			Handler.OnDespawn();
			Handler = null;
		}
	}
	public abstract class EMPHandler
	{
		protected enum DeviceState
		{
			On,
			Off,
			Unknown
		}

		private static long next_handler_id = 0L;

		protected DeviceState _deviceState;

		protected float stateTimer;

		protected float delayTimer;

		private bool _destroyed;

		protected static Dictionary<long, EMPHandler> Handlers { get; } = new Dictionary<long, EMPHandler>();


		public static IEnumerable<EMPHandler> AllHandlers => Handlers.Values;

		protected long HandlerId { get; private set; }

		public EMPState State { get; protected set; }

		protected HashSet<EMPShock> AffectedBy { get; } = new HashSet<EMPShock>();


		public GameObject go { get; protected set; }

		public Vector3 position
		{
			get
			{
				//IL_0015: Unknown result type (might be due to invalid IL or missing references)
				//IL_000a: Unknown result type (might be due to invalid IL or missing references)
				GameObject obj = go;
				if (obj == null)
				{
					return Vector3.zero;
				}
				return obj.transform.position;
			}
		}

		protected virtual float FlickerDuration => 0.2f;

		protected virtual float OnToOffMinDelay => 0f;

		protected virtual float OnToOffMaxDelay => 0.75f;

		protected virtual float OffToOnMinDelay => 0.85f;

		protected virtual float OffToOnMaxDelay => 1.5f;

		protected virtual bool IsDeviceOnPlayer => false;

		public virtual bool IsEMPed()
		{
			foreach (EMPShock item in AffectedBy)
			{
				if (Clock.Time < item.endTime)
				{
					return true;
				}
			}
			return false;
		}

		public virtual void Setup(GameObject gameObject, EMPController controller)
		{
			//IL_002c: 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)
			go = gameObject;
			foreach (EMPShock activeEMP in EMPManager.Current.ActiveEMPs)
			{
				if (Vector3.Distance(go.transform.position, activeEMP.position) < activeEMP.range)
				{
					AddAffectedBy(activeEMP);
				}
			}
			HandlerId = next_handler_id++;
			if (Handlers.ContainsKey(HandlerId))
			{
				EOSLogger.Warning("What the hell we got a duplicate EMPHandler ID!?");
			}
			Handlers[HandlerId] = this;
		}

		public virtual void OnDespawn()
		{
			_destroyed = true;
			AffectedBy.Clear();
			Handlers.Remove(HandlerId);
			go = null;
		}

		public void AddAffectedBy(EMPShock empShock)
		{
			AffectedBy.Add(empShock);
		}

		public void RemoveAffectedBy(EMPShock empShock)
		{
			AffectedBy.Remove(empShock);
		}

		internal void RemoveEndedEMPs()
		{
			float time = Clock.Time;
			AffectedBy.RemoveWhere((EMPShock emp) => emp.endTime < time);
		}

		public void ForceState(EMPState state)
		{
			if (State != state)
			{
				State = state;
				delayTimer = Clock.Time - 1f;
				stateTimer = Clock.Time - 1f;
				switch (state)
				{
				case EMPState.Off:
					_deviceState = DeviceState.Off;
					DeviceOff();
					break;
				default:
					_deviceState = DeviceState.Unknown;
					break;
				case EMPState.On:
					_deviceState = DeviceState.On;
					DeviceOn();
					break;
				}
			}
		}

		public void Tick()
		{
			if (_destroyed)
			{
				return;
			}
			bool flag = IsEMPed();
			if (flag && State == EMPState.On)
			{
				float randomDelay = Random.GetRandomDelay(OnToOffMinDelay, OnToOffMaxDelay);
				State = EMPState.FlickerOff;
				delayTimer = Clock.Time + randomDelay;
				stateTimer = Clock.Time + randomDelay + FlickerDuration;
			}
			if (!flag && State == EMPState.Off)
			{
				float randomDelay2 = Random.GetRandomDelay(OffToOnMinDelay, OffToOnMaxDelay);
				State = EMPState.FlickerOn;
				delayTimer = Clock.Time + randomDelay2;
				stateTimer = Clock.Time + randomDelay2 + FlickerDuration;
			}
			switch (State)
			{
			case EMPState.On:
				if (_deviceState != 0)
				{
					DeviceOn();
					_deviceState = DeviceState.On;
				}
				break;
			case EMPState.FlickerOff:
				if (!(Clock.Time < delayTimer))
				{
					if (Clock.Time < stateTimer)
					{
						FlickerDevice();
					}
					else
					{
						State = EMPState.Off;
					}
				}
				break;
			case EMPState.Off:
				if (_deviceState != DeviceState.Off)
				{
					DeviceOff();
					_deviceState = DeviceState.Off;
				}
				break;
			case EMPState.FlickerOn:
				if (!(Clock.Time < delayTimer))
				{
					if (Clock.Time < stateTimer)
					{
						FlickerDevice();
					}
					else
					{
						State = EMPState.On;
					}
				}
				break;
			}
			OnTick(flag);
		}

		protected virtual void OnTick(bool isEMPD)
		{
		}

		protected abstract void FlickerDevice();

		protected abstract void DeviceOn();

		protected abstract void DeviceOff();
	}
	public class EMPShock
	{
		public static readonly ItemToDisable DISABLE_NOTHING = new ItemToDisable
		{
			BioTracker = false,
			PlayerFlashLight = false,
			PlayerHUD = false,
			Sentry = false,
			EnvLight = false,
			GunSight = false,
			Map = false
		};

		public virtual ActiveState State
		{
			get
			{
				if (!(RemainingTime > 0f))
				{
					return ActiveState.DISABLED;
				}
				return ActiveState.ENABLED;
			}
		}

		public Vector3 position { get; protected set; }

		public float range { get; protected set; }

		public float endTime { get; protected set; }

		public virtual float RemainingTime => endTime - Clock.Time;

		public virtual ItemToDisable ItemToDisable => new ItemToDisable();

		public EMPShock(Vector3 position, float range, float endTime)
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			this.position = position;
			this.range = range;
			this.endTime = endTime;
		}

		public bool InRange(Vector3 position)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			return Vector3.Distance(position, this.position) < range;
		}

		public override bool Equals(object obj)
		{
			//IL_000b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			if (obj is EMPShock eMPShock && position == eMPShock.position)
			{
				return range == eMPShock.range;
			}
			return false;
		}

		public override int GetHashCode()
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			return HashCode.Combine<ActiveState, Vector3, float, float, float, ItemToDisable>(State, position, range, endTime, RemainingTime, ItemToDisable);
		}
	}
	public enum EMPState
	{
		On,
		FlickerOff,
		Off,
		FlickerOn
	}
	internal static class Random
	{
		internal static System.Random _rand { get; private set; } = new System.Random();


		internal static float GetRandomDelay(float min, float max)
		{
			return min + GetRandom01() * (max - min);
		}

		internal static float GetRandom01()
		{
			return (float)_rand.NextDouble();
		}

		internal static int GetRandomRange(int min, int maxPlusOne)
		{
			return _rand.Next(min, maxPlusOne);
		}

		internal static int Index(int length)
		{
			return _rand.Next(0, length);
		}

		internal static bool FlickerUtil(int oneInX = 2)
		{
			return Index(oneInX) == 0;
		}
	}
}
namespace EOSExt.EMP.Impl.PersistentEMP
{
	public enum ActiveState
	{
		DISABLED,
		ENABLED
	}
	public class pEMP : EMPShock
	{
		private uint replicatorID;

		public pEMPDefinition def { get; private set; }

		public StateReplicator<pEMPState> StateReplicator { get; private set; }

		public override ActiveState State
		{
			get
			{
				if (StateReplicator == null)
				{
					return ActiveState.DISABLED;
				}
				return StateReplicator.State.status;
			}
		}

		public override float RemainingTime => base.endTime;

		public override ItemToDisable ItemToDisable => def?.ItemToDisable ?? EMPShock.DISABLE_NOTHING;

		private void OnStateChanged(pEMPState oldState, pEMPState newState, bool isRecall)
		{
			if (isRecall)
			{
				ChangeToStateUnsynced(newState.status);
			}
		}

		private void ChangeToStateUnsynced(ActiveState newState)
		{
			//IL_00c0: Unknown result type (might be due to invalid IL or missing references)
			EOSLogger.Debug($"pEMP_{def.pEMPIndex} Change state: {State} -> {newState}");
			switch (newState)
			{
			case ActiveState.DISABLED:
				base.endTime = float.NegativeInfinity;
				break;
			case ActiveState.ENABLED:
				base.endTime = float.PositiveInfinity;
				break;
			default:
				throw new NotImplementedException();
			}
			if (!ItemToDisable.EnvLight)
			{
				return;
			}
			foreach (EMPLightHandler instance in EMPLightHandler.Instances)
			{
				switch (newState)
				{
				case ActiveState.DISABLED:
					instance.RemoveAffectedBy(this);
					break;
				case ActiveState.ENABLED:
					if (InRange(instance.position))
					{
						instance.AddAffectedBy(this);
					}
					else
					{
						instance.RemoveAffectedBy(this);
					}
					break;
				default:
					throw new NotImplementedException();
				}
			}
		}

		public void ChangeToState(ActiveState newState)
		{
			ChangeToStateUnsynced(newState);
			if (SNet.IsMaster)
			{
				StateReplicator?.SetState(new pEMPState
				{
					status = newState
				});
			}
		}

		internal void SetupReplicator(uint replicatorID)
		{
			this.replicatorID = replicatorID;
			StateReplicator = StateReplicator<pEMPState>.Create(replicatorID, new pEMPState
			{
				status = ActiveState.DISABLED
			}, (LifeTimeType)1, (IStateReplicatorHolder<pEMPState>)null);
			StateReplicator.OnStateChanged += OnStateChanged;
		}

		public pEMP(pEMPDefinition def)
			: base(def.Position.ToVector3(), def.Range, float.NegativeInfinity)
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			this.def = new pEMPDefinition(def);
		}

		internal void Destroy()
		{
			base.endTime = float.NegativeInfinity;
			StateReplicator = null;
			def = null;
		}

		public override bool Equals(object obj)
		{
			if (obj is pEMP pEMP2 && def.Equals(pEMP2.def))
			{
				return replicatorID == pEMP2.replicatorID;
			}
			return false;
		}

		public override int GetHashCode()
		{
			return HashCode.Combine(def, replicatorID);
		}
	}
	public struct pEMPState
	{
		public ActiveState status;

		public pEMPState()
		{
			status = ActiveState.DISABLED;
		}

		public pEMPState(ActiveState status)
		{
			this.status = status;
		}

		public pEMPState(pEMPState o)
		{
			status = o.status;
		}
	}
}
namespace EOSExt.EMP.Impl.Handlers
{
	public class EMPBioTrackerHandler : EMPHandler
	{
		private EnemyScanner _scanner;

		public static EMPBioTrackerHandler Instance { get; private set; }

		static EMPBioTrackerHandler()
		{
		}

		public override void Setup(GameObject gameObject, EMPController controller)
		{
			if (Instance != null)
			{
				EOSLogger.Warning("EMP: re-setup EMPBioTrackerHandler");
				Instance.OnDespawn();
			}
			base.Setup(gameObject, controller);
			_scanner = gameObject.GetComponent<EnemyScanner>();
			if ((Object)(object)_scanner == (Object)null)
			{
				EOSLogger.Error("Couldn't get bio-tracker component!");
			}
			Instance = this;
		}

		public override void OnDespawn()
		{
			base.OnDespawn();
			Instance = null;
		}

		protected override void DeviceOff()
		{
			((ItemEquippable)_scanner).Sound.Post(EVENTS.BIOTRACKER_TOOL_LOOP_STOP, true);
			_scanner.m_graphics.m_display.enabled = false;
		}

		protected override void DeviceOn()
		{
			_scanner.m_graphics.m_display.enabled = true;
		}

		protected override void FlickerDevice()
		{
			((Behaviour)_scanner).enabled = Random.FlickerUtil();
		}
	}
	public class EMPGunSightHandler : EMPHandler
	{
		private static List<EMPGunSightHandler> handlers;

		public GameObject[] _sightPictures;

		public static IEnumerable<EMPGunSightHandler> Instances => handlers;

		static EMPGunSightHandler()
		{
			handlers = new List<EMPGunSightHandler>();
			LevelAPI.OnLevelCleanup += Clear;
			LevelAPI.OnBuildStart += Clear;
		}

		private void SetupGunSights()
		{
			Il2CppArrayBase<Renderer> componentsInChildren = base.go.GetComponentsInChildren<Renderer>(true);
			if (componentsInChildren != null)
			{
				_sightPictures = (from x in (IEnumerable<Renderer>)componentsInChildren
					where (Object)(object)x.sharedMaterial != (Object)null && (Object)(object)x.sharedMaterial.shader != (Object)null
					where ((Object)x.sharedMaterial.shader).name.Contains("HolographicSight")
					select ((Component)x).gameObject).ToArray();
			}
			if (_sightPictures == null || _sightPictures.Length < 1)
			{
				EOSLogger.Error("Unable to find sight on " + ((Object)base.go).name + "!");
			}
		}

		public override void Setup(GameObject gameObject, EMPController controller)
		{
			base.Setup(gameObject, controller);
			SetupGunSights();
			handlers.Add(this);
		}

		protected override void DeviceOff()
		{
			ForEachSights(delegate(GameObject x)
			{
				x.SetActive(false);
			});
		}

		protected override void DeviceOn()
		{
			ForEachSights(delegate(GameObject x)
			{
				x.SetActive(true);
			});
		}

		protected override void FlickerDevice()
		{
			ForEachSights(delegate(GameObject x)
			{
				x.SetActive(Random.FlickerUtil());
			});
		}

		private void ForEachSights(Action<GameObject> action)
		{
			GameObject[] sightPictures = _sightPictures;
			foreach (GameObject val in sightPictures)
			{
				if ((Object)(object)val != (Object)null)
				{
					action?.Invoke(val);
				}
			}
		}

		private static void Clear()
		{
			handlers.Clear();
		}
	}
	public class EMPLightHandler : EMPHandler
	{
		private static Dictionary<IntPtr, EMPLightHandler> handlers;

		private LG_Light _light;

		private float _originalIntensity;

		private Color _originalColor;

		public static IEnumerable<EMPLightHandler> Instances => handlers.Values;

		internal static EMPLightHandler GetHandler(LG_Light light)
		{
			if (!handlers.TryGetValue(((Il2CppObjectBase)light).Pointer, out var value))
			{
				return null;
			}
			return value;
		}

		private static void Clear()
		{
			handlers.Clear();
		}

		static EMPLightHandler()
		{
			handlers = new Dictionary<IntPtr, EMPLightHandler>();
			LevelAPI.OnBuildStart += Clear;
			LevelAPI.OnLevelCleanup += Clear;
		}

		public override void Setup(GameObject gameObject, EMPController controller)
		{
			//IL_0046: Unknown result type (might be due to invalid IL or missing references)
			//IL_0056: Unknown result type (might be due to invalid IL or missing references)
			//IL_0066: 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_0080: Unknown result type (might be due to invalid IL or missing references)
			//IL_0085: Unknown result type (might be due to invalid IL or missing references)
			base.Setup(gameObject, controller);
			_light = gameObject.GetComponent<LG_Light>();
			if ((Object)(object)_light == (Object)null)
			{
				EOSLogger.Warning("No Light!");
			}
			else
			{
				_originalIntensity = _light.GetIntensity();
				_originalColor = new Color(_light.m_color.r, _light.m_color.g, _light.m_color.b, _light.m_color.a);
				base.State = EMPState.On;
			}
			handlers[((Il2CppObjectBase)_light).Pointer] = this;
		}

		public void SetOriginalColor(Color color)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			_originalColor = color;
		}

		public void SetOriginalIntensity(float intensity)
		{
			_originalIntensity = intensity;
		}

		protected override void OnTick(bool isEMPD)
		{
			base.OnTick(isEMPD);
		}

		protected override void FlickerDevice()
		{
			if (!((Object)(object)_light == (Object)null))
			{
				_light.ChangeIntensity(Random.GetRandom01() * _originalIntensity);
			}
		}

		protected override void DeviceOn()
		{
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			if (!((Object)(object)_light == (Object)null))
			{
				_light.ChangeIntensity(_originalIntensity);
				_light.ChangeColor(_originalColor);
			}
		}

		protected override void DeviceOff()
		{
			//IL_0025: Unknown result type (might be due to invalid IL or missing references)
			if (!((Object)(object)_light == (Object)null))
			{
				_light.ChangeIntensity(0f);
				_light.ChangeColor(Color.black);
			}
		}
	}
	public class EMPPlayerFlashLightHandler : EMPHandler
	{
		private PlayerInventoryBase _inventory;

		private float _originalIntensity;

		private bool _originalFlashlightState;

		public static EMPPlayerFlashLightHandler Instance { get; private set; }

		protected override bool IsDeviceOnPlayer => true;

		private bool FlashlightEnabled => _inventory.FlashlightEnabled;

		static EMPPlayerFlashLightHandler()
		{
		}

		public override void Setup(GameObject gameObject, EMPController controller)
		{
			if (Instance != null)
			{
				EOSLogger.Warning("EMP: re-setup EMPPlayerFlashLightHandler");
				Instance.OnDespawn();
			}
			base.Setup(gameObject, controller);
			_inventory = gameObject.GetComponent<PlayerAgent>().Inventory;
			if ((Object)(object)_inventory == (Object)null)
			{
				EOSLogger.Warning("Player inventory was null!");
			}
			else
			{
				base.State = EMPState.On;
				Events.FlashLightWielded = (Action<GearPartFlashlight>)Delegate.Combine(Events.FlashLightWielded, new Action<GearPartFlashlight>(InventoryEvents_ItemWielded));
			}
			Instance = this;
		}

		public override void OnDespawn()
		{
			base.OnDespawn();
			Events.FlashLightWielded = (Action<GearPartFlashlight>)Delegate.Remove(Events.FlashLightWielded, new Action<GearPartFlashlight>(Instance.InventoryEvents_ItemWielded));
			Instance = null;
		}

		private void InventoryEvents_ItemWielded(GearPartFlashlight flashlight)
		{
			_originalIntensity = GameDataBlockBase<FlashlightSettingsDataBlock>.GetBlock(flashlight.m_settingsID).intensity;
		}

		protected override void DeviceOff()
		{
			_originalFlashlightState = FlashlightEnabled;
			if (_originalFlashlightState)
			{
				_inventory.Owner.Sync.WantsToSetFlashlightEnabled(false, false);
			}
		}

		protected override void DeviceOn()
		{
			if (_originalFlashlightState != FlashlightEnabled)
			{
				_inventory.Owner.Sync.WantsToSetFlashlightEnabled(_originalFlashlightState, false);
			}
			_inventory.m_flashlight.intensity = _originalIntensity;
		}

		protected override void FlickerDevice()
		{
			if (FlashlightEnabled)
			{
				_inventory.m_flashlight.intensity = Random.GetRandom01() * _originalIntensity;
			}
		}
	}
	public class EMPPlayerHudHandler : EMPHandler
	{
		private readonly List<RectTransformComp> _targets = new List<RectTransformComp>();

		public static EMPPlayerHudHandler Instance { get; private set; }

		static EMPPlayerHudHandler()
		{
		}

		public override void Setup(GameObject gameObject, EMPController controller)
		{
			if (Instance != null)
			{
				EOSLogger.Warning("EMP: re-setup EMPPlayerHudHandler");
				Instance.OnDespawn();
			}
			_targets.Clear();
			base.Setup(gameObject, controller);
			_targets.Add((RectTransformComp)(object)GuiManager.PlayerLayer.m_compass);
			_targets.Add((RectTransformComp)(object)GuiManager.PlayerLayer.m_wardenObjective);
			_targets.Add((RectTransformComp)(object)GuiManager.PlayerLayer.Inventory);
			_targets.Add((RectTransformComp)(object)GuiManager.PlayerLayer.m_playerStatus);
			Instance = this;
		}

		public override void OnDespawn()
		{
			base.OnDespawn();
			_targets.Clear();
			Instance = null;
		}

		private void ForAllComponents(bool enabled)
		{
			foreach (RectTransformComp target in _targets)
			{
				((Component)target).gameObject.SetActive(enabled);
			}
		}

		private void ForPlayerNavMarker(bool enabled)
		{
			Enumerator<PlayerAgent> enumerator = PlayerManager.PlayerAgentsInLevel.GetEnumerator();
			while (enumerator.MoveNext())
			{
				PlayerAgent current = enumerator.Current;
				if (!((Agent)current).IsLocallyOwned)
				{
					current.NavMarker.SetMarkerVisible(enabled);
				}
			}
		}

		private void ForPlayerGhostOpacity(bool enabled)
		{
			CellSettingsApply.ApplyPlayerGhostOpacity(enabled ? CellSettingsManager.SettingsData.HUD.Player_GhostOpacity.Value : 0f);
		}

		protected override void OnTick(bool isEMPD)
		{
			base.OnTick(isEMPD);
			if (base.State == EMPState.Off)
			{
				DeviceOff();
			}
			else if (base.State == EMPState.On)
			{
				DeviceOn();
			}
		}

		protected override void DeviceOff()
		{
			ForAllComponents(enabled: false);
			ForPlayerNavMarker(enabled: false);
			ForPlayerGhostOpacity(enabled: false);
		}

		protected override void DeviceOn()
		{
			ForAllComponents(enabled: true);
			ForPlayerNavMarker(enabled: true);
			ForPlayerGhostOpacity(enabled: true);
		}

		protected override void FlickerDevice()
		{
			bool enabled = Random.FlickerUtil();
			ForAllComponents(enabled);
			ForPlayerNavMarker(enabled);
			ForPlayerGhostOpacity(enabled);
		}
	}
	public class EMPSentryHandler : EMPHandler
	{
		private static Color _offColor;

		private SentryGunInstance _sentry;

		private SentryGunInstance_ScannerVisuals_Plane _visuals;

		public static EMPSentryHandler Instance { get; private set; }

		static EMPSentryHandler()
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0038: Unknown result type (might be due to invalid IL or missing references)
			//IL_0039: Unknown result type (might be due to invalid IL or missing references)
			_offColor = new Color
			{
				r = 0f,
				g = 0f,
				b = 0f,
				a = 0f
			};
		}

		public override void Setup(GameObject gameObject, EMPController controller)
		{
			if (Instance != null)
			{
				EOSLogger.Warning("EMP: re-setup EMPSentryHandler");
				Instance.OnDespawn();
			}
			base.Setup(gameObject, controller);
			_sentry = gameObject.GetComponent<SentryGunInstance>();
			_visuals = gameObject.GetComponent<SentryGunInstance_ScannerVisuals_Plane>();
			if ((Object)(object)_sentry == (Object)null || (Object)(object)_visuals == (Object)null)
			{
				EOSLogger.Error($"Missing components on Sentry! Has Sentry?: {(Object)(object)_sentry == (Object)null}, Has Visuals?: {(Object)(object)_visuals == (Object)null}");
			}
			Instance = this;
		}

		public override void OnDespawn()
		{
			base.OnDespawn();
			Instance = null;
		}

		protected override void DeviceOff()
		{
			//IL_000b: Unknown result type (might be due to invalid IL or missing references)
			//IL_001b: Unknown result type (might be due to invalid IL or missing references)
			_visuals.m_scannerPlane.SetColor(_offColor);
			_visuals.UpdateLightProps(_offColor, false);
			_sentry.m_isSetup = false;
			_sentry.m_isScanning = false;
			_sentry.m_isFiring = false;
			((ItemEquippable)_sentry).Sound.Post(EVENTS.SENTRYGUN_STOP_ALL_LOOPS, true);
		}

		protected override void DeviceOn()
		{
			_sentry.m_isSetup = true;
			_sentry.m_visuals.SetVisualStatus((eSentryGunStatus)0, true);
			_sentry.m_isScanning = false;
			_sentry.m_startScanTimer = Clock.Time + _sentry.m_initialScanDelay;
			((ItemEquippable)_sentry).Sound.Post(EVENTS.SENTRYGUN_LOW_AMMO_WARNING, true);
		}

		protected override void FlickerDevice()
		{
			int randomRange = Random.GetRandomRange(0, 3);
			_sentry.StopFiring();
			switch (randomRange)
			{
			case 0:
				_visuals.SetVisualStatus((eSentryGunStatus)4, true);
				break;
			case 1:
				_visuals.SetVisualStatus((eSentryGunStatus)1, true);
				break;
			case 2:
				_visuals.SetVisualStatus((eSentryGunStatus)2, true);
				break;
			}
		}
	}
}
namespace EOSExt.EMP.Definition
{
	public class ItemToDisable
	{
		public bool BioTracker { get; set; } = true;


		public bool PlayerHUD { get; set; } = true;


		public bool PlayerFlashLight { get; set; } = true;


		public bool EnvLight { get; set; } = true;


		public bool GunSight { get; set; } = true;


		public bool Sentry { get; set; } = true;


		public bool Map { get; set; } = true;


		public override bool Equals(object obj)
		{
			if (obj is ItemToDisable itemToDisable && BioTracker == itemToDisable.BioTracker && PlayerHUD == itemToDisable.PlayerHUD && PlayerFlashLight == itemToDisable.PlayerFlashLight && EnvLight == itemToDisable.EnvLight && GunSight == itemToDisable.GunSight && Sentry == itemToDisable.Sentry)
			{
				return Map == itemToDisable.Map;
			}
			return false;
		}

		public override int GetHashCode()
		{
			return HashCode.Combine(BioTracker, PlayerHUD, PlayerFlashLight, EnvLight, GunSight, Sentry, Map);
		}

		public override string ToString()
		{
			return $"ItemToDisable:\nBioTracker: {BioTracker}, PlayerHUD: {PlayerHUD}, PlayerFlashLight: {PlayerFlashLight},\nEnvLight: {EnvLight}, GunSight: {GunSight}, Sentry: {Sentry}, Map: {Map}";
		}
	}
	public class pEMPDefinition
	{
		public uint pEMPIndex { get; set; }

		public Vec3 Position { get; set; } = new Vec3();


		public float Range { get; set; }

		public ItemToDisable ItemToDisable { get; set; } = new ItemToDisable();


		public pEMPDefinition()
		{
		}//IL_0001: Unknown result type (might be due to invalid IL or missing references)
		//IL_000b: Expected O, but got Unknown


		public pEMPDefinition(pEMPDefinition other)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_000b: Expected O, but got Unknown
			//IL_0029: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Unknown result type (might be due to invalid IL or missing references)
			//IL_003f: 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_0066: Expected O, but got Unknown
			pEMPIndex = other.pEMPIndex;
			Position = new Vec3
			{
				x = other.Position.x,
				y = other.Position.y,
				z = other.Position.z
			};
			Range = other.Range;
			ItemToDisable = new ItemToDisable
			{
				BioTracker = other.ItemToDisable.BioTracker,
				PlayerHUD = other.ItemToDisable.PlayerHUD,
				PlayerFlashLight = other.ItemToDisable.PlayerFlashLight,
				EnvLight = other.ItemToDisable.EnvLight,
				GunSight = other.ItemToDisable.GunSight,
				Sentry = other.ItemToDisable.Sentry,
				Map = other.ItemToDisable.Map
			};
		}

		public override bool Equals(object obj)
		{
			//IL_001e: 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)
			if (obj is pEMPDefinition pEMPDefinition2 && pEMPIndex == pEMPDefinition2.pEMPIndex && Position.ToVector3() == pEMPDefinition2.Position.ToVector3() && Range == pEMPDefinition2.Range)
			{
				return ItemToDisable.Equals(pEMPDefinition2.ItemToDisable);
			}
			return false;
		}

		public override int GetHashCode()
		{
			return HashCode.Combine<uint, Vec3, float, ItemToDisable>(pEMPIndex, Position, Range, ItemToDisable);
		}
	}
}

plugins/TrickyBall's Paradise/Custom/Inas07.ExtraObjectiveSetup.dll

Decompiled 8 months ago
using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using System.Text;
using System.Text.Json;
using System.Text.Json.Serialization;
using AIGraph;
using AK;
using Agents;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Logging;
using BepInEx.Unity.IL2CPP;
using BepInEx.Unity.IL2CPP.Utils.Collections;
using ChainedPuzzles;
using Enemies;
using ExtraObjectiveSetup.BaseClasses;
using ExtraObjectiveSetup.BaseClasses.CustomTerminalDefinition;
using ExtraObjectiveSetup.Expedition;
using ExtraObjectiveSetup.Expedition.Gears;
using ExtraObjectiveSetup.Expedition.IndividualGeneratorGroup;
using ExtraObjectiveSetup.ExtendedWardenEvents;
using ExtraObjectiveSetup.Instances;
using ExtraObjectiveSetup.Instances.ChainedPuzzle;
using ExtraObjectiveSetup.JSON;
using ExtraObjectiveSetup.Objectives.ActivateSmallHSU;
using ExtraObjectiveSetup.Objectives.GeneratorCluster;
using ExtraObjectiveSetup.Objectives.IndividualGenerator;
using ExtraObjectiveSetup.Objectives.ObjectiveCounter;
using ExtraObjectiveSetup.Objectives.TerminalUplink;
using ExtraObjectiveSetup.Tweaks.BossEvents;
using ExtraObjectiveSetup.Tweaks.Scout;
using ExtraObjectiveSetup.Tweaks.TerminalPosition;
using ExtraObjectiveSetup.Tweaks.TerminalTweak;
using ExtraObjectiveSetup.Utils;
using FloLib.Networks.Replications;
using GTFO.API;
using GTFO.API.Extensions;
using GTFO.API.JSON.Converters;
using GTFO.API.Utilities;
using GameData;
using Gear;
using HarmonyLib;
using Il2CppInterop.Runtime.InteropTypes;
using Il2CppInterop.Runtime.InteropTypes.Arrays;
using Il2CppSystem;
using Il2CppSystem.Collections.Generic;
using LevelGeneration;
using Localization;
using MTFO.API;
using Microsoft.CodeAnalysis;
using Player;
using SNetwork;
using StateMachines;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETCoreApp,Version=v6.0", FrameworkDisplayName = ".NET 6.0")]
[assembly: AssemblyCompany("Inas07.ExtraObjectiveSetup")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0+0ed85c89f89e18967872da5c48fee511edd6ad21")]
[assembly: AssemblyProduct("Inas07.ExtraObjectiveSetup")]
[assembly: AssemblyTitle("Inas07.ExtraObjectiveSetup")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.0.0.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace ExtraObjectiveSetup
{
	public static class EOSNetworking
	{
		public const uint INVALID_ID = 0u;

		public const uint FOREVER_REPLICATOR_ID_START = 1000u;

		public const uint REPLICATOR_ID_START = 10000u;

		private static uint currentForeverID;

		private static uint currentID;

		private static HashSet<uint> foreverUsedIDs;

		private static HashSet<uint> usedIDs;

		public static uint AllotReplicatorID()
		{
			while (currentID >= 10000 && usedIDs.Contains(currentID))
			{
				currentID++;
			}
			if (currentID < 10000)
			{
				EOSLogger.Error("Replicator ID depleted. How?");
				return 0u;
			}
			uint num = currentID;
			usedIDs.Add(num);
			currentID++;
			return num;
		}

		public static bool TryAllotID(uint id)
		{
			return usedIDs.Add(id);
		}

		public static uint AllotForeverReplicatorID()
		{
			while (currentForeverID < 10000 && foreverUsedIDs.Contains(currentForeverID))
			{
				currentForeverID++;
			}
			if (currentForeverID >= 10000)
			{
				EOSLogger.Error("Forever Replicator ID depleted.");
				return 0u;
			}
			uint num = currentForeverID;
			foreverUsedIDs.Add(num);
			currentForeverID++;
			return num;
		}

		private static void Clear()
		{
			usedIDs.Clear();
			currentID = 10000u;
		}

		public static void ClearForever()
		{
			foreverUsedIDs.Clear();
			currentForeverID = 1000u;
		}

		static EOSNetworking()
		{
			currentForeverID = 1000u;
			currentID = 10000u;
			foreverUsedIDs = new HashSet<uint>();
			usedIDs = new HashSet<uint>();
			LevelAPI.OnBuildStart += Clear;
			LevelAPI.OnLevelCleanup += Clear;
		}
	}
	public sealed class BatchBuildManager
	{
		private Dictionary<BatchName, Action> OnBatchDone = new Dictionary<BatchName, Action>();

		public static BatchBuildManager Current { get; private set; }

		public void Init()
		{
			//IL_0034: Unknown result type (might be due to invalid IL or missing references)
			if (OnBatchDone.Count > 0)
			{
				return;
			}
			foreach (object value in Enum.GetValues(typeof(BatchName)))
			{
				OnBatchDone[(BatchName)value] = null;
			}
		}

		public void Add_OnBatchDone(BatchName batchName, Action action)
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			//IL_000a: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			Dictionary<BatchName, Action> onBatchDone = OnBatchDone;
			onBatchDone[batchName] = (Action)Delegate.Combine(onBatchDone[batchName], action);
		}

		public void Remove_OnBatchDone(BatchName batchName, Action action)
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			//IL_000a: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			Dictionary<BatchName, Action> onBatchDone = OnBatchDone;
			onBatchDone[batchName] = (Action)Delegate.Remove(onBatchDone[batchName], action);
		}

		public Action Get_OnBatchDone(BatchName batchName)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			return OnBatchDone[batchName];
		}

		private BatchBuildManager()
		{
		}

		static BatchBuildManager()
		{
			Current = new BatchBuildManager();
		}
	}
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInPlugin("Inas.ExtraObjectiveSetup", "ExtraObjectiveSetup", "1.6.4")]
	public class EntryPoint : BasePlugin
	{
		public const string AUTHOR = "Inas";

		public const string PLUGIN_NAME = "ExtraObjectiveSetup";

		public const string VERSION = "1.6.4";

		private Harmony m_Harmony;

		public override void Load()
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_0010: Expected O, but got Unknown
			m_Harmony = new Harmony("ExtraObjectiveSetup");
			m_Harmony.PatchAll();
			SetupManagers();
		}

		private void SetupManagers()
		{
			BatchBuildManager.Current.Init();
			IndividualGeneratorObjectiveManager.Current.Init();
			GeneratorClusterObjectiveManager.Current.Init();
			HSUActivatorObjectiveManager.Current.Init();
			UplinkObjectiveManager.Current.Init();
			TerminalPositionOverrideManager.Current.Init();
			ScoutScreamEventManager.Current.Init();
			BossDeathEventManager.Current.Init();
			ExpeditionDefinitionManager.Current.Init();
			ExpeditionGearManager.Current.Init();
			ExpeditionIGGroupManager.Current.Init();
			GeneratorClusterInstanceManager.Current.Init();
			HSUActivatorInstanceManager.Current.Init();
			PowerGeneratorInstanceManager.Current.Init();
			TerminalInstanceManager.Current.Init();
			ObjectiveCounterManager.Current.Init();
		}
	}
}
namespace ExtraObjectiveSetup.Utils
{
	public static class EOSTerminalUtils
	{
		public static List<LG_ComputerTerminal> FindTerminal(eDimensionIndex dimensionIndex, LG_LayerType layerType, eLocalZoneIndex localIndex, Predicate<LG_ComputerTerminal> predicate)
		{
			//IL_0005: 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_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_0032: Unknown result type (might be due to invalid IL or missing references)
			//IL_0033: Unknown result type (might be due to invalid IL or missing references)
			//IL_0034: Unknown result type (might be due to invalid IL or missing references)
			//IL_0073: Unknown result type (might be due to invalid IL or missing references)
			//IL_0074: Unknown result type (might be due to invalid IL or missing references)
			//IL_0075: Unknown result type (might be due to invalid IL or missing references)
			LG_Zone val = default(LG_Zone);
			if (!Builder.CurrentFloor.TryGetZoneByLocalIndex(dimensionIndex, layerType, localIndex, ref val) || (Object)(object)val == (Object)null)
			{
				EOSLogger.Error($"SelectTerminal: Could NOT find zone {(dimensionIndex, layerType, localIndex)}");
				return null;
			}
			if (val.TerminalsSpawnedInZone.Count <= 0)
			{
				EOSLogger.Error($"SelectTerminal: Could not find any terminals in zone {(dimensionIndex, layerType, localIndex)}");
				return null;
			}
			List<LG_ComputerTerminal> list = new List<LG_ComputerTerminal>();
			Enumerator<LG_ComputerTerminal> enumerator = val.TerminalsSpawnedInZone.GetEnumerator();
			while (enumerator.MoveNext())
			{
				LG_ComputerTerminal current = enumerator.Current;
				if (predicate != null)
				{
					if (predicate(current))
					{
						list.Add(current);
					}
				}
				else
				{
					list.Add(current);
				}
			}
			return list;
		}

		public static TerminalLogFileData GetLocalLog(this LG_ComputerTerminal terminal, string logName)
		{
			Dictionary<string, TerminalLogFileData> localLogs = terminal.GetLocalLogs();
			logName = logName.ToUpperInvariant();
			if (!localLogs.ContainsKey(logName))
			{
				return null;
			}
			return localLogs[logName];
		}

		public static void ResetInitialOutput(this LG_ComputerTerminal terminal)
		{
			terminal.m_command.ClearOutputQueueAndScreenBuffer();
			terminal.m_command.AddInitialTerminalOutput();
			if (terminal.IsPasswordProtected)
			{
				terminal.m_command.AddPasswordProtectedOutput((Il2CppStringArray)null);
			}
		}

		public static List<WardenObjectiveEventData> GetUniqueCommandEvents(this LG_ComputerTerminal terminal, string command)
		{
			//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_0037: Unknown result type (might be due to invalid IL or missing references)
			//IL_004a: Expected I4, but got Unknown
			//IL_0100: 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_0091: Unknown result type (might be due to invalid IL or missing references)
			//IL_017b: Unknown result type (might be due to invalid IL or missing references)
			//IL_018b: Unknown result type (might be due to invalid IL or missing references)
			List<WardenObjectiveEventData> result = new List<WardenObjectiveEventData>();
			if ((Object)(object)terminal.ConnectedReactor != (Object)null)
			{
				return result;
			}
			uint num = 0u;
			if (terminal.SpawnNode.m_dimension.IsMainDimension)
			{
				LG_LayerType layerType = terminal.SpawnNode.LayerType;
				switch ((int)layerType)
				{
				case 0:
					num = RundownManager.ActiveExpedition.LevelLayoutData;
					break;
				case 1:
					num = RundownManager.ActiveExpedition.SecondaryLayout;
					break;
				case 2:
					num = RundownManager.ActiveExpedition.ThirdLayout;
					break;
				default:
					EOSLogger.Error($"GetCommandEvents: Unimplemented layer type {terminal.SpawnNode.LayerType}");
					return result;
				}
			}
			else
			{
				num = terminal.SpawnNode.m_dimension.DimensionData.LevelLayoutData;
			}
			LevelLayoutDataBlock block = GameDataBlockBase<LevelLayoutDataBlock>.GetBlock(num);
			if (block == null)
			{
				EOSLogger.Error($"GetCommandEvents: {terminal.ItemKey} is in {terminal.SpawnNode.LayerType}, {terminal.SpawnNode.m_dimension.DimensionIndex} but its LevelLayoutData is not found!");
				return result;
			}
			int num2 = terminal.SpawnNode.m_zone.TerminalsSpawnedInZone.IndexOf(terminal);
			ExpeditionZoneData val = null;
			Enumerator<ExpeditionZoneData> enumerator = block.Zones.GetEnumerator();
			while (enumerator.MoveNext())
			{
				ExpeditionZoneData current = enumerator.Current;
				if (current.LocalIndex == terminal.SpawnNode.m_zone.LocalIndex)
				{
					val = current;
					break;
				}
			}
			if (val == null)
			{
				EOSLogger.Error("GetCommandEvents: Cannot find target zone data.");
				return result;
			}
			if (num2 >= val.TerminalPlacements.Count)
			{
				EOSLogger.Debug("GetCommandEvents: TerminalDataIndex >= TargetZoneData.TerminalPlacements.Count: found a custom terminal, skipped");
				return result;
			}
			Enumerator<CustomTerminalCommand> enumerator2 = val.TerminalPlacements[num2].UniqueCommands.GetEnumerator();
			while (enumerator2.MoveNext())
			{
				CustomTerminalCommand current2 = enumerator2.Current;
				if (current2.Command.ToLower().Equals(command.ToLower()))
				{
					return current2.CommandEvents.ToManaged<WardenObjectiveEventData>();
				}
			}
			EOSLogger.Error("GetCommandEvents: command '" + command + "' not found on " + terminal.ItemKey);
			return result;
		}

		public static LG_ComputerTerminal SelectPasswordTerminal(eDimensionIndex dimensionIndex, LG_LayerType layerType, eLocalZoneIndex localIndex, eSeedType seedType, int staticSeed = 1)
		{
			//IL_0000: 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_0030: Unknown result type (might be due to invalid IL or missing references)
			//IL_0031: Unknown result type (might be due to invalid IL or missing references)
			//IL_001b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0072: Unknown result type (might be due to invalid IL or missing references)
			//IL_0073: Unknown result type (might be due to invalid IL or missing references)
			//IL_0074: Unknown result type (might be due to invalid IL or missing references)
			//IL_0119: Unknown result type (might be due to invalid IL or missing references)
			//IL_011b: Unknown result type (might be due to invalid IL or missing references)
			//IL_012d: Expected I4, but got Unknown
			//IL_00bd: Unknown result type (might be due to invalid IL or missing references)
			//IL_00be: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bf: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e9: Unknown result type (might be due to invalid IL or missing references)
			if ((int)seedType == 0)
			{
				EOSLogger.Error($"SelectTerminal: unsupported seed type {seedType}");
				return null;
			}
			List<LG_ComputerTerminal> list = FindTerminal(dimensionIndex, layerType, localIndex, (LG_ComputerTerminal x) => !x.HasPasswordPart);
			if (list == null)
			{
				EOSLogger.Error($"SelectTerminal: Could not find zone {(dimensionIndex, layerType, localIndex)}!");
				return null;
			}
			if (list.Count <= 0)
			{
				EOSLogger.Error($"SelectTerminal: Could not find any terminals without a password part in zone {(dimensionIndex, layerType, localIndex)}, putting the password on random (session) already used terminal.");
				LG_Zone val = default(LG_Zone);
				Builder.CurrentFloor.TryGetZoneByLocalIndex(dimensionIndex, layerType, localIndex, ref val);
				return val.TerminalsSpawnedInZone[Builder.SessionSeedRandom.Range(0, val.TerminalsSpawnedInZone.Count, "NO_TAG")];
			}
			switch (seedType - 1)
			{
			case 0:
				return list[Builder.SessionSeedRandom.Range(0, list.Count, "NO_TAG")];
			case 1:
				return list[Builder.BuildSeedRandom.Range(0, list.Count, "NO_TAG")];
			case 2:
				Random.InitState(staticSeed);
				return list[Random.Range(0, list.Count)];
			default:
				EOSLogger.Error("SelectTerminal: did not have a valid SeedType!!");
				return null;
			}
		}

		public static void BuildPassword(LG_ComputerTerminal terminal, TerminalPasswordData data)
		{
			//IL_01e1: Unknown result type (might be due to invalid IL or missing references)
			//IL_02c8: Unknown result type (might be due to invalid IL or missing references)
			//IL_02cf: Unknown result type (might be due to invalid IL or missing references)
			//IL_02d6: Unknown result type (might be due to invalid IL or missing references)
			//IL_02dd: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f2: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f9: Unknown result type (might be due to invalid IL or missing references)
			//IL_0200: Unknown result type (might be due to invalid IL or missing references)
			//IL_0427: Unknown result type (might be due to invalid IL or missing references)
			//IL_042c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0498: Unknown result type (might be due to invalid IL or missing references)
			//IL_0499: Unknown result type (might be due to invalid IL or missing references)
			//IL_049e: Unknown result type (might be due to invalid IL or missing references)
			//IL_04c0: Unknown result type (might be due to invalid IL or missing references)
			//IL_04cc: Expected O, but got Unknown
			//IL_04ce: Expected O, but got Unknown
			if (!data.PasswordProtected)
			{
				return;
			}
			if (terminal.IsPasswordProtected)
			{
				EOSLogger.Error("EOSTerminalUtils.BuildPassword: " + terminal.PublicName + " is already password-protected!");
				return;
			}
			if (!data.GeneratePassword)
			{
				terminal.LockWithPassword(data.Password, new string[1] { data.PasswordHintText });
				return;
			}
			if (data.TerminalZoneSelectionDatas.Count <= 0)
			{
				EOSLogger.Error($"Tried to generate a password for terminal {terminal.PublicName} with no {typeof(TerminalZoneSelectionData).Name}!! This is not allowed.");
				return;
			}
			string codeWord = SerialGenerator.GetCodeWord();
			string passwordHintText = data.PasswordHintText;
			string text = "<b>[Forgot your password?]</b> Backup security key(s) located in logs on ";
			int num = data.PasswordPartCount;
			if (codeWord.Length % num != 0)
			{
				EOSLogger.Error($"Build() password.Length ({codeWord.Length}) not divisible by passwordParts ({num}). Defaulting to 1.");
				num = 1;
			}
			string[] array = ((num > 1) ? Il2CppArrayBase<string>.op_Implicit((Il2CppArrayBase<string>)(object)StringUtils.SplitIntoChunksArray(codeWord, codeWord.Length / num)) : new string[1] { codeWord });
			string text2 = "";
			if (data.ShowPasswordPartPositions)
			{
				for (int i = 0; i < array[0].Length; i++)
				{
					text2 += "-";
				}
			}
			HashSet<LG_ComputerTerminal> hashSet = new HashSet<LG_ComputerTerminal>();
			LG_Zone val = default(LG_Zone);
			for (int j = 0; j < num; j++)
			{
				int index = j % data.TerminalZoneSelectionDatas.Count;
				List<CustomTerminalZoneSelectionData> list = data.TerminalZoneSelectionDatas[index];
				int index2 = Builder.SessionSeedRandom.Range(0, list.Count, "NO_TAG");
				CustomTerminalZoneSelectionData customTerminalZoneSelectionData = list[index2];
				LG_ComputerTerminal val2;
				if ((int)customTerminalZoneSelectionData.SeedType == 0)
				{
					if (!Builder.CurrentFloor.TryGetZoneByLocalIndex(customTerminalZoneSelectionData.DimensionIndex, customTerminalZoneSelectionData.LayerType, customTerminalZoneSelectionData.LocalIndex, ref val) || (Object)(object)val == (Object)null)
					{
						EOSLogger.Error($"BuildPassword: seedType {0} specified but cannot find zone {customTerminalZoneSelectionData.GlobalZoneIndexTuple()}");
					}
					if (val.TerminalsSpawnedInZone.Count <= 0)
					{
						EOSLogger.Error($"BuildPassword: seedType {0} specified but cannot find terminal zone {customTerminalZoneSelectionData.GlobalZoneIndexTuple()}");
					}
					val2 = val.TerminalsSpawnedInZone[customTerminalZoneSelectionData.TerminalIndex];
				}
				else
				{
					val2 = SelectPasswordTerminal(customTerminalZoneSelectionData.DimensionIndex, customTerminalZoneSelectionData.LayerType, customTerminalZoneSelectionData.LocalIndex, customTerminalZoneSelectionData.SeedType);
				}
				if ((Object)(object)val2 == (Object)null)
				{
					EOSLogger.Error($"BuildPassword: CRITICAL ERROR, could not get a LG_ComputerTerminal for password part ({j + 1}/{num}) for {terminal.PublicName} backup log.");
					continue;
				}
				string text3 = "";
				string text4;
				if (data.ShowPasswordPartPositions)
				{
					for (int k = 0; k < j; k++)
					{
						text3 += text2;
					}
					text4 = text3 + array[j];
					for (int l = j; l < num - 1; l++)
					{
						text4 += text2;
					}
				}
				else
				{
					text4 = array[j];
				}
				string value = (data.ShowPasswordPartPositions ? $"0{j + 1}" : $"0{Builder.SessionSeedRandom.Range(0, 9, "NO_TAG")}");
				TerminalLogFileData val3 = new TerminalLogFileData
				{
					FileName = $"key{value}_{LG_TerminalPasswordLinkerJob.GetTerminalNumber(terminal)}{(val2.HasPasswordPart ? "_1" : "")}.LOG",
					FileContent = new LocalizedText
					{
						UntranslatedText = string.Format(Text.Get((num > 1) ? 1431221909u : 2260297836u), text4),
						Id = 0u
					}
				};
				val2.AddLocalLog(val3, true);
				if (!hashSet.Contains(val2))
				{
					if (j > 0)
					{
						text += ", ";
					}
					text = text + val2.PublicName + " in " + val2.SpawnNode.m_zone.AliasName;
				}
				hashSet.Add(val2);
				val2.HasPasswordPart = true;
			}
			string text5 = text + ".";
			if (data.ShowPasswordLength)
			{
				terminal.LockWithPassword(codeWord, new string[3]
				{
					passwordHintText,
					text5,
					"Char[" + codeWord.Length + "]"
				});
			}
			else
			{
				terminal.LockWithPassword(codeWord, new string[2] { passwordHintText, text5 });
			}
		}

		public static void AddUniqueCommand(LG_ComputerTerminal terminal, CustomCommand cmd)
		{
			//IL_0053: Unknown result type (might be due to invalid IL or missing references)
			//IL_0061: Unknown result type (might be due to invalid IL or missing references)
			//IL_0141: Unknown result type (might be due to invalid IL or missing references)
			//IL_019f: Unknown result type (might be due to invalid IL or missing references)
			if (terminal.m_command.m_commandsPerString.ContainsKey(cmd.Command))
			{
				EOSLogger.Error("Duplicate command name: '" + cmd.Command + "', cannot add command");
				return;
			}
			TERM_Command val = default(TERM_Command);
			if (!terminal.m_command.TryGetUniqueCommandSlot(ref val))
			{
				EOSLogger.Error("Cannot get more unique command slot, max: 5");
				return;
			}
			terminal.m_command.AddCommand(val, cmd.Command, cmd.CommandDesc, cmd.SpecialCommandRule, ListExtensions.ToIl2Cpp<WardenObjectiveEventData>(cmd.CommandEvents), ListExtensions.ToIl2Cpp<TerminalOutput>(cmd.PostCommandOutputs));
			for (int i = 0; i < cmd.CommandEvents.Count; i++)
			{
				WardenObjectiveEventData val2 = cmd.CommandEvents[i];
				if (val2.ChainPuzzle == 0)
				{
					continue;
				}
				ChainedPuzzleDataBlock block = GameDataBlockBase<ChainedPuzzleDataBlock>.GetBlock(val2.ChainPuzzle);
				if (block == null)
				{
					continue;
				}
				LG_Area val3;
				Transform val4;
				if (terminal.SpawnNode != null)
				{
					val3 = terminal.SpawnNode.m_area;
					val4 = terminal.m_wardenObjectiveSecurityScanAlign;
				}
				else
				{
					LG_WardenObjective_Reactor connectedReactor = terminal.ConnectedReactor;
					object obj;
					if (connectedReactor == null)
					{
						obj = null;
					}
					else
					{
						AIG_CourseNode spawnNode = connectedReactor.SpawnNode;
						obj = ((spawnNode != null) ? spawnNode.m_area : null);
					}
					if (obj == null)
					{
						obj = null;
					}
					val3 = (LG_Area)obj;
					LG_WardenObjective_Reactor connectedReactor2 = terminal.ConnectedReactor;
					val4 = ((connectedReactor2 != null) ? connectedReactor2.m_chainedPuzzleAlign : null) ?? null;
				}
				if ((Object)(object)val3 == (Object)null)
				{
					EOSLogger.Error("Terminal Source Area is not found! Cannot create chained puzzle for command " + cmd.Command + "!");
					continue;
				}
				ChainedPuzzleInstance val5 = ChainedPuzzleManager.CreatePuzzleInstance(block, val3, val4.position, val4, val2.UseStaticBioscanPoints);
				List<WardenObjectiveEventData> events = ListExtensions.ToIl2Cpp<WardenObjectiveEventData>(cmd.CommandEvents.GetRange(i, cmd.CommandEvents.Count - i));
				val5.OnPuzzleSolved += Action.op_Implicit((Action)delegate
				{
					WardenObjectiveManager.CheckAndExecuteEventsOnTrigger(events, (eWardenObjectiveEventTrigger)0, true, 0f, (Il2CppStructArray<eWardenObjectiveEventType>)null);
				});
				terminal.SetChainPuzzleForCommand(val, i, val5);
			}
		}
	}
	public static class EOSUtils
	{
		public static List<T> ToManaged<T>(this List<T> il2cppList)
		{
			List<T> list = new List<T>();
			Enumerator<T> enumerator = il2cppList.GetEnumerator();
			while (enumerator.MoveNext())
			{
				T current = enumerator.Current;
				list.Add(current);
			}
			return list;
		}

		public static void ResetProgress(this ChainedPuzzleInstance chainedPuzzle)
		{
			//IL_0014: 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_0023: Expected O, but got Unknown
			//IL_005d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0062: 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_006e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0075: Unknown result type (might be due to invalid IL or missing references)
			//IL_0090: Unknown result type (might be due to invalid IL or missing references)
			//IL_0091: Unknown result type (might be due to invalid IL or missing references)
			//IL_0098: 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_00a4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a9: Unknown result type (might be due to invalid IL or missing references)
			if (chainedPuzzle.Data.DisableSurvivalWaveOnComplete)
			{
				chainedPuzzle.m_sound = new CellSoundPlayer(chainedPuzzle.m_parent.position);
			}
			foreach (iChainedPuzzleCore item in (Il2CppArrayBase<iChainedPuzzleCore>)(object)chainedPuzzle.m_chainedPuzzleCores)
			{
				ResetChild(item);
			}
			if (SNet.IsMaster)
			{
				pChainedPuzzleState state = chainedPuzzle.m_stateReplicator.State;
				pChainedPuzzleState val = default(pChainedPuzzleState);
				val.status = (eChainedPuzzleStatus)0;
				val.currentSurvivalWave_EventID = state.currentSurvivalWave_EventID;
				val.isSolved = false;
				val.isActive = false;
				pChainedPuzzleState val2 = val;
				chainedPuzzle.m_stateReplicator.InteractWithState(val2, new pChainedPuzzleInteraction
				{
					type = (eChainedPuzzleInteraction)2
				});
			}
			static void ResetChild(iChainedPuzzleCore ICore)
			{
				CP_Bioscan_Core val3 = ((Il2CppObjectBase)ICore).TryCast<CP_Bioscan_Core>();
				if ((Object)(object)val3 != (Object)null)
				{
					((Il2CppObjectBase)val3.m_spline).Cast<CP_Holopath_Spline>();
					((Il2CppObjectBase)val3.PlayerScanner).Cast<CP_PlayerScanner>().ResetScanProgression(0f);
					val3.Deactivate();
				}
				else
				{
					CP_Cluster_Core val4 = ((Il2CppObjectBase)ICore).TryCast<CP_Cluster_Core>();
					if ((Object)(object)val4 == (Object)null)
					{
						EOSLogger.Error("ResetChild: found iChainedPuzzleCore that is neither CP_Bioscan_Core nor CP_Cluster_Core...");
					}
					else
					{
						((Il2CppObjectBase)val4.m_spline).Cast<CP_Holopath_Spline>();
						foreach (iChainedPuzzleCore item2 in (Il2CppArrayBase<iChainedPuzzleCore>)(object)val4.m_childCores)
						{
							ResetChild(item2);
						}
						val4.Deactivate();
					}
				}
			}
		}
	}
	public class EOSColor
	{
		public float r { get; set; }

		public float g { get; set; }

		public float b { get; set; }

		public float a { get; set; } = 1f;


		public Color ToUnityColor()
		{
			//IL_0018: Unknown result type (might be due to invalid IL or missing references)
			return new Color(r, g, b, a);
		}
	}
	public static class VanillaTMPPros
	{
		public const string VANILLA_CP_PREFAB_PATH = "Assets/AssetPrefabs/Complex/Generic/ChainedPuzzles/CP_Bioscan_sustained_RequireAll.prefab";

		public static GameObject Instantiate(GameObject parent = null)
		{
			GameObject loadedAsset = AssetAPI.GetLoadedAsset<GameObject>("Assets/AssetPrefabs/Complex/Generic/ChainedPuzzles/CP_Bioscan_sustained_RequireAll.prefab");
			if ((Object)(object)loadedAsset == (Object)null)
			{
				EOSLogger.Error("VanillaTMPPros.Instantiate: Cannot find TMPPro from vanilla CP!");
				return null;
			}
			GameObject gameObject = ((Component)loadedAsset.transform.GetChild(0).GetChild(1).GetChild(0)).gameObject;
			if (!((Object)(object)parent != (Object)null))
			{
				return Object.Instantiate<GameObject>(gameObject.gameObject);
			}
			return Object.Instantiate<GameObject>(gameObject.gameObject, parent.transform);
		}
	}
	public class Vec4 : Vec3
	{
		[JsonPropertyOrder(-9)]
		public float w { get; set; }

		public Vector4 ToVector4()
		{
			//IL_0018: Unknown result type (might be due to invalid IL or missing references)
			return new Vector4(base.x, base.y, base.z, w);
		}
	}
	public class Vec3
	{
		[JsonPropertyOrder(-10)]
		public float x { get; set; }

		[JsonPropertyOrder(-10)]
		public float y { get; set; }

		[JsonPropertyOrder(-10)]
		public float z { get; set; }

		public Vector3 ToVector3()
		{
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			return new Vector3(x, y, z);
		}

		public Quaternion ToQuaternion()
		{
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			return Quaternion.Euler(x, y, z);
		}
	}
	public static class EOSLogger
	{
		private static ManualLogSource logger = Logger.CreateLogSource("ExtraObjectiveSetup");

		public static void Log(string format, params object[] args)
		{
			Log(string.Format(format, args));
		}

		public static void Log(string str)
		{
			if (logger != null)
			{
				logger.Log((LogLevel)8, (object)str);
			}
		}

		public static void Warning(string format, params object[] args)
		{
			Warning(string.Format(format, args));
		}

		public static void Warning(string str)
		{
			if (logger != null)
			{
				logger.Log((LogLevel)4, (object)str);
			}
		}

		public static void Error(string format, params object[] args)
		{
			Error(string.Format(format, args));
		}

		public static void Error(string str)
		{
			if (logger != null)
			{
				logger.Log((LogLevel)2, (object)str);
			}
		}

		public static void Debug(string format, params object[] args)
		{
			Debug(string.Format(format, args));
		}

		public static void Debug(string str)
		{
			if (logger != null)
			{
				logger.Log((LogLevel)32, (object)str);
			}
		}
	}
}
namespace ExtraObjectiveSetup.Tweaks.TerminalTweak
{
	public struct TerminalState
	{
		public bool Enabled;

		public TerminalState()
		{
			Enabled = true;
		}

		public TerminalState(bool Enabled)
		{
			this.Enabled = true;
			this.Enabled = Enabled;
		}

		public TerminalState(TerminalState o)
		{
			Enabled = true;
			Enabled = o.Enabled;
		}
	}
	public class TerminalWrapper
	{
		public LG_ComputerTerminal lgTerminal { get; private set; }

		public StateReplicator<TerminalState> stateReplicator { get; private set; }

		private void ChangeStateUnsynced(bool enabled)
		{
			EOSLogger.Debug($"{lgTerminal.ItemKey} state, enabled: {enabled}");
			lgTerminal.OnProximityExit();
			Interact_ComputerTerminal componentInChildren = ((Component)lgTerminal).GetComponentInChildren<Interact_ComputerTerminal>(true);
			bool flag = enabled;
			if ((Object)(object)componentInChildren != (Object)null)
			{
				((Behaviour)componentInChildren).enabled = flag;
				((Interact_Base)componentInChildren).SetActive(flag);
			}
			lgTerminal.m_interfaceScreen.SetActive(flag);
			lgTerminal.m_loginScreen.SetActive(flag);
			if ((Object)(object)lgTerminal.m_text != (Object)null)
			{
				((Behaviour)lgTerminal.m_text).enabled = flag;
			}
			if (!flag)
			{
				PlayerAgent localInteractionSource = lgTerminal.m_localInteractionSource;
				if ((Object)(object)localInteractionSource != (Object)null && localInteractionSource.FPItemHolder.InTerminalTrigger)
				{
					lgTerminal.ExitFPSView();
				}
			}
		}

		public void ChangeState(bool enabled)
		{
			ChangeStateUnsynced(enabled);
			if (SNet.IsMaster)
			{
				stateReplicator.SetState(new TerminalState
				{
					Enabled = enabled
				});
			}
		}

		private void OnStateChanged(TerminalState oldState, TerminalState newState, bool isRecall)
		{
			if (isRecall)
			{
				ChangeStateUnsynced(newState.Enabled);
			}
		}

		public static TerminalWrapper Instantiate(LG_ComputerTerminal lgTerminal, uint replicatorID)
		{
			if ((Object)(object)lgTerminal == (Object)null || replicatorID == 0)
			{
				return null;
			}
			TerminalWrapper terminalWrapper = new TerminalWrapper();
			terminalWrapper.lgTerminal = lgTerminal;
			terminalWrapper.stateReplicator = StateReplicator<TerminalState>.Create(replicatorID, new TerminalState
			{
				Enabled = true
			}, (LifeTimeType)1, (IStateReplicatorHolder<TerminalState>)null);
			terminalWrapper.stateReplicator.OnStateChanged += terminalWrapper.OnStateChanged;
			return terminalWrapper;
		}

		private TerminalWrapper()
		{
		}
	}
}
namespace ExtraObjectiveSetup.Tweaks.TerminalPosition
{
	public class TerminalPosition : BaseInstanceDefinition
	{
		public Vec3 Position { get; set; } = new Vec3();


		public Vec3 Rotation { get; set; } = new Vec3();

	}
	internal class TerminalPositionOverrideManager : InstanceDefinitionManager<TerminalPosition>
	{
		public static TerminalPositionOverrideManager Current;

		protected override string DEFINITION_NAME => "TerminalPosition";

		private TerminalPositionOverrideManager()
		{
		}

		static TerminalPositionOverrideManager()
		{
			Current = new TerminalPositionOverrideManager();
		}
	}
}
namespace ExtraObjectiveSetup.Tweaks.Scout
{
	public class EventsOnZoneScoutScream : GlobalZoneIndex
	{
		public bool SuppressVanillaScoutWave { get; set; }

		public List<WardenObjectiveEventData> EventsOnScoutScream { get; set; } = new List<WardenObjectiveEventData>();

	}
	internal class ScoutScreamEventManager : ZoneDefinitionManager<EventsOnZoneScoutScream>
	{
		public static ScoutScreamEventManager Current;

		protected override string DEFINITION_NAME => "EventsOnScoutScream";

		private ScoutScreamEventManager()
		{
		}

		static ScoutScreamEventManager()
		{
			Current = new ScoutScreamEventManager();
		}
	}
}
namespace ExtraObjectiveSetup.Tweaks.BossEvents
{
	public struct FiniteBDEState
	{
		public int ApplyToHibernateCount;

		public int ApplyToWaveCount;

		public FiniteBDEState()
		{
			ApplyToHibernateCount = int.MaxValue;
			ApplyToWaveCount = int.MaxValue;
		}

		public FiniteBDEState(FiniteBDEState other)
		{
			ApplyToHibernateCount = int.MaxValue;
			ApplyToWaveCount = int.MaxValue;
			ApplyToHibernateCount = other.ApplyToHibernateCount;
			ApplyToHibernateCount = other.ApplyToWaveCount;
		}

		public FiniteBDEState(int ApplyToHibernateCount, int ApplyToWaveCount)
		{
			this.ApplyToHibernateCount = int.MaxValue;
			this.ApplyToWaveCount = int.MaxValue;
			this.ApplyToHibernateCount = ApplyToHibernateCount;
			this.ApplyToWaveCount = ApplyToWaveCount;
		}
	}
	public class EventsOnZoneBossDeath : GlobalZoneIndex
	{
		public bool ApplyToHibernate { get; set; } = true;


		public int ApplyToHibernateCount { get; set; } = int.MaxValue;


		public bool ApplyToWave { get; set; }

		public int ApplyToWaveCount { get; set; } = int.MaxValue;


		public List<uint> BossIDs { get; set; } = new List<uint> { 29u, 36u, 37u };


		public List<WardenObjectiveEventData> EventsOnBossDeath { get; set; } = new List<WardenObjectiveEventData>();


		[JsonIgnore]
		public StateReplicator<FiniteBDEState> FiniteBDEStateReplicator { get; private set; }

		[JsonIgnore]
		public int RemainingWaveBDE
		{
			get
			{
				if (FiniteBDEStateReplicator == null)
				{
					return ApplyToWaveCount;
				}
				return FiniteBDEStateReplicator.State.ApplyToWaveCount;
			}
		}

		[JsonIgnore]
		public int RemainingHibernateBDE
		{
			get
			{
				if (FiniteBDEStateReplicator == null)
				{
					return ApplyToHibernateCount;
				}
				return FiniteBDEStateReplicator.State.ApplyToHibernateCount;
			}
		}

		public void SetupReplicator(uint replicatorID)
		{
			if (ApplyToHibernateCount != int.MaxValue || ApplyToWaveCount != int.MaxValue)
			{
				FiniteBDEStateReplicator = StateReplicator<FiniteBDEState>.Create(replicatorID, new FiniteBDEState
				{
					ApplyToHibernateCount = ApplyToHibernateCount,
					ApplyToWaveCount = ApplyToWaveCount
				}, (LifeTimeType)1, (IStateReplicatorHolder<FiniteBDEState>)null);
				FiniteBDEStateReplicator.OnStateChanged += OnStateChanged;
			}
		}

		private void OnStateChanged(FiniteBDEState oldState, FiniteBDEState newState, bool isRecall)
		{
		}

		internal void Destroy()
		{
			FiniteBDEStateReplicator = null;
		}
	}
	internal class BossDeathEventManager : ZoneDefinitionManager<EventsOnZoneBossDeath>
	{
		public enum Mode
		{
			HIBERNATE,
			WAVE
		}

		public static BossDeathEventManager Current;

		public const int UNLIMITED_COUNT = int.MaxValue;

		private ConcurrentDictionary<(eDimensionIndex, LG_LayerType, eLocalZoneIndex), EventsOnZoneBossDeath> LevelBDEs { get; } = new ConcurrentDictionary<(eDimensionIndex, LG_LayerType, eLocalZoneIndex), EventsOnZoneBossDeath>();


		protected override string DEFINITION_NAME => "EventsOnBossDeath";

		public bool TryConsumeBDEventsExecutionTimes(EventsOnZoneBossDeath def, Mode mode)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			return TryConsumeBDEventsExecutionTimes(def.DimensionIndex, def.LayerType, def.LocalIndex, mode);
		}

		public bool TryConsumeBDEventsExecutionTimes(eDimensionIndex dimensionIndex, LG_LayerType layer, eLocalZoneIndex localIndex, Mode mode)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_0008: 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_0051: 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_002d: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Unknown result type (might be due to invalid IL or missing references)
			//IL_002f: Unknown result type (might be due to invalid IL or missing references)
			if (!LevelBDEs.ContainsKey((dimensionIndex, layer, localIndex)))
			{
				EOSLogger.Error($"BossDeathEventManager: got an unregistered entry: {(dimensionIndex, layer, localIndex, mode)}");
				return false;
			}
			EventsOnZoneBossDeath eventsOnZoneBossDeath = LevelBDEs[(dimensionIndex, layer, localIndex)];
			int num = ((mode == Mode.HIBERNATE) ? eventsOnZoneBossDeath.RemainingHibernateBDE : eventsOnZoneBossDeath.RemainingWaveBDE);
			if (num == int.MaxValue)
			{
				return true;
			}
			if (num > 0)
			{
				FiniteBDEState state = eventsOnZoneBossDeath.FiniteBDEStateReplicator.State;
				if (SNet.IsMaster)
				{
					eventsOnZoneBossDeath.FiniteBDEStateReplicator.SetState(new FiniteBDEState
					{
						ApplyToHibernateCount = ((mode == Mode.HIBERNATE) ? (num - 1) : state.ApplyToHibernateCount),
						ApplyToWaveCount = ((mode == Mode.WAVE) ? (num - 1) : state.ApplyToWaveCount)
					});
				}
				return true;
			}
			return false;
		}

		private void Clear()
		{
			foreach (EventsOnZoneBossDeath value in LevelBDEs.Values)
			{
				value.Destroy();
			}
			LevelBDEs.Clear();
		}

		private void SetupForCurrentExpedition()
		{
			if (!definitions.ContainsKey(RundownManager.ActiveExpedition.LevelLayoutData))
			{
				return;
			}
			foreach (EventsOnZoneBossDeath definition in definitions[RundownManager.ActiveExpedition.LevelLayoutData].Definitions)
			{
				if (LevelBDEs.ContainsKey(definition.GlobalZoneIndexTuple()))
				{
					EOSLogger.Error($"BossDeathEvent: found duplicate setup for zone {definition.GlobalZoneIndexTuple()}, will overwrite!");
				}
				if (definition.ApplyToHibernateCount != int.MaxValue || definition.ApplyToWaveCount != int.MaxValue)
				{
					uint num = EOSNetworking.AllotReplicatorID();
					if (num != 0)
					{
						definition.SetupReplicator(num);
					}
					else
					{
						EOSLogger.Error("BossDeathEvent: replicator ID depleted, cannot setup replicator!");
					}
				}
				LevelBDEs[definition.GlobalZoneIndexTuple()] = definition;
			}
		}

		private BossDeathEventManager()
		{
			LevelAPI.OnBuildStart += delegate
			{
				Clear();
				SetupForCurrentExpedition();
			};
			LevelAPI.OnLevelCleanup += Clear;
		}

		static BossDeathEventManager()
		{
			Current = new BossDeathEventManager();
		}
	}
}
namespace ExtraObjectiveSetup.Patches
{
	[HarmonyPatch]
	internal class Patch_CheckAndExecuteEventsOnTrigger
	{
		[HarmonyPrefix]
		[HarmonyPatch(typeof(WardenObjectiveManager), "CheckAndExecuteEventsOnTrigger", new Type[]
		{
			typeof(WardenObjectiveEventData),
			typeof(eWardenObjectiveEventTrigger),
			typeof(bool),
			typeof(float)
		})]
		private static bool Pre_CheckAndExecuteEventsOnTrigger(WardenObjectiveEventData eventToTrigger, eWardenObjectiveEventTrigger trigger, bool ignoreTrigger, float currentDuration)
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0028: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Expected I4, but got Unknown
			if (eventToTrigger == null || (!ignoreTrigger && eventToTrigger.Trigger != trigger) || ((double)currentDuration != 0.0 && eventToTrigger.Delay <= currentDuration))
			{
				return true;
			}
			uint num = (uint)(int)eventToTrigger.Type;
			if (!EOSWardenEventManager.Current.HasEventDefinition(num))
			{
				return true;
			}
			string value = (EOSWardenEventManager.Current.IsVanillaEventID(num) ? "overriding vanilla event implementation..." : "executing...");
			EOSLogger.Debug($"WardenEvent: found definition for event ID {num}, {value}");
			EOSWardenEventManager.Current.ExecuteEvent(eventToTrigger, currentDuration);
			return false;
		}
	}
	[HarmonyPatch]
	internal class Patch_EventsOnBossDeath
	{
		private static HashSet<ushort> ExecutedForInstances;

		[HarmonyPostfix]
		[HarmonyPatch(typeof(EnemySync), "OnSpawn")]
		private static void Post_SpawnEnemy(EnemySync __instance, pEnemySpawnData spawnData)
		{
			//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_0043: 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_008b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0091: Invalid comparison between Unknown and I4
			//IL_0093: Unknown result type (might be due to invalid IL or missing references)
			//IL_0094: Unknown result type (might be due to invalid IL or missing references)
			//IL_009a: Invalid comparison between Unknown and I4
			//IL_00c1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c8: Invalid comparison between Unknown and I4
			//IL_00a9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00aa: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b0: Invalid comparison between Unknown and I4
			//IL_012a: Unknown result type (might be due to invalid IL or missing references)
			//IL_012b: Unknown result type (might be due to invalid IL or missing references)
			AIG_CourseNode val = default(AIG_CourseNode);
			if (!((pCourseNode)(ref spawnData.courseNode)).TryGet(ref val) || val == null)
			{
				EOSLogger.Error("Failed to get spawnnode for a boss! Skipped EventsOnBossDeath for it");
				return;
			}
			LG_Zone zone = val.m_zone;
			EventsOnZoneBossDeath def = BossDeathEventManager.Current.GetDefinition(zone.DimensionIndex, zone.Layer.m_type, zone.LocalIndex);
			if (def == null)
			{
				return;
			}
			EnemyAgent enemy = __instance.m_agent;
			if (!def.BossIDs.Contains(((GameDataBlockBase<EnemyDataBlock>)(object)enemy.EnemyData).persistentID) || ((((int)spawnData.mode != 4 && (int)spawnData.mode != 3) || !def.ApplyToHibernate) && ((int)spawnData.mode != 1 || !def.ApplyToWave)))
			{
				return;
			}
			BossDeathEventManager.Mode mode = (((int)spawnData.mode != 4) ? BossDeathEventManager.Mode.WAVE : BossDeathEventManager.Mode.HIBERNATE);
			enemy.OnDeadCallback += Action.op_Implicit((Action)delegate
			{
				//IL_0000: Unknown result type (might be due to invalid IL or missing references)
				//IL_0007: Invalid comparison between Unknown and I4
				if ((int)GameStateManager.CurrentStateName == 10)
				{
					if (!BossDeathEventManager.Current.TryConsumeBDEventsExecutionTimes(def, mode))
					{
						EOSLogger.Debug($"EventsOnBossDeath: execution times depleted for {def.GlobalZoneIndexTuple()}, {mode}");
					}
					else
					{
						ushort globalID = ((Agent)enemy).GlobalID;
						if (ExecutedForInstances.Contains(globalID))
						{
							ExecutedForInstances.Remove(globalID);
						}
						else
						{
							def.EventsOnBossDeath.ForEach(delegate(WardenObjectiveEventData e)
							{
								WardenObjectiveManager.CheckAndExecuteEventsOnTrigger(e, (eWardenObjectiveEventTrigger)0, true, 0f);
							});
							ExecutedForInstances.Add(globalID);
						}
					}
				}
			});
			EOSLogger.Debug($"EventsOnBossDeath: added for enemy with id  {((GameDataBlockBase<EnemyDataBlock>)(object)enemy.EnemyData).persistentID}, mode: {spawnData.mode}");
		}

		static Patch_EventsOnBossDeath()
		{
			ExecutedForInstances = new HashSet<ushort>();
			LevelAPI.OnLevelCleanup += ExecutedForInstances.Clear;
		}
	}
	[HarmonyPatch]
	internal class Patch_EventsOnZoneScoutScream
	{
		[HarmonyPrefix]
		[HarmonyPatch(typeof(ES_ScoutScream), "CommonUpdate")]
		private static bool Pre_ES_ScoutScream_CommonUpdate(ES_ScoutScream __instance)
		{
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			//IL_001d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0028: Unknown result type (might be due to invalid IL or missing references)
			//IL_0039: Unknown result type (might be due to invalid IL or missing references)
			//IL_003f: Invalid comparison between Unknown and I4
			//IL_0153: Unknown result type (might be due to invalid IL or missing references)
			//IL_0159: Unknown result type (might be due to invalid IL or missing references)
			AIG_CourseNode courseNode = ((Agent)((ES_Base)__instance).m_enemyAgent).CourseNode;
			EventsOnZoneScoutScream definition = ScoutScreamEventManager.Current.GetDefinition(courseNode.m_dimension.DimensionIndex, courseNode.LayerType, courseNode.m_zone.LocalIndex);
			if (definition == null)
			{
				return true;
			}
			if ((int)__instance.m_state != 3 || __instance.m_stateDoneTimer >= Clock.Time)
			{
				return true;
			}
			if (definition.EventsOnScoutScream != null && definition.EventsOnScoutScream.Count > 0)
			{
				EOSLogger.Debug($"EventsOnZoneScoutScream: found config for {definition.GlobalZoneIndexTuple()}, executing events.");
				definition.EventsOnScoutScream.ForEach(delegate(WardenObjectiveEventData e)
				{
					WardenObjectiveManager.CheckAndExecuteEventsOnTrigger(e, (eWardenObjectiveEventTrigger)0, true, 0f);
				});
			}
			if (!definition.SuppressVanillaScoutWave)
			{
				if (SNet.IsMaster && ((Agent)((ES_Base)__instance).m_enemyAgent).CourseNode != null)
				{
					if (RundownManager.ActiveExpedition.Expedition.ScoutWaveSettings != 0 && RundownManager.ActiveExpedition.Expedition.ScoutWavePopulation != 0)
					{
						ushort num = default(ushort);
						Mastermind.Current.TriggerSurvivalWave(((Agent)((ES_Base)__instance).m_enemyAgent).CourseNode, RundownManager.ActiveExpedition.Expedition.ScoutWaveSettings, RundownManager.ActiveExpedition.Expedition.ScoutWavePopulation, ref num, (SurvivalWaveSpawnType)0, 0f, 2f, true, false, default(Vector3), "");
					}
					else
					{
						Debug.LogError(Object.op_Implicit("ES_ScoutScream, a scout is screaming but we can't spawn a wave because the the scout settings are not set for this expedition! ScoutWaveSettings: " + RundownManager.ActiveExpedition.Expedition.ScoutWaveSettings + " ScoutWavePopulation: " + RundownManager.ActiveExpedition.Expedition.ScoutWavePopulation));
					}
				}
			}
			else
			{
				EOSLogger.Debug("Vanilla scout wave suppressed.");
			}
			if (SNet.IsMaster)
			{
				((ES_Base)__instance).m_enemyAgent.AI.m_behaviour.ChangeState((EB_States)5);
			}
			((MachineState<ES_Base>)(object)__instance).m_machine.ChangeState(2);
			__instance.m_state = (ScoutScreamState)4;
			return false;
		}
	}
}
namespace ExtraObjectiveSetup.Patches.Uplink
{
	[HarmonyPatch]
	internal static class CorruptedUplinkConfirm
	{
		[HarmonyPrefix]
		[HarmonyPatch(typeof(LG_ComputerTerminalCommandInterpreter), "TerminalCorruptedUplinkConfirm")]
		private static bool Pre_LG_ComputerTerminalCommandInterpreter_TerminalCorruptedUplinkConfirm(LG_ComputerTerminalCommandInterpreter __instance, string param1, string param2, ref bool __result)
		{
			LG_ComputerTerminal receiver = __instance.m_terminal;
			LG_ComputerTerminal sender = __instance.m_terminal.CorruptedUplinkReceiver;
			if ((Object)(object)sender == (Object)null)
			{
				EOSLogger.Error("TerminalCorruptedUplinkConfirm() critical failure because terminal does not have a CorruptedUplinkReceiver (sender).");
				__result = false;
				return false;
			}
			if (sender.m_isWardenObjective)
			{
				return true;
			}
			(eDimensionIndex, LG_LayerType, eLocalZoneIndex) globalZoneIndex = TerminalInstanceManager.Current.GetGlobalZoneIndex(sender);
			uint zoneInstanceIndex = TerminalInstanceManager.Current.GetZoneInstanceIndex(sender);
			UplinkObjectiveManager.Current.GetDefinition(globalZoneIndex, zoneInstanceIndex);
			receiver.m_command.AddOutput((TerminalLineType)0, string.Format(Text.Get(2816126705u), sender.PublicName), 0f, (TerminalSoundType)0, (TerminalSoundType)0);
			if ((Object)(object)sender.ChainedPuzzleForWardenObjective != (Object)null)
			{
				ChainedPuzzleInstance chainedPuzzleForWardenObjective = sender.ChainedPuzzleForWardenObjective;
				chainedPuzzleForWardenObjective.OnPuzzleSolved += Action.op_Implicit((Action)delegate
				{
					receiver.m_command.StartTerminalUplinkSequence(string.Empty, true);
					UplinkObjectiveManager.Current.ChangeState(sender, new UplinkState
					{
						Status = UplinkStatus.InProgress,
						CurrentRoundIndex = 0
					});
				});
				sender.m_command.AddOutput("", true);
				sender.m_command.AddOutput(Text.Get(3268596368u), true);
				sender.m_command.AddOutput(Text.Get(2277987284u), true);
				receiver.m_command.AddOutput("", true);
				receiver.m_command.AddOutput(Text.Get(3268596368u), true);
				receiver.m_command.AddOutput(Text.Get(2277987284u), true);
				if (SNet.IsMaster)
				{
					sender.ChainedPuzzleForWardenObjective.AttemptInteract((eChainedPuzzleInteraction)0);
				}
			}
			else
			{
				receiver.m_command.StartTerminalUplinkSequence(string.Empty, true);
				UplinkObjectiveManager.Current.ChangeState(sender, new UplinkState
				{
					Status = UplinkStatus.InProgress,
					CurrentRoundIndex = 0
				});
			}
			__result = true;
			return false;
		}
	}
	[HarmonyPatch]
	internal static class CorruptedUplinkConnect
	{
		[HarmonyPrefix]
		[HarmonyPatch(typeof(LG_ComputerTerminalCommandInterpreter), "TerminalCorruptedUplinkConnect")]
		private static bool Pre_LG_ComputerTerminalCommandInterpreter_TerminalCorruptedUplinkConnect(LG_ComputerTerminalCommandInterpreter __instance, string param1, string param2, ref bool __result)
		{
			//IL_01b4: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b9: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c9: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d6: Expected O, but got Unknown
			LG_ComputerTerminal terminal = __instance.m_terminal;
			if (terminal.m_isWardenObjective)
			{
				return true;
			}
			__result = false;
			LG_ComputerTerminal corruptedUplinkReceiver = terminal.CorruptedUplinkReceiver;
			if ((Object)(object)corruptedUplinkReceiver == (Object)null)
			{
				EOSLogger.Error("TerminalCorruptedUplinkConnect() critical failure because terminal does not have a CorruptedUplinkReceiver.");
				return false;
			}
			if (LG_ComputerTerminalManager.OngoingUplinkConnectionTerminalId != 0 && LG_ComputerTerminalManager.OngoingUplinkConnectionTerminalId != terminal.SyncID)
			{
				__instance.AddOngoingUplinkOutput();
				__result = false;
				return false;
			}
			LG_ComputerTerminalManager.OngoingUplinkConnectionTerminalId = terminal.SyncID;
			(eDimensionIndex, LG_LayerType, eLocalZoneIndex) globalZoneIndex = TerminalInstanceManager.Current.GetGlobalZoneIndex(terminal);
			uint zoneInstanceIndex = TerminalInstanceManager.Current.GetZoneInstanceIndex(terminal);
			UplinkDefinition definition = UplinkObjectiveManager.Current.GetDefinition(globalZoneIndex, zoneInstanceIndex);
			if (definition.UseUplinkAddress)
			{
				param1 = param1.ToUpper();
				EOSLogger.Debug("TerminalCorruptedUplinkConnect, param1: " + param1 + ", TerminalUplink: " + ((Object)terminal.UplinkPuzzle).ToString());
			}
			else
			{
				param1 = terminal.UplinkPuzzle.TerminalUplinkIP.ToUpper();
				EOSLogger.Debug("TerminalCorruptedUplinkConnect, not using uplink address, TerminalUplink: " + ((Object)terminal.UplinkPuzzle).ToString());
			}
			if (!definition.UseUplinkAddress || param1 == terminal.UplinkPuzzle.TerminalUplinkIP)
			{
				if (corruptedUplinkReceiver.m_command.HasRegisteredCommand((TERM_Command)27))
				{
					terminal.m_command.AddUplinkCorruptedOutput();
				}
				else
				{
					terminal.m_command.AddUplinkCorruptedOutput();
					terminal.m_command.AddOutput("", true);
					terminal.m_command.AddOutput((TerminalLineType)4, string.Format(Text.Get(3492863045u), corruptedUplinkReceiver.PublicName), 3f, (TerminalSoundType)0, (TerminalSoundType)0);
					terminal.m_command.AddOutput((TerminalLineType)0, Text.Get(2761366063u), 0.6f, (TerminalSoundType)0, (TerminalSoundType)0);
					terminal.m_command.AddOutput("", true);
					terminal.m_command.AddOutput((TerminalLineType)0, Text.Get(3435969025u), 0.8f, (TerminalSoundType)0, (TerminalSoundType)0);
					corruptedUplinkReceiver.m_command.AddCommand((TERM_Command)27, "UPLINK_CONFIRM", new LocalizedText
					{
						UntranslatedText = Text.Get(112719254u),
						Id = 0u
					}, (TERM_CommandRule)2);
					corruptedUplinkReceiver.m_command.AddOutput((TerminalLineType)0, string.Format(Text.Get(1173595354u), terminal.PublicName), 0f, (TerminalSoundType)0, (TerminalSoundType)0);
				}
			}
			else
			{
				terminal.m_command.AddUplinkWrongAddressError(param1);
			}
			return false;
		}
	}
	[HarmonyPatch]
	internal static class StartTerminalUplinkSequence
	{
		[HarmonyPrefix]
		[HarmonyPatch(typeof(LG_ComputerTerminalCommandInterpreter), "StartTerminalUplinkSequence")]
		private static bool Pre_LG_ComputerTerminalCommandInterpreter_StartTerminalUplinkSequence(LG_ComputerTerminalCommandInterpreter __instance, string uplinkIp, bool corrupted)
		{
			if (!corrupted)
			{
				LG_ComputerTerminal uplinkTerminal = __instance.m_terminal;
				if (uplinkTerminal.m_isWardenObjective)
				{
					return true;
				}
				(eDimensionIndex, LG_LayerType, eLocalZoneIndex) globalZoneIndex = TerminalInstanceManager.Current.GetGlobalZoneIndex(uplinkTerminal);
				uint zoneInstanceIndex = TerminalInstanceManager.Current.GetZoneInstanceIndex(uplinkTerminal);
				UplinkDefinition uplinkConfig = UplinkObjectiveManager.Current.GetDefinition(globalZoneIndex, zoneInstanceIndex);
				uplinkTerminal.m_command.AddOutput((TerminalLineType)4, string.Format(Text.Get(2583360288u), uplinkIp), 3f, (TerminalSoundType)0, (TerminalSoundType)0);
				__instance.TerminalUplinkSequenceOutputs(uplinkTerminal, false);
				uplinkTerminal.m_command.OnEndOfQueue = Action.op_Implicit((Action)delegate
				{
					EOSLogger.Debug("UPLINK CONNECTION DONE!");
					uplinkTerminal.UplinkPuzzle.Connected = true;
					uplinkTerminal.UplinkPuzzle.CurrentRound.ShowGui = true;
					uplinkTerminal.UplinkPuzzle.OnStartSequence();
					uplinkConfig.EventsOnCommence.ForEach(delegate(WardenObjectiveEventData e)
					{
						WardenObjectiveManager.CheckAndExecuteEventsOnTrigger(e, (eWardenObjectiveEventTrigger)0, true, 0f);
					});
					int num2 = uplinkConfig.RoundOverrides.FindIndex((UplinkRound o) => o.RoundIndex == 0);
					((num2 != -1) ? uplinkConfig.RoundOverrides[num2] : null)?.EventsOnRound.ForEach(delegate(WardenObjectiveEventData e)
					{
						WardenObjectiveManager.CheckAndExecuteEventsOnTrigger(e, (eWardenObjectiveEventTrigger)1, false, 0f);
					});
				});
			}
			else
			{
				LG_ComputerTerminal terminal = __instance.m_terminal;
				LG_ComputerTerminal sender = __instance.m_terminal.CorruptedUplinkReceiver;
				if (sender.m_isWardenObjective)
				{
					return true;
				}
				(eDimensionIndex, LG_LayerType, eLocalZoneIndex) globalZoneIndex2 = TerminalInstanceManager.Current.GetGlobalZoneIndex(sender);
				uint zoneInstanceIndex2 = TerminalInstanceManager.Current.GetZoneInstanceIndex(sender);
				UplinkDefinition uplinkConfig2 = UplinkObjectiveManager.Current.GetDefinition(globalZoneIndex2, zoneInstanceIndex2);
				sender.m_command.AddOutput((TerminalLineType)4, string.Format(Text.Get(2056072887u), sender.PublicName), 3f, (TerminalSoundType)0, (TerminalSoundType)0);
				sender.m_command.AddOutput("", true);
				terminal.m_command.AddOutput((TerminalLineType)4, string.Format(Text.Get(2056072887u), sender.PublicName), 3f, (TerminalSoundType)0, (TerminalSoundType)0);
				terminal.m_command.AddOutput("", true);
				terminal.m_command.TerminalUplinkSequenceOutputs(sender, false);
				terminal.m_command.TerminalUplinkSequenceOutputs(terminal, true);
				terminal.m_command.OnEndOfQueue = Action.op_Implicit((Action)delegate
				{
					EOSLogger.Debug("UPLINK CONNECTION DONE!");
					sender.UplinkPuzzle.Connected = true;
					sender.UplinkPuzzle.CurrentRound.ShowGui = true;
					sender.UplinkPuzzle.OnStartSequence();
					uplinkConfig2.EventsOnCommence.ForEach(delegate(WardenObjectiveEventData e)
					{
						WardenObjectiveManager.CheckAndExecuteEventsOnTrigger(e, (eWardenObjectiveEventTrigger)0, true, 0f);
					});
					int num = uplinkConfig2.RoundOverrides.FindIndex((UplinkRound o) => o.RoundIndex == 0);
					((num != -1) ? uplinkConfig2.RoundOverrides[num] : null)?.EventsOnRound.ForEach(delegate(WardenObjectiveEventData e)
					{
						WardenObjectiveManager.CheckAndExecuteEventsOnTrigger(e, (eWardenObjectiveEventTrigger)1, false, 0f);
					});
				});
			}
			return false;
		}
	}
	[HarmonyPatch]
	internal static class TerminalUplinkConnect
	{
		[HarmonyPrefix]
		[HarmonyPatch(typeof(LG_ComputerTerminalCommandInterpreter), "TerminalUplinkConnect")]
		private static bool Pre_LG_ComputerTerminalCommandInterpreter_TerminalUplinkConnect(LG_ComputerTerminalCommandInterpreter __instance, string param1, string param2, ref bool __result)
		{
			LG_ComputerTerminal terminal = __instance.m_terminal;
			if (terminal.m_isWardenObjective)
			{
				return true;
			}
			if (LG_ComputerTerminalManager.OngoingUplinkConnectionTerminalId != 0 && LG_ComputerTerminalManager.OngoingUplinkConnectionTerminalId != terminal.SyncID)
			{
				__instance.AddOngoingUplinkOutput();
				return false;
			}
			(eDimensionIndex, LG_LayerType, eLocalZoneIndex) globalZoneIndex = TerminalInstanceManager.Current.GetGlobalZoneIndex(__instance.m_terminal);
			uint zoneInstanceIndex = TerminalInstanceManager.Current.GetZoneInstanceIndex(terminal);
			UplinkDefinition definition = UplinkObjectiveManager.Current.GetDefinition(globalZoneIndex, zoneInstanceIndex);
			if (!definition.UseUplinkAddress)
			{
				param1 = __instance.m_terminal.UplinkPuzzle.TerminalUplinkIP;
			}
			if (!definition.UseUplinkAddress || param1 == __instance.m_terminal.UplinkPuzzle.TerminalUplinkIP)
			{
				__instance.m_terminal.TrySyncSetCommandRule((TERM_Command)25, (TERM_CommandRule)1);
				if ((Object)(object)__instance.m_terminal.ChainedPuzzleForWardenObjective != (Object)null)
				{
					ChainedPuzzleInstance chainedPuzzleForWardenObjective = __instance.m_terminal.ChainedPuzzleForWardenObjective;
					chainedPuzzleForWardenObjective.OnPuzzleSolved += Action.op_Implicit((Action)delegate
					{
						__instance.StartTerminalUplinkSequence(param1, false);
					});
					__instance.AddOutput("", true);
					__instance.AddOutput(Text.Get(3268596368u), true);
					__instance.AddOutput(Text.Get(3041541194u), true);
					if (SNet.IsMaster)
					{
						__instance.m_terminal.ChainedPuzzleForWardenObjective.AttemptInteract((eChainedPuzzleInteraction)0);
					}
				}
				else
				{
					__instance.StartTerminalUplinkSequence(param1, false);
				}
				__result = true;
			}
			else
			{
				__instance.AddUplinkWrongAddressError(param1);
				__result = false;
			}
			return false;
		}
	}
	[HarmonyPatch]
	internal static class TerminalUplinkSequenceOutput
	{
		[HarmonyPrefix]
		[HarmonyPatch(typeof(LG_ComputerTerminalCommandInterpreter), "TerminalUplinkSequenceOutputs")]
		private static bool Pre_LG_ComputerTerminalCommandInterpreter_TerminalUplinkSequenceOutputs(LG_ComputerTerminal terminal, bool corrupted)
		{
			if (terminal.m_isWardenObjective)
			{
				return true;
			}
			(eDimensionIndex, LG_LayerType, eLocalZoneIndex) globalZoneIndex = TerminalInstanceManager.Current.GetGlobalZoneIndex(terminal);
			uint zoneInstanceIndex = TerminalInstanceManager.Current.GetZoneInstanceIndex(terminal);
			UplinkDefinition definition = UplinkObjectiveManager.Current.GetDefinition(globalZoneIndex, zoneInstanceIndex);
			if (definition == null)
			{
				if (!((Object)(object)terminal.CorruptedUplinkReceiver != (Object)null))
				{
					return true;
				}
				LG_ComputerTerminal corruptedUplinkReceiver = terminal.CorruptedUplinkReceiver;
				globalZoneIndex = TerminalInstanceManager.Current.GetGlobalZoneIndex(corruptedUplinkReceiver);
				zoneInstanceIndex = TerminalInstanceManager.Current.GetZoneInstanceIndex(corruptedUplinkReceiver);
				definition = UplinkObjectiveManager.Current.GetDefinition(globalZoneIndex, zoneInstanceIndex);
				if (definition == null || definition.DisplayUplinkWarning)
				{
					return true;
				}
			}
			terminal.m_command.AddOutput((TerminalLineType)3, Text.Get(3418104670u), 3f, (TerminalSoundType)0, (TerminalSoundType)0);
			terminal.m_command.AddOutput("", true);
			if (!corrupted)
			{
				terminal.m_command.AddOutput(string.Format(Text.Get(947485599u), terminal.UplinkPuzzle.CurrentRound.CorrectPrefix), true);
			}
			return false;
		}
	}
	[HarmonyPatch]
	internal static class TerminalUplinkVerify
	{
		[HarmonyPrefix]
		[HarmonyPatch(typeof(LG_ComputerTerminalCommandInterpreter), "TerminalUplinkVerify")]
		private static bool Pre_LG_ComputerTerminalCommandInterpreter_TerminalUplinkVerify(LG_ComputerTerminalCommandInterpreter __instance, string param1, string param2, ref bool __result)
		{
			if (__instance.m_terminal.m_isWardenObjective)
			{
				return true;
			}
			TerminalUplinkPuzzle uplinkPuzzle = __instance.m_terminal.UplinkPuzzle;
			(eDimensionIndex, LG_LayerType, eLocalZoneIndex) globalZoneIndex = TerminalInstanceManager.Current.GetGlobalZoneIndex(__instance.m_terminal);
			uint zoneInstanceIndex = TerminalInstanceManager.Current.GetZoneInstanceIndex(__instance.m_terminal);
			UplinkDefinition definition = UplinkObjectiveManager.Current.GetDefinition(globalZoneIndex, zoneInstanceIndex);
			int CurrentRoundIndex = uplinkPuzzle.m_roundIndex;
			int num = definition.RoundOverrides.FindIndex((UplinkRound o) => o.RoundIndex == CurrentRoundIndex);
			UplinkRound roundOverride = ((num != -1) ? definition.RoundOverrides[num] : null);
			TimeSettings timeSettings = ((num != -1) ? roundOverride.OverrideTimeSettings : definition.DefaultTimeSettings);
			float num2 = ((timeSettings.TimeToStartVerify >= 0f) ? timeSettings.TimeToStartVerify : definition.DefaultTimeSettings.TimeToStartVerify);
			float timeToCompleteVerify = ((timeSettings.TimeToCompleteVerify >= 0f) ? timeSettings.TimeToCompleteVerify : definition.DefaultTimeSettings.TimeToCompleteVerify);
			float num3 = ((timeSettings.TimeToRestoreFromFail >= 0f) ? timeSettings.TimeToRestoreFromFail : definition.DefaultTimeSettings.TimeToRestoreFromFail);
			if (uplinkPuzzle.Connected)
			{
				__instance.AddOutput((TerminalLineType)3, Text.Get(2734004688u), num2, (TerminalSoundType)0, (TerminalSoundType)0);
				if (!uplinkPuzzle.Solved && uplinkPuzzle.CurrentRound.CorrectCode.ToUpper() == param1.ToUpper())
				{
					__instance.AddOutput(string.Format(Text.Get(1221800228u), uplinkPuzzle.CurrentProgress), true);
					if (uplinkPuzzle.TryGoToNextRound())
					{
						int newRoundIndex = uplinkPuzzle.m_roundIndex;
						int num4 = definition.RoundOverrides.FindIndex((UplinkRound o) => o.RoundIndex == newRoundIndex);
						UplinkRound newRoundOverride = ((num4 != -1) ? definition.RoundOverrides[num4] : null);
						roundOverride?.EventsOnRound.ForEach(delegate(WardenObjectiveEventData e)
						{
							WardenObjectiveManager.CheckAndExecuteEventsOnTrigger(e, (eWardenObjectiveEventTrigger)2, false, 0f);
						});
						if (roundOverride != null && (Object)(object)roundOverride.ChainedPuzzleToEndRoundInstance != (Object)null)
						{
							TextDataBlock block = GameDataBlockBase<TextDataBlock>.GetBlock("InGame.UplinkTerminal.ScanRequiredToProgress");
							if (block != null)
							{
								__instance.AddOutput((TerminalLineType)4, Text.Get(((GameDataBlockBase<TextDataBlock>)(object)block).persistentID), 0f, (TerminalSoundType)0, (TerminalSoundType)0);
							}
							ChainedPuzzleInstance chainedPuzzleToEndRoundInstance = roundOverride.ChainedPuzzleToEndRoundInstance;
							chainedPuzzleToEndRoundInstance.OnPuzzleSolved += Action.op_Implicit((Action)delegate
							{
								__instance.AddOutput((TerminalLineType)4, Text.Get(27959760u), timeToCompleteVerify, (TerminalSoundType)0, (TerminalSoundType)0);
								__instance.AddOutput("", true);
								__instance.AddOutput(string.Format(Text.Get(4269617288u), uplinkPuzzle.CurrentProgress, uplinkPuzzle.CurrentRound.CorrectPrefix), true);
								__instance.OnEndOfQueue = Action.op_Implicit((Action)delegate
								{
									EOSLogger.Log("UPLINK VERIFICATION GO TO NEXT ROUND!");
									uplinkPuzzle.CurrentRound.ShowGui = true;
									newRoundOverride?.EventsOnRound.ForEach(delegate(WardenObjectiveEventData e)
									{
										WardenObjectiveManager.CheckAndExecuteEventsOnTrigger(e, (eWardenObjectiveEventTrigger)1, false, 0f);
									});
									UplinkObjectiveManager.Current.ChangeState(__instance.m_terminal, new UplinkState
									{
										Status = UplinkStatus.InProgress,
										CurrentRoundIndex = uplinkPuzzle.m_roundIndex
									});
								});
							});
							if (SNet.IsMaster)
							{
								roundOverride.ChainedPuzzleToEndRoundInstance.AttemptInteract((eChainedPuzzleInteraction)0);
							}
						}
						else
						{
							__instance.AddOutput((TerminalLineType)4, Text.Get(27959760u), timeToCompleteVerify, (TerminalSoundType)0, (TerminalSoundType)0);
							__instance.AddOutput("", true);
							__instance.AddOutput(string.Format(Text.Get(4269617288u), uplinkPuzzle.CurrentProgress, uplinkPuzzle.CurrentRound.CorrectPrefix), true);
							__instance.OnEndOfQueue = Action.op_Implicit((Action)delegate
							{
								EOSLogger.Log("UPLINK VERIFICATION GO TO NEXT ROUND!");
								uplinkPuzzle.CurrentRound.ShowGui = true;
								newRoundOverride?.EventsOnRound.ForEach(delegate(WardenObjectiveEventData e)
								{
									WardenObjectiveManager.CheckAndExecuteEventsOnTrigger(e, (eWardenObjectiveEventTrigger)1, false, 0f);
								});
								UplinkObjectiveManager.Current.ChangeState(__instance.m_terminal, new UplinkState
								{
									Status = UplinkStatus.InProgress,
									CurrentRoundIndex = uplinkPuzzle.m_roundIndex
								});
							});
						}
					}
					else
					{
						__instance.AddOutput((TerminalLineType)3, Text.Get(1780488547u), 3f, (TerminalSoundType)0, (TerminalSoundType)0);
						__instance.AddOutput("", true);
						__instance.OnEndOfQueue = Action.op_Implicit((Action)delegate
						{
							roundOverride?.EventsOnRound.ForEach(delegate(WardenObjectiveEventData e)
							{
								WardenObjectiveManager.CheckAndExecuteEventsOnTrigger(e, (eWardenObjectiveEventTrigger)2, false, 0f);
							});
							uplinkPuzzle.CurrentRound.ShowGui = false;
							if (roundOverride != null && (Object)(object)roundOverride.ChainedPuzzleToEndRoundInstance != (Object)null)
							{
								ChainedPuzzleInstance chainedPuzzleToEndRoundInstance2 = roundOverride.ChainedPuzzleToEndRoundInstance;
								chainedPuzzleToEndRoundInstance2.OnPuzzleSolved += Action.op_Implicit((Action)delegate
								{
									__instance.AddOutput((TerminalLineType)0, string.Format(Text.Get(3928683780u), uplinkPuzzle.TerminalUplinkIP), 2f, (TerminalSoundType)0, (TerminalSoundType)0);
									__instance.AddOutput("", true);
									__instance.OnEndOfQueue = Action.op_Implicit((Action)delegate
									{
										EOSLogger.Error("UPLINK VERIFICATION SEQUENCE DONE!");
										LG_ComputerTerminalManager.OngoingUplinkConnectionTerminalId = 0u;
										uplinkPuzzle.Solved = true;
										Action onPuzzleSolved2 = uplinkPuzzle.OnPuzzleSolved;
										if (onPuzzleSolved2 != null)
										{
											onPuzzleSolved2.Invoke();
										}
										UplinkObjectiveManager.Current.ChangeState(__instance.m_terminal, new UplinkState
										{
											Status = UplinkStatus.Finished,
											CurrentRoundIndex = uplinkPuzzle.m_roundIndex
										});
									});
								});
								if (SNet.IsMaster)
								{
									roundOverride.ChainedPuzzleToEndRoundInstance.AttemptInteract((eChainedPuzzleInteraction)0);
								}
							}
							else
							{
								__instance.AddOutput((TerminalLineType)0, string.Format(Text.Get(3928683780u), uplinkPuzzle.TerminalUplinkIP), 2f, (TerminalSoundType)0, (TerminalSoundType)0);
								__instance.AddOutput("", true);
								EOSLogger.Error("UPLINK VERIFICATION SEQUENCE DONE!");
								LG_ComputerTerminalManager.OngoingUplinkConnectionTerminalId = 0u;
								uplinkPuzzle.Solved = true;
								Action onPuzzleSolved = uplinkPuzzle.OnPuzzleSolved;
								if (onPuzzleSolved != null)
								{
									onPuzzleSolved.Invoke();
								}
								UplinkObjectiveManager.Current.ChangeState(__instance.m_terminal, new UplinkState
								{
									Status = UplinkStatus.Finished,
									CurrentRoundIndex = uplinkPuzzle.m_roundIndex
								});
							}
						});
					}
				}
				else if (uplinkPuzzle.Solved)
				{
					__instance.AddOutput("", true);
					__instance.AddOutput((TerminalLineType)1, Text.Get(4080876165u), 0f, (TerminalSoundType)0, (TerminalSoundType)0);
					__instance.AddOutput((TerminalLineType)0, Text.Get(4104839742u), 6f, (TerminalSoundType)0, (TerminalSoundType)0);
				}
				else
				{
					__instance.AddOutput("", true);
					__instance.AddOutput((TerminalLineType)1, string.Format(Text.Get(507647514u), uplinkPuzzle.CurrentRound.CorrectPrefix), 0f, (TerminalSoundType)0, (TerminalSoundType)0);
					__instance.AddOutput((TerminalLineType)0, Text.Get(4104839742u), num3, (TerminalSoundType)0, (TerminalSoundType)0);
				}
			}
			else
			{
				__instance.AddOutput("", true);
				__instance.AddOutput(Text.Get(403360908u), true);
			}
			__result = false;
			return false;
		}
	}
	[HarmonyPatch]
	internal static class UplinkGUI_Update
	{
		[HarmonyPostfix]
		[HarmonyPatch(typeof(LG_ComputerTerminal), "Update")]
		private static void Post_LG_ComputerTerminal_Update(LG_ComputerTerminal __instance)
		{
			if (!__instance.m_isWardenObjective && __instance.UplinkPuzzle != null)
			{
				__instance.UplinkPuzzle.UpdateGUI(false);
			}
		}
	}
}
namespace ExtraObjectiveSetup.Patches.PowerGenerator
{
	[HarmonyPatch]
	internal static class Patch_LG_PowerGeneratorCluster
	{
		[HarmonyPostfix]
		[HarmonyPatch(typeof(LG_PowerGeneratorCluster), "Setup")]
		private static void Post_PowerGeneratorCluster_Setup(LG_PowerGeneratorCluster __instance)
		{
			uint instanceIndex = GeneratorClusterInstanceManager.Current.Register(__instance);
			(eDimensionIndex, LG_LayerType, eLocalZoneIndex) globalZoneIndex = GeneratorClusterInstanceManager.Current.GetGlobalZoneIndex(__instance);
			GeneratorClusterDefinition definition = GeneratorClusterObjectiveManager.Current.GetDefinition(globalZoneIndex, instanceIndex);
			if (definition == null)
			{
				return;
			}
			EOSLogger.Debug("Found LG_PowerGeneratorCluster and its definition! Building this Generator cluster...");
			__instance.m_serialNumber = SerialGenerator.GetUniqueSerialNo();
			__instance.m_itemKey = "GENERATOR_CLUSTER_" + __instance.m_serialNumber;
			__instance.m_terminalItem = GOUtil.GetInterfaceFromComp<iTerminalItem>(__instance.m_terminalItemComp);
			__instance.m_terminalItem.Setup(__instance.m_itemKey, (AIG_CourseNode)null);
			__instance.m_terminalItem.FloorItemStatus = (eFloorInventoryObjectStatus)4;
			if (__instance.SpawnNode != null)
			{
				__instance.m_terminalItem.FloorItemLocation = __instance.SpawnNode.m_zone.NavInfo.GetFormattedText((LG_NavInfoFormat)7);
			}
			List<Transform> list = new List<Transform>((IEnumerable<Transform>)__instance.m_generatorAligns);
			uint numberOfGenerators = definition.NumberOfGenerators;
			__instance.m_generators = Il2CppReferenceArray<LG_PowerGenerator_Core>.op_Implicit((LG_PowerGenerator_Core[])(object)new LG_PowerGenerator_Core[numberOfGenerators]);
			if (list.Count >= numberOfGenerators)
			{
				for (int i = 0; i < numberOfGenerators; i++)
				{
					int index = Builder.BuildSeedRandom.Range(0, list.Count, "NO_TAG");
					LG_PowerGenerator_Core val = GOUtil.SpawnChildAndGetComp<LG_PowerGenerator_Core>(__instance.m_generatorPrefab, list[index]);
					((Il2CppArrayBase<LG_PowerGenerator_Core>)(object)__instance.m_generators)[i] = val;
					val.SpawnNode = __instance.SpawnNode;
					PowerGeneratorInstanceManager.Current.MarkAsGCGenerator(__instance, val);
					val.Setup();
					val.SetCanTakePowerCell(true);
					Debug.Log(Object.op_Implicit("Spawning generator at alignIndex: " + index));
					list.RemoveAt(index);
				}
			}
			else
			{
				Debug.LogError(Object.op_Implicit("LG_PowerGeneratorCluster does NOT have enough generator aligns to support the warden objective! Has " + list.Count + " needs " + numberOfGenerators));
			}
			__instance.ObjectiveItemSolved = true;
			if (definition.EndSequenceChainedPuzzle != 0)
			{
				GeneratorClusterObjectiveManager.Current.RegisterForChainedPuzzleBuild(__instance, definition);
			}
		}
	}
	[HarmonyPatch]
	internal static class Patch_LG_PowerGenerator_Core_SyncStatusChanged
	{
		[HarmonyPostfix]
		[HarmonyPatch(typeof(LG_PowerGenerator_Core), "SyncStatusChanged")]
		private static void Post_SyncStatusChanged(LG_PowerGenerator_Core __instance, pPowerGeneratorState state, bool isDropinState)
		{
			//IL_0058: Unknown result type (might be due to invalid IL or missing references)
			//IL_0059: Unknown result type (might be due to invalid IL or missing references)
			//IL_005e: Unknown result type (might be due to invalid IL or missing references)
			//IL_007e: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a5: Unknown result type (might be due to invalid IL or missing references)
			//IL_026f: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cb: Unknown result type (might be due to invalid IL or missing references)
			//IL_02d4: Unknown result type (might be due to invalid IL or missing references)
			//IL_02d9: Unknown result type (might be due to invalid IL or missing references)
			uint zoneInstanceIndex = PowerGeneratorInstanceManager.Current.GetZoneInstanceIndex(__instance);
			(eDimensionIndex, LG_LayerType, eLocalZoneIndex) globalZoneIndex = PowerGeneratorInstanceManager.Current.GetGlobalZoneIndex(__instance);
			LG_PowerGeneratorCluster parentGeneratorCluster = PowerGeneratorInstanceManager.Current.GetParentGeneratorCluster(__instance);
			GeneratorClusterDefinition generatorClusterDefinition = null;
			if ((Object)(object)parentGeneratorCluster != (Object)null)
			{
				uint zoneInstanceIndex2 = GeneratorClusterInstanceManager.Current.GetZoneInstanceIndex(parentGeneratorCluster);
				(eDimensionIndex, LG_LayerType, eLocalZoneIndex) globalZoneIndex2 = GeneratorClusterInstanceManager.Current.GetGlobalZoneIndex(parentGeneratorCluster);
				generatorClusterDefinition = GeneratorClusterObjectiveManager.Current.GetDefinition(globalZoneIndex2, zoneInstanceIndex2);
			}
			ePowerGeneratorStatus status = state.status;
			if (generatorClusterDefinition != null)
			{
				EOSLogger.Log($"LG_PowerGeneratorCluster.powerGenerator.OnSyncStatusChanged! status: {status}, isDropinState: {isDropinState}");
				if ((int)status == 0)
				{
					uint num = 0u;
					for (int i = 0; i < ((Il2CppArrayBase<LG_PowerGenerator_Core>)(object)parentGeneratorCluster.m_generators).Length; i++)
					{
						if ((int)((Il2CppArrayBase<LG_PowerGenerator_Core>)(object)parentGeneratorCluster.m_generators)[i].m_stateReplicator.State.status == 0)
						{
							num++;
						}
					}
					EOSLogger.Log($"Generator Cluster PowerCell inserted ({num} / {((Il2CppArrayBase<LG_PowerGenerator_Core>)(object)parentGeneratorCluster.m_generators).Count})");
					List<List<WardenObjectiveEventData>> eventsOnInsertCell = generatorClusterDefinition.EventsOnInsertCell;
					int num2 = (int)(num - 1);
					if (!isDropinState)
					{
						if (num2 >= 0 && num2 < eventsOnInsertCell.Count)
						{
							EOSLogger.Log($"Executing events ({num} / {((Il2CppArrayBase<LG_PowerGenerator_Core>)(object)parentGeneratorCluster.m_generators).Count}). Event count: {eventsOnInsertCell[num2].Count}");
							eventsOnInsertCell[num2].ForEach(delegate(WardenObjectiveEventData e)
							{
								WardenObjectiveManager.CheckAndExecuteEventsOnTrigger(e, (eWardenObjectiveEventTrigger)0, true, 0f);
							});
						}
						if (num == ((Il2CppArrayBase<LG_PowerGenerator_Core>)(object)parentGeneratorCluster.m_generators).Count && !parentGeneratorCluster.m_endSequenceTriggered)
						{
							EOSLogger.Log("All generators powered, executing end sequence");
							((MonoBehaviour)__instance).StartCoroutine(parentGeneratorCluster.ObjectiveEndSequence());
							parentGeneratorCluster.m_endSequenceTriggered = true;
						}
					}
					else if (num != ((Il2CppArrayBase<LG_PowerGenerator_Core>)(object)parentGeneratorCluster.m_generators).Count)
					{
						parentGeneratorCluster.m_endSequenceTriggered = false;
					}
				}
			}
			IndividualGeneratorDefinition definition = IndividualGeneratorObjectiveManager.Current.GetDefinition(globalZoneIndex, zoneInstanceIndex);
			if (definition != null && definition.EventsOnInsertCell != null && (int)status == 0 && !isDropinState)
			{
				definition.EventsOnInsertCell.ForEach(delegate(WardenObjectiveEventData e)
				{
					WardenObjectiveManager.CheckAndExecuteEventsOnTrigger(e, (eWardenObjectiveEventTrigger)0, true, 0f);
				});
			}
			ExpeditionIGGroup expeditionIGGroup = ExpeditionIGGroupManager.Current.FindGroupDefOf(__instance);
			if (expeditionIGGroup == null)
			{
				return;
			}
			int num3 = 0;
			foreach (LG_PowerGenerator_Core generatorInstance in expeditionIGGroup.GeneratorInstances)
			{
				if ((int)generatorInstance.m_stateReplicator.State.status == 0)
				{
					num3++;
				}
			}
			if (isDropinState)
			{
				return;
			}
			if (num3 == expeditionIGGroup.GeneratorInstances.Count && expeditionIGGroup.PlayEndSequenceOnGroupComplete)
			{
				Coroutine val = CoroutineManager.StartCoroutine(CollectionExtensions.WrapToIl2Cpp(ExpeditionIGGroupManager.PlayGroupEndSequence(expeditionIGGroup)), (Action)null);
				WorldEventManager.m_worldEventEventCoroutines.Add(val);
				return;
			}
			int num4 = num3 - 1;
			if (num4 >= 0 && num4 < expeditionIGGroup.EventsOnInsertCell.Count)
			{
				expeditionIGGroup.EventsOnInsertCell[num4].ForEach(delegate(WardenObjectiveEventData e)
				{
					WardenObjectiveManager.CheckAndExecuteEventsOnTrigger(e, (eWardenObjectiveEventTrigger)0, true, 0f);
				});
			}
		}
	}
	[HarmonyPatch]
	internal static class Patch_LG_PowerGenerator_Core_Setup
	{
		[HarmonyPostfix]
		[HarmonyPatch(typeof(LG_PowerGenerator_Core), "Setup")]
		private static void Post_PowerGenerator_Setup(LG_PowerGenerator_Core __instance)
		{
			//IL_0085: 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_0092: 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_0099: 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_00b2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d8: Unknown result type (might be due to invalid IL or missing references)
			iCarryItemInteractionTarget powerCellInteraction = __instance.m_powerCellInteraction;
			powerCellInteraction.AttemptCarryItemInsert += Action<SNet_Player, Item>.op_Implicit((Action<SNet_Player, Item>)delegate(SNet_Player p, Item item)
			{
				//IL_0001: Unknown result type (might be due to invalid IL or missing references)
				Item val2 = default(Item);
				if (PlayerBackpackManager.TryGetItemInLevelFromItemData(item.Get_pItemData(), ref val2))
				{
					((Il2CppObjectBase)val2).Cast<ItemInLevel>().CanWarp = false;
				}
				else
				{
					EOSLogger.Error($"Inserting sth other than PowerCell ({item.PublicName}) into {__instance.m_itemKey}, how?");
				}
			});
			if (PowerGeneratorInstanceManager.Current.IsGCGenerator(__instance))
			{
				return;
			}
			uint num = PowerGeneratorInstanceManager.Current.Register(__instance);
			(eDimensionIndex, LG_LayerType, eLocalZoneIndex) globalZoneIndex = PowerGeneratorInstanceManager.Current.GetGlobalZoneIndex(__instance);
			IndividualGeneratorDefinition definition = IndividualGeneratorObjectiveManager.Current.GetDefinition(globalZoneIndex, num);
			if (definition != null)
			{
				Vector3 val = definition.Position.ToVector3();
				Quaternion rotation = definition.Rotation.ToQuaternion();
				if (val != Vector3.zero)
				{
					((Component)__instance).transform.position = val;
					((Component)__instance).transform.rotation = rotation;
					__instance.m_sound.UpdatePosition(val);
					EOSLogger.Debug("LG_PowerGenerator_Core: modified position / rotation");
				}
				if (definition.ForceAllowPowerCellInsertion)
				{
					__instance.SetCanTakePowerCell(true);
				}
				EOSLogger.Debug($"LG_PowerGenerator_Core: overriden, instance {num} in {globalZoneIndex}");
			}
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(LG_PowerGenerator_Core), "SyncStatusChanged")]
		private static void Post_SyncStatusChanged(LG_PowerGenerator_Core __instance, pPowerGeneratorState state, bool isDropinState)
		{
			//IL_0030: Unknown result type (might be due to invalid IL or missing references)
			//IL_0031: Unknown result type (might be due to invalid IL or missing references)
			//IL_0037: Invalid comparison between Unknown and I4
			uint zoneInstanceIndex = PowerGeneratorInstanceManager.Current.GetZoneInstanceIndex(__instance);
			(eDimensionIndex, LG_LayerType, eLocalZoneIndex) globalZoneIndex = PowerGeneratorInstanceManager.Current.GetGlobalZoneIndex(__instance);
			IndividualGeneratorDefinition definition = IndividualGeneratorObjectiveManager.Current.GetDefinition(globalZoneIndex, zoneInstanceIndex);
			if (!(definition == null || definition.EventsOnInsertCell == null || (int)state.status > 0 || isDropinState) && definition.EventsOnInsertCell.Count > 0)
			{
				definition.EventsOnInsertCell.ForEach(delegate(WardenObjectiveEventData e)
				{
					WardenObjectiveManager.CheckAndExecuteEventsOnTrigger(e, (eWardenObjectiveEventTrigger)0, true, 0f);
				});
			}
		}
	}
}
namespace ExtraObjectiveSetup.Patches.Terminal
{
	[HarmonyPatch]
	internal static class Patch_FixHiddenCommandExecution
	{
		[HarmonyPrefix]
		[HarmonyPatch(typeof(LG_ComputerTerminalCommandInterpreter), "ReceiveCommand")]
		private static void Pre_TerminalInterpreter_ReceiveCommand(LG_ComputerTerminalCommandInterpreter __instance, ref TERM_Command cmd)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0003: Unknown result type (might be due to invalid IL or missing references)
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b7: Expected I4, but got Unknown
			TERM_Command val = cmd;
			switch (val - 1)
			{
			case 0:
			case 1:
			case 2:
			case 3:
			case 11:
			case 13:
			case 14:
			case 17:
			case 18:
			case 19:
			case 20:
			case 21:
			case 22:
			case 23:
			case 24:
			case 25:
			case 26:
			case 27:
			case 28:
			case 31:
			case 32:
			case 33:
			case 42:
				if (__instance.m_terminal.CommandIsHidden(cmd))
				{
					cmd = (TERM_Command)10;
				}
				break;
			case 4:
			case 5:
			case 6:
			case 7:
			case 8:
			case 9:
			case 10:
			case 12:
			case 15:
			case 16:
			case 29:
			case 30:
			case 34:
			case 35:
			case 36:
			case 37:
			case 38:
			case 39:
			case 40:
			case 41:
				break;
			}
		}
	}
	[HarmonyPatch]
	internal static class Patch_FixRepeatablePuzzleBugs
	{
		[HarmonyPrefix]
		[HarmonyPatch(typeof(CP_Cluster_Core), "OnSyncStateChange")]
		private static bool Pre_CheckEventsOnPuzzleSolved(CP_Cluster_Core __instance, eClusterStatus newStatus, bool isDropinState)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_000b: Unknown result type (might be due to invalid IL or missing references)
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0011: Invalid comparison between Unknown and I4
			//IL_004b: 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_0052: Invalid comparison between Unknown and I4
			//IL_0054: Unknown result type (might be due to invalid IL or missing references)
			//IL_0056: Invalid comparison between Unknown and I4
			pClusterState currentState = __instance.m_sync.GetCurrentState();
			if (isDropinState && (int)newStatus == 3)
			{
				__instance.m_spline.SetVisible(false);
				for (int i = 0; i < ((Il2CppArrayBase<iChainedPuzzleCore>)(object)__instance.m_childCores).Length; i++)
				{
					((Il2CppArrayBase<iChainedPuzzleCore>)(object)__instance.m_childCores)[i].Deactivate();
				}
				return false;
			}
			if (!isDropinState && (int)currentState.status == 3 && (int)newStatus == 1)
			{
				__instance.m_spline.Reveal(0f);
				return false;
			}
			return true;
		}
	}
	[HarmonyPatch]
	internal static class Patch_LG_ComputerTerminal_Setup
	{
		[HarmonyPostfix]
		[HarmonyPatch(typeof(LG_ComputerTerminal), "Setup")]
		private static void Post_LG_ComputerTerminal_Setup(LG_ComputerTerminal __instance)
		{
			//IL_0043: Unknown result type (might be due to invalid IL or missing references)
			//IL_0048: Unknown result type (might be due to invalid IL or missing references)
			//IL_0099: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cb: Unknown result type (might be due to invalid IL or missing references)
			//IL_0060: 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)
			uint instanceIndex = TerminalInstanceManager.Current.Register(__instance);
			TerminalInstanceManager.Current.SetupTerminalWrapper(__instance);
			if (__instance.SpawnNode == null)
			{
				return;
			}
			(eDimensionIndex, LG_LayerType, eLocalZoneIndex) globalZoneIndex = TerminalInstanceManager.Current.GetGlobalZoneIndex(__instance);
			TerminalPosition definition = TerminalPositionOverrideManager.Current.GetDefinition(globalZoneIndex, instanceIndex);
			if (definition != null)
			{
				if (definition.Position.ToVector3() != Vector3.zeroVector)
				{
					((Component)__instance).transform.position = definition.Position.ToVector3();
					((Component)__instance).transform.rotation = definition.Rotation.ToQuaternion();
				}
				EOSLogger.Debug($"TerminalPositionOverride: {definition.LocalIndex}, {definition.LayerType}, {definition.DimensionIndex}, TerminalIndex {definition.InstanceIndex}");
			}
		}
	}
	[HarmonyPatch]
	internal static class Patch_RepeatableCommandEventFix
	{
		[HarmonyPostfix]
		[HarmonyPatch(typeof(LG_ComputerTerminalCommandInterpreter), "SetupCommandEvents")]
		private static void Post_ResetRepeatableUniqueCommandChainedPuzzle(LG_ComputerTerminalCommandInterpreter __instance)
		{
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			//IL_001e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0025: Unknown result type (might be due to invalid IL or missing references)
			//IL_0036: Unknown result type (might be due to invalid IL or missing references)
			//IL_0043: Unknown result type (might be due to invalid IL or missing references)
			//IL_0044: Unknown result type (might be due to invalid IL or missing references)
			//IL_007d: Unknown result type (might be due to invalid IL or missing references)
			LG_ComputerTerminal terminal = __instance.m_terminal;
			ChainedPuzzleInstance val = default(ChainedPuzzleInstance);
			foreach (TERM_Command uNIQUE_CMD in TerminalInstanceManager.UNIQUE_CMDS)
			{
				if (!__instance.m_commandsPerEnum.ContainsKey(uNIQUE_CMD))
				{
					continue;
				}
				string text = __instance.m_commandsPerEnum[uNIQUE_CMD];
				if ((int)__instance.m_terminal.GetCommandRule(uNIQUE_CMD) != 0)
				{
					continue;
				}
				List<WardenObjectiveEventData> uniqueCommandEvents = __instance.m_terminal.GetUniqueCommandEvents(text);
				for (int i = 0; i < uniqueCommandEvents.Count; i++)
				{
					if (uniqueCommandEvents[i].ChainPuzzle != 0)
					{
						if (__instance.m_terminal.TryGetChainPuzzleForCommand(uNIQUE_CMD, i, ref val) && (Object)(object)val != (Object)null)
						{
							ChainedPuzzleInstance obj = val;
							obj.OnPuzzleSolved += Action.op_Implicit((Action)val.ResetProgress);
						}
						EOSLogger.Debug($"TerminalTweak: {terminal.ItemKey}, command {text} set to be repeatable!");
					}
				}
			}
		}
	}
}
namespace ExtraObjectiveSetup.Patches.LGFactory
{
	[HarmonyPatch]
	internal class Patch_LG_Factory_NextBatch
	{
		[HarmonyPostfix]
		[HarmonyPatch(typeof(LG_Factory), "NextBatch")]
		private static void Post_LG_Factory_NextBatch(LG_Factory __instance)
		{
			//IL_001a: Unknown result type (might be due to invalid IL or missing references)
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0025: 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)
			int num = __instance.m_batchStep - 1;
			if (num >= 0)
			{
				BatchName batchName = ((Il2CppArrayBase<LG_FactoryBatch>)(object)__instance.m_batches)[num].m_batchName;
				Action action = BatchBuildManager.Current.Get_OnBatchDone(batchName);
				if (action != null)
				{
					EOSLogger.Warning($"On Batch '{batchName}' Done: {action.GetInvocationList().Length} injected jobs");
					action();
				}
			}
		}
	}
}
namespace ExtraObjectiveSetup.Patches.HSUActivator
{
	[HarmonyPatch]
	internal class SetupFromCustomGeomorph
	{
		[HarmonyPostfix]
		[HarmonyPatch(typeof(LG_HSUActivator_Core), "SetupFromCustomGeomorph")]
		private static void Post_LG_HSUActivator_Core_SetupFromCustomGeomorph(LG_HSUActivator_Core __instance)
		{
			//IL_0033: Unknown result type (might be due to invalid IL or missing references)
			//IL_0043: Unknown result type (might be due to invalid IL or missing references)
			//IL_0058: Unknown result type (might be due to invalid IL or missing references)
			//IL_00aa: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cd: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f5: Unknown result type (might be due to invalid IL or missing references)
			//IL_0239: Unknown result type (might be due to invalid IL or missing references)
			//IL_023f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0245: Unknown result type (might be due to invalid IL or missing references)
			uint instanceIndex = HSUActivatorInstanceManager.Current.Register(__instance);
			HSUActivatorDefinition definition = HSUActivatorObjectiveManager.Current.GetDefinition(__instance.SpawnNode.m_dimension.DimensionIndex, __instance.SpawnNode.LayerType, __instance.SpawnNode.m_zone.LocalIndex, instanceIndex);
			if (definition == null)
			{
				return;
			}
			if (__instance.m_isWardenObjective)
			{
				EOSLogger.Error("BuildCustomHSUActivator: the HSUActivator has been set up by vanilla! Aborting custom setup...");
				EOSLogger.Error($"HSUActivator in {__instance.SpawnNode.m_zone.LocalIndex}, {__instance.SpawnNode.LayerType}, {__instance.SpawnNode.m_dimension.DimensionIndex}");
				return;
			}
			__instance.m_linkedItemGoingIn = __instance.SpawnPickupItemOnAlign(definition.ItemFromStart, __instance.m_itemGoingInAlign, false, -1);
			__instance.m_linkedItemComingOut = __instance.SpawnPickupItemOnAlign(definition.ItemAfterActivation, __instance.m_itemComingOutAlign, false, -1);
			LG_LevelInteractionManager.DeregisterTerminalItem(((Component)__instance.m_linkedItemGoingIn).GetComponentInChildren<iTerminalItem>());
			LG_LevelInteractionManager.DeregisterTerminalItem(((Component)__instance.m_linkedItemComingOut).GetComponentInChildren<iTerminalItem>());
			__instance.m_linkedItemGoingIn.SetPickupInteractionEnabled(false);
			__instance.m_linkedItemComingOut.SetPickupInteractionEnabled(false);
			__instance.m_insertHSUInteraction.OnInteractionSelected = Action<PlayerAgent>.op_Implicit((Action<PlayerAgent>)delegate
			{
			});
			__instance.m_sequencerInsertItem.OnSequenceDone = Action.op_Implicit((Action)delegate
			{
				//IL_000b: Unknown result type (might be due to invalid IL or missing references)
				//IL_0010: Unknown result type (might be due to invalid IL or missing references)
				//IL_0011: Unknown result type (might be due to invalid IL or missing references)
				//IL_0036: Unknown result type (might be due to invalid IL or missing references)
				pHSUActivatorState state2 = __instance.m_stateReplicator.State;
				if (!state2.isSequenceIncomplete)
				{
					EOSLogger.Log(">>>>>> HSUInsertSequenceDone! Sequence was already complete");
				}
				state2.isSequenceIncomplete = false;
				__instance.m_stateReplicator.SetStateUnsynced(state2);
				EOSLogger.Log(">>>>>> HSUInsertSequenceDone!");
				if (__instance.m_triggerExtractSequenceRoutine != null)
				{
					((MonoBehaviour)__instance).StopCoroutine(__instance.m_triggerExtractSequenceRoutine);
				}
			});
			__instance.m_sequencerExtractItem.OnSequenceDone = Action.op_Implicit((Action)delegate
			{
				//IL_0016: Unknown result type (might be due to invalid IL or missing references)
				//IL_001b: Unknown result type (might be due to invalid IL or missing references)
				//IL_0024: Unknown result type (might be due to invalid IL or missing references)
				//IL_0039: 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)
				SNet_StateReplicator<pHSUActivatorState, pHSUActivatorInteraction> stateReplicator = __instance.m_stateReplicator;
				pHSUActivatorState state = __instance.m_stateReplicator.State;
				state.isSequenceIncomplete = true;
				stateReplicator.SetStateUnsynced(state);
				if (SNet.IsMaster)
				{
					__instance.AttemptInteract(new pHSUActivatorInteraction
					{
						type = (eHSUActivatorInteractionType)2
					});
				}
			});
			EOSLogger.Debug($"HSUActivator: {(definition.DimensionIndex, definition.LayerType, definition.LocalIndex, definition.InstanceIndex)}, custom setup complete");
		}
	}
	[HarmonyPatch]
	internal class SyncStatusChanged
	{
		[HarmonyPrefix]
		[HarmonyPatch(typeof(LG_HSUActivator_Core), "SyncStatusChanged")]
		private static bool Pre_LG_HSUActivator_Core_SyncStatusChanged(LG_HSUActivator_Core __instance, pHSUActivatorState newState, bool isRecall)
		{
			//IL_0060: Unknown result type (might be due to invalid IL or missing references)
			//IL_006b: Unknown result type (might be due to invalid IL or missing references)
			//IL_007b: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cf: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ee: Expected I4, but got Unknown
			//IL_030b: Unknown result type (might be due to invalid IL or missing references)
			if (__instance.m_isWardenObjective)
			{
				return true;
			}
			uint zoneInstanceIndex = HSUActivatorInstanceManager.Current.GetZoneInstanceIndex(__instance);
			if (zoneInstanceIndex == uint.MaxValue)
			{
				EOSLogger.Error($"Found unregistered HSUActivator!! {HSUActivatorInstanceManager.Current.GetGlobalZoneIndex(__instance)}");
				return true;
			}
			HSUActivatorDefinition definition = HSUActivatorObjectiveManager.Current.GetDefinition(__instance.SpawnNode.m_dimension.DimensionIndex, __instance.SpawnNode.LayerType, __instance.SpawnNode.m_zone.LocalIndex, zoneInstanceIndex);
			if (definition == null)
			{
				return true;
			}
			if (__instance.m_triggerExtractSequenceRoutine != null)
			{
				((MonoBehaviour)__instance).StopCoroutine(__instance.m_triggerExtractSequenceRoutine);
			}
			bool goingInVisibleForPostCulling = __instance.m_goingInVisibleForPostCulling;
			bool comingOutVisibleForPostCulling = __instance.m_comingOutVisibleForPostCulling;
			EOSLogger.Debug("LG_HSUActivator_Core.OnSyncStatusChanged " + ((object)(eHSUActivatorStatus)(ref newState.status)).ToString());
			eHSUActivatorStatus status = newState.status;
			switch ((int)status)
			{
			case 0:
				__instance.m_insertHSUInteraction.SetActive(true);
				__instance.ResetItem(__instance.m_itemGoingInAlign, __instance.m_linkedItemGoingIn, false, false, true, ref goingInVisibleForPostCulling);
				__instance.ResetItem(__instance.m_itemComingOutAlign, __instance.m_linkedItemComingOut, false, false, true, ref comingOutVisibleForPostCulling);
				__instance.m_sequencerWaitingForItem.StartSequence();
				__instance.m_sequencerInsertItem.StopSequence();
				__instance.m_sequencerExtractItem.StopSequence();
				__instance.m_sequencerExtractionDone.StopSequence();
				break;
			case 1:
				__instance.m_insertHSUInteraction.SetActive(false);
				__instance.ResetItem(__instance.m_itemGoingInAlign, __instance.m_linkedItemGoingIn, true, false, true, ref goingInVisibleForPostCulling);
				__instance.ResetItem(__instance.m_itemComingOutAlign, __instance.m_linkedItemComingOut, false, false, true, ref comingOutVisibleForPostCulling);
				__instance.m_sequencerWaitingFor

plugins/TrickyBall's Paradise/Custom/PortalPuzzleChanger.dll

Decompiled 8 months ago
using System;
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 System.Text.Json;
using System.Text.Json.Serialization;
using AK;
using Agents;
using AssetShards;
using BepInEx;
using BepInEx.Logging;
using BepInEx.Unity.IL2CPP;
using ChainedPuzzles;
using Enemies;
using FX_EffectSystem;
using GTFO.API;
using GTFO.API.Components;
using GTFO.API.JSON.Converters;
using GTFO.API.Wrappers;
using GameData;
using Gear;
using HarmonyLib;
using Il2CppInterop.Runtime.Injection;
using Il2CppInterop.Runtime.InteropTypes.Arrays;
using Il2CppSystem;
using LevelGeneration;
using MTFO.Managers;
using Microsoft.CodeAnalysis;
using Player;
using PortalPuzzleChanger.ConfigFiles;
using PortalPuzzleChanger.GameScripts;
using PortalPuzzleChanger.Plugin;
using SNetwork;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: TargetFramework(".NETCoreApp,Version=v6.0", FrameworkDisplayName = ".NET 6.0")]
[assembly: AssemblyCompany("PortalPuzzleChanger")]
[assembly: AssemblyConfiguration("Debug")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0")]
[assembly: AssemblyProduct("PortalPuzzleChanger")]
[assembly: AssemblyTitle("PortalPuzzleChanger")]
[assembly: AssemblyVersion("1.0.0.0")]
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;
		}
	}
}
namespace PortalPuzzleChanger.Plugin
{
	[BepInPlugin("com.Breeze.PortalPuzzleChanger", "PortalPuzzleChanger", "0.0.1")]
	[BepInProcess("GTFO.exe")]
	internal class EntryPoint : BasePlugin
	{
		public static Dictionary<string, Sprite> CachedSprites;

		public static readonly JsonSerializerOptions SerializerOptions = new JsonSerializerOptions
		{
			ReadCommentHandling = JsonCommentHandling.Skip,
			PropertyNameCaseInsensitive = true,
			IncludeFields = true,
			AllowTrailingCommas = true,
			WriteIndented = true
		};

		public static ManualLogSource? LogSource { get; private set; }

		public static Harmony? m_Harmony { get; private set; }

		public override void Load()
		{
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			//IL_001c: Expected O, but got Unknown
			//IL_0032: Unknown result type (might be due to invalid IL or missing references)
			//IL_003c: Expected O, but got Unknown
			//IL_0047: Unknown result type (might be due to invalid IL or missing references)
			//IL_0051: Expected O, but got Unknown
			//IL_005c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0066: Expected O, but got Unknown
			//IL_0071: Unknown result type (might be due to invalid IL or missing references)
			//IL_007b: Expected O, but got Unknown
			LogSource = ((BasePlugin)this).Log;
			m_Harmony = new Harmony("_PortalPuzzleChanger_");
			m_Harmony.PatchAll();
			SerializerOptions.Converters.Add((JsonConverter)new LocalizedTextConverter());
			SerializerOptions.Converters.Add((JsonConverter)new Vector3Converter());
			SerializerOptions.Converters.Add((JsonConverter)new Vector2Converter());
			SerializerOptions.Converters.Add((JsonConverter)new ColorConverter());
			PortalPuzzleChangerSetup.Load();
			EnemyTagChangerConfigSetup.Load();
			GrenadeLauncherConfigSetup.Load();
			ClassInjector.RegisterTypeInIl2Cpp<GrenadeProjectile>();
			AssetAPI.OnAssetBundlesLoaded += OnAssetsLoaded;
		}

		public void OnAssetsLoaded()
		{
			//IL_0060: Unknown result type (might be due to invalid IL or missing references)
			//IL_006f: Unknown result type (might be due to invalid IL or missing references)
			List<EnemyTagChanger> list = EnemyTagChangerConfigSetup.EnabledConfigs.Values.ToList();
			for (int i = 0; i < list.Count; i++)
			{
				if (!string.IsNullOrEmpty(list[i].CustomImagePath))
				{
					Texture2D loadedAsset = AssetAPI.GetLoadedAsset<Texture2D>(list[i].CustomImagePath);
					Sprite val = Sprite.Create(loadedAsset, new Rect(0f, 0f, (float)((Texture)loadedAsset).width, (float)((Texture)loadedAsset).height), new Vector2(0.5f, 0.5f), 64f);
					((Object)val).hideFlags = (HideFlags)61;
					((Object)val).name = list[i].CustomImagePath;
					CachedSprites.Add(((Object)val).name, val);
					Debug("Created a sprite from path: " + list[i].CustomImagePath);
				}
			}
		}

		public static void Debug(string message)
		{
			LogSource.LogDebug((object)("[DEBUG] " + message));
		}

		public static void DebugWarning(string message)
		{
			LogSource.LogWarning((object)("[WARNING] " + message));
		}

		public static void DebugError(string message)
		{
			LogSource.LogError((object)("[ERROR] " + message));
		}
	}
	public class PortalPuzzleChangerSetup
	{
		public static Dictionary<uint, List<PortalEntry>> EnabledConfigs = new Dictionary<uint, List<PortalEntry>>();

		private static List<PortalChangerConfig>? Configs;

		public static string Name { get; } = "PortalPuzzleChanger.json";


		public static void Load()
		{
			string path = Path.Combine(ConfigManager.CustomPath, Name);
			if (File.Exists(path))
			{
				Configs = JsonSerializer.Deserialize<List<PortalChangerConfig>>(File.ReadAllText(path), EntryPoint.SerializerOptions);
				EntryPoint.Debug(Name + " has loaded successfully");
			}
			else
			{
				Configs = new List<PortalChangerConfig>
				{
					new PortalChangerConfig()
				};
				string contents = JsonSerializer.Serialize(Configs, EntryPoint.SerializerOptions);
				File.WriteAllText(path, contents);
				EntryPoint.DebugWarning(Name + " did not exist, creating it now");
			}
			EnabledConfigs.Clear();
			int count = Configs.Count;
			for (int i = 0; i < count; i++)
			{
				if (Configs[i].InternalEnabled)
				{
					EnabledConfigs.Add(Configs[i].MainLevelLayoutID, Configs[i].PortalEntries);
				}
			}
		}
	}
	public class EnemyTagChangerConfigSetup
	{
		public static Dictionary<uint, EnemyTagChanger> EnabledConfigs = new Dictionary<uint, EnemyTagChanger>();

		private static List<EnemyTagChanger>? Configs;

		public static string Name { get; } = "EnemyTags.json";


		public static void Load()
		{
			string path = Path.Combine(ConfigManager.CustomPath, Name);
			if (File.Exists(path))
			{
				Configs = JsonSerializer.Deserialize<List<EnemyTagChanger>>(File.ReadAllText(path), EntryPoint.SerializerOptions);
				EntryPoint.Debug(Name + " has loaded successfully");
			}
			else
			{
				Configs = new List<EnemyTagChanger>
				{
					new EnemyTagChanger()
				};
				string contents = JsonSerializer.Serialize(Configs, EntryPoint.SerializerOptions);
				File.WriteAllText(path, contents);
				EntryPoint.DebugWarning(Name + " did not exist, creating it now");
			}
			EnabledConfigs.Clear();
			int count = Configs.Count;
			for (int i = 0; i < count; i++)
			{
				if (Configs[i].internalEnabled)
				{
					EnabledConfigs.Add(Configs[i].EnemyID, Configs[i]);
				}
			}
		}
	}
	public class GrenadeLauncherConfigSetup
	{
		public static Dictionary<uint, GrenadeLauncherConfig> EnabledConfigs = new Dictionary<uint, GrenadeLauncherConfig>();

		private static List<GrenadeLauncherConfig>? Configs;

		public static string Name { get; } = "GrenadeLauncher.json";


		public static void Load()
		{
			string path = Path.Combine(ConfigManager.CustomPath, Name);
			if (File.Exists(path))
			{
				Configs = JsonSerializer.Deserialize<List<GrenadeLauncherConfig>>(File.ReadAllText(path), EntryPoint.SerializerOptions);
				EntryPoint.Debug(Name + " has loaded successfully");
			}
			else
			{
				Configs = new List<GrenadeLauncherConfig>
				{
					new GrenadeLauncherConfig()
				};
				string contents = JsonSerializer.Serialize(Configs, EntryPoint.SerializerOptions);
				File.WriteAllText(path, contents);
				EntryPoint.DebugWarning(Name + " did not exist, creating it now");
			}
			EnabledConfigs.Clear();
			int count = Configs.Count;
			for (int i = 0; i < count; i++)
			{
				if (Configs[i].internalEnabled)
				{
					EnabledConfigs.Add(Configs[i].PersistentID, Configs[i]);
				}
			}
		}
	}
}
namespace PortalPuzzleChanger.Patches
{
	[HarmonyPatch(typeof(LG_DimensionPortal), "Setup")]
	public static class DimensionPortalPatch
	{
		public static void Prefix(LG_DimensionPortal __instance)
		{
			//IL_002e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0039: Unknown result type (might be due to invalid IL or missing references)
			//IL_0049: Unknown result type (might be due to invalid IL or missing references)
			//IL_0080: Unknown result type (might be due to invalid IL or missing references)
			//IL_0087: Unknown result type (might be due to invalid IL or missing references)
			//IL_008e: Unknown result type (might be due to invalid IL or missing references)
			//IL_00aa: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b8: Unknown result type (might be due to invalid IL or missing references)
			if (!PortalPuzzleChangerSetup.EnabledConfigs.ContainsKey(RundownManager.ActiveExpedition.LevelLayoutData))
			{
				return;
			}
			(eDimensionIndex, LG_LayerType, eLocalZoneIndex) original = (__instance.SpawnNode.m_dimension.DimensionIndex, __instance.SpawnNode.LayerType, __instance.SpawnNode.m_zone.LocalIndex);
			List<PortalEntry> list = PortalPuzzleChangerSetup.EnabledConfigs[RundownManager.ActiveExpedition.LevelLayoutData];
			foreach (PortalEntry item in list)
			{
				(eDimensionIndex, LG_LayerType, eLocalZoneIndex) comparingTo = (item.DimensionIndex, item.LayerType, item.ZoneIndex);
				if (DoesZoneMatch(original, comparingTo))
				{
					__instance.m_targetDimension = item.TargetDimension;
					__instance.m_targetZone = item.TargetZoneIndex;
					__instance.PortalChainPuzzle = item.PortalChainedPuzzleId;
					EntryPoint.Debug("Changing the ChainedPuzzleID on " + __instance.PublicName);
				}
			}
		}

		public static void Postfix(LG_DimensionPortal __instance)
		{
			//IL_002e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0039: Unknown result type (might be due to invalid IL or missing references)
			//IL_0049: Unknown result type (might be due to invalid IL or missing references)
			//IL_0083: 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_0091: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d1: Unknown result type (might be due to invalid IL or missing references)
			if (!PortalPuzzleChangerSetup.EnabledConfigs.ContainsKey(RundownManager.ActiveExpedition.LevelLayoutData))
			{
				return;
			}
			(eDimensionIndex, LG_LayerType, eLocalZoneIndex) original = (__instance.SpawnNode.m_dimension.DimensionIndex, __instance.SpawnNode.LayerType, __instance.SpawnNode.m_zone.LocalIndex);
			List<PortalEntry> list = PortalPuzzleChangerSetup.EnabledConfigs[RundownManager.ActiveExpedition.LevelLayoutData];
			foreach (PortalEntry item in list)
			{
				(eDimensionIndex, LG_LayerType, eLocalZoneIndex) comparingTo = (item.DimensionIndex, item.LayerType, item.ZoneIndex);
				if (DoesZoneMatch(original, comparingTo) && item.CreateTeamScanAsLast)
				{
					ChainedPuzzleInstance puzzleInstance = ChainedPuzzleManager.CreatePuzzleInstance(4u, __instance.SpawnNode.m_area, __instance.m_portalBioScanPoint.position, __instance.m_portalBioScanPoint);
					puzzleInstance.OnPuzzleSolved = __instance.m_portalChainPuzzleInstance.OnPuzzleSolved;
					__instance.m_portalChainPuzzleInstance.OnPuzzleSolved = Action.op_Implicit((Action)delegate
					{
						puzzleInstance.AttemptInteract((eChainedPuzzleInteraction)0);
					});
					EntryPoint.Debug("Adding team scan on " + __instance.PublicName);
				}
			}
		}

		private static bool DoesZoneMatch((eDimensionIndex, LG_LayerType, eLocalZoneIndex) original, (eDimensionIndex, LG_LayerType, eLocalZoneIndex) comparingTo)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0014: Unknown result type (might be due to invalid IL or missing references)
			//IL_001a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0022: Unknown result type (might be due to invalid IL or missing references)
			//IL_0028: Unknown result type (might be due to invalid IL or missing references)
			(eDimensionIndex, LG_LayerType, eLocalZoneIndex) tuple = original;
			(eDimensionIndex, LG_LayerType, eLocalZoneIndex) tuple2 = comparingTo;
			return tuple.Item1 == tuple2.Item1 && tuple.Item2 == tuple2.Item2 && tuple.Item3 == tuple2.Item3;
		}
	}
	[HarmonyPatch(typeof(HackingTool), "Setup")]
	public static class HackingToolTest
	{
		public static void Postfix(HackingTool __instance)
		{
		}
	}
	[HarmonyPatch(typeof(EnemyAgent), "SyncPlaceNavMarkerTag")]
	internal static class EnemyTagPatch
	{
		public static void Postfix(EnemyAgent __instance)
		{
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			if (EnemyTagChangerConfigSetup.EnabledConfigs.ContainsKey(__instance.EnemyDataID))
			{
				EnemyTagChanger enemyTagChanger = EnemyTagChangerConfigSetup.EnabledConfigs[__instance.EnemyDataID];
				NavMarker tagMarker = __instance.m_tagMarker;
				if (!string.IsNullOrEmpty(enemyTagChanger.CustomImagePath))
				{
					SpriteRenderer component = ((Component)tagMarker.m_enemySubObj).GetComponent<SpriteRenderer>();
					component.sprite = EntryPoint.CachedSprites[enemyTagChanger.CustomImagePath];
				}
				tagMarker.SetColor(enemyTagChanger.TagColor);
			}
		}
	}
	[HarmonyPatch(typeof(GrenadeBase), "Awake")]
	internal static class GrenadeBase_Setup
	{
		public static void Postfix(GrenadeBase __instance)
		{
			GrenadeProjectile grenadeProjectile = ((Component)__instance).gameObject.AddComponent<GrenadeProjectile>();
			((Behaviour)grenadeProjectile).enabled = true;
			grenadeProjectile.GrenadeBase = __instance;
		}
	}
	[HarmonyPatch(typeof(GrenadeBase), "GrenadeDelay")]
	internal static class GrenadeBase_GrenadeDelay
	{
		public static bool Prefix()
		{
			return false;
		}
	}
	[HarmonyPatch(typeof(GrenadeBase), "Start")]
	internal static class GrenadeBase_Start
	{
		public static void Postfix(GrenadeBase __instance)
		{
			((MonoBehaviour)__instance).CancelInvoke("GrenadeDelay");
		}
	}
	[HarmonyPatch(typeof(BulletWeapon), "Fire")]
	internal static class BulletWeapon_Fire
	{
		public static void Prefix(BulletWeapon __instance)
		{
			if (GrenadeLauncherConfigSetup.EnabledConfigs.ContainsKey(((ItemEquippable)__instance).ArchetypeID))
			{
				GrenadeLauncherConfig config = GrenadeLauncherConfigSetup.EnabledConfigs[((ItemEquippable)__instance).ArchetypeID];
				GrenadeLauncherFire.Fire(__instance, config);
			}
		}
	}
	internal static class GrenadeLauncherFire
	{
		public static void Fire(BulletWeapon weapon, GrenadeLauncherConfig config)
		{
			//IL_0003: Unknown result type (might be due to invalid IL or missing references)
			//IL_001b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0020: Unknown result type (might be due to invalid IL or missing references)
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			//IL_0028: 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_0037: 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_004c: 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_005e: Unknown result type (might be due to invalid IL or missing references)
			pItemData val = default(pItemData);
			val.itemID_gearCRC = 136u;
			Vector3 targetLookDir = ((Agent)((Item)weapon).Owner).TargetLookDir;
			Vector3 normalized = ((Vector3)(ref targetLookDir)).normalized;
			ItemReplicationManager.ThrowItem(val, (delItemCallback)null, (ItemMode)3, ((Component)((ItemEquippable)weapon).MuzzleAlign).transform.position, ((Component)((ItemEquippable)weapon).MuzzleAlign).transform.rotation, normalized * config.ShootForce, ((Component)weapon).transform.position, ((Agent)((Item)weapon).Owner).CourseNode, ((Item)weapon).Owner);
			((Weapon)weapon).MaxRayDist = 0f;
		}
	}
}
namespace PortalPuzzleChanger.GameScripts
{
	public class GrenadeProjectile : ConsumableInstance
	{
		public GrenadeBase GrenadeBase;

		private static FX_Pool explosionPool;

		private float damageRadiusHigh;

		private float damageRadiusLow;

		private float damageValueHigh;

		private float damageValueLow;

		private float explosionForce;

		private readonly int explosionTargetMask = LayerManager.MASK_EXPLOSION_TARGETS;

		private readonly int explosionBlockMask = LayerManager.MASK_EXPLOSION_BLOCKERS;

		private bool madeNoise = false;

		private bool collision = false;

		private bool addForce = false;

		private float decayTime;

		private Rigidbody rigidbody;

		private CellSoundPlayer cellSoundPlayer;

		public GrenadeProjectile(IntPtr hdl)
			: base(hdl)
		{
		}

		private void Awake()
		{
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0018: Expected O, but got Unknown
			rigidbody = ((Component)this).GetComponent<Rigidbody>();
			cellSoundPlayer = new CellSoundPlayer();
			if (!Object.op_Implicit((Object)(object)explosionPool))
			{
				explosionPool = FX_Manager.GetEffectPool(AssetShardManager.GetLoadedAsset<GameObject>("Assets/AssetPrefabs/FX_Effects/FX_Tripmine.prefab", false));
			}
		}

		private void Start()
		{
			GrenadeLauncherConfig grenadeLauncherConfig = GrenadeLauncherConfigSetup.EnabledConfigs[((Item)GrenadeBase).Owner.Inventory.WieldedItem.ArchetypeID];
			damageRadiusHigh = grenadeLauncherConfig.MaximumDamageRange.Radius;
			damageRadiusLow = grenadeLauncherConfig.MinimumDamageRange.Radius;
			damageValueHigh = grenadeLauncherConfig.MaximumDamageRange.Damage;
			damageValueLow = grenadeLauncherConfig.MinimumDamageRange.Damage;
			explosionForce = grenadeLauncherConfig.ExplosionForce;
		}

		private void FixedUpdate()
		{
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			//IL_0022: Unknown result type (might be due to invalid IL or missing references)
			//IL_002c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0031: Unknown result type (might be due to invalid IL or missing references)
			//IL_0036: 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_005f: Unknown result type (might be due to invalid IL or missing references)
			if (rigidbody.useGravity)
			{
				Vector3 val = ((Component)this).transform.position + rigidbody.velocity * Time.fixedDeltaTime;
			}
			else if (!madeNoise)
			{
				MakeNoise();
				((Component)this).transform.position = Vector3.down * 100f;
				madeNoise = true;
			}
		}

		private void Update()
		{
			//IL_001d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0022: Unknown result type (might be due to invalid IL or missing references)
			if (rigidbody.useGravity)
			{
				cellSoundPlayer.UpdatePosition(((Component)this).transform.position);
				if (collision)
				{
					DetonateSequence();
				}
			}
			else if (Time.time > decayTime)
			{
				((Item)GrenadeBase).ReplicationWrapper.Replicator.Despawn();
			}
		}

		private void OnCollisionEnter()
		{
			if (rigidbody.useGravity)
			{
				DetonateSequence();
			}
		}

		private void DetonateSequence()
		{
			//IL_001f: 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)
			Detonate();
			decayTime = Time.time + 10f;
			rigidbody.velocity = Vector3.zero;
			rigidbody.angularVelocity = Vector3.zero;
			rigidbody.useGravity = false;
		}

		private void Detonate()
		{
			//IL_0014: 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_001e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0039: Unknown result type (might be due to invalid IL or missing references)
			//IL_006e: Unknown result type (might be due to invalid IL or missing references)
			FX_EffectBase val = (FX_EffectBase)(object)explosionPool.AquireEffect();
			val.Play((FX_Trigger)null, ((Component)this).transform.position, Quaternion.LookRotation(Vector3.up));
			if (SNet.IsMaster)
			{
				DamageUtil.DoExplosionDamage(((Component)this).transform.position, damageRadiusHigh, damageValueHigh, explosionTargetMask, explosionBlockMask, addForce, explosionForce);
				DamageUtil.DoExplosionDamage(((Component)this).transform.position, damageRadiusLow, damageValueLow, explosionTargetMask, explosionBlockMask, addForce, explosionForce);
			}
		}

		private void MakeNoise()
		{
			//IL_000d: 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_00a1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ba: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bf: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cc: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ed: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f9: Unknown result type (might be due to invalid IL or missing references)
			//IL_0105: Unknown result type (might be due to invalid IL or missing references)
			//IL_010d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0115: Unknown result type (might be due to invalid IL or missing references)
			//IL_011f: Expected O, but got Unknown
			List<string> list = new List<string>();
			Il2CppReferenceArray<Collider> val = Physics.OverlapSphere(((Component)this).transform.position, 50f, LayerManager.MASK_ENEMY_DAMAGABLE);
			foreach (Collider item in (Il2CppArrayBase<Collider>)(object)val)
			{
				Dam_EnemyDamageLimb component = ((Component)item).GetComponent<Dam_EnemyDamageLimb>();
				if ((Object)(object)component == (Object)null)
				{
					continue;
				}
				EnemyAgent glueTargetEnemyAgent = component.GlueTargetEnemyAgent;
				if (!((Object)(object)glueTargetEnemyAgent == (Object)null) && !list.Contains(((Object)((Component)glueTargetEnemyAgent).gameObject).name))
				{
					list.Add(((Object)((Component)glueTargetEnemyAgent).gameObject).name);
					if (!Physics.Linecast(((Component)this).transform.position, ((Agent)glueTargetEnemyAgent).EyePosition, LayerManager.MASK_WORLD))
					{
						NM_NoiseData val2 = new NM_NoiseData
						{
							position = ((Agent)glueTargetEnemyAgent).EyePosition,
							node = ((Agent)glueTargetEnemyAgent).CourseNode,
							type = (NM_NoiseType)0,
							radiusMin = 0.01f,
							radiusMax = 100f,
							yScale = 1f,
							noiseMaker = null,
							raycastFirstNode = false,
							includeToNeightbourAreas = false
						};
						NoiseManager.MakeNoise(val2);
					}
				}
			}
			cellSoundPlayer.Post(EVENTS.FRAGGRENADEEXPLODE, true);
		}

		public override void OnDespawn()
		{
			((ItemWrapped)this).OnDespawn();
		}
	}
}
namespace PortalPuzzleChanger.ConfigFiles
{
	public class EnemyTagChanger
	{
		public bool internalEnabled { get; set; }

		public string internalName { get; set; }

		public uint EnemyID { get; set; }

		public Color TagColor { get; set; }

		public string CustomImagePath { get; set; }

		public EnemyTagChanger()
		{
			//IL_0025: Unknown result type (might be due to invalid IL or missing references)
			internalEnabled = false;
			internalName = string.Empty;
			EnemyID = 0u;
			TagColor = Color.red;
			CustomImagePath = string.Empty;
		}
	}
	public class GrenadeLauncherConfig
	{
		public DamageMinMax MaximumDamageRange { get; set; }

		public DamageMinMax MinimumDamageRange { get; set; }

		public float ExplosionForce { get; set; }

		public float ShootForce { get; set; }

		public uint PersistentID { get; set; }

		public string internalName { get; set; }

		public bool internalEnabled { get; set; }

		public GrenadeLauncherConfig()
		{
			MaximumDamageRange = new DamageMinMax();
			MinimumDamageRange = new DamageMinMax();
			ExplosionForce = 1000f;
			PersistentID = 0u;
			internalName = string.Empty;
			internalEnabled = false;
		}
	}
	public class DamageMinMax
	{
		public float Radius { get; set; }

		public float Damage { get; set; }

		public DamageMinMax()
		{
			Radius = 0f;
			Damage = 0f;
		}
	}
	public class PortalChangerConfig
	{
		public uint MainLevelLayoutID { get; set; }

		public bool InternalEnabled { get; set; }

		public string? InternalName { get; set; }

		public List<PortalEntry> PortalEntries { get; set; }

		public PortalChangerConfig()
		{
			PortalEntries = new List<PortalEntry>
			{
				new PortalEntry()
			};
			InternalEnabled = false;
			InternalName = "Test";
			MainLevelLayoutID = 0u;
		}
	}
	public class PortalEntry
	{
		public eLocalZoneIndex ZoneIndex { get; set; }

		public LG_LayerType LayerType { get; set; }

		public eDimensionIndex DimensionIndex { get; set; }

		public eDimensionIndex TargetDimension { get; set; }

		public eLocalZoneIndex TargetZoneIndex { get; set; }

		public uint PortalChainedPuzzleId { get; set; }

		public bool CreateTeamScanAsLast { get; set; }

		public PortalEntry()
		{
			ZoneIndex = (eLocalZoneIndex)0;
			LayerType = (LG_LayerType)0;
			DimensionIndex = (eDimensionIndex)0;
			TargetDimension = (eDimensionIndex)1;
			TargetZoneIndex = (eLocalZoneIndex)0;
			PortalChainedPuzzleId = 4u;
			CreateTeamScanAsLast = false;
		}
	}
}

plugins/TrickyBall's Paradise/Custom/ScanPosOverride.dll

Decompiled 8 months ago
using System;
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 System.Security;
using System.Security.Permissions;
using System.Text;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Threading;
using AIGraph;
using Agents;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Core.Logging.Interpolation;
using BepInEx.Logging;
using BepInEx.Unity.IL2CPP;
using ChainedPuzzles;
using GTFO.API;
using GTFO.API.Extensions;
using GTFO.API.Utilities;
using GameData;
using HarmonyLib;
using Il2CppInterop.Runtime.Injection;
using Il2CppInterop.Runtime.InteropTypes;
using Il2CppInterop.Runtime.InteropTypes.Arrays;
using Il2CppSystem;
using Il2CppSystem.Collections.Generic;
using Il2CppSystem.Text;
using LevelGeneration;
using Localization;
using MTFO.API;
using Microsoft.CodeAnalysis;
using Player;
using ScanPosOverride.Component;
using ScanPosOverride.JSON;
using ScanPosOverride.Managers;
using ScanPosOverride.PuzzleOverrideData;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETCoreApp,Version=v6.0", FrameworkDisplayName = ".NET 6.0")]
[assembly: AssemblyCompany("ScanPosOverride")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0")]
[assembly: AssemblyProduct("ScanPosOverride")]
[assembly: AssemblyTitle("ScanPosOverride")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.0.0.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace ScanPosOverride
{
	internal static class SPOLogger
	{
		private static readonly ManualLogSource logger = Logger.CreateLogSource("ScanPosOverride");

		public static void Log(string format, params object[] args)
		{
			Log(string.Format(format, args));
		}

		public static void Log(string str)
		{
			if (logger != null)
			{
				logger.Log((LogLevel)8, (object)str);
			}
		}

		public static void Warning(string format, params object[] args)
		{
			Warning(string.Format(format, args));
		}

		public static void Warning(string str)
		{
			if (logger != null)
			{
				logger.Log((LogLevel)4, (object)str);
			}
		}

		public static void Error(string format, params object[] args)
		{
			Error(string.Format(format, args));
		}

		public static void Error(string str)
		{
			if (logger != null)
			{
				logger.Log((LogLevel)2, (object)str);
			}
		}

		public static void Debug(string format, params object[] args)
		{
			Debug(string.Format(format, args));
		}

		public static void Debug(string str)
		{
			if (logger != null)
			{
				logger.Log((LogLevel)32, (object)str);
			}
		}

		public static void Log(BepInExDebugLogInterpolatedStringHandler logHandler)
		{
			logger.LogDebug(logHandler);
		}
	}
	[BepInPlugin("ScanPositionOverride", "ScanPositionOverride", "1.6.7")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	internal sealed class Plugin : BasePlugin
	{
		[CompilerGenerated]
		private static class <>O
		{
			public static LiveEditEventHandler <0>__LiveEdit_FileChanged;
		}

		private static Dictionary<uint, Dictionary<uint, PuzzleOverride>> PuzzleOverrides = new Dictionary<uint, Dictionary<uint, PuzzleOverride>>();

		public static readonly string OVERRIDE_SCAN_POS_PATH = Path.Combine(MTFOPathAPI.CustomPath, "ScanPositionOverrides");

		private static LiveEditListener listener = null;

		private static Harmony m_Harmony = null;

		public override void Load()
		{
			//IL_01f5: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ff: Expected O, but got Unknown
			//IL_01e0: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e5: Unknown result type (might be due to invalid IL or missing references)
			//IL_01eb: Expected O, but got Unknown
			SPOLogger.Error(OVERRIDE_SCAN_POS_PATH);
			if (!Directory.Exists(OVERRIDE_SCAN_POS_PATH))
			{
				Directory.CreateDirectory(OVERRIDE_SCAN_POS_PATH);
				StreamWriter streamWriter = File.CreateText(Path.Combine(OVERRIDE_SCAN_POS_PATH, "Template.json"));
				streamWriter.WriteLine(Json.Serialize(new PuzzleOverrideJsonFile()));
				streamWriter.Flush();
				streamWriter.Close();
				return;
			}
			foreach (string item in Directory.EnumerateFiles(OVERRIDE_SCAN_POS_PATH, "*.json", SearchOption.AllDirectories))
			{
				Json.Load<PuzzleOverrideJsonFile>(item, out var config);
				if (PuzzleOverrides.ContainsKey(config.MainLevelLayout))
				{
					SPOLogger.Warning("Duplicate MainLevelLayout {0}, won't load.", config.MainLevelLayout);
					continue;
				}
				Dictionary<uint, PuzzleOverride> dictionary = new Dictionary<uint, PuzzleOverride>();
				foreach (PuzzleOverride puzzle in config.Puzzles)
				{
					if (dictionary.ContainsKey(puzzle.Index))
					{
						SPOLogger.Error("Duplicate Puzzle Override found. MainLevelLayout {0}, Index {1}.", config.MainLevelLayout, puzzle.Index);
						continue;
					}
					puzzle.EventsOnBioscanProgress.RemoveAll((BioscanProgressEvent e) => e.Progress <= 0f);
					puzzle.EventsOnBioscanProgress.Sort((BioscanProgressEvent e1, BioscanProgressEvent e2) => Mathf.RoundToInt(e1.Progress - e2.Progress));
					dictionary.Add(puzzle.Index, puzzle);
				}
				PuzzleOverrides.Add(config.MainLevelLayout, dictionary);
			}
			listener = LiveEdit.CreateListener(OVERRIDE_SCAN_POS_PATH, "*.json", true);
			LiveEditListener obj = listener;
			object obj2 = <>O.<0>__LiveEdit_FileChanged;
			if (obj2 == null)
			{
				LiveEditEventHandler val = LiveEdit_FileChanged;
				<>O.<0>__LiveEdit_FileChanged = val;
				obj2 = (object)val;
			}
			obj.FileChanged += (LiveEditEventHandler)obj2;
			m_Harmony = new Harmony("ScanPosOverride.Patches");
			m_Harmony.PatchAll();
		}

		private static void LiveEdit_FileChanged(LiveEditEventArgs e)
		{
			SPOLogger.Warning("LiveEdit File Changed: " + e.FullPath + ".");
			LiveEdit.TryReadFileContent(e.FullPath, (Action<string>)delegate(string content)
			{
				PuzzleOverrideJsonFile puzzleOverrideJsonFile = Json.Deserialize<PuzzleOverrideJsonFile>(content);
				if (!PuzzleOverrides.ContainsKey(puzzleOverrideJsonFile.MainLevelLayout))
				{
					SPOLogger.Warning("MainLevelLayout not found, which is now not supported. Will not replace.");
				}
				else
				{
					Dictionary<uint, PuzzleOverride> dictionary = PuzzleOverrides[puzzleOverrideJsonFile.MainLevelLayout];
					dictionary.Clear();
					foreach (PuzzleOverride puzzle in puzzleOverrideJsonFile.Puzzles)
					{
						if (dictionary.ContainsKey(puzzle.Index))
						{
							SPOLogger.Error("Duplicate Puzzle Override found. MainLevelLayout {0}, Index {1}.", puzzleOverrideJsonFile.MainLevelLayout, puzzle.Index);
						}
						else
						{
							puzzle.EventsOnBioscanProgress.Sort((BioscanProgressEvent e1, BioscanProgressEvent e2) => Mathf.RoundToInt(e1.Progress - e2.Progress));
							dictionary.Add(puzzle.Index, puzzle);
						}
					}
					SPOLogger.Warning("Replaced Override Puzzle with MainLevelLayout {0}", puzzleOverrideJsonFile.MainLevelLayout);
				}
			});
		}

		internal static PuzzleOverride GetOverride(uint mainLevelLayout, uint puzzleIndex)
		{
			if (!PuzzleOverrides.ContainsKey(mainLevelLayout))
			{
				return null;
			}
			Dictionary<uint, PuzzleOverride> dictionary = PuzzleOverrides[mainLevelLayout];
			if (!dictionary.ContainsKey(puzzleIndex))
			{
				return null;
			}
			return dictionary[puzzleIndex];
		}
	}
	public static class Utils
	{
	}
}
namespace ScanPosOverride.PuzzleOverrideData
{
	internal sealed class PuzzleOverrideJsonFile
	{
		public uint MainLevelLayout { get; set; }

		public List<PuzzleOverride> Puzzles { get; set; } = new List<PuzzleOverride>
		{
			new PuzzleOverride()
		};

	}
	public class BioscanProgressEvent
	{
		public float Progress { get; set; } = -1f;


		public List<WardenObjectiveEventData> Events { get; set; } = new List<WardenObjectiveEventData>();

	}
	public class ClusterProgressEvent
	{
		public int Count { get; set; } = -1;


		public List<WardenObjectiveEventData> Events { get; set; } = new List<WardenObjectiveEventData>();

	}
	public class PuzzleOverride
	{
		public uint Index { get; set; }

		public Vec3 Position { get; set; } = new Vec3();


		public Vec3 Rotation { get; set; } = new Vec3();


		public bool HideSpline { get; set; }

		public Vec3 PrevPosOverride { get; set; } = new Vec3();


		public uint PrevPosOverrideIndex { get; set; }

		public bool ConcurrentCluster { get; set; }

		public float TMoveSpeedMulti { get; set; } = -1f;


		public List<BioscanProgressEvent> EventsOnBioscanProgress { get; set; } = new List<BioscanProgressEvent>
		{
			new BioscanProgressEvent()
		};


		public List<ClusterProgressEvent> EventsOnClusterProgress { get; set; } = new List<ClusterProgressEvent>
		{
			new ClusterProgressEvent()
		};


		public List<Vec3> TPositions { get; set; } = new List<Vec3>
		{
			new Vec3()
		};


		public List<int> RequiredItemsIndices { get; set; } = new List<int> { 0 };


		public List<WardenObjectiveEventData> EventsOnPuzzleSolved { get; set; } = new List<WardenObjectiveEventData>();

	}
	public class Vec3
	{
		public float x { get; set; }

		public float y { get; set; }

		public float z { get; set; }

		public Vector3 ToVector3()
		{
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			return new Vector3(x, y, z);
		}

		public Quaternion ToQuaternion()
		{
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			return Quaternion.Euler(x, y, z);
		}
	}
}
namespace ScanPosOverride.Patches
{
	[HarmonyPatch]
	internal static class Patch_CP_BasicMovable_TryGetNextIndex
	{
	}
	[HarmonyPatch]
	internal static class Patch_CP_Bioscan_Core_OnSyncStateChange
	{
		private static Dictionary<IntPtr, int> EOPIndex;

		static Patch_CP_Bioscan_Core_OnSyncStateChange()
		{
			EOPIndex = new Dictionary<IntPtr, int>();
			LevelAPI.OnBuildStart += EOPIndex.Clear;
			LevelAPI.OnLevelCleanup += EOPIndex.Clear;
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(CP_Bioscan_Core), "OnSyncStateChange")]
		private static void Post_OnSyncStateChanged_CheckEOPAndEventsOnPuzzleSolved(CP_Bioscan_Core __instance, float progress, eBioscanStatus status, List<PlayerAgent> playersInScan, bool isDropinState)
		{
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0061: Invalid comparison between Unknown and I4
			uint bioscanCoreOverrideIndex = PuzzleOverrideManager.Current.GetBioscanCoreOverrideIndex(__instance);
			PuzzleOverride def = Plugin.GetOverride(PuzzleOverrideManager.MainLevelLayout, bioscanCoreOverrideIndex);
			if (def != null)
			{
				if (def.EventsOnBioscanProgress.Count > 0)
				{
					CheckBioscanEventsOnProgress();
				}
				if ((int)status == 4 && !isDropinState && def.EventsOnPuzzleSolved.Count > 0)
				{
					WardenObjectiveManager.CheckAndExecuteEventsOnTrigger(ListExtensions.ToIl2Cpp<WardenObjectiveEventData>(def.EventsOnPuzzleSolved), (eWardenObjectiveEventTrigger)0, true, 0f, (Il2CppStructArray<eWardenObjectiveEventType>)null);
				}
			}
			void CheckBioscanEventsOnProgress()
			{
				if (!EOPIndex.ContainsKey(((Il2CppObjectBase)__instance).Pointer))
				{
					EOPIndex[((Il2CppObjectBase)__instance).Pointer] = 0;
				}
				int i = EOPIndex[((Il2CppObjectBase)__instance).Pointer];
				if (isDropinState)
				{
					for (; i < def.EventsOnBioscanProgress.Count && !(def.EventsOnBioscanProgress[i].Progress > progress); i++)
					{
					}
				}
				else if (i < def.EventsOnBioscanProgress.Count && def.EventsOnBioscanProgress[i].Progress < progress)
				{
					WardenObjectiveManager.CheckAndExecuteEventsOnTrigger(ListExtensions.ToIl2Cpp<WardenObjectiveEventData>(def.EventsOnBioscanProgress[i].Events), (eWardenObjectiveEventTrigger)0, true, 0f, (Il2CppStructArray<eWardenObjectiveEventType>)null);
					EOPIndex[((Il2CppObjectBase)__instance).Pointer] = i + 1;
				}
			}
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(CP_Bioscan_Core), "OnSyncStateChange")]
		private static void Post_OnSyncStateChanged_CheckReqItemAndConcurrentCluster(CP_Bioscan_Core __instance, float progress, eBioscanStatus status, List<PlayerAgent> playersInScan, bool isDropinState)
		{
			//IL_006e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0070: Invalid comparison between Unknown and I4
			//IL_002f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0075: Unknown result type (might be due to invalid IL or missing references)
			//IL_0077: Invalid comparison between Unknown and I4
			//IL_0129: Unknown result type (might be due to invalid IL or missing references)
			//IL_0146: Unknown result type (might be due to invalid IL or missing references)
			//IL_014c: Invalid comparison between Unknown and I4
			//IL_0158: Unknown result type (might be due to invalid IL or missing references)
			//IL_015e: Invalid comparison between Unknown and I4
			//IL_018f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0194: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a3: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d2: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d8: Invalid comparison between Unknown and I4
			//IL_01bc: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c1: Unknown result type (might be due to invalid IL or missing references)
			//IL_0335: Unknown result type (might be due to invalid IL or missing references)
			//IL_02c1: Unknown result type (might be due to invalid IL or missing references)
			//IL_0224: Unknown result type (might be due to invalid IL or missing references)
			//IL_0229: Unknown result type (might be due to invalid IL or missing references)
			//IL_022b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0230: Unknown result type (might be due to invalid IL or missing references)
			//IL_0206: Unknown result type (might be due to invalid IL or missing references)
			//IL_020b: Unknown result type (might be due to invalid IL or missing references)
			bool flag = PlayerScannerManager.Current.IsConcurrentCluster(__instance);
			if (flag && __instance.m_reqItemsEnabled)
			{
				SPOLogger.Warning($"OnSyncStateChange: status - {status}, playersInScan - {playersInScan.Count}, progress: {progress}");
			}
			if ((int)status != 3)
			{
				if (flag)
				{
					if ((int)status == 4)
					{
						CP_Cluster_Core val = ((Il2CppObjectBase)__instance.Owner).TryCast<CP_Cluster_Core>();
						if ((Object)(object)val == (Object)null)
						{
							SPOLogger.Error("Cannot find parent cluster core! The concurrent cluster may fail!");
						}
						else
						{
							PlayerScannerManager.Current.CompleteConcurrentCluster(val, __instance);
						}
					}
					else
					{
						PlayerScannerManager.Current.CCShouldProgress(__instance, IsThisScanShouldProgress: false);
					}
				}
				if (__instance.m_reqItemsEnabled)
				{
					__instance.m_graphics.SetColorMode((eChainedPuzzleGraphicsColorMode)((!__instance.m_hasAlarm) ? 1 : 4));
				}
			}
			else
			{
				if (!__instance.IsMovable && !flag && !__instance.m_reqItemsEnabled)
				{
					return;
				}
				CP_PlayerScanner cacheScanner = PlayerScannerManager.Current.GetCacheScanner(__instance);
				if ((Object)(object)cacheScanner == (Object)null)
				{
					return;
				}
				int count = playersInScan.Count;
				List<PlayerAgent> playerAgentsInLevel = PlayerManager.PlayerAgentsInLevel;
				float num = 0f;
				float[] cacheOriginalScanSpeed = PlayerScannerManager.Current.GetCacheOriginalScanSpeed(__instance);
				if ((int)__instance.m_playerScanner.ScanPlayersRequired == 0)
				{
					num = ((count <= 0) ? 0f : cacheOriginalScanSpeed[count - 1]);
				}
				else if (((int)cacheScanner.m_playerRequirement == 1 && count == playerAgentsInLevel.Count) || ((int)cacheScanner.m_playerRequirement == 2 && count == 1))
				{
					num = cacheOriginalScanSpeed[0];
				}
				bool flag2 = num > 0f;
				if (flag2 && cacheScanner.m_reqItemsEnabled)
				{
					for (int i = 0; i < ((Il2CppArrayBase<iWardenObjectiveItem>)(object)cacheScanner.m_reqItems).Length; i++)
					{
						Vector3 val2 = Vector3.zero;
						if ((int)((Il2CppArrayBase<iWardenObjectiveItem>)(object)cacheScanner.m_reqItems)[i].PickupItemStatus == 0)
						{
							val2 = ((Il2CppArrayBase<iWardenObjectiveItem>)(object)cacheScanner.m_reqItems)[i].transform.position;
						}
						else if ((int)((Il2CppArrayBase<iWardenObjectiveItem>)(object)cacheScanner.m_reqItems)[i].PickupItemStatus == 1)
						{
							if ((Object)(object)((Il2CppArrayBase<iWardenObjectiveItem>)(object)cacheScanner.m_reqItems)[i].PickedUpByPlayer != (Object)null)
							{
								val2 = ((Agent)((Il2CppArrayBase<iWardenObjectiveItem>)(object)cacheScanner.m_reqItems)[i].PickedUpByPlayer).Position;
							}
							else
							{
								Debug.LogError(Object.op_Implicit("Playerscanner is looking for an item that has ePickupItemStatus.PickedUp but null player, how come!?"));
							}
						}
						Vector3 val3 = ((Component)cacheScanner).transform.position - val2;
						if (((Vector3)(ref val3)).sqrMagnitude >= cacheScanner.m_scanRadiusSqr)
						{
							flag2 = false;
							break;
						}
					}
				}
				if (flag)
				{
					if (flag2)
					{
						flag2 = PlayerScannerManager.Current.CCShouldProgress(__instance, IsThisScanShouldProgress: true);
					}
					else
					{
						PlayerScannerManager.Current.CCShouldProgress(__instance, IsThisScanShouldProgress: false);
					}
				}
				if (flag2)
				{
					if (flag)
					{
						CP_Cluster_Core parent = ((Il2CppObjectBase)__instance.Owner).Cast<CP_Cluster_Core>();
						PlayerScannerManager.Current.RestoreCCScanSpeed(parent);
					}
					if (__instance.IsMovable)
					{
						__instance.m_movingComp.ResumeMovement();
					}
					if (cacheScanner.m_reqItemsEnabled)
					{
						if ((int)cacheScanner.m_playerRequirement == 0)
						{
							((Il2CppArrayBase<float>)(object)cacheScanner.m_scanSpeeds)[0] = ((count > 0) ? cacheOriginalScanSpeed[count - 1] : 0f);
						}
						__instance.m_graphics.SetColorMode((eChainedPuzzleGraphicsColorMode)(__instance.m_hasAlarm ? 5 : 2));
					}
					return;
				}
				if (flag)
				{
					CP_Cluster_Core parent2 = ((Il2CppObjectBase)__instance.Owner).Cast<CP_Cluster_Core>();
					PlayerScannerManager.Current.ZeroCCScanSpeed(parent2);
				}
				if (__instance.IsMovable)
				{
					__instance.m_movingComp.PauseMovement();
				}
				if (cacheScanner.m_reqItemsEnabled)
				{
					if ((int)cacheScanner.m_playerRequirement == 0)
					{
						PlayerScannerManager.Current.GetCacheOriginalScanSpeed(__instance);
						((Il2CppArrayBase<float>)(object)cacheScanner.m_scanSpeeds)[0] = 0f;
					}
					__instance.m_graphics.SetColorMode((eChainedPuzzleGraphicsColorMode)((!__instance.m_hasAlarm) ? 1 : 4));
				}
			}
		}
	}
	[HarmonyPatch]
	internal class Patch_CP_Bioscan_Core_Setup
	{
		[HarmonyPrefix]
		[HarmonyPatch(typeof(CP_Bioscan_Core), "Setup")]
		private static void Pre_CP_Bioscan_Core_Setup(CP_Bioscan_Core __instance, int puzzleIndex, iChainedPuzzleOwner owner, ref Vector3 prevPuzzlePos, ref bool revealWithHoloPath, ref bool onlyShowHUDWhenPlayerIsClose)
		{
			//IL_021d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0222: Unknown result type (might be due to invalid IL or missing references)
			//IL_0039: Unknown result type (might be due to invalid IL or missing references)
			//IL_003e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0357: Unknown result type (might be due to invalid IL or missing references)
			//IL_035c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0235: Unknown result type (might be due to invalid IL or missing references)
			//IL_023a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0051: Unknown result type (might be due to invalid IL or missing references)
			//IL_0056: Unknown result type (might be due to invalid IL or missing references)
			//IL_0389: Unknown result type (might be due to invalid IL or missing references)
			//IL_038e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0291: Unknown result type (might be due to invalid IL or missing references)
			//IL_03bd: Unknown result type (might be due to invalid IL or missing references)
			//IL_03c8: Unknown result type (might be due to invalid IL or missing references)
			//IL_03a0: Unknown result type (might be due to invalid IL or missing references)
			//IL_03a5: Unknown result type (might be due to invalid IL or missing references)
			//IL_018a: Unknown result type (might be due to invalid IL or missing references)
			//IL_018f: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a9: Unknown result type (might be due to invalid IL or missing references)
			//IL_0296: Unknown result type (might be due to invalid IL or missing references)
			//IL_0298: Unknown result type (might be due to invalid IL or missing references)
			//IL_029a: Unknown result type (might be due to invalid IL or missing references)
			//IL_028a: Unknown result type (might be due to invalid IL or missing references)
			//IL_027e: Unknown result type (might be due to invalid IL or missing references)
			//IL_01fd: Unknown result type (might be due to invalid IL or missing references)
			//IL_0202: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ae: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b2: 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)
			//IL_0096: Unknown result type (might be due to invalid IL or missing references)
			//IL_0346: Unknown result type (might be due to invalid IL or missing references)
			//IL_0348: Unknown result type (might be due to invalid IL or missing references)
			//IL_0339: Unknown result type (might be due to invalid IL or missing references)
			//IL_033e: Unknown result type (might be due to invalid IL or missing references)
			//IL_014e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0150: Unknown result type (might be due to invalid IL or missing references)
			//IL_047c: Unknown result type (might be due to invalid IL or missing references)
			//IL_049f: Unknown result type (might be due to invalid IL or missing references)
			ChainedPuzzleInstance val = ((Il2CppObjectBase)owner).TryCast<ChainedPuzzleInstance>();
			uint num = PuzzleOverrideManager.Current.Register(__instance);
			PuzzleOverride @override = Plugin.GetOverride(PuzzleOverrideManager.MainLevelLayout, num);
			if ((Object)(object)val != (Object)null)
			{
				bool flag = false;
				if (@override != null)
				{
					if (@override.PrevPosOverride.ToVector3() != Vector3.zero)
					{
						prevPuzzlePos = @override.PrevPosOverride.ToVector3();
						flag = true;
					}
					else if (@override.PrevPosOverrideIndex != 0)
					{
						CP_Bioscan_Core bioscanCore = PuzzleOverrideManager.Current.GetBioscanCore(@override.PrevPosOverrideIndex);
						? val2;
						if (bioscanCore == null)
						{
							CP_Cluster_Core clusterCore = PuzzleOverrideManager.Current.GetClusterCore(@override.PrevPosOverrideIndex);
							val2 = ((clusterCore != null) ? ((Component)clusterCore).transform.position : Vector3.zero);
						}
						else
						{
							val2 = bioscanCore.m_position;
						}
						Vector3 val3 = (Vector3)val2;
						if (val3 == Vector3.zero)
						{
							SPOLogger.Error($"PuzzleOverrideIndex: {num} - trying to use 'PrevPosOverrideIndex' ({@override.PrevPosOverrideIndex}) but the puzzle is not found.");
							SPOLogger.Error($"The puzzle is probably yet registered. NOTE: 'PrevPosOverrideIndex' could only be a integer that is less than PuzzleOverrideIndex({num})");
							flag = false;
						}
						else
						{
							prevPuzzlePos = val3;
							flag = true;
						}
					}
				}
				if (!flag && puzzleIndex != 0)
				{
					CP_Bioscan_Core val4 = ((Il2CppObjectBase)((Il2CppArrayBase<iChainedPuzzleCore>)(object)val.m_chainedPuzzleCores)[puzzleIndex - 1]).TryCast<CP_Bioscan_Core>();
					if ((Object)(object)val4 != (Object)null)
					{
						prevPuzzlePos = ((Component)val4).transform.position;
					}
					else
					{
						CP_Cluster_Core val5 = ((Il2CppObjectBase)((Il2CppArrayBase<iChainedPuzzleCore>)(object)val.m_chainedPuzzleCores)[puzzleIndex - 1]).TryCast<CP_Cluster_Core>();
						if ((Object)(object)val5 == (Object)null)
						{
							SPOLogger.Error($"Cannot cast m_chainedPuzzleCores[{puzzleIndex - 1}] to neither CP_Bioscan_Core or CP_Cluster_Core! WTF???");
						}
						else
						{
							prevPuzzlePos = ((Component)val5).transform.position;
						}
					}
				}
			}
			else
			{
				CP_Cluster_Core val6 = ((Il2CppObjectBase)owner).Cast<CP_Cluster_Core>();
				if (@override != null && @override.PrevPosOverride.ToVector3() != Vector3.zero)
				{
					prevPuzzlePos = @override.PrevPosOverride.ToVector3();
				}
				else if (@override != null && @override.PrevPosOverrideIndex != 0)
				{
					CP_Bioscan_Core bioscanCore2 = PuzzleOverrideManager.Current.GetBioscanCore(@override.PrevPosOverrideIndex);
					? val7;
					if (bioscanCore2 == null)
					{
						CP_Cluster_Core clusterCore2 = PuzzleOverrideManager.Current.GetClusterCore(@override.PrevPosOverrideIndex);
						val7 = ((clusterCore2 != null) ? ((Component)clusterCore2).transform.position : Vector3.zero);
					}
					else
					{
						val7 = bioscanCore2.m_position;
					}
					Vector3 val8 = (Vector3)val7;
					if (val8 == Vector3.zero)
					{
						SPOLogger.Error($"PuzzleOverrideIndex: {num} - trying to use 'PrevPosOverrideIndex' ({@override.PrevPosOverrideIndex}) but the puzzle is not found.");
						SPOLogger.Error($"The puzzle is probably yet registered. NOTE: 'PrevPosOverrideIndex' could only be a integer that is less than PuzzleOverrideIndex({num})");
						prevPuzzlePos = ((Component)val6).transform.position;
					}
					else
					{
						prevPuzzlePos = val8;
					}
				}
				else
				{
					prevPuzzlePos = ((Component)val6).transform.position;
				}
				val = ((Il2CppObjectBase)val6.m_owner).Cast<ChainedPuzzleInstance>();
				if (val.Data.OnlyShowHUDWhenPlayerIsClose)
				{
					onlyShowHUDWhenPlayerIsClose = true;
				}
			}
			if (@override != null)
			{
				if (@override.Position.ToVector3() != Vector3.zero || @override.Rotation.ToVector3() != Vector3.zero)
				{
					((Component)__instance).transform.SetPositionAndRotation(@override.Position.ToVector3(), @override.Rotation.ToQuaternion());
				}
				if (@override.HideSpline || ((Object)(object)__instance.m_movingComp != (Object)null && __instance.m_movingComp.IsMoveConfigured))
				{
					revealWithHoloPath = false;
				}
				if (@override.RequiredItemsIndices != null && @override.RequiredItemsIndices.Count > 0)
				{
					PuzzleReqItemManager.Current.QueueForAddingReqItems(__instance, @override.RequiredItemsIndices);
				}
				SPOLogger.Warning("Overriding CP_Bioscan_Core." + (((Object)(object)val == (Object)null) ? "" : $"Zone {val.m_sourceArea.m_zone.Alias}, Layer {val.m_sourceArea.m_zone.Layer.m_type}, Dim {val.m_sourceArea.m_zone.DimensionIndex}"));
			}
		}
	}
	[HarmonyPatch]
	internal class Patch_ChainedPuzzleInstance_SetupMovement
	{
		[HarmonyPrefix]
		[HarmonyPatch(typeof(ChainedPuzzleInstance), "SetupMovement")]
		private static bool Pre_SetupMovement(ChainedPuzzleInstance __instance, GameObject gameObject)
		{
			//IL_00b3: Unknown result type (might be due to invalid IL or missing references)
			iChainedPuzzleMovable movingComp = gameObject.GetComponent<iChainedPuzzleMovable>();
			if (movingComp == null || !movingComp.UsingStaticBioscanPoints)
			{
				return true;
			}
			CP_BasicMovable val = ((Il2CppObjectBase)movingComp).Cast<CP_BasicMovable>();
			CP_Bioscan_Core core = ((Il2CppObjectBase)gameObject.GetComponent<iChainedPuzzleCore>()).Cast<CP_Bioscan_Core>();
			uint bioscanCoreOverrideIndex = PuzzleOverrideManager.Current.GetBioscanCoreOverrideIndex(core);
			if (bioscanCoreOverrideIndex == 0)
			{
				SPOLogger.Error("Did not find registered movable override for this movable scan.");
				return true;
			}
			PuzzleOverride @override = Plugin.GetOverride(PuzzleOverrideManager.MainLevelLayout, bioscanCoreOverrideIndex);
			if (@override == null || @override.TPositions.Count < 1)
			{
				SPOLogger.Error("No Override for this T-Scan, falling back to vanilla impl.");
				return true;
			}
			@override.TPositions.ForEach(delegate(Vec3 pos)
			{
				//IL_000c: Unknown result type (might be due to invalid IL or missing references)
				movingComp.ScanPositions.Add(pos.ToVector3());
			});
			gameObject.transform.position = @override.TPositions[0].ToVector3();
			val.m_amountOfPositions = @override.TPositions.Count;
			if (@override.TMoveSpeedMulti > 0f)
			{
				val.m_movementSpeed *= @override.TMoveSpeedMulti;
			}
			SPOLogger.Warning("Overriding T-Scan pos!");
			return false;
		}
	}
	[HarmonyPatch]
	internal class Patch_CarryItemPickup_Core_Setup
	{
		[HarmonyPostfix]
		[HarmonyPatch(typeof(CarryItemPickup_Core), "Setup")]
		private static void Post_CarryItemPickup_Core_Setup(CarryItemPickup_Core __instance)
		{
			PuzzleReqItemManager.Current.Register(__instance);
		}
	}
	[HarmonyPatch]
	internal static class Patch_CP_Cluster_Core_OnSyncStateChange
	{
		[HarmonyPostfix]
		[HarmonyPatch(typeof(CP_Cluster_Core), "OnSyncStateChange")]
		private static void Post_CheckEventsOnPuzzleSolved(CP_Cluster_Core __instance, eClusterStatus newStatus, bool isDropinState)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0002: Invalid comparison between Unknown and I4
			if ((int)newStatus == 3)
			{
				uint clusterCoreOverrideIndex = PuzzleOverrideManager.Current.GetClusterCoreOverrideIndex(__instance);
				PuzzleOverride @override = Plugin.GetOverride(PuzzleOverrideManager.MainLevelLayout, clusterCoreOverrideIndex);
				if (@override != null && @override.EventsOnPuzzleSolved.Count > 0 && !isDropinState)
				{
					WardenObjectiveManager.CheckAndExecuteEventsOnTrigger(ListExtensions.ToIl2Cpp<WardenObjectiveEventData>(@override.EventsOnPuzzleSolved), (eWardenObjectiveEventTrigger)0, true, 0f, (Il2CppStructArray<eWardenObjectiveEventType>)null);
				}
			}
		}
	}
	[HarmonyPatch]
	internal class Patch_CP_Cluster_Core_Setup
	{
		[HarmonyPrefix]
		[HarmonyPatch(typeof(CP_Cluster_Core), "Setup")]
		private static void Pre_CP_Cluster_Core_Setup(CP_Cluster_Core __instance, int puzzleIndex, iChainedPuzzleOwner owner, ref Vector3 prevPuzzlePos, ref bool revealWithHoloPath)
		{
			//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)
			//IL_0045: Unknown result type (might be due to invalid IL or missing references)
			//IL_004a: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ff: Unknown result type (might be due to invalid IL or missing references)
			//IL_0204: Unknown result type (might be due to invalid IL or missing references)
			//IL_0233: Unknown result type (might be due to invalid IL or missing references)
			//IL_023e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0216: Unknown result type (might be due to invalid IL or missing references)
			//IL_021b: Unknown result type (might be due to invalid IL or missing references)
			//IL_017e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0183: Unknown result type (might be due to invalid IL or missing references)
			//IL_009d: Unknown result type (might be due to invalid IL or missing references)
			//IL_01eb: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f0: 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)
			//IL_00a4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a6: Unknown result type (might be due to invalid IL or missing references)
			//IL_0096: 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_0142: Unknown result type (might be due to invalid IL or missing references)
			//IL_0144: Unknown result type (might be due to invalid IL or missing references)
			uint num = PuzzleOverrideManager.Current.Register(__instance);
			PuzzleOverride @override = Plugin.GetOverride(PuzzleOverrideManager.MainLevelLayout, num);
			ChainedPuzzleInstance val = ((Il2CppObjectBase)owner).Cast<ChainedPuzzleInstance>();
			bool flag = false;
			if (@override != null)
			{
				if (@override.PrevPosOverride.ToVector3() != Vector3.zero)
				{
					prevPuzzlePos = @override.PrevPosOverride.ToVector3();
					flag = true;
				}
				else if (@override.PrevPosOverrideIndex != 0)
				{
					CP_Bioscan_Core bioscanCore = PuzzleOverrideManager.Current.GetBioscanCore(@override.PrevPosOverrideIndex);
					? val2;
					if (bioscanCore == null)
					{
						CP_Cluster_Core clusterCore = PuzzleOverrideManager.Current.GetClusterCore(@override.PrevPosOverrideIndex);
						val2 = ((clusterCore != null) ? ((Component)clusterCore).transform.position : Vector3.zero);
					}
					else
					{
						val2 = bioscanCore.m_position;
					}
					Vector3 val3 = (Vector3)val2;
					if (val3 == Vector3.zero)
					{
						SPOLogger.Error($"PuzzleOverrideIndex: {num} - trying to use 'PrevPosOverrideIndex' ({@override.PrevPosOverrideIndex}) but the puzzle is not found.");
						SPOLogger.Error($"The puzzle is probably yet registered. NOTE: 'PrevPosOverrideIndex' could only be a integer that is less than PuzzleOverrideIndex({num})");
						flag = false;
					}
					else
					{
						prevPuzzlePos = val3;
						flag = true;
					}
				}
			}
			if (!flag && puzzleIndex != 0)
			{
				CP_Bioscan_Core val4 = ((Il2CppObjectBase)((Il2CppArrayBase<iChainedPuzzleCore>)(object)val.m_chainedPuzzleCores)[puzzleIndex - 1]).TryCast<CP_Bioscan_Core>();
				if ((Object)(object)val4 != (Object)null)
				{
					prevPuzzlePos = ((Component)val4).transform.position;
				}
				else
				{
					CP_Cluster_Core val5 = ((Il2CppObjectBase)((Il2CppArrayBase<iChainedPuzzleCore>)(object)val.m_chainedPuzzleCores)[puzzleIndex - 1]).TryCast<CP_Cluster_Core>();
					if ((Object)(object)val5 == (Object)null)
					{
						SPOLogger.Error($"Cannot cast m_chainedPuzzleCores[{puzzleIndex - 1}] to neither CP_Bioscan_Core or CP_Cluster_Core! WTF???");
					}
					else
					{
						prevPuzzlePos = ((Component)val5).transform.position;
					}
				}
			}
			if (@override != null)
			{
				if (@override.Position.ToVector3() != Vector3.zero || @override.Rotation.ToVector3() != Vector3.zero)
				{
					((Component)__instance).transform.SetPositionAndRotation(@override.Position.ToVector3(), @override.Rotation.ToQuaternion());
				}
				if (@override.RequiredItemsIndices != null && @override.RequiredItemsIndices.Count > 0)
				{
					PuzzleReqItemManager.Current.QueueForAddingReqItems(__instance, @override.RequiredItemsIndices);
				}
				if (@override.HideSpline)
				{
					revealWithHoloPath = false;
				}
				SPOLogger.Warning("Overriding CP_Cluster_Core!");
			}
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(CP_Cluster_Core), "Setup")]
		private static void Post_CP_Cluster_Core_Setup(CP_Cluster_Core __instance)
		{
			ChainedPuzzleInstance val = ((Il2CppObjectBase)__instance.m_owner).Cast<ChainedPuzzleInstance>();
			foreach (iChainedPuzzleCore item in (Il2CppArrayBase<iChainedPuzzleCore>)(object)__instance.m_childCores)
			{
				if (item.IsMovable && PuzzleOverrideManager.Current.GetBioscanCoreOverrideIndex(((Il2CppObjectBase)item).Pointer) != 0)
				{
					val.SetupMovement(((Component)((Il2CppObjectBase)item).Cast<CP_Bioscan_Core>()).gameObject, val.m_sourceArea);
				}
			}
			uint clusterCoreOverrideIndex = PuzzleOverrideManager.Current.GetClusterCoreOverrideIndex(__instance);
			if (clusterCoreOverrideIndex == 0)
			{
				return;
			}
			PuzzleOverride def = Plugin.GetOverride(PuzzleOverrideManager.MainLevelLayout, clusterCoreOverrideIndex);
			if (def == null)
			{
				return;
			}
			if (def.ConcurrentCluster)
			{
				if (2 <= ((Il2CppArrayBase<iChainedPuzzleCore>)(object)__instance.m_childCores).Count && ((Il2CppArrayBase<iChainedPuzzleCore>)(object)__instance.m_childCores).Count <= 4)
				{
					CP_Cluster_Hud val2 = ((Il2CppObjectBase)__instance.m_hud).Cast<CP_Cluster_Hud>();
					ConcurrentClusterHud concurrentClusterHud = ((Component)val2).gameObject.AddComponent<ConcurrentClusterHud>();
					concurrentClusterHud.parent = __instance;
					concurrentClusterHud.parentHud = ((Il2CppObjectBase)val2.m_hud).Cast<CP_Bioscan_Hud>();
					concurrentClusterHud.def = def;
					if (concurrentClusterHud.Setup())
					{
						PlayerScannerManager.Current.RegisterConcurrentCluster(__instance);
						SPOLogger.Warning("Setting up CP_Cluster_Core as Concurrent Cluster!");
					}
					else
					{
						SPOLogger.Warning("Concurrent Cluster: failed to setup");
					}
				}
				else
				{
					SPOLogger.Error("Trying to setup concurrent cluster, " + $"but the cluster scan has {((Il2CppArrayBase<iChainedPuzzleCore>)(object)__instance.m_childCores).Count}, which is senseless or is impossible for 4 players to complete");
				}
			}
			if (def.EventsOnClusterProgress.Count <= 0)
			{
				return;
			}
			foreach (iChainedPuzzleCore item2 in (Il2CppArrayBase<iChainedPuzzleCore>)(object)__instance.m_childCores)
			{
				item2.OnPuzzleDone += Action<int>.op_Implicit((Action<int>)CheckEventsOnClusterProgress);
			}
			void CheckEventsOnClusterProgress(int puzzleIndex)
			{
				int num = 0;
				for (int i = 0; i < ((Il2CppArrayBase<iChainedPuzzleCore>)(object)__instance.m_childCores).Length; i++)
				{
					if (((Il2CppArrayBase<iChainedPuzzleCore>)(object)__instance.m_childCores)[i].IsFinished())
					{
						num++;
					}
				}
				foreach (ClusterProgressEvent item3 in def.EventsOnClusterProgress)
				{
					if (item3.Count == num)
					{
						WardenObjectiveManager.CheckAndExecuteEventsOnTrigger(ListExtensions.ToIl2Cpp<WardenObjectiveEventData>(item3.Events), (eWardenObjectiveEventTrigger)0, true, 0f, (Il2CppStructArray<eWardenObjectiveEventType>)null);
					}
				}
			}
		}
	}
	[HarmonyPatch]
	internal class Patches_CP_Cluster_Hud_ReqItems
	{
		private static Dictionary<IntPtr, List<bool>> childrenReqItemEnabled { get; }

		private static Dictionary<IntPtr, List<string[]>> clustersChildrenReqItemNames { get; }

		private static Dictionary<IntPtr, List<Il2CppStructArray<bool>>> clustersChildrenReqItemsStatus { get; }

		[HarmonyPostfix]
		[HarmonyPatch(typeof(CP_Bioscan_Core), "AddRequiredItems")]
		private static void Post_CP_Bioscan_Core_AddRequiredItems(CP_Bioscan_Core __instance, Il2CppReferenceArray<iWardenObjectiveItem> requiredItems)
		{
			CP_Cluster_Core val = ((Il2CppObjectBase)__instance.Owner).TryCast<CP_Cluster_Core>();
			if ((Object)(object)val == (Object)null)
			{
				return;
			}
			if (__instance.m_hud == null)
			{
				SPOLogger.Error("CP_Cluster_Hud_ReqItems: replacement Cluster_hud is null.");
				return;
			}
			CP_Cluster_Hud val2 = ((Il2CppObjectBase)__instance.m_hud).Cast<CP_Cluster_Hud>();
			string[] array = new string[((Il2CppArrayBase<iWardenObjectiveItem>)(object)requiredItems).Count];
			for (int i = 0; i < __instance.m_reqItems.Count; i++)
			{
				if (__instance.m_reqItems[i] != null)
				{
					array[i] = __instance.m_reqItems[i].PublicName;
				}
				else
				{
					SPOLogger.Error("Post_CP_Bioscan_Core_AddRequiredItems: CP_Bioscan_Core " + ((Object)__instance).name + " has a missing m_reqItem! " + i);
				}
			}
			List<bool> list;
			List<string[]> list2;
			if (childrenReqItemEnabled.ContainsKey(((Il2CppObjectBase)val2).Pointer))
			{
				list = childrenReqItemEnabled[((Il2CppObjectBase)val2).Pointer];
				list2 = clustersChildrenReqItemNames[((Il2CppObjectBase)val2).Pointer];
			}
			else
			{
				list = Enumerable.Repeat(element: false, val.NRofPuzzles()).ToList();
				list2 = Enumerable.Repeat(new string[0], val.NRofPuzzles()).ToList();
				childrenReqItemEnabled.Add(((Il2CppObjectBase)val2).Pointer, list);
				clustersChildrenReqItemNames.Add(((Il2CppObjectBase)val2).Pointer, list2);
			}
			list[__instance.m_puzzleIndex] = __instance.m_reqItemsEnabled;
			list2[__instance.m_puzzleIndex] = array;
		}

		[HarmonyPrefix]
		[HarmonyPatch(typeof(CP_Cluster_Hud), "SetRequiredItemData")]
		private static bool Pre_CP_Cluster_Hud_SetRequiredItemData(CP_Cluster_Hud __instance, int puzzleIndex, Il2CppStructArray<bool> reqItemStatus)
		{
			List<Il2CppStructArray<bool>> list;
			if (!clustersChildrenReqItemsStatus.ContainsKey(((Il2CppObjectBase)__instance).Pointer))
			{
				list = Enumerable.Repeat<Il2CppStructArray<bool>>(null, __instance.m_clusterSize).ToList();
				clustersChildrenReqItemsStatus.Add(((Il2CppObjectBase)__instance).Pointer, list);
			}
			else
			{
				list = clustersChildrenReqItemsStatus[((Il2CppObjectBase)__instance).Pointer];
			}
			list[puzzleIndex] = reqItemStatus;
			return false;
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(CP_Cluster_Hud), "UpdateDataFor")]
		private static void Post_CP_Cluster_Hud_UpdateDataFor(CP_Cluster_Hud __instance, int index)
		{
			if (clustersChildrenReqItemsStatus.ContainsKey(((Il2CppObjectBase)__instance).Pointer))
			{
				if (!childrenReqItemEnabled.ContainsKey(((Il2CppObjectBase)__instance).Pointer) || !clustersChildrenReqItemNames.ContainsKey(((Il2CppObjectBase)__instance).Pointer))
				{
					SPOLogger.Error("CP_Cluster_Hud_UpdateDataFor: Found registered reqItemStatus but ReqItemEnabled or ReqItemNames is missing!");
					return;
				}
				Il2CppStructArray<bool> val = clustersChildrenReqItemsStatus[((Il2CppObjectBase)__instance).Pointer][index];
				__instance.m_hud.SetupRequiredItems(childrenReqItemEnabled[((Il2CppObjectBase)__instance).Pointer][index], Il2CppStringArray.op_Implicit(clustersChildrenReqItemNames[((Il2CppObjectBase)__instance).Pointer][index]));
				__instance.m_hud.SetRequiredItemData(__instance.m_puzzleIndex, val);
			}
		}

		private static void Clear()
		{
			clustersChildrenReqItemsStatus.Clear();
			clustersChildrenReqItemNames.Clear();
			childrenReqItemEnabled.Clear();
		}

		static Patches_CP_Cluster_Hud_ReqItems()
		{
			childrenReqItemEnabled = new Dictionary<IntPtr, List<bool>>();
			clustersChildrenReqItemNames = new Dictionary<IntPtr, List<string[]>>();
			clustersChildrenReqItemsStatus = new Dictionary<IntPtr, List<Il2CppStructArray<bool>>>();
			LevelAPI.OnLevelCleanup += Clear;
		}
	}
}
namespace ScanPosOverride.Managers
{
	public class PlayerScannerManager
	{
		private static readonly float[] ZERO_SCAN_SPEED;

		private Mutex CCStateMutex;

		private Dictionary<IntPtr, CP_PlayerScanner> ChildScanners = new Dictionary<IntPtr, CP_PlayerScanner>();

		public static PlayerScannerManager Current { get; }

		private Dictionary<IntPtr, List<CP_PlayerScanner>> CCCores { get; } = new Dictionary<IntPtr, List<CP_PlayerScanner>>();


		private Dictionary<IntPtr, HashSet<IntPtr>> CCChildren { get; } = new Dictionary<IntPtr, HashSet<IntPtr>>();


		private Dictionary<IntPtr, HashSet<IntPtr>> CCChildrenState { get; } = new Dictionary<IntPtr, HashSet<IntPtr>>();


		private Dictionary<IntPtr, float[]> OriginalClusterScanSpeeds { get; } = new Dictionary<IntPtr, float[]>();


		private Dictionary<IntPtr, float[]> OriginalScanSpeed { get; } = new Dictionary<IntPtr, float[]>();


		internal bool RegisterConcurrentCluster(CP_Cluster_Core core)
		{
			if (CCCores.ContainsKey(((Il2CppObjectBase)core).Pointer))
			{
				return false;
			}
			List<CP_PlayerScanner> list = Enumerable.Repeat<CP_PlayerScanner>(null, core.m_amountOfPuzzles).ToList();
			HashSet<IntPtr> hashSet = new HashSet<IntPtr>();
			for (int i = 0; i < ((Il2CppArrayBase<iChainedPuzzleCore>)(object)core.m_childCores).Count; i++)
			{
				if ((Object)(object)list[i] != (Object)null)
				{
					SPOLogger.Error("SetupConcurrentClusterScanners: Duplicate child scanner for child scan. ??");
					continue;
				}
				iChainedPuzzleCore val = ((Il2CppArrayBase<iChainedPuzzleCore>)(object)core.m_childCores)[i];
				CP_Bioscan_Core val2 = ((Il2CppObjectBase)val).TryCast<CP_Bioscan_Core>();
				if ((Object)(object)val2 == (Object)null)
				{
					SPOLogger.Error("SetupConcurrentClusterScanners: Failed to cast child to CP_Bioscan_Core");
					continue;
				}
				CP_PlayerScanner val3 = ((Il2CppObjectBase)val2.PlayerScanner).TryCast<CP_PlayerScanner>();
				if ((Object)(object)val3 == (Object)null)
				{
					SPOLogger.Error("SetupConcurrentClusterScanners: Failed to cast CP_Bioscan_Core.PlayerScanner to CP_PlayerScanner");
					continue;
				}
				list[i] = val3;
				ChildScanners.Add(((Il2CppObjectBase)val).Pointer, val3);
				hashSet.Add(((Il2CppObjectBase)val2).Pointer);
				if (!OriginalClusterScanSpeeds.ContainsKey(((Il2CppObjectBase)core).Pointer))
				{
					Il2CppStructArray<float> scanSpeeds = val3.m_scanSpeeds;
					float[] array = new float[((Il2CppArrayBase<float>)(object)scanSpeeds).Length];
					Array.Copy(Il2CppArrayBase<float>.op_Implicit((Il2CppArrayBase<float>)(object)scanSpeeds), array, ((Il2CppArrayBase<float>)(object)scanSpeeds).Length);
					OriginalClusterScanSpeeds.Add(((Il2CppObjectBase)core).Pointer, array);
				}
			}
			CCCores.Add(((Il2CppObjectBase)core).Pointer, list);
			CCChildren.Add(((Il2CppObjectBase)core).Pointer, hashSet);
			CCChildrenState.Add(((Il2CppObjectBase)core).Pointer, new HashSet<IntPtr>());
			return true;
		}

		internal bool IsConcurrentCluster(CP_Cluster_Core core)
		{
			return CCCores.ContainsKey(((Il2CppObjectBase)core).Pointer);
		}

		internal bool IsConcurrentCluster(CP_Bioscan_Core core)
		{
			return CCCores.ContainsKey(((Il2CppObjectBase)core.Owner).Pointer);
		}

		internal void ZeroCCScanSpeed(CP_Cluster_Core parent)
		{
			if (!CCCores.ContainsKey(((Il2CppObjectBase)parent).Pointer))
			{
				return;
			}
			foreach (CP_PlayerScanner item in CCCores[((Il2CppObjectBase)parent).Pointer])
			{
				bool flag = true;
				for (int i = 0; i < 4; i++)
				{
					flag = flag && ((Il2CppArrayBase<float>)(object)item.m_scanSpeeds)[i] == 0f;
					((Il2CppArrayBase<float>)(object)item.m_scanSpeeds)[i] = 0f;
				}
				if (flag)
				{
					break;
				}
			}
		}

		internal void RestoreCCScanSpeed(CP_Cluster_Core parent)
		{
			if (!CCCores.ContainsKey(((Il2CppObjectBase)parent).Pointer) || !OriginalClusterScanSpeeds.ContainsKey(((Il2CppObjectBase)parent).Pointer))
			{
				return;
			}
			float[] array = OriginalClusterScanSpeeds[((Il2CppObjectBase)parent).Pointer];
			foreach (CP_PlayerScanner item in CCCores[((Il2CppObjectBase)parent).Pointer])
			{
				bool flag = false;
				for (int i = 0; i < 4; i++)
				{
					flag = flag || ((Il2CppArrayBase<float>)(object)item.m_scanSpeeds)[i] != 0f;
					((Il2CppArrayBase<float>)(object)item.m_scanSpeeds)[i] = array[i];
				}
				if (flag)
				{
					break;
				}
			}
		}

		internal float[] GetCacheOriginalScanSpeed(CP_Bioscan_Core core)
		{
			if (IsConcurrentCluster(core))
			{
				if (!CCCores.ContainsKey(((Il2CppObjectBase)core.Owner).Pointer))
				{
					return ZERO_SCAN_SPEED;
				}
				return OriginalClusterScanSpeeds[((Il2CppObjectBase)core.Owner).Pointer];
			}
			if (OriginalScanSpeed.ContainsKey(((Il2CppObjectBase)core).Pointer))
			{
				return OriginalScanSpeed[((Il2CppObjectBase)core).Pointer];
			}
			CP_PlayerScanner cacheScanner = GetCacheScanner(core);
			if ((Object)(object)cacheScanner == (Object)null)
			{
				SPOLogger.Error("GetCacheOriginalScanSpeed: cannot get scanner for this CP_Bioscan_Core");
				return ZERO_SCAN_SPEED;
			}
			float[] array = new float[4];
			Array.Copy(Il2CppArrayBase<float>.op_Implicit((Il2CppArrayBase<float>)(object)cacheScanner.m_scanSpeeds), array, array.Length);
			OriginalScanSpeed.Add(((Il2CppObjectBase)core).Pointer, array);
			return array;
		}

		public CP_PlayerScanner GetCacheScanner(CP_Bioscan_Core core)
		{
			if (ChildScanners.ContainsKey(((Il2CppObjectBase)core).Pointer))
			{
				return ChildScanners[((Il2CppObjectBase)core).Pointer];
			}
			CP_PlayerScanner val = ((Il2CppObjectBase)core.PlayerScanner).TryCast<CP_PlayerScanner>();
			if ((Object)(object)val == (Object)null)
			{
				return null;
			}
			ChildScanners.Add(((Il2CppObjectBase)core).Pointer, val);
			return val;
		}

		internal bool CCShouldProgress(CP_Bioscan_Core child, bool IsThisScanShouldProgress)
		{
			if (CCStateMutex == null)
			{
				CCStateMutex = new Mutex();
			}
			if (CCStateMutex.WaitOne(2000))
			{
				if (!CCCores.ContainsKey(((Il2CppObjectBase)child.Owner).Pointer))
				{
					SPOLogger.Error("ConcurrentClusterShouldProgress: failed to find cluster parent!");
					CCStateMutex.ReleaseMutex();
					return false;
				}
				CP_Cluster_Core val = ((Il2CppObjectBase)child.Owner).Cast<CP_Cluster_Core>();
				if (!CCChildrenState.ContainsKey(((Il2CppObjectBase)val).Pointer))
				{
					SPOLogger.Error("ConcurrentClusterShouldProgress: ConcurrentClusterChildScanState initialization error!");
					CCStateMutex.ReleaseMutex();
					return false;
				}
				HashSet<IntPtr> hashSet = CCChildrenState[((Il2CppObjectBase)val).Pointer];
				bool result;
				if (IsThisScanShouldProgress)
				{
					hashSet.Add(((Il2CppObjectBase)child).Pointer);
					result = hashSet.Count == val.m_amountOfPuzzles;
				}
				else
				{
					hashSet.Remove(((Il2CppObjectBase)child).Pointer);
					result = false;
				}
				CCStateMutex.ReleaseMutex();
				return result;
			}
			SPOLogger.Debug("ConcurrentCluster: Failed to acquire scan mutex.");
			return false;
		}

		internal void CompleteConcurrentCluster(CP_Cluster_Core parent, CP_Bioscan_Core child)
		{
			if (CCChildren.ContainsKey(((Il2CppObjectBase)parent).Pointer))
			{
				HashSet<IntPtr> hashSet = CCChildren[((Il2CppObjectBase)parent).Pointer];
				hashSet.Remove(((Il2CppObjectBase)child).Pointer);
				if (hashSet.Count < 1)
				{
					CCChildren.Remove(((Il2CppObjectBase)parent).Pointer);
				}
			}
		}

		public List<CP_PlayerScanner> GetCCChildrenScanner(CP_Cluster_Core parent)
		{
			if (!CCCores.ContainsKey(((Il2CppObjectBase)parent).Pointer))
			{
				return null;
			}
			return CCCores[((Il2CppObjectBase)parent).Pointer];
		}

		public void Clear()
		{
			CCCores.Clear();
			CCChildren.Clear();
			CCChildrenState.Clear();
			OriginalClusterScanSpeeds.Clear();
			ChildScanners.Clear();
			OriginalScanSpeed.Clear();
			if (CCStateMutex != null)
			{
				CCStateMutex.Dispose();
			}
			CCStateMutex = null;
		}

		static PlayerScannerManager()
		{
			ZERO_SCAN_SPEED = new float[4];
			Current = new PlayerScannerManager();
			LevelAPI.OnLevelCleanup += Current.Clear;
		}

		private PlayerScannerManager()
		{
		}
	}
	public class PuzzleReqItemManager
	{
		public static readonly PuzzleReqItemManager Current;

		private Dictionary<int, CarryItemPickup_Core> BigPickupItemsInLevel = new Dictionary<int, CarryItemPickup_Core>();

		private int itemIndexCounter = 1;

		private List<(CP_Bioscan_Core, List<int>)> bioscanCoresToAddReqItems = new List<(CP_Bioscan_Core, List<int>)>();

		private List<(CP_Cluster_Core, List<int>)> clusterCoresToAddReqItems = new List<(CP_Cluster_Core, List<int>)>();

		private Dictionary<IntPtr, CP_Bioscan_Core> movableScansWithReqItems = new Dictionary<IntPtr, CP_Bioscan_Core>();

		internal int Register(CarryItemPickup_Core item)
		{
			int num = itemIndexCounter;
			itemIndexCounter++;
			BigPickupItemsInLevel.Add(num, item);
			return num;
		}

		internal void QueueForAddingReqItems(CP_Bioscan_Core core, List<int> itemsIndices)
		{
			bioscanCoresToAddReqItems.Add((core, itemsIndices));
		}

		internal void QueueForAddingReqItems(CP_Cluster_Core core, List<int> itemsIndices)
		{
			clusterCoresToAddReqItems.Add((core, itemsIndices));
		}

		internal CP_Bioscan_Core GetMovableCoreWithReqItem(CP_PlayerScanner scanner)
		{
			if (!movableScansWithReqItems.ContainsKey(((Il2CppObjectBase)scanner).Pointer))
			{
				return null;
			}
			return movableScansWithReqItems[((Il2CppObjectBase)scanner).Pointer];
		}

		public CarryItemPickup_Core GetBigPickupItem(int bigPickupInLevelIndex)
		{
			if (!BigPickupItemsInLevel.ContainsKey(bigPickupInLevelIndex))
			{
				return null;
			}
			return BigPickupItemsInLevel[bigPickupInLevelIndex];
		}

		public bool AddReqItems(CP_Bioscan_Core puzzle, int itemIndex)
		{
			//IL_0065: Unknown result type (might be due to invalid IL or missing references)
			//IL_006b: Expected O, but got Unknown
			if ((Object)(object)puzzle == (Object)null || itemIndex == 0L)
			{
				return false;
			}
			if (!BigPickupItemsInLevel.ContainsKey(itemIndex))
			{
				SPOLogger.Error($"Unregistered BigPickup Item with index {itemIndex}");
				return false;
			}
			CarryItemPickup_Core val = BigPickupItemsInLevel[itemIndex];
			puzzle.AddRequiredItems(Il2CppReferenceArray<iWardenObjectiveItem>.op_Implicit((iWardenObjectiveItem[])(object)new iWardenObjectiveItem[1]
			{
				new iWardenObjectiveItem(((Il2CppObjectBase)val).Pointer)
			}));
			return true;
		}

		public bool AddReqItems(CP_Cluster_Core puzzle, int itemIndex)
		{
			//IL_0078: Unknown result type (might be due to invalid IL or missing references)
			//IL_007e: Expected O, but got Unknown
			if ((Object)(object)puzzle == (Object)null || itemIndex == 0L)
			{
				return false;
			}
			if (!BigPickupItemsInLevel.ContainsKey(itemIndex))
			{
				SPOLogger.Error($"Unregistered BigPickup Item with index {itemIndex}");
				return false;
			}
			CarryItemPickup_Core val = BigPickupItemsInLevel[itemIndex];
			foreach (iChainedPuzzleCore item in (Il2CppArrayBase<iChainedPuzzleCore>)(object)puzzle.m_childCores)
			{
				item.AddRequiredItems(Il2CppReferenceArray<iWardenObjectiveItem>.op_Implicit((iWardenObjectiveItem[])(object)new iWardenObjectiveItem[1]
				{
					new iWardenObjectiveItem(((Il2CppObjectBase)val).Pointer)
				}));
			}
			return true;
		}

		public bool AddReqItems(CP_Bioscan_Core puzzle, List<int> itemsIndices)
		{
			if ((Object)(object)puzzle == (Object)null || itemsIndices == null || itemsIndices.Count < 1)
			{
				return false;
			}
			bool flag = false;
			foreach (int item in itemsIndices.ToHashSet())
			{
				flag |= AddReqItems(puzzle, item);
			}
			if (puzzle.IsMovable && flag)
			{
				movableScansWithReqItems.Add(((Il2CppObjectBase)puzzle.m_playerScanner).Pointer, puzzle);
			}
			return flag;
		}

		public void RemoveReqItem(CP_Bioscan_Core puzzle, int itemIndex)
		{
			//IL_0063: Unknown result type (might be due to invalid IL or missing references)
			//IL_0069: Expected O, but got Unknown
			if (!((Object)(object)puzzle == (Object)null))
			{
				if (!BigPickupItemsInLevel.ContainsKey(itemIndex) && itemIndex != 0L)
				{
					SPOLogger.Error($"Unregistered BigPickup Item with index {itemIndex}");
				}
				else
				{
					CarryItemPickup_Core val = BigPickupItemsInLevel[itemIndex];
					puzzle.RemoveRequiredItems((iWardenObjectiveItem[])(object)new iWardenObjectiveItem[1]
					{
						new iWardenObjectiveItem(((Il2CppObjectBase)val).Pointer)
					});
				}
			}
		}

		public void RemoveReqItem(CP_Cluster_Core puzzle, int itemIndex)
		{
			//IL_0076: Unknown result type (might be due to invalid IL or missing references)
			//IL_007c: Expected O, but got Unknown
			if ((Object)(object)puzzle == (Object)null)
			{
				return;
			}
			if (!BigPickupItemsInLevel.ContainsKey(itemIndex) && itemIndex != 0L)
			{
				SPOLogger.Error($"Unregistered BigPickup Item with index {itemIndex}");
				return;
			}
			CarryItemPickup_Core val = BigPickupItemsInLevel[itemIndex];
			foreach (iChainedPuzzleCore item in (Il2CppArrayBase<iChainedPuzzleCore>)(object)puzzle.m_childCores)
			{
				item.RemoveRequiredItems((iWardenObjectiveItem[])(object)new iWardenObjectiveItem[1]
				{
					new iWardenObjectiveItem(((Il2CppObjectBase)val).Pointer)
				});
			}
		}

		private void AddQueuedReqItems()
		{
			foreach (var (puzzle, itemsIndices) in bioscanCoresToAddReqItems)
			{
				AddReqItems(puzzle, itemsIndices);
			}
			foreach (var (val, itemsIndices2) in clusterCoresToAddReqItems)
			{
				foreach (iChainedPuzzleCore item in (Il2CppArrayBase<iChainedPuzzleCore>)(object)val.m_childCores)
				{
					CP_Bioscan_Core val2 = ((Il2CppObjectBase)item).TryCast<CP_Bioscan_Core>();
					if ((Object)(object)val2 == (Object)null)
					{
						SPOLogger.Error("Failed to cast child core to CP_Bioscan_Core");
					}
					else
					{
						AddReqItems(val2, itemsIndices2);
					}
				}
			}
		}

		public void OutputLevelBigPickupInfo()
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: Expected O, but got Unknown
			//IL_010a: Unknown result type (might be due to invalid IL or missing references)
			//IL_012e: Unknown result type (might be due to invalid IL or missing references)
			StringBuilder val = new StringBuilder();
			val.AppendLine();
			List<CarryItemPickup_Core> list = new List<CarryItemPickup_Core>(BigPickupItemsInLevel.Values);
			list.Sort(delegate(CarryItemPickup_Core b1, CarryItemPickup_Core b2)
			{
				//IL_0014: 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_0043: 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_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_0068: Unknown result type (might be due to invalid IL or missing references)
				//IL_0073: Unknown result type (might be due to invalid IL or missing references)
				//IL_0051: Unknown result type (might be due to invalid IL or missing references)
				//IL_0057: Unknown result type (might be due to invalid IL or missing references)
				//IL_0080: Unknown result type (might be due to invalid IL or missing references)
				//IL_008b: Unknown result type (might be due to invalid IL or missing references)
				AIG_CourseNode spawnNode = b1.SpawnNode;
				AIG_CourseNode spawnNode2 = b2.SpawnNode;
				if (spawnNode.m_dimension.DimensionIndex != spawnNode2.m_dimension.DimensionIndex)
				{
					if (spawnNode.m_dimension.DimensionIndex > spawnNode2.m_dimension.DimensionIndex)
					{
						return 1;
					}
					return -1;
				}
				if (spawnNode.LayerType != spawnNode2.LayerType)
				{
					if (spawnNode.LayerType >= spawnNode2.LayerType)
					{
						return 1;
					}
					return -1;
				}
				return (spawnNode.m_zone.LocalIndex != spawnNode2.m_zone.LocalIndex) ? ((spawnNode.m_zone.LocalIndex >= spawnNode2.m_zone.LocalIndex) ? 1 : (-1)) : 0;
			});
			Dictionary<CarryItemPickup_Core, int> dictionary = new Dictionary<CarryItemPickup_Core, int>();
			foreach (int key in BigPickupItemsInLevel.Keys)
			{
				dictionary.Add(BigPickupItemsInLevel[key], key);
			}
			foreach (CarryItemPickup_Core item in list)
			{
				val.AppendLine("Item Name: " + ((Item)item).ItemDataBlock.publicName);
				val.AppendLine($"Zone {item.SpawnNode.m_zone.Alias}, {item.SpawnNode.LayerType}, Dim {item.SpawnNode.m_dimension.DimensionIndex}");
				val.AppendLine($"Item Index: {dictionary[item]}");
				val.AppendLine();
			}
			SPOLogger.Debug(((Object)val).ToString());
		}

		internal void OnEnterLevel()
		{
			AddQueuedReqItems();
			OutputLevelBigPickupInfo();
		}

		public void Clear()
		{
			BigPickupItemsInLevel.Clear();
			itemIndexCounter = 1;
			bioscanCoresToAddReqItems.Clear();
			clusterCoresToAddReqItems.Clear();
			movableScansWithReqItems.Clear();
		}

		static PuzzleReqItemManager()
		{
			Current = new PuzzleReqItemManager();
			LevelAPI.OnLevelCleanup += Current.Clear;
			LevelAPI.OnEnterLevel += Current.OnEnterLevel;
		}

		private PuzzleReqItemManager()
		{
		}
	}
	public class PuzzleOverrideManager
	{
		public static readonly PuzzleOverrideManager Current;

		private uint puzzleOverrideIndex = 1u;

		public static uint MainLevelLayout => RundownManager.ActiveExpedition.LevelLayoutData;

		private Dictionary<IntPtr, uint> bioscanIndex { get; } = new Dictionary<IntPtr, uint>();


		private Dictionary<IntPtr, uint> clusterIndex { get; } = new Dictionary<IntPtr, uint>();


		private Dictionary<uint, CP_Bioscan_Core> index2Bioscan { get; } = new Dictionary<uint, CP_Bioscan_Core>();


		private Dictionary<uint, CP_Cluster_Core> index2Cluster { get; } = new Dictionary<uint, CP_Cluster_Core>();


		public uint Register(CP_Bioscan_Core __instance)
		{
			if ((Object)(object)__instance == (Object)null)
			{
				return 0u;
			}
			uint num = puzzleOverrideIndex;
			puzzleOverrideIndex++;
			if (!bioscanIndex.ContainsKey(((Il2CppObjectBase)__instance).Pointer))
			{
				bioscanIndex.Add(((Il2CppObjectBase)__instance).Pointer, num);
				index2Bioscan.Add(num, __instance);
				return num;
			}
			return GetBioscanCoreOverrideIndex(__instance);
		}

		public uint Register(CP_Cluster_Core __instance)
		{
			if ((Object)(object)__instance == (Object)null)
			{
				return 0u;
			}
			uint num = puzzleOverrideIndex;
			puzzleOverrideIndex++;
			if (!clusterIndex.ContainsKey(((Il2CppObjectBase)__instance).Pointer))
			{
				clusterIndex.Add(((Il2CppObjectBase)__instance).Pointer, num);
				index2Cluster.Add(num, __instance);
				return num;
			}
			return GetClusterCoreOverrideIndex(__instance);
		}

		public void OutputLevelPuzzleInfo()
		{
			//IL_00bd: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d7: Unknown result type (might be due to invalid IL or missing references)
			//IL_0234: Unknown result type (might be due to invalid IL or missing references)
			//IL_045d: Unknown result type (might be due to invalid IL or missing references)
			List<ChainedPuzzleInstance> list = new List<ChainedPuzzleInstance>();
			Enumerator<ChainedPuzzleInstance> enumerator = ChainedPuzzleManager.Current.m_instances.GetEnumerator();
			while (enumerator.MoveNext())
			{
				ChainedPuzzleInstance current = enumerator.Current;
				list.Add(current);
			}
			list.Sort(delegate(ChainedPuzzleInstance c1, ChainedPuzzleInstance c2)
			{
				//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_003e: 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_0027: Unknown result type (might be due to invalid IL or missing references)
				//IL_002d: Unknown result type (might be due to invalid IL or missing references)
				//IL_006d: Unknown result type (might be due to invalid IL or missing references)
				//IL_0073: Unknown result type (might be due to invalid IL or missing references)
				//IL_0056: Unknown result type (might be due to invalid IL or missing references)
				//IL_0061: Unknown result type (might be due to invalid IL or missing references)
				LG_Zone zone2 = c1.m_sourceArea.m_zone;
				LG_Zone zone3 = c2.m_sourceArea.m_zone;
				if (zone2.DimensionIndex != zone3.DimensionIndex)
				{
					if (zone2.DimensionIndex >= zone3.DimensionIndex)
					{
						return 1;
					}
					return -1;
				}
				if (zone2.Layer.m_type != zone3.Layer.m_type)
				{
					if (zone2.Layer.m_type >= zone3.Layer.m_type)
					{
						return 1;
					}
					return -1;
				}
				return (zone2.LocalIndex >= zone3.LocalIndex) ? 1 : (-1);
			});
			StringBuilder stringBuilder = new StringBuilder();
			foreach (ChainedPuzzleInstance item in list)
			{
				LG_Zone zone = item.m_sourceArea.m_zone;
				StringBuilder stringBuilder2 = stringBuilder;
				StringBuilder stringBuilder3 = stringBuilder2;
				StringBuilder.AppendInterpolatedStringHandler handler = new StringBuilder.AppendInterpolatedStringHandler(15, 3, stringBuilder2);
				handler.AppendLiteral("\nZone ");
				handler.AppendFormatted(zone.Alias);
				handler.AppendLiteral(", ");
				handler.AppendFormatted<LG_LayerType>(zone.m_layer.m_type);
				handler.AppendLiteral(", Dim ");
				handler.AppendFormatted<eDimensionIndex>(zone.DimensionIndex);
				handler.AppendLiteral("\n");
				stringBuilder3.Append(ref handler);
				stringBuilder2 = stringBuilder;
				StringBuilder stringBuilder4 = stringBuilder2;
				handler = new StringBuilder.AppendInterpolatedStringHandler(14, 1, stringBuilder2);
				handler.AppendLiteral("Alarm name: ");
				handler.AppendFormatted(item.Data.PublicAlarmName);
				handler.AppendLiteral(":\n");
				stringBuilder4.Append(ref handler);
				for (int i = 0; i < ((Il2CppArrayBase<iChainedPuzzleCore>)(object)item.m_chainedPuzzleCores).Count; i++)
				{
					iChainedPuzzleCore val = ((Il2CppArrayBase<iChainedPuzzleCore>)(object)item.m_chainedPuzzleCores)[i];
					if (bioscanIndex.ContainsKey(((Il2CppObjectBase)val).Pointer))
					{
						uint value = bioscanIndex[((Il2CppObjectBase)val).Pointer];
						stringBuilder2 = stringBuilder;
						StringBuilder stringBuilder5 = stringBuilder2;
						handler = new StringBuilder.AppendInterpolatedStringHandler(15, 1, stringBuilder2);
						handler.AppendLiteral("puzzle index: ");
						handler.AppendFormatted(i);
						handler.AppendLiteral("\n");
						stringBuilder5.Append(ref handler);
						stringBuilder.Append("type: CP_Bioscan_Core\n");
						stringBuilder2 = stringBuilder;
						StringBuilder stringBuilder6 = stringBuilder2;
						handler = new StringBuilder.AppendInterpolatedStringHandler(22, 1, stringBuilder2);
						handler.AppendLiteral("PuzzleOverrideIndex: ");
						handler.AppendFormatted(value);
						handler.AppendLiteral("\n");
						stringBuilder6.Append(ref handler);
						CP_Bioscan_Core val2 = ((Il2CppObjectBase)val).Cast<CP_Bioscan_Core>();
						CP_PlayerScanner val3 = ((Il2CppObjectBase)val2.PlayerScanner).Cast<CP_PlayerScanner>();
						stringBuilder2 = stringBuilder;
						StringBuilder stringBuilder7 = stringBuilder2;
						handler = new StringBuilder.AppendInterpolatedStringHandler(11, 1, stringBuilder2);
						handler.AppendLiteral("Position: ");
						handler.AppendFormatted<Vector3>(val2.m_position);
						handler.AppendLiteral("\n");
						stringBuilder7.Append(ref handler);
						stringBuilder2 = stringBuilder;
						StringBuilder stringBuilder8 = stringBuilder2;
						handler = new StringBuilder.AppendInterpolatedStringHandler(9, 1, stringBuilder2);
						handler.AppendLiteral("Radius: ");
						handler.AppendFormatted(val3.Radius);
						handler.AppendLiteral("\n");
						stringBuilder8.Append(ref handler);
					}
					else if (clusterIndex.ContainsKey(((Il2CppObjectBase)val).Pointer))
					{
						uint value2 = clusterIndex[((Il2CppObjectBase)val).Pointer];
						CP_Cluster_Core val4 = ((Il2CppObjectBase)val).Cast<CP_Cluster_Core>();
						stringBuilder2 = stringBuilder;
						StringBuilder stringBuilder9 = stringBuilder2;
						handler = new StringBuilder.AppendInterpolatedStringHandler(15, 1, stringBuilder2);
						handler.AppendLiteral("puzzle index: ");
						handler.AppendFormatted(i);
						handler.AppendLiteral("\n");
						stringBuilder9.Append(ref handler);
						stringBuilder.Append("type: CP_Cluster_Core\n");
						stringBuilder2 = stringBuilder;
						StringBuilder stringBuilder10 = stringBuilder2;
						handler = new StringBuilder.AppendInterpolatedStringHandler(22, 1, stringBuilder2);
						handler.AppendLiteral("PuzzleOverrideIndex: ");
						handler.AppendFormatted(value2);
						handler.AppendLiteral("\n");
						stringBuilder10.Append(ref handler);
						stringBuilder.Append("=== Clustered puzzles info: ===\n");
						for (int j = 0; j < val4.m_amountOfPuzzles; j++)
						{
							iChainedPuzzleCore val5 = ((Il2CppArrayBase<iChainedPuzzleCore>)(object)val4.m_childCores)[j];
							if (!bioscanIndex.ContainsKey(((Il2CppObjectBase)val5).Pointer))
							{
								SPOLogger.Error("Unregistered clustered iChainedPuzzleCore found...");
								continue;
							}
							uint value3 = bioscanIndex[((Il2CppObjectBase)val5).Pointer];
							stringBuilder2 = stringBuilder;
							StringBuilder stringBuilder11 = stringBuilder2;
							handler = new StringBuilder.AppendInterpolatedStringHandler(15, 1, stringBuilder2);
							handler.AppendLiteral("puzzle index: ");
							handler.AppendFormatted(j);
							handler.AppendLiteral("\n");
							stringBuilder11.Append(ref handler);
							stringBuilder.Append("type: CP_Bioscan_Core\n");
							stringBuilder2 = stringBuilder;
							StringBuilder stringBuilder12 = stringBuilder2;
							handler = new StringBuilder.AppendInterpolatedStringHandler(22, 1, stringBuilder2);
							handler.AppendLiteral("PuzzleOverrideIndex: ");
							handler.AppendFormatted(value3);
							handler.AppendLiteral("\n");
							stringBuilder12.Append(ref handler);
							CP_Bioscan_Core val6 = ((Il2CppObjectBase)val5).Cast<CP_Bioscan_Core>();
							CP_PlayerScanner val7 = ((Il2CppObjectBase)val6.PlayerScanner).Cast<CP_PlayerScanner>();
							stringBuilder2 = stringBuilder;
							StringBuilder stringBuilder13 = stringBuilder2;
							handler = new StringBuilder.AppendInterpolatedStringHandler(11, 1, stringBuilder2);
							handler.AppendLiteral("Position: ");
							handler.AppendFormatted<Vector3>(val6.m_position);
							handler.AppendLiteral("\n");
							stringBuilder13.Append(ref handler);
							stringBuilder2 = stringBuilder;
							StringBuilder stringBuilder14 = stringBuilder2;
							handler = new StringBuilder.AppendInterpolatedStringHandler(9, 1, stringBuilder2);
							handler.AppendLiteral("Radius: ");
							handler.AppendFormatted(val7.Radius);
							handler.AppendLiteral("\n");
							stringBuilder14.Append(ref handler);
						}
						stringBuilder.Append("=== Clustered puzzles END ===\n");
					}
					else
					{
						SPOLogger.Error("Unregistered iChainedPuzzleCore found...");
					}
				}
				stringBuilder.Append('\n');
			}
			SPOLogger.Debug(stringBuilder.ToString());
		}

		public uint GetBioscanCoreOverrideIndex(CP_Bioscan_Core core)
		{
			if (bioscanIndex.ContainsKey(((Il2CppObjectBase)core).Pointer))
			{
				return bioscanIndex[((Il2CppObjectBase)core).Pointer];
			}
			return 0u;
		}

		public uint GetClusterCoreOverrideIndex(CP_Cluster_Core core)
		{
			if (clusterIndex.ContainsKey(((Il2CppObjectBase)core).Pointer))
			{
				return clusterIndex[((Il2CppObjectBase)core).Pointer];
			}
			return 0u;
		}

		public uint GetBioscanCoreOverrideIndex(IntPtr pointer)
		{
			if (bioscanIndex.ContainsKey(pointer))
			{
				return bioscanIndex[pointer];
			}
			return 0u;
		}

		public uint GetClusterCoreOverrideIndex(IntPtr pointer)
		{
			if (clusterIndex.ContainsKey(pointer))
			{
				return clusterIndex[pointer];
			}
			return 0u;
		}

		public CP_Bioscan_Core GetBioscanCore(uint puzzleOverrideIndex)
		{
			if (!index2Bioscan.ContainsKey(puzzleOverrideIndex))
			{
				return null;
			}
			return index2Bioscan[puzzleOverrideIndex];
		}

		public CP_Cluster_Core GetClusterCore(uint puzzleOverrideIndex)
		{
			if (!index2Cluster.ContainsKey(puzzleOverrideIndex))
			{
				return null;
			}
			return index2Cluster[puzzleOverrideIndex];
		}

		public void Clear()
		{
			puzzleOverrideIndex = 1u;
			bioscanIndex.Clear();
			clusterIndex.Clear();
			index2Bioscan.Clear();
			index2Cluster.Clear();
		}

		private PuzzleOverrideManager()
		{
		}

		static PuzzleOverrideManager()
		{
			Current = new PuzzleOverrideManager();
			LevelAPI.OnEnterLevel += Current.OutputLevelPuzzleInfo;
			LevelAPI.OnBuildStart += Current.Clear;
			LevelAPI.OnLevelCleanup += Current.Clear;
		}

		public iChainedPuzzleOwner ChainedPuzzleInstanceOwner(CP_Bioscan_Core bioscanCore)
		{
			if ((Object)(object)bioscanCore == (Object)null)
			{
				return null;
			}
			iChainedPuzzleOwner owner = bioscanCore.Owner;
			if ((Object)(object)((Il2CppObjectBase)owner).TryCast<ChainedPuzzleInstance>() != (Object)null)
			{
				return owner;
			}
			CP_Cluster_Core val = ((Il2CppObjectBase)owner).TryCast<CP_Cluster_Core>();
			if ((Object)(object)val != (Object)null)
			{
				return val.m_owner;
			}
			SPOLogger.Error("Failed to find CP_BioScan_Core owner (instance of ChainedPuzzleInstance).");
			return null;
		}
	}
}
namespace ScanPosOverride.JSON
{
	public static class InjectLibUtil
	{
		public const string PLUGIN_GUID = "GTFO.InjectLib";

		public static JsonConverter InjectLibConnector { get; private set; }

		public static bool IsLoaded { get; private set; }

		static InjectLibUtil()
		{
			if (!((BaseChainloader<BasePlugin>)(object)IL2CPPChainloader.Instance).Plugins.TryGetValue("GTFO.InjectLib", out var value))
			{
				return;
			}
			try
			{
				Assembly obj = ((value == null) ? null : value.Instance?.GetType()?.Assembly) ?? null;
				if ((object)obj == null)
				{
					throw new Exception("Assembly is Missing!");
				}
				InjectLibConnector = (JsonConverter)Activator.CreateInstance(obj.GetTypes().First((Type t) => t.Name == "InjectLibConnector") ?? throw new Exception("Unable to Find InjectLibConnector Class"));
				IsLoaded = true;
			}
			catch (Exception value2)
			{
				SPOLogger.Error($"Exception thrown while reading data from GTFO.AWO: {value2}");
			}
		}
	}
	internal class LocalizedTextConverter : JsonConverter<LocalizedText>
	{
		public override bool HandleNull => false;

		public override LocalizedText Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
		{
			//IL_0018: Unknown result type (might be due to invalid IL or missing references)
			//IL_001d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002c: Expected O, but got Unknown
			//IL_002c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0031: 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_0045: Expected O, but got Unknown
			switch (reader.TokenType)
			{
			case JsonTokenType.String:
			{
				string @string = reader.GetString();
				return new LocalizedText
				{
					Id = 0u,
					UntranslatedText = @string
				};
			}
			case JsonTokenType.Number:
				return new LocalizedText
				{
					Id = reader.GetUInt32(),
					UntranslatedText = null
				};
			default:
				throw new JsonException($"LocalizedTextJson type: {reader.TokenType} is not implemented!");
			}
		}

		public override void Write(Utf8JsonWriter writer, LocalizedText value, JsonSerializerOptions options)
		{
			JsonSerializer.Serialize<LocalizedText>(writer, value, options);
		}
	}
	public sealed class MyVector3Converter : JsonConverter<Vector3>
	{
		public override bool HandleNull => false;

		public override Vector3 Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			//IL_0114: 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_0065: Unknown result type (might be due to invalid IL or missing references)
			Vector3 vector = Vector3.zero;
			switch (reader.TokenType)
			{
			case JsonTokenType.StartObject:
			{
				int currentDepth = reader.CurrentDepth;
				while (reader.Read())
				{
					if (reader.TokenType == JsonTokenType.EndObject && reader.CurrentDepth == currentDepth)
					{
						SPOLogger.Warning($"Parsed Vector3 : {vector}");
						return vector;
					}
					if (reader.TokenType != JsonTokenType.PropertyName)
					{
						throw new JsonException("Expected PropertyName token");
					}
					string? @string = reader.GetString();
					reader.Read();
					switch (@string.ToLowerInvariant())
					{
					case "x":
						vector.x = reader.GetSingle();
						break;
					case "y":
						vector.y = reader.GetSingle();
						break;
					case "z":
						vector.z = reader.GetSingle();
						break;
					}
				}
				throw new JsonException("Expected EndObject token");
			}
			case JsonTokenType.String:
			{
				string text = reader.GetString().Trim();
				if (TryParseVector3(text, out vector))
				{
					return vector;
				}
				throw new JsonException("Vector3 format is not right: " + text);
			}
			default:
				throw new JsonException($"Vector3Json type: {reader.TokenType} is not implemented!");
			}
		}

		private static bool TryParseVector3(string input, out Vector3 vector)
		{
			//IL_000b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_0034: Unknown result type (might be due to invalid IL or missing references)
			//IL_0039: Unknown result type (might be due to invalid IL or missing references)
			//IL_001e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			float[] array = default(float[]);
			if (!RegexUtils.TryParseVectorString(input, ref array))
			{
				vector = Vector3.zero;
				return false;
			}
			if (array.Length < 3)
			{
				vector = Vector3.zero;
				return false;
			}
			vector = new Vector3(array[0], array[1], array[2]);
			return true;
		}

		public override void Write(Utf8JsonWriter writer, Vector3 value, JsonSerializerOptions options)
		{
			//IL_0018: Unknown result type (might be due to invalid IL or missing references)
			//IL_0031: Unknown result type (might be due to invalid IL or missing references)
			//IL_004a: Unknown result type (might be due to invalid IL or missing references)
			writer.WriteStringValue($"({value.x} {value.y} {value.z})");
		}
	}
	internal static class Json
	{
		private static readonly JsonSerializerOptions _setting;

		static Json()
		{
			_setting = new JsonSerializerOptions
			{
				ReadCommentHandling = JsonCommentHandling.Skip,
				IncludeFields = false,
				PropertyNameCaseInsensitive = true,
				WriteIndented = true,
				IgnoreReadOnlyProperties = true
			};
			_setting.Converters.Add(new JsonStringEnumConverter());
			_setting.Converters.Add(new MyVector3Converter());
			if (MTFOPartialDataUtil.IsLoaded && MTFOPartialDataUtil.Initialized)
			{
				_setting.Converters.Add(MTFOPartialDataUtil.PersistentIDConverter);
				_setting.Converters.Add(MTFOPartialDataUtil.LocalizedTextConverter);
				SPOLogger.Log("PartialData Support Found!");
			}
			else
			{
				_setting.Converters.Add(new LocalizedTextConverter());
			}
			if (InjectLibUtil.IsLoaded)
			{
				_setting.Converters.Add(InjectLibUtil.InjectLibConnector);
				SPOLogger.Log("InjectLib (AWO) support found!");
			}
		}

		public static T Deserialize<T>(string json)
		{
			return JsonSerializer.Deserialize<T>(json, _setting);
		}

		public static object Deserialize(Type type, string json)
		{
			return JsonSerializer.Deserialize(json, type, _setting);
		}

		public static string Serialize<T>(T value)
		{
			return JsonSerializer.Serialize(value, _setting);
		}

		public static void Load<T>(string file, out T config) where T : new()
		{
			if (file.Length < ".json".Length)
			{
				config = default(T);
				return;
			}
			if (file.Substring(file.Length - ".json".Length) != ".json")
			{
				file += ".json";
			}
			file = File.ReadAllText(Path.Combine(Plugin.OVERRIDE_SCAN_POS_PATH, file));
			config = Deserialize<T>(file);
		}
	}
	public static class MTFOPartialDataUtil
	{
		public const string PLUGIN_GUID = "MTFO.Extension.PartialBlocks";

		public static JsonConverter PersistentIDConverter { get; private set; }

		public static JsonConverter LocalizedTextConverter { get; private set; }

		public static bool IsLoaded { get; private set; }

		public static bool Initialized { get; private set; }

		public static string PartialDataPath { get; private set; }

		public static string ConfigPath { get; private set; }

		static MTFOPartialDataUtil()
		{
			PersistentIDConverter = null;
			LocalizedTextConverter = null;
			IsLoaded = false;
			Initialized = false;
			PartialDataPath = string.Empty;
			ConfigPath = string.Empty;
			if (!((BaseChainloader<BasePlugin>)(object)IL2CPPChainloader.Instance).Plugins.TryGetValue("MTFO.Extension.PartialBlocks", out var value))
			{
				return;
			}
			try
			{
				Assembly obj = ((value == null) ? null : value.Instance?.GetType()?.Assembly) ?? null;
				if ((object)obj == null)
				{
					throw new Exception("Assembly is Missing!");
				}
				Type[] types = obj.GetTypes();
				Type type = types.First((Type t) => t.Name == "PersistentIDConverter");
				if ((object)type == null)
				{
					throw new Exception("Unable to Find PersistentIDConverter Class");
				}
				Type type2 = types.First((Type t) => t.Name == "PartialDataManager");
				if ((object)type2 == null)
				{
					throw new Exception("Unable to Find PartialDataManager Class");
				}
				Type type3 = types.First((Type t) => t.Name == "LocalizedTextConverter") ?? throw new Exception("Unable to Find LocalizedTextConverter Class");
				PropertyInfo property = type2.GetProperty("Initialized", BindingFlags.Static | BindingFlags.Public);
				PropertyInfo property2 = type2.GetProperty("PartialDataPath", BindingFlags.Static | BindingFlags.Public);
				PropertyInfo? property3 = type2.GetProperty("ConfigPath", BindingFlags.Static | BindingFlags.Public);
				if ((object)property == null)
				{
					throw new Exception("Unable to Find Property: Initialized");
				}
				if ((object)property2 == null)
				{
					throw new Exception("Unable to Find Property: PartialDataPath");
				}
				if ((object)property3 == null)
				{
					throw new Exception("Unable to Find Field: ConfigPath");
				}
				Initialized = (bool)property.GetValue(null);
				PartialDataPath = (string)property2.GetValue(null);
				ConfigPath = (string)property3.GetValue(null);
				PersistentIDConverter = (JsonConverter)Activator.CreateInstance(type);
				LocalizedTextConverter = (JsonConverter)Activator.CreateInstance(type3);
				IsLoaded = true;
			}
			catch (Exception value2)
			{
				SPOLogger.Error($"Exception thrown while reading data from MTFO_Extension_PartialData:\n{value2}");
			}
		}
	}
	public static class MTFOUtil
	{
		public const string PLUGIN_GUID = "com.dak.MTFO";

		public const BindingFlags PUBLIC_STATIC = BindingFlags.Static | BindingFlags.Public;

		public static string GameDataPath { get; private set; }

		public static string CustomPath { get; private set; }

		public static bool HasCustomContent { get; private set; }

		public static bool IsLoaded { get; private set; }

		static MTFOUtil()
		{
			GameDataPath = string.Empty;
			CustomPath = string.Empty;
			HasCustomContent = false;
			IsLoaded = false;
			if (!((BaseChainloader<BasePlugin>)(object)IL2CPPChainloader.Instance).Plugins.TryGetValue("com.dak.MTFO", out var value))
			{
				return;
			}
			try
			{
				Assembly obj = ((value == null) ? null : value.Instance?.GetType()?.Assembly) ?? null;
				if ((object)obj == null)
				{
					throw new Exception("Assembly is Missing!");
				}
				Type obj2 = obj.GetTypes().First((Type t) => t.Name == "ConfigManager") ?? throw new Exception("Unable to Find ConfigManager Class");
				FieldInfo field = obj2.GetField("GameDataPath", BindingFlags.Static | BindingFlags.Public);
				FieldInfo field2 = obj2.GetField("CustomPath", BindingFlags.Static | BindingFlags.Public);
				FieldInfo? field3 = obj2.GetField("HasCustomContent", BindingFlags.Static | BindingFlags.Public);
				if ((object)field == null)
				{
					throw new Exception("Unable to Find Field: GameDataPath");
				}
				if ((object)field2 == null)
				{
					throw new Exception("Unable to Find Field: CustomPath");
				}
				if ((object)field3 == null)
				{
					throw new Exception("Unable to Find Field: HasCustomContent");
				}
				GameDataPath = (string)field.GetValue(null);
				CustomPath = (string)field2.GetValue(null);
				HasCustomContent = (bool)field3.GetValue(null);
				IsLoaded = true;
			}
			catch (Exception value2)
			{
				SPOLogger.Error($"Exception thrown while reading path from DataDumper (MTFO): \n{value2}");
			}
		}
	}
}
namespace ScanPosOverride.Component
{
	internal class ConcurrentClusterHud : MonoBehaviour
	{
		public enum PlayerCountRequirement
		{
			INVALID,
			ANY,
			SOLO,
			DUO
		}

		private StringBuilder displayText = new StringBuilder();

		private bool m_isValid;

		private List<CP_Bioscan_Core> children;

		private float childRadius = -1f;

		private int[] playerInScanCount;

		private readonly string[] ROMAN = new string[4] { "I", "II", "III", "IV" };

		internal CP_Cluster_Core parent { get; set; }

		internal CP_Bioscan_Hud parentHud { get; set; }

		internal PuzzleOverride def { get; set; }

		public PlayerCountRequirement playerCountReq { get; private set; }

		private PlayerCountRequirement ReqPlayerCount(iChainedPuzzleCore child)
		{
			//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_001d: Unknown result type (might be due to invalid IL or missing references)
			//IL_002f: Expected I4, but got Unknown
			CP_PlayerScanner obj = ((Il2CppObjectBase)((Il2CppObjectBase)child).Cast<CP_Bioscan_Core>().m_playerScanner).Cast<CP_PlayerScanner>();
			PlayerRequirement playerRequirement = obj.m_playerRequirement;
			Il2CppStructArray<float> scanSpeeds = obj.m_scanSpeeds;
			switch ((int)playerRequirement)
			{
			case 2:
				if (!(((Il2CppArrayBase<float>)(object)scanSpeeds)[0] > 0f))
				{
					return PlayerCountRequirement.INVALID;
				}
				return PlayerCountRequirement.SOLO;
			case 0:
			{
				int i;
				for (i = 0; i < ((Il2CppArrayBase<float>)(object)scanSpeeds).Count && ((Il2CppArrayBase<float>)(object)scanSpeeds)[i] == 0f; i++)
				{
				}
				if (i >= 2)
				{
					return PlayerCountRequirement.INVALID;
				}
				if (i == 1)
				{
					return PlayerCountRequirement.DUO;
				}
				if (!(((Il2CppArrayBase<float>)(object)scanSpeeds)[i + 1] > 0f))
				{
					return PlayerCountRequirement.SOLO;
				}
				return PlayerCountRequirement.ANY;
			}
			default:
				return PlayerCountRequirement.INVALID;
			}
		}

		internal bool Setup()
		{
			if (((Il2CppArrayBase<iChainedPuzzleCore>)(object)parent.m_childCores).Count < 2 || ((Il2CppArrayBase<iChainedPuzzleCore>)(object)parent.m_childCores).Count > 4)
			{
				SPOLogger.Error($"ConcurrentClusterHud: got cluster scan with {((Il2CppArrayBase<iChainedPuzzleCore>)(object)parent.m_childCores).Count} children, which is invalid for concurrent cluster");
				return false;
			}
			playerCountReq = ReqPlayerCount(((Il2CppArrayBase<iChainedPuzzleCore>)(object)parent.m_childCores)[0]);
			if (playerCountReq == PlayerCountRequirement.INVALID)
			{
				SPOLogger.Error($"ConcurrentCluster setup: playerRequirement is {1}, which is invalid for concurrent cluster");
				return false;
			}
			switch (((Il2CppArrayBase<iChainedPuzzleCore>)(object)parent.m_childCores).Count)
			{
			case 2:
				switch (playerCountReq)
				{
				case PlayerCountRequirement.ANY:
				case PlayerCountRequirement.SOLO:
					m_isValid = true;
					break;
				case PlayerCountRequirement.DUO:
					m_isValid = true;
					break;
				}
				break;
			case 4:
			{
				PlayerCountRequirement playerCountRequirement = playerCountReq;
				if ((uint)(playerCountRequirement - 1) <= 1u)
				{
					m_isValid = true;
				}
				break;
			}
			case 3:
			{
				PlayerCountRequirement playerCountRequirement = playerCountReq;
				if ((uint)(playerCountRequirement - 1) <= 1u)
				{
					m_isValid = true;
				}
				break;
			}
			}
			if (!m_isValid)
			{
				SPOLogger.Error($"ConcurrentCluster setup: Something went wrong! PlayerCountRequirement: {playerCountReq}, children num: {((Il2CppArrayBase<iChainedPuzzleCore>)(object)parent.m_childCores).Count}");
				return false;
			}
			playerInScanCount = new int[((Il2CppArrayBase<iChainedPuzzleCore>)(object)parent.m_childCores).Count];
			Array.Fill(playerInScanCount, 0);
			children = ((IEnumerable<iChainedPuzzleCore>)parent.m_childCores).ToList().ConvertAll((iChainedPuzzleCore c) => ((Il2CppObjectBase)c).Cast<CP_Bioscan_Core>());
			childRadius = ((Il2CppObjectBase)((Il2CppObjectBase)((Il2CppArrayBase<iChainedPuzzleCore>)(object)parent.m_childCores)[0]).Cast<CP_Bioscan_Core>().m_playerScanner).Cast<CP_PlayerScanner>().Radius;
			return true;
		}

		private void LateUpdate()
		{
			//IL_032b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0070: Unknown result type (might be due to invalid IL or missing references)
			//IL_007b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0080: Unknown result type (might be due to invalid IL or missing references)
			//IL_0085: Unknown result type (might be due to invalid IL or missing references)
			if (!m_isValid || !parentHud.m_visible || !parentHud.m_isClosestToPlayer)
			{
				return;
			}
			displayText.Clear();
			displayText.AppendLine().Append("<color=white>");
			for (int i = 0; i < children.Count; i++)
			{
				int num = 0;
				CP_Bioscan_Core val = children[i];
				Enumerator<PlayerAgent> enumerator = PlayerManager.PlayerAgentsInLevel.GetEnumerator();
				while (enumerator.MoveNext())
				{
					Vector3 val2 = ((Agent)enumerator.Current).Position - ((Component)val).transform.position;
					if (((Vector3)(ref val2)).magnitude < childRadius)
					{
						num++;
					}
				}
				playerInScanCount[i] = num;
				string value = string.Empty;
				string value2 = string.Empty;
				switch (playerCountReq)
				{
				case PlayerCountRequirement.ANY:
					switch (num)
					{
					case 0:
						value = " ";
						break;
					case 1:
						value = "A";
						break;
					case 2:
						value = "A,B";
						break;
					case 3:
						value = "A,B,C";
						break;
					case 4:
						value = "A,B,C,D";
						break;
					}
					value2 = ((num > 0) ? "white" : "orange");
					break;
				case PlayerCountRequirement.SOLO:
					switch (num)
					{
					case 0:
						value = " ";
						value2 = "orange";
						break;
					case 1:
						value = "A";
						value2 = "white";
						break;
					case 2:
						value = "A,<color=red>B</color>";
						value2 = "orange";
						break;
					case 3:
						value = "A,<color=red>B</color>,<color=red>C</color>";
						value2 = "orange";
						break;
					case 4:
						value = "A,<color=red>B</color>,<color=red>C</color>,<color=red>D</color>";
						value2 = "orange";
						break;
					}
					break;
				case PlayerCountRequirement.DUO:
					switch (num)
					{
					case 0:
						value = " , ";
						value2 = "orange";
						break;
					case 1:
						value = "A, ";
						value2 = "orange";
						break;
					case 2:
						value = "A,B";
						value2 = "white";
						break;
					case 3:
						value = "A,B,<color=red>C</color>";
						value2 = "orange";
						break;
					case 4:
						value = "A,B,<color=red>C</color>,<color=red>D</color>";
						value2 = "orange";
						break;
					}
					break;
				}
				StringBuilder stringBuilder = displayText;
				StringBuilder.AppendInterpolatedStringHandler handler = new StringBuilder.AppendInterpolatedStringHandler(8, 1, stringBuilder);
				handler.AppendLiteral("<color=");
				handler.AppendFormatted(value2);
				handler.AppendLiteral(">");
				StringBuilder stringBuilder2 = stringBuilder.Append(ref handler).Append(ROMAN[i]).Append(": ")
					.Append("[")
					.Append(value)
					.Append("]");
				StringBuilder.AppendInterpolatedStringHandler handler2 = new StringBuilder.AppendInterpolatedStringHandler(9, 1, stringBuilder2);
				handler2.AppendLiteral("</color=");
				handler2.AppendFormatted(value2);
				handler2.AppendLiteral(">");
				stringBuilder2.Append(ref handler2);
				if (i != children.Count - 1)
				{
					displayText.Append(" | ");
				}
			}
			displayText.Append("</color=white>");
			parentHud.m_msgCharBuffer.Add(displayText.ToString());
			GuiManager.InteractionLayer.SetMessage(parentHud.m_msgCharBuffer, parentHud.m_msgStyle, 0);
		}

		private void OnDestroy()
		{
			parent = null;
			parentHud = null;
			def = null;
			children.Clear();
			children = null;
			m_isValid = false;
			playerInScanCount = null;
			displayText = null;
		}

		static ConcurrentClusterHud()
		{
			ClassInjector.RegisterTypeInIl2Cpp<ConcurrentClusterHud>();
		}
	}
}