Decompiled source of Fusion v1.5.10

plugins/Fusion/extra/Endlessinferno.plugins.dll

Decompiled a week ago
using System;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using BepInEx;
using BepInEx.Unity.IL2CPP;
using GameData;
using Gear;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using Player;

[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("weapon")]
[assembly: AssemblyConfiguration("Debug")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0")]
[assembly: AssemblyProduct("weapon")]
[assembly: AssemblyTitle("weapon")]
[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 Interference_Weapon
{
	[HarmonyPatch(typeof(BulletWeapon))]
	internal static class Inject_BulletWeapon
	{
		[HarmonyPostfix]
		[HarmonyPatch("UpdateAmmoStatus")]
		private static void Post_UpdateAmmoStatus(BulletWeapon __instance)
		{
			DoReload(__instance);
		}

		[HarmonyPostfix]
		[HarmonyPatch("OnWield")]
		private static void Post_Wield(BulletWeapon __instance)
		{
			DoReload(__instance);
		}

		private static void DoReload(BulletWeapon weapon)
		{
			if (weapon.m_clip == 0 && (((GameDataBlockBase<ItemDataBlock>)(object)((Item)weapon).ItemDataBlock).persistentID == 5001 || ((GameDataBlockBase<ItemDataBlock>)(object)((Item)weapon).ItemDataBlock).persistentID == 5005))
			{
				((Item)weapon).Owner.Inventory.DoReload();
			}
			else if (weapon.m_clip == 0 && (((GameDataBlockBase<ItemDataBlock>)(object)((Item)weapon).ItemDataBlock).persistentID == 5002 || ((GameDataBlockBase<ItemDataBlock>)(object)((Item)weapon).ItemDataBlock).persistentID == 5003) && ((PlayerInventoryBase)((Weapon)weapon).m_inventory).CanReloadCurrent())
			{
				((ItemEquippable)weapon).TryTriggerReloadAnimationSequence();
				if (((Item)weapon).Owner.Locomotion.IsRunning)
				{
					((Item)weapon).Owner.Locomotion.ChangeState((PLOC_State)0, false);
				}
			}
		}
	}
	[BepInPlugin("Yoake.Endlessinferno-Weapon", "Plugin for Endlessinferno Weaponpack", "1.1.0.0")]
	[BepInProcess("GTFO.exe")]
	public class EntryPoint : BasePlugin
	{
		public override void Load()
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			new Harmony("Interference.Weapon.Harmony").PatchAll();
		}
	}
}

plugins/Fusion/extra/Flowaria.MeltdownReactor.dll

Decompiled a week 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.Json;
using System.Text.Json.Serialization;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Logging;
using BepInEx.Unity.IL2CPP;
using ChainedPuzzles;
using GTFO.API;
using GTFO.API.Utilities;
using GameData;
using HarmonyLib;
using Il2CppInterop.Runtime.Injection;
using Il2CppInterop.Runtime.InteropTypes.Arrays;
using Il2CppSystem;
using Il2CppSystem.Collections.Generic;
using LevelGeneration;
using Localization;
using MTFO.Managers;
using MeltdownReactor.Json;
using MeltdownReactor.Json.PartialData;
using MeltdownReactor.ReactorData;
using Microsoft.CodeAnalysis;
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("Flowaria.MeltdownReactor")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0")]
[assembly: AssemblyProduct("Flowaria.MeltdownReactor")]
[assembly: AssemblyTitle("Flowaria.MeltdownReactor")]
[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 MeltdownReactor
{
	[BepInPlugin("Flowaria.MeltdownReactor", "MeltdownReactor", "2.1.4")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	public class EntryPoint : BasePlugin
	{
		[CompilerGenerated]
		private static class <>O
		{
			public static LiveEditEventHandler <0>__Listener_FileChanged1;
		}

		public const string PLUGIN_NAME = "MeltdownReactor";

		public const string AUTHOR = "Flowaria";

		public const string GUID = "Flowaria.MeltdownReactor";

		public const string VERSION = "2.1.4";

		public static string REACTOR_OVERRIDE_DATA_PATH = Path.Combine(MTFOUtil.CustomPath, "MeltdownReactor");

		public static readonly Dictionary<uint, ReactorOverrideData> ReactorOverrideDatas = new Dictionary<uint, ReactorOverrideData>();

		private Harmony m_Harmony;

		private LiveEditListener listener;

		public override void Load()
		{
			//IL_0066: Unknown result type (might be due to invalid IL or missing references)
			//IL_0070: Expected O, but got Unknown
			//IL_0133: Unknown result type (might be due to invalid IL or missing references)
			//IL_0138: Unknown result type (might be due to invalid IL or missing references)
			//IL_013e: Expected O, but got Unknown
			MeltdownReactorLogger.Debug("This plugin is dev-ed based on Flowaria.MeltdownReactor, which is only used in rundowns Flowaria.Modulation and Flowaria.Paradigm");
			MeltdownReactorLogger.Debug("All credits belong to Flowaria.");
			if (!Directory.Exists(REACTOR_OVERRIDE_DATA_PATH))
			{
				Directory.CreateDirectory(REACTOR_OVERRIDE_DATA_PATH);
				StreamWriter streamWriter = File.CreateText(Path.Combine(REACTOR_OVERRIDE_DATA_PATH, "Template.json"));
				streamWriter.WriteLine(JSON.Serialize(new ReactorOverrideData()));
				streamWriter.Flush();
				streamWriter.Close();
				return;
			}
			ClassInjector.RegisterTypeInIl2Cpp<MeltdownReactor>();
			m_Harmony = new Harmony("Flowaria.MeltdownReactor");
			m_Harmony.PatchAll();
			foreach (string item in Directory.EnumerateFiles(REACTOR_OVERRIDE_DATA_PATH, "*.json", SearchOption.AllDirectories))
			{
				JSON.Load<ReactorOverrideData>(item, out var config);
				if (ReactorOverrideDatas.ContainsKey(config.ObjectiveDataID))
				{
					MeltdownReactorLogger.Error($"Duplicate ObjectiveDataID {config.ObjectiveDataID}");
				}
				else
				{
					ReactorOverrideDatas.Add(config.ObjectiveDataID, config);
				}
			}
			listener = LiveEdit.CreateListener(REACTOR_OVERRIDE_DATA_PATH, "*.json", true);
			LiveEditListener obj = listener;
			object obj2 = <>O.<0>__Listener_FileChanged1;
			if (obj2 == null)
			{
				LiveEditEventHandler val = Listener_FileChanged1;
				<>O.<0>__Listener_FileChanged1 = val;
				obj2 = (object)val;
			}
			obj.FileChanged += (LiveEditEventHandler)obj2;
		}

		private static void Listener_FileChanged1(LiveEditEventArgs e)
		{
			MeltdownReactorLogger.Warning("LiveEdit File Changed: " + e.FullPath + ".");
			LiveEdit.TryReadFileContent(e.FullPath, (Action<string>)delegate(string content)
			{
				ReactorOverrideData reactorOverrideData = JSON.Deserialize<ReactorOverrideData>(content);
				if (!ReactorOverrideDatas.ContainsKey(reactorOverrideData.ObjectiveDataID))
				{
					MeltdownReactorLogger.Error("Changing ObjectiveDataID is not allowed, will not update.");
				}
				else
				{
					ReactorOverrideDatas[reactorOverrideData.ObjectiveDataID] = reactorOverrideData;
					MeltdownReactorLogger.Warning($"Updated override data with ObjectiveDataID {reactorOverrideData.ObjectiveDataID}");
				}
			});
		}
	}
	public class MeltdownReactor : MonoBehaviour
	{
		private const string MAINTERMINAL_NAME = "Main Terminal";

		private const float HIDE_TIMER_THRESHOLD = 43200f;

		private static Color LowTemperature;

		private static Color HighTemperature;

		private static uint VerifyTextID;

		private static uint MainTerminalTextID;

		private static uint CooldownCommandDescTextID;

		private static uint InfiniteWaveVerifyTextID;

		internal static uint NotReadyForVerificationOutputTextID;

		internal static uint IncorrectTerminalOutputTextID;

		internal static uint CorrectTerminalOutputTextID;

		private LG_Light[] _lights;

		private float _updateTimer;

		private Dictionary<int, LG_ComputerTerminal> verifyZoneOverrideTerminals = new Dictionary<int, LG_ComputerTerminal>();

		internal ReactorOverrideData overrideData;

		private Dictionary<int, string> meltdownWaveTerminalKeys;

		private HashSet<int> infiniteWaveIndices;

		private WardenObjectiveDataBlock objectiveDataBlock;

		private Dictionary<TERM_Command, List<WardenObjectiveEventData>> commandEventMap = new Dictionary<TERM_Command, List<WardenObjectiveEventData>>();

		private Dictionary<TERM_Command, List<TerminalOutput>> commandPostOutputMap = new Dictionary<TERM_Command, List<TerminalOutput>>();

		internal LG_WardenObjective_Reactor ChainedReactor { get; set; }

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


		public bool IsCorrectTerminal(LG_ComputerTerminal terminal)
		{
			int num = ChainedReactor.m_currentWaveCount - 1;
			if (num >= 0)
			{
				MeltdownReactorLogger.Error($"Index: {num}");
				MeltdownReactorLogger.Error("Comp Terminal Key1: " + terminal.ItemKey);
				MeltdownReactorLogger.Error("Comp Terminal Key2: " + (meltdownWaveTerminalKeys.ContainsKey(num) ? meltdownWaveTerminalKeys[num] : "empty"));
				if (meltdownWaveTerminalKeys.ContainsKey(num) && meltdownWaveTerminalKeys[num].Equals(terminal.ItemKey, StringComparison.InvariantCultureIgnoreCase))
				{
					return true;
				}
			}
			return false;
		}

		public void Init()
		{
			if (overrideData == null)
			{
				MeltdownReactorLogger.Error("ReactorOverrideData is null!");
				return;
			}
			meltdownWaveTerminalKeys = new Dictionary<int, string>();
			overrideData.MeltdownWaveIndices.ForEach(delegate(int index)
			{
				meltdownWaveTerminalKeys.TryAdd(index, string.Empty);
			});
			infiniteWaveIndices = overrideData.InfiniteWaveIndices.ToHashSet();
			LevelAPI.OnEnterLevel += OnDrop;
			if (VerifyTextID == 0)
			{
				VerifyTextID = GameDataBlockBase<TextDataBlock>.GetBlockID("InGame.WardenObjective_Reactor.MeltdownVerification");
				MainTerminalTextID = GameDataBlockBase<TextDataBlock>.GetBlockID("InGame.WardenObjective_Reactor.MeltdownMainTerminalName");
				CooldownCommandDescTextID = GameDataBlockBase<TextDataBlock>.GetBlockID("InGame.WardenObjective_Reactor.MeltdownCoolDown.CommandDesc");
				InfiniteWaveVerifyTextID = GameDataBlockBase<TextDataBlock>.GetBlockID("InGame.WardenObjective_Reactor.Verification.InfiniteWave");
				NotReadyForVerificationOutputTextID = GameDataBlockBase<TextDataBlock>.GetBlockID("InGame.WardenObjective_Reactor.MeltdownCoolDown.Not_ReadyForVerification_Output");
				IncorrectTerminalOutputTextID = GameDataBlockBase<TextDataBlock>.GetBlockID("InGame.WardenObjective_Reactor.MeltdownCoolDown.IncorrectTerminal_Output");
				CorrectTerminalOutputTextID = GameDataBlockBase<TextDataBlock>.GetBlockID("InGame.WardenObjective_Reactor.MeltdownCoolDown.CorrectTerminal_Output");
			}
		}

		private void OnDrop()
		{
			//IL_006c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0072: Invalid comparison between Unknown and I4
			//IL_004f: Unknown result type (might be due to invalid IL or missing references)
			LG_WardenObjective_Reactor chainedReactor = ChainedReactor;
			LG_ComputerTerminal terminal = ChainedReactor.m_terminal;
			objectiveDataBlock = GameDataBlockBase<WardenObjectiveDataBlock>.GetBlock(overrideData.ObjectiveDataID);
			if (objectiveDataBlock == null)
			{
				MeltdownReactorLogger.Error($"Failed to get the Reactor Startup objective for layer {chainedReactor.SpawnNode.LayerType}");
				return;
			}
			if ((int)objectiveDataBlock.Type != 1)
			{
				MeltdownReactorLogger.Error("Only Reactor Startup is supported");
				((Behaviour)this).enabled = false;
				return;
			}
			if (UsingLightEffect)
			{
				_lights = ((IEnumerable<LG_Light>)chainedReactor.SpawnNode.m_lightsInNode).Where((LG_Light x) => (int)x.m_category == 3).ToArray();
				chainedReactor.m_lightCollection.RemoveLights(Il2CppReferenceArray<LG_Light>.op_Implicit(_lights));
			}
			if (overrideData.StartupOnDrop && SNet.IsMaster)
			{
				chainedReactor.AttemptInteract((eReactorInteraction)0, 0f);
				terminal.TrySyncSetCommandHidden((TERM_Command)21);
			}
			SetupVerifyZoneOverride();
			SetupMeltdownAndInfiniteWave();
			if (overrideData.ReactorTerminal != null && overrideData.ReactorTerminal.TerminalPassword.PasswordProtected)
			{
				BuildReactorTerminalPassword();
			}
		}

		private void SetupVerifyZoneOverride()
		{
			//IL_01b6: 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)
			//IL_01cc: Unknown result type (might be due to invalid IL or missing references)
			//IL_0223: Unknown result type (might be due to invalid IL or missing references)
			//IL_022a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0231: Unknown result type (might be due to invalid IL or missing references)
			//IL_0263: Unknown result type (might be due to invalid IL or missing references)
			//IL_027d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0297: Unknown result type (might be due to invalid IL or missing references)
			//IL_02f0: Unknown result type (might be due to invalid IL or missing references)
			//IL_030a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0324: Unknown result type (might be due to invalid IL or missing references)
			LG_Zone val3 = default(LG_Zone);
			foreach (VerifyZoneOverride verifyZoneOverride in overrideData.VerifyZoneOverrides)
			{
				if (verifyZoneOverrideTerminals.ContainsKey(verifyZoneOverride.WaveIndex))
				{
					MeltdownReactorLogger.Error($"VerifyZoneOverrides: Duplicate Wave Index {verifyZoneOverride.WaveIndex}");
					continue;
				}
				if (infiniteWaveIndices.Contains(verifyZoneOverride.WaveIndex))
				{
					MeltdownReactorLogger.Error($"VerifyZoneOverrides: Wave Index {verifyZoneOverride.WaveIndex} is specified as Infinite Wave but VerifyZoneOverride is specified! Will not process");
					continue;
				}
				if (verifyZoneOverride.WaveIndex < 0 || verifyZoneOverride.WaveIndex >= objectiveDataBlock.ReactorWaves.Count)
				{
					MeltdownReactorLogger.Error($"VerifyZoneOverrides: Invalid Wave Index {verifyZoneOverride.WaveIndex}. Valid value for this reactor is: [0, {objectiveDataBlock.ReactorWaves.Count - 1}]");
					continue;
				}
				ReactorWaveData val = objectiveDataBlock.ReactorWaves[verifyZoneOverride.WaveIndex];
				if (!val.VerifyInOtherZone)
				{
					MeltdownReactorLogger.Error($"VerifyZoneOverrides: `VerifyInOtherZone` is false for wave {verifyZoneOverride.WaveIndex}. You need to set it to true to generate the log, and thereby enabling moving the log.");
					continue;
				}
				LG_ComputerTerminal val2 = Utils.FindTerminalWithTerminalSerial(val.VerificationTerminalSerial, ChainedReactor.SpawnNode.m_dimension.DimensionIndex, ChainedReactor.SpawnNode.LayerType, val.ZoneForVerification);
				if ((Object)(object)val2 == (Object)null)
				{
					MeltdownReactorLogger.Error($"VerifyZoneOverrides: Cannot find wave log terminal. Wave index: {verifyZoneOverride.WaveIndex}");
					continue;
				}
				TargetZone targetZone = verifyZoneOverride.TargetZone;
				if (!Builder.CurrentFloor.TryGetZoneByLocalIndex(targetZone.DimensionIndex, targetZone.LayerType, targetZone.LocalIndex, ref val3) || (Object)(object)val3 == (Object)null)
				{
					MeltdownReactorLogger.Error($"VerifyZoneOverrides: Cannot find target zone {targetZone.LocalIndex}, {targetZone.LayerType}, {targetZone.DimensionIndex}.");
					continue;
				}
				if (val3.TerminalsSpawnedInZone == null || val3.TerminalsSpawnedInZone.Count < 0)
				{
					MeltdownReactorLogger.Error($"VerifyZoneOverrides: No spawned terminal found in target zone {targetZone.LocalIndex}, {targetZone.LayerType}, {targetZone.DimensionIndex}..");
					continue;
				}
				int num = Builder.SessionSeedRandom.Seed;
				if (num < 0)
				{
					num = ((num != int.MinValue) ? (-num) : int.MaxValue);
				}
				int num2 = num % val3.TerminalsSpawnedInZone.Count;
				LG_ComputerTerminal val4 = val3.TerminalsSpawnedInZone[num2];
				string text = val.VerificationTerminalFileName.ToUpperInvariant();
				TerminalLogFileData localLog = val2.GetLocalLog(text);
				if (localLog == null)
				{
					MeltdownReactorLogger.Error("VerifyZoneOverrides: Cannot find reactor verify log on terminal.");
					continue;
				}
				val2.RemoveLocalLog(text);
				val4.AddLocalLog(localLog, true);
				val.VerificationTerminalSerial = val4.ItemKey;
				val2.ResetInitialOutput();
				val4.ResetInitialOutput();
				MeltdownReactorLogger.Debug($"VerifyZoneOverrides: moved wave {verifyZoneOverride.WaveIndex} verify log from {val2.ItemKey} to {val4.ItemKey}");
				verifyZoneOverrideTerminals.Add(verifyZoneOverride.WaveIndex, val4);
			}
		}

		private void SetupMeltdownAndInfiniteWave()
		{
			//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)
			//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_0134: Unknown result type (might be due to invalid IL or missing references)
			//IL_0135: Unknown result type (might be due to invalid IL or missing references)
			//IL_0138: Unknown result type (might be due to invalid IL or missing references)
			//IL_015e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0172: Unknown result type (might be due to invalid IL or missing references)
			//IL_0188: Unknown result type (might be due to invalid IL or missing references)
			LG_WardenObjective_Reactor chainedReactor = ChainedReactor;
			LG_ComputerTerminal terminal = ChainedReactor.m_terminal;
			eDimensionIndex dimensionIndex = chainedReactor.SpawnNode.m_dimension.DimensionIndex;
			LG_LayerType layerType = chainedReactor.SpawnNode.LayerType;
			LG_Zone val3 = default(LG_Zone);
			for (int i = 0; i < objectiveDataBlock.ReactorWaves.Count; i++)
			{
				if (!meltdownWaveTerminalKeys.ContainsKey(i) && !infiniteWaveIndices.Contains(i))
				{
					continue;
				}
				ReactorWaveData val = objectiveDataBlock.ReactorWaves[i];
				if (!val.HasVerificationTerminal)
				{
					_ = terminal.m_command;
					if (meltdownWaveTerminalKeys.ContainsKey(i))
					{
						meltdownWaveTerminalKeys[i] = terminal.ItemKey;
						AddVerifyCommand(terminal);
						MeltdownReactorLogger.Debug($"MeltdownWave: Setup as Meltdown Wave for wave index {i}");
					}
					else
					{
						MeltdownReactorLogger.Debug($"InfiniteWave: Setup as Infinite Wavefor wave index {i}");
					}
					continue;
				}
				LG_ComputerTerminal val2 = null;
				if (verifyZoneOverrideTerminals.ContainsKey(i))
				{
					val2 = verifyZoneOverrideTerminals[i];
				}
				else
				{
					if (!Builder.CurrentFloor.TryGetZoneByLocalIndex(dimensionIndex, layerType, val.ZoneForVerification, ref val3))
					{
						MeltdownReactorLogger.Error($"Cannot find LG_Zone {dimensionIndex}, {layerType}, {val.ZoneForVerification}");
						continue;
					}
					for (int j = 0; j < val3.TerminalsSpawnedInZone.Count; j++)
					{
						LG_ComputerTerminal val4 = val3.TerminalsSpawnedInZone[j];
						if (val4.ItemKey.Equals(val.VerificationTerminalSerial, StringComparison.InvariantCultureIgnoreCase))
						{
							val2 = val4;
							break;
						}
					}
				}
				if ((Object)(object)val2 == (Object)null)
				{
					MeltdownReactorLogger.Error($"MeltdownWave: cannot find verify terminal for wave index {i}");
					continue;
				}
				val2.ConnectedReactor = chainedReactor;
				val2.RemoveLocalLog(val.VerificationTerminalFileName.ToUpperInvariant());
				if (meltdownWaveTerminalKeys.ContainsKey(i))
				{
					meltdownWaveTerminalKeys[i] = val2.ItemKey;
					AddVerifyCommand(val2);
					MeltdownReactorLogger.Debug($"MeltdownWave: Setup as Meltdown Wave for wave index {i}");
				}
				else
				{
					MeltdownReactorLogger.Debug($"InfiniteWave: Setup as Infinite Wavefor wave index {i}");
				}
				val2.ResetInitialOutput();
			}
			if (meltdownWaveTerminalKeys.Count == objectiveDataBlock.ReactorWaves.Count)
			{
				terminal.TrySyncSetCommandHidden((TERM_Command)22);
			}
		}

		private void AddVerifyCommand(LG_ComputerTerminal terminal)
		{
			//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_0047: Unknown result type (might be due to invalid IL or missing references)
			//IL_0054: Expected O, but got Unknown
			LG_ComputerTerminalCommandInterpreter command = terminal.m_command;
			if (command.HasRegisteredCommand((TERM_Command)42))
			{
				MeltdownReactorLogger.Debug("TERM_Command.UniqueCommand5 already registered. If this terminal is specified as objective terminal for 2 waves and the number of commands in 'UniqueCommands' on this terminal isn't more than 4, simply ignore this message.");
				return;
			}
			command.AddCommand((TERM_Command)42, "REACTOR_COOLDOWN", new LocalizedText
			{
				UntranslatedText = ((CooldownCommandDescTextID == 0) ? "Confirm Reactor Startup Cooling Protocol" : Text.Get(CooldownCommandDescTextID)),
				Id = 0u
			}, (TERM_CommandRule)0);
			terminal.TrySyncSetCommandRule((TERM_Command)42, (TERM_CommandRule)0);
		}

		private void SetIdle()
		{
			//IL_0011: 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_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_0048: Unknown result type (might be due to invalid IL or missing references)
			if (!((Object)(object)ChainedReactor == (Object)null))
			{
				pReactorState val = default(pReactorState);
				val.status = (eReactorStatus)0;
				val.stateCount = 0;
				val.stateProgress = 0f;
				val.verifyFailed = false;
				pReactorState state = val;
				ChainedReactor.m_stateReplicator.State = state;
			}
		}

		private void OnDestroy()
		{
			LevelAPI.OnEnterLevel -= OnDrop;
			ChainedReactor = null;
			infiniteWaveIndices?.Clear();
			meltdownWaveTerminalKeys?.Clear();
			verifyZoneOverrideTerminals?.Clear();
			commandEventMap?.Clear();
			commandPostOutputMap?.Clear();
			infiniteWaveIndices = null;
			meltdownWaveTerminalKeys = null;
			overrideData = null;
			objectiveDataBlock = null;
			verifyZoneOverrideTerminals = null;
			commandEventMap = null;
			commandPostOutputMap = null;
		}

		private void LateUpdate()
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Invalid comparison between Unknown and I4
			//IL_0010: 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_001a: 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_0024: Unknown result type (might be due to invalid IL or missing references)
			if ((int)GameStateManager.CurrentStateName == 10)
			{
				eReactorStatus status = ChainedReactor.m_currentState.status;
				if (UsingLightEffect)
				{
					UpdateLight(status, ChainedReactor.m_currentWaveProgress);
				}
				UpdateGUIText(status);
			}
		}

		private void UpdateGUIText(eReactorStatus status)
		{
			//IL_002b: Unknown result type (might be due to invalid IL or missing references)
			//IL_002d: Invalid comparison between Unknown and I4
			int num = ChainedReactor.m_currentWaveCount - 1;
			if (num < 0)
			{
				return;
			}
			bool flag = ChainedReactor.m_currentWaveData.Verify < 43200f;
			if ((int)status != 4)
			{
				return;
			}
			if (meltdownWaveTerminalKeys.ContainsKey(num))
			{
				string text = ((MainTerminalTextID == 0) ? "Main Terminal" : Text.Get(MainTerminalTextID));
				if (ChainedReactor.m_currentWaveData.HasVerificationTerminal)
				{
					text = ChainedReactor.m_currentWaveData.VerificationTerminalSerial;
				}
				ChainedReactor.SetGUIMessage(true, FormatText(VerifyTextID, ChainedReactor.m_currentWaveCount, ChainedReactor.m_waveCountMax, "<color=orange>" + text + "</color>"), (ePUIMessageStyle)3, flag, "<size=125%>" + Text.Get(1104u), "</size>");
			}
			else if (infiniteWaveIndices.Contains(num))
			{
				ChainedReactor.SetGUIMessage(true, string.Format(Text.Get(InfiniteWaveVerifyTextID), ChainedReactor.m_currentWaveCount, ChainedReactor.m_waveCountMax), (ePUIMessageStyle)3, flag, "<size=125%>" + Text.Get(1104u), "</size>");
			}
			else if (ChainedReactor.m_currentWaveData.HasVerificationTerminal)
			{
				ChainedReactor.SetGUIMessage(true, Text.Format(1103u, (Object[])(object)new Object[3]
				{
					Object.op_Implicit(ChainedReactor.m_currentWaveCount),
					Object.op_Implicit(ChainedReactor.m_waveCountMax),
					Object.op_Implicit("<color=orange>" + ChainedReactor.m_currentWaveData.VerificationTerminalSerial + "</color>")
				}), (ePUIMessageStyle)3, flag, "<size=125%>" + Text.Get(1104u), "</size>");
			}
			else
			{
				ChainedReactor.SetGUIMessage(true, Text.Format(1105u, (Object[])(object)new Object[3]
				{
					Object.op_Implicit(ChainedReactor.m_currentWaveCount),
					Object.op_Implicit(ChainedReactor.m_waveCountMax),
					Object.op_Implicit("<color=orange>" + ChainedReactor.CurrentStateOverrideCode + "</color>")
				}), (ePUIMessageStyle)3, flag, "<size=125%>" + Text.Get(1104u), "</size>");
			}
		}

		private void UpdateLight(eReactorStatus status, float progress)
		{
			//IL_001f: 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_003b: Expected I4, but got Unknown
			//IL_003d: 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_004e: 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_0060: 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_006b: 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_0083: Unknown result type (might be due to invalid IL or missing references)
			if (!(_updateTimer > Clock.Time))
			{
				_updateTimer = Clock.Time + 0.15f;
				switch (status - 1)
				{
				case 0:
					SetLightColor(Color.black);
					break;
				case 1:
					SetLightColor(Color.Lerp(LowTemperature, HighTemperature, progress));
					break;
				case 2:
					SetLightColor(Color.Lerp(HighTemperature, LowTemperature, progress));
					break;
				case 3:
					SetLightColor(LowTemperature);
					break;
				case 4:
					SetLightColor(LowTemperature);
					break;
				}
			}
		}

		private void SetLightColor(Color color)
		{
			//IL_001d: Unknown result type (might be due to invalid IL or missing references)
			if (UsingLightEffect && _lights != null)
			{
				for (int i = 0; i < _lights.Length; i++)
				{
					_lights[i].ChangeColor(color);
				}
			}
		}

		private void BuildReactorTerminalPassword()
		{
			//IL_027e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0285: Expected O, but got Unknown
			//IL_02e0: Unknown result type (might be due to invalid IL or missing references)
			//IL_02e5: Unknown result type (might be due to invalid IL or missing references)
			//IL_0308: Unknown result type (might be due to invalid IL or missing references)
			//IL_0314: Expected O, but got Unknown
			LG_ComputerTerminal terminal = ChainedReactor.m_terminal;
			TerminalPassword terminalPassword = overrideData.ReactorTerminal.TerminalPassword;
			if (!terminalPassword.GeneratePassword)
			{
				terminal.LockWithPassword(terminalPassword.Password, new string[1] { "" });
				return;
			}
			if (terminalPassword.TerminalZoneSelectionDatas.Count <= 0)
			{
				MeltdownReactorLogger.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 = terminalPassword.PasswordHintText;
			string text = "<b>[Forgot your password?]</b> Backup security key(s) located in logs on ";
			int num = terminalPassword.PasswordPartCount;
			if (codeWord.Length % num != 0)
			{
				MeltdownReactorLogger.Error($"Build() password.Length ({codeWord.Length}) not divisible by passwordParts ({terminalPassword.PasswordPartCount}). 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 (terminalPassword.ShowPasswordPartPositions)
			{
				for (int i = 0; i < array[0].Length; i++)
				{
					text2 += "-";
				}
			}
			HashSet<LG_ComputerTerminal> hashSet = new HashSet<LG_ComputerTerminal>();
			for (int j = 0; j < num; j++)
			{
				int index = j % terminalPassword.TerminalZoneSelectionDatas.Count;
				LG_ComputerTerminal val = Utils.SelectTerminalFromSelectionData(terminalPassword.TerminalZoneSelectionDatas[index][Builder.SessionSeedRandom.Range(0, terminalPassword.TerminalZoneSelectionDatas[index].Count, "NO_TAG")]);
				if ((Object)(object)val != (Object)null)
				{
					string text3 = "";
					string text4;
					if (terminalPassword.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 text5 = (terminalPassword.ShowPasswordPartPositions ? ("0" + (j + 1)) : ("0" + Builder.SessionSeedRandom.Range(0, 9, "NO_TAG")));
					TerminalLogFileData val2 = new TerminalLogFileData();
					val2.FileName = "key" + text5 + "_" + terminal.m_serialNumber + (val.HasPasswordPart ? "_1" : "") + ".LOG";
					val2.FileContent = new LocalizedText
					{
						UntranslatedText = string.Format(Text.Get((num == 1) ? 1431221909u : 2260297836u), text4),
						Id = 0u
					};
					TerminalLogFileData val3 = val2;
					val.AddLocalLog(val3, true);
					if (!hashSet.Contains(val))
					{
						if (j > 0)
						{
							text += ", ";
						}
						text = text + val.PublicName + " in " + val.SpawnNode.m_zone.AliasName;
					}
					hashSet.Add(val);
					val.HasPasswordPart = true;
				}
				else
				{
					MeltdownReactorLogger.Error($"Build() CRITICAL ERROR, could not get a LG_ComputerTerminal for password part ({j + 1}/{num}) for {terminal.PublicName} backup log.");
				}
			}
			string text6 = text + ".";
			if (terminalPassword.ShowPasswordLength)
			{
				terminal.LockWithPassword(codeWord, new string[3]
				{
					passwordHintText,
					text6,
					"Char[" + codeWord.Length + "]"
				});
			}
			else
			{
				terminal.LockWithPassword(codeWord, new string[2] { passwordHintText, text6 });
			}
			foreach (LG_ComputerTerminal item in hashSet)
			{
				item.ResetInitialOutput();
			}
		}

		private void BuildReactorTerminalCustomCommands()
		{
			//IL_0044: 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_0064: 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_016e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0176: 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_00ef: 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)
			LG_ComputerTerminal terminal = ChainedReactor.m_terminal;
			List<ReactorCustomTerminalCommand> uniqueCommands = overrideData.ReactorTerminal.UniqueCommands;
			TERM_Command val = default(TERM_Command);
			for (int i = 0; i < uniqueCommands.Count; i++)
			{
				ReactorCustomTerminalCommand reactorCustomTerminalCommand = uniqueCommands[i];
				if (terminal.m_command.TryGetUniqueCommandSlot(ref val))
				{
					terminal.m_command.AddCommand(val, reactorCustomTerminalCommand.Command, reactorCustomTerminalCommand.CommandDesc, reactorCustomTerminalCommand.SpecialCommandRule);
					commandEventMap.Add(val, reactorCustomTerminalCommand.CommandEvents);
					commandPostOutputMap.Add(val, reactorCustomTerminalCommand.PostCommandOutputs);
					for (int j = 0; j < reactorCustomTerminalCommand.CommandEvents.Count; j++)
					{
						WardenObjectiveEventData val2 = reactorCustomTerminalCommand.CommandEvents[j];
						if (val2.ChainPuzzle != 0)
						{
							ChainedPuzzleDataBlock block = GameDataBlockBase<ChainedPuzzleDataBlock>.GetBlock(val2.ChainPuzzle);
							if (block != null)
							{
								ChainedPuzzleInstance val3 = ChainedPuzzleManager.CreatePuzzleInstance(block, terminal.ConnectedReactor.SpawnNode.m_area, terminal.ConnectedReactor.m_chainedPuzzleAlign.position, terminal.ConnectedReactor.m_chainedPuzzleAlign, val2.UseStaticBioscanPoints);
								terminal.SetChainPuzzleForCommand(val, j, val3);
							}
						}
					}
				}
				else
				{
					MeltdownReactorLogger.Error($"LG_ComputerTerminal: Could not get any more unique command slots for this terminal!! Have you added too many unique commands to this terminal? (Yours: {uniqueCommands.Count}, Max: 5)");
				}
			}
			ChainedPuzzleInstance val6 = default(ChainedPuzzleInstance);
			for (int k = 38; k <= 42; k++)
			{
				TERM_Command val4 = (TERM_Command)(byte)k;
				if (!commandEventMap.TryGetValue(val4, out var value) || value == null)
				{
					continue;
				}
				ChainedPuzzleInstance val5 = null;
				for (int l = 0; l < value.Count; l++)
				{
					WardenObjectiveEventData eventData = value[l];
					if (eventData == null)
					{
						continue;
					}
					if (ChainedReactor.m_terminal.TryGetChainPuzzleForCommand(val4, l, ref val6) && (Object)(object)val6 != (Object)null)
					{
						ChainedPuzzleInstance obj = val6;
						obj.OnPuzzleSolved += Action.op_Implicit((Action)delegate
						{
							WardenObjectiveManager.CheckAndExecuteEventsOnTrigger(eventData, (eWardenObjectiveEventTrigger)0, true, 0f);
						});
						val5 = val6;
					}
					else if ((Object)(object)val5 != (Object)null)
					{
						ChainedPuzzleInstance obj2 = val5;
						obj2.OnPuzzleSolved += Action.op_Implicit((Action)delegate
						{
							WardenObjectiveManager.CheckAndExecuteEventsOnTrigger(eventData, (eWardenObjectiveEventTrigger)0, true, 0f);
						});
					}
				}
			}
			MeltdownReactorLogger.Warning("CustomCommand built!");
		}

		private static string FormatText(uint id, params object[] objs)
		{
			return string.Format(Text.Get(id), objs);
		}

		static MeltdownReactor()
		{
			//IL_0005: 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_0014: 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_0028: 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)
			LowTemperature = ColorExt.Hex("#23E4F2") * 2.5f;
			HighTemperature = ColorExt.Hex("#F63838") * 12f;
			VerifyTextID = 0u;
			MainTerminalTextID = 0u;
			CooldownCommandDescTextID = 0u;
			InfiniteWaveVerifyTextID = 0u;
			NotReadyForVerificationOutputTextID = 0u;
			IncorrectTerminalOutputTextID = 0u;
			CorrectTerminalOutputTextID = 0u;
		}
	}
	internal static class MeltdownReactorLogger
	{
		private static readonly ManualLogSource _logger = Logger.CreateLogSource("MeltdownReactor");

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

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

		public static void Verbose(object data)
		{
		}

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

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

		public static void Warning(object data)
		{
			_logger.LogWarning((object)Format(data));
		}
	}
	internal static class Utils
	{
		public static LG_ComputerTerminal FindTerminalWithTerminalSerial(string itemKey, eDimensionIndex dim, LG_LayerType layer, eLocalZoneIndex localIndex)
		{
			//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)
			LG_Zone val = null;
			if (Builder.CurrentFloor.TryGetZoneByLocalIndex(dim, layer, localIndex, ref val) && (Object)(object)val != (Object)null)
			{
				Enumerator<LG_ComputerTerminal> enumerator = val.TerminalsSpawnedInZone.GetEnumerator();
				while (enumerator.MoveNext())
				{
					LG_ComputerTerminal current = enumerator.Current;
					if (current.ItemKey.Equals(itemKey, StringComparison.InvariantCultureIgnoreCase))
					{
						return current;
					}
				}
			}
			return null;
		}

		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 LG_ComputerTerminal SelectTerminalFromSelectionData(PasswordTerminalZoneSelectionData selectionData)
		{
			//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_0019: 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_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_0120: Unknown result type (might be due to invalid IL or missing references)
			//IL_0137: Expected I4, but got Unknown
			//IL_00ce: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d3: Unknown result type (might be due to invalid IL or missing references)
			TargetZone targetZone = selectionData.TargetZone;
			LG_Zone val = default(LG_Zone);
			if (!Builder.CurrentFloor.TryGetZoneByLocalIndex(targetZone.DimensionIndex, targetZone.LayerType, targetZone.LocalIndex, ref val) || (Object)(object)val == (Object)null)
			{
				MeltdownReactorLogger.Error("SelectTerminalFromSelectionData() Could NOT find zone with " + targetZone);
				return null;
			}
			if (val.TerminalsSpawnedInZone.Count <= 0)
			{
				MeltdownReactorLogger.Error("SelectTerminalFromSelectionData() Could not find any terminals in zone with " + targetZone?.ToString() + ". At least one terminal required!!");
				return null;
			}
			List<LG_ComputerTerminal> list = new List<LG_ComputerTerminal>();
			if ((int)selectionData.SeedType != 0)
			{
				Enumerator<LG_ComputerTerminal> enumerator = val.TerminalsSpawnedInZone.GetEnumerator();
				while (enumerator.MoveNext())
				{
					LG_ComputerTerminal current = enumerator.Current;
					if (!current.HasPasswordPart)
					{
						list.Add(current);
					}
				}
				if (list.Count <= 0)
				{
					eLocalZoneIndex localIndex = targetZone.LocalIndex;
					MeltdownReactorLogger.Error("SelectTerminalFromSelectionData() Could not find any terminals without a password part in zone with " + ((object)(eLocalZoneIndex)(ref localIndex)).ToString() + ". Putting the password on random (session) already used terminal.");
					return val.TerminalsSpawnedInZone[Builder.SessionSeedRandom.Range(0, val.TerminalsSpawnedInZone.Count, "NO_TAG")];
				}
			}
			eSeedType seedType = selectionData.SeedType;
			switch ((int)seedType)
			{
			case 0:
				return val.TerminalsSpawnedInZone[Mathf.Clamp(0, val.TerminalsSpawnedInZone.Count - 1, selectionData.TerminalIndex)];
			case 1:
				return list[Builder.SessionSeedRandom.Range(0, list.Count, "NO_TAG")];
			case 2:
				return list[Builder.BuildSeedRandom.Range(0, list.Count, "NO_TAG")];
			case 3:
				Random.InitState(selectionData.StaticSeed);
				return list[Random.Range(0, list.Count)];
			default:
				MeltdownReactorLogger.Error("SelectTerminalFromSelectionData() did not have a valid SeedType!!");
				return null;
			}
		}
	}
}
namespace MeltdownReactor.ReactorData
{
	public class PasswordTerminalZoneSelectionData
	{
		public TargetZone TargetZone { get; set; } = new TargetZone();


		public eSeedType SeedType { get; set; }

		public int TerminalIndex { get; set; }

		public int StaticSeed { get; set; }

		public PasswordTerminalZoneSelectionData()
		{
			SeedType = (eSeedType)1;
		}

		public override string ToString()
		{
			//IL_0026: 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)
			string[] obj = new string[7]
			{
				TargetZone?.ToString(),
				" ",
				null,
				null,
				null,
				null,
				null
			};
			eSeedType seedType = SeedType;
			obj[2] = ((object)(eSeedType)(ref seedType)).ToString();
			obj[3] = " ";
			obj[4] = TerminalIndex.ToString();
			obj[5] = " ";
			obj[6] = StaticSeed.ToString();
			return string.Concat(obj);
		}
	}
	public class ReactorCustomTerminalCommand
	{
		public string Command { get; set; }

		public LocalizedText CommandDesc { get; set; }

		public List<TerminalOutput> PostCommandOutputs { get; set; }

		public List<WardenObjectiveEventData> CommandEvents { get; set; }

		public TERM_CommandRule SpecialCommandRule { get; set; }

		public ReactorCustomTerminalCommand()
		{
			PostCommandOutputs = new List<TerminalOutput>();
			CommandEvents = new List<WardenObjectiveEventData>();
		}
	}
	public class ReactorOverrideData
	{
		public uint ObjectiveDataID { get; set; }

		public bool StartupOnDrop { get; set; }

		public List<int> MeltdownWaveIndices { get; set; } = new List<int>();


		public List<int> InfiniteWaveIndices { get; set; } = new List<int>();


		public ReactorTerminalSetting ReactorTerminal { get; set; } = new ReactorTerminalSetting();


		public List<VerifyZoneOverride> VerifyZoneOverrides { get; set; } = new List<VerifyZoneOverride>
		{
			new VerifyZoneOverride()
		};

	}
	public class ReactorTerminalSetting
	{
		public List<ReactorCustomTerminalCommand> UniqueCommands { get; set; } = new List<ReactorCustomTerminalCommand>();


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

	}
	public class TargetZone
	{
		public eDimensionIndex DimensionIndex { get; set; }

		public LG_LayerType LayerType { get; set; }

		public eLocalZoneIndex LocalIndex { get; set; }

		public override string ToString()
		{
			//IL_000c: 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_003e: Unknown result type (might be due to invalid IL or missing references)
			return $"{LocalIndex}, {LayerType}, {DimensionIndex}";
		}
	}
	public class TerminalPassword
	{
		public bool PasswordProtected { get; set; }

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


		public string PasswordHintText { get; set; } = "Password Required.";


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


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


		public bool ShowPasswordLength { get; set; }

		public bool ShowPasswordPartPositions { get; set; }

		public List<List<PasswordTerminalZoneSelectionData>> TerminalZoneSelectionDatas { get; set; } = new List<List<PasswordTerminalZoneSelectionData>>
		{
			new List<PasswordTerminalZoneSelectionData>()
		};

	}
	public class VerifyZoneOverride
	{
		public int WaveIndex { get; set; } = -1;


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

	}
}
namespace MeltdownReactor.Patches
{
	[HarmonyPatch]
	internal static class Patch_LG_ComputerTerminal
	{
		[HarmonyPrefix]
		[HarmonyPatch(typeof(LG_ComputerTerminal), "OnStateChange")]
		private static bool Pre_OnStateChange(LG_ComputerTerminal __instance, bool isRecall)
		{
			if (__instance.SpawnNode != null || !isRecall)
			{
				return true;
			}
			return false;
		}
	}
	[HarmonyPatch(typeof(LG_ComputerTerminalCommandInterpreter), "ReceiveCommand")]
	internal static class Patch_Meltdown_Reactor_Terminal
	{
		private static bool Prefix(LG_ComputerTerminalCommandInterpreter __instance, TERM_Command cmd)
		{
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			//IL_0018: Invalid comparison between Unknown and I4
			//IL_0022: Unknown result type (might be due to invalid IL or missing references)
			LG_WardenObjective_Reactor connectedReactor = __instance.m_terminal.ConnectedReactor;
			if ((Object)(object)connectedReactor == (Object)null || (int)cmd != 42)
			{
				return true;
			}
			if (__instance.m_terminal.CommandIsHidden(cmd))
			{
				return true;
			}
			_ = __instance.m_terminal.ItemKey;
			MeltdownReactor component = ((Component)connectedReactor).gameObject.GetComponent<MeltdownReactor>();
			if ((Object)(object)component == (Object)null)
			{
				return true;
			}
			if (!connectedReactor.ReadyForVerification)
			{
				__instance.AddOutput("", true);
				__instance.AddOutput((TerminalLineType)3, Text.Get(MeltdownReactor.NotReadyForVerificationOutputTextID), 4f, (TerminalSoundType)0, (TerminalSoundType)0);
				__instance.AddOutput("", true);
				return false;
			}
			if (component.IsCorrectTerminal(__instance.m_terminal))
			{
				MeltdownReactorLogger.Info("Reactor Verify Correct!");
				if (SNet.IsMaster)
				{
					if (connectedReactor.m_currentWaveCount == connectedReactor.m_waveCountMax)
					{
						connectedReactor.AttemptInteract((eReactorInteraction)5, 0f);
					}
					else
					{
						connectedReactor.AttemptInteract((eReactorInteraction)3, 0f);
					}
				}
				__instance.AddOutput(Text.Get(MeltdownReactor.CorrectTerminalOutputTextID), true);
			}
			else
			{
				MeltdownReactorLogger.Info("Reactor Verify Incorrect!");
				__instance.AddOutput("", true);
				__instance.AddOutput((TerminalLineType)3, Text.Get(MeltdownReactor.IncorrectTerminalOutputTextID), 4f, (TerminalSoundType)0, (TerminalSoundType)0);
				__instance.AddOutput("", true);
			}
			return false;
		}
	}
	[HarmonyPatch]
	internal static class Patch_Meltdown_Reactor
	{
		[HarmonyPostfix]
		[HarmonyPatch(typeof(LG_WardenObjective_Reactor), "OnBuildDone")]
		private static void Post_BuildDone(LG_WardenObjective_Reactor __instance)
		{
			//IL_000d: 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_0051: Invalid comparison between Unknown and I4
			WardenObjectiveDataBlock val = default(WardenObjectiveDataBlock);
			if (!WardenObjectiveManager.Current.TryGetActiveWardenObjectiveData(__instance.SpawnNode.LayerType, ref val))
			{
				MeltdownReactorLogger.Error("Failed to get WardenObjectiveData for this reactor");
			}
			else if (EntryPoint.ReactorOverrideDatas.ContainsKey(((GameDataBlockBase<WardenObjectiveDataBlock>)(object)val).persistentID))
			{
				ReactorOverrideData overrideData = EntryPoint.ReactorOverrideDatas[((GameDataBlockBase<WardenObjectiveDataBlock>)(object)val).persistentID];
				if ((int)val.Type != 1)
				{
					MeltdownReactorLogger.Error($"ObjectiveDataID {((GameDataBlockBase<WardenObjectiveDataBlock>)(object)val).persistentID} is not reactor startup, which is unsupported.");
					return;
				}
				MeltdownReactor meltdownReactor = ((Component)__instance).gameObject.AddComponent<MeltdownReactor>();
				meltdownReactor.ChainedReactor = __instance;
				meltdownReactor.UsingLightEffect = false;
				meltdownReactor.overrideData = overrideData;
				meltdownReactor.Init();
				MeltdownReactorLogger.Warning($"Override Reactor Data for ObjectiveID {((GameDataBlockBase<WardenObjectiveDataBlock>)(object)val).persistentID}");
			}
		}
	}
}
namespace MeltdownReactor.Json
{
	internal static class JSON
	{
		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 obj)
		{
			return JsonSerializer.Serialize(obj, s_SerializerOptions);
		}

		static JSON()
		{
			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);
				MeltdownReactorLogger.Info("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, "MeltdownReactor", file));
			config = Deserialize<T>(file);
		}
	}
	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);
		}
	}
}
namespace MeltdownReactor.Json.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)
			{
				MeltdownReactorLogger.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)
			{
				MeltdownReactorLogger.Error($"Exception thrown while reading path from DataDumper (MTFO): \n{value2}");
			}
		}
	}
}

plugins/Fusion/extra/MeleeFix.dll

Decompiled a week ago
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using BepInEx;
using BepInEx.Unity.IL2CPP;
using HarmonyLib;
using Player;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: AssemblyTitle("MeleeFix")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("MeleeFix")]
[assembly: AssemblyCopyright("Copyright ©  2022")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
[assembly: Guid("0419bef8-8fd3-47f2-96e2-897346c1410e")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: TargetFramework(".NETFramework,Version=v4.7.2", FrameworkDisplayName = ".NET Framework 4.7.2")]
[assembly: AssemblyVersion("1.0.0.0")]
namespace MeleeFix
{
	[BepInPlugin("com.Sexypanda.MeleeFix", "MeleeFix", "1.0.0")]
	public class EntryPoint : BasePlugin
	{
		public override void Load()
		{
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			new Harmony("com.Sexypanda.MeleeFix").PatchAll();
		}
	}
}
namespace MeleeFix.Patches
{
	[HarmonyPatch]
	internal static class MeleeFix_Patch
	{
		[HarmonyPatch(typeof(FirstPersonItemHolder), "MeleeAttackShortcut")]
		[HarmonyPrefix]
		public static void MeleeAttackShortcut__Prefix(FirstPersonItemHolder __instance)
		{
			__instance.m_inventoryLocal.SetWieldDelayOverride(0f);
			__instance.m_owner.Sync.WantsToWieldSlot((InventorySlot)10, false);
		}
	}
}

plugins/Fusion/extra/net6/AggroFix.dll

Decompiled a week ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using AIGraph;
using API;
using Agents;
using AggroFix.BepInEx;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using BepInEx.Unity.IL2CPP;
using Enemies;
using GameData;
using HarmonyLib;
using Il2CppInterop.Runtime.InteropTypes;
using Il2CppSystem.Collections.Generic;
using LevelGeneration;
using Microsoft.CodeAnalysis;
using Player;
using SNetwork;
using StateMachines;
using UnityEngine;
using UnityEngine.Analytics;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETCoreApp,Version=v6.0", FrameworkDisplayName = ".NET 6.0")]
[assembly: AssemblyCompany("AggroFix")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0+993b34134528fcfa51e1e8571e9ad84aea5be391")]
[assembly: AssemblyProduct("AggroFix")]
[assembly: AssemblyTitle("AggroFix")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.0.0.0")]
[module: UnverifiableCode]
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 AggroFix
{
	[HarmonyPatch]
	internal static class Fix
	{
		private static bool patch = true;

		private static bool IsTargetReachable(AIG_CourseNode source, AIG_CourseNode target)
		{
			//IL_0086: Unknown result type (might be due to invalid IL or missing references)
			//IL_008d: Invalid comparison between Unknown and I4
			//IL_0091: Unknown result type (might be due to invalid IL or missing references)
			//IL_0098: Invalid comparison between Unknown and I4
			if (source == null || target == null)
			{
				return false;
			}
			if (source.NodeID == target.NodeID)
			{
				return true;
			}
			AIG_SearchID.IncrementSearchID();
			ushort searchID = AIG_SearchID.SearchID;
			Queue<AIG_CourseNode> queue = new Queue<AIG_CourseNode>();
			queue.Enqueue(source);
			while (queue.Count > 0)
			{
				AIG_CourseNode val = queue.Dequeue();
				((AIG_CourseGraphMember)val).m_searchID = searchID;
				Enumerator<AIG_CoursePortal> enumerator = val.m_portals.GetEnumerator();
				while (enumerator.MoveNext())
				{
					AIG_CoursePortal current = enumerator.Current;
					LG_Gate gate = current.Gate;
					object obj;
					if (gate == null)
					{
						obj = null;
					}
					else
					{
						iLG_Door_Core spawnedDoor = gate.SpawnedDoor;
						obj = ((spawnedDoor != null) ? ((Il2CppObjectBase)spawnedDoor).TryCast<LG_SecurityDoor>() : null);
					}
					LG_SecurityDoor val2 = (LG_SecurityDoor)obj;
					if ((Object)(object)val2 != (Object)null && (int)val2.LastStatus != 10 && (int)val2.LastStatus != 16)
					{
						continue;
					}
					AIG_CourseNode oppositeNode = current.GetOppositeNode(val);
					if (((AIG_CourseGraphMember)oppositeNode).m_searchID != searchID)
					{
						if (oppositeNode.NodeID == target.NodeID)
						{
							return true;
						}
						queue.Enqueue(oppositeNode);
					}
				}
			}
			return false;
		}

		[HarmonyPatch(typeof(EnemyCourseNavigation), "UpdateTracking")]
		[HarmonyPostfix]
		private static void UpdateTracking(EnemyCourseNavigation __instance)
		{
			//IL_0046: Unknown result type (might be due to invalid IL or missing references)
			//IL_004d: Invalid comparison between Unknown and I4
			if (!patch || !SNet.IsMaster)
			{
				return;
			}
			EnemyAgent owner = __instance.m_owner;
			if (((Agent)owner).CourseNode == null || __instance.m_targetRef == null || (Object)(object)__instance.m_targetRef.m_agent == (Object)null || (int)((StateMachine<ES_Base>)(object)owner.Locomotion).m_currentState.m_stateEnum == 14)
			{
				return;
			}
			if (!IsTargetReachable(((Agent)owner).CourseNode, __instance.m_targetRef.m_agent.CourseNode))
			{
				APILogger.Debug("Invalid current " + ((Il2CppObjectBase)__instance.m_targetRef.m_agent).Cast<PlayerAgent>().Owner.NickName);
				bool flag = false;
				int num = Random.RandomRangeInt(0, PlayerManager.PlayerAgentsInLevel.Count);
				PlayerAgent val = PlayerManager.PlayerAgentsInLevel[num];
				for (int i = 0; i < PlayerManager.PlayerAgentsInLevel.Count; i++)
				{
					APILogger.Debug("Checking " + val.Owner.NickName);
					if (((Agent)val).Alive && ((Object)val).GetInstanceID() != ((Object)__instance.m_targetRef.m_agent).GetInstanceID() && IsTargetReachable(((Agent)owner).CourseNode, ((Agent)val).CourseNode))
					{
						flag = true;
						break;
					}
					num = (num + 1) % PlayerManager.PlayerAgentsInLevel.Count;
					val = PlayerManager.PlayerAgentsInLevel[num];
				}
				if (flag)
				{
					APILogger.Debug("Rerouted to " + val.Owner.NickName);
					patch = false;
					((AgentAI)owner.AI).SetTarget((Agent)(object)val);
					patch = true;
				}
				else
				{
					APILogger.Debug("No valid target found " + ((Il2CppObjectBase)__instance.m_targetRef.m_agent).Cast<PlayerAgent>().Owner.NickName);
				}
			}
			else
			{
				APILogger.Debug("Current " + ((Il2CppObjectBase)__instance.m_targetRef.m_agent).Cast<PlayerAgent>().Owner.NickName);
			}
		}
	}
}
namespace AggroFix.BepInEx
{
	public static class Module
	{
		public const string GUID = "randomuserhi.AggroFix";

		public const string Name = "AggroFix";

		public const string Version = "0.0.1";
	}
	public static class ConfigManager
	{
		public static ConfigFile configFile;

		private static ConfigEntry<bool> debug;

		public static bool Debug
		{
			get
			{
				return debug.Value;
			}
			set
			{
				debug.Value = value;
			}
		}

		static ConfigManager()
		{
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_001a: Expected O, but got Unknown
			configFile = new ConfigFile(Path.Combine(Paths.ConfigPath, "AggroFix.cfg"), true);
			debug = configFile.Bind<bool>("Debug", "enable", false, "Enables debug messages when true.");
		}
	}
	[BepInPlugin("randomuserhi.AggroFix", "AggroFix", "0.0.1")]
	public class Plugin : BasePlugin
	{
		private static Harmony? harmony;

		public override void Load()
		{
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0019: Expected O, but got Unknown
			APILogger.Log("Plugin is loaded!");
			harmony = new Harmony("randomuserhi.AggroFix");
			harmony.PatchAll();
			APILogger.Log("Debug is " + (ConfigManager.Debug ? "Enabled" : "Disabled"));
		}
	}
}
namespace API
{
	[HarmonyPatch(typeof(GameDataInit))]
	internal class GameDataInit_Patches
	{
		[HarmonyPatch("Initialize")]
		[HarmonyWrapSafe]
		[HarmonyPostfix]
		public static void Initialize_Postfix()
		{
			Analytics.enabled = false;
		}
	}
	internal static class APILogger
	{
		private static readonly ManualLogSource logger;

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

		private static string Format(string module, object msg)
		{
			return $"[{module}]: {msg}";
		}

		public static void Info(string module, object data)
		{
			logger.LogMessage((object)Format(module, data));
		}

		public static void Verbose(string module, object data)
		{
		}

		public static void Log(object data)
		{
			logger.LogDebug((object)Format("AggroFix", data));
		}

		public static void Debug(object data)
		{
			if (ConfigManager.Debug)
			{
				Log(data);
			}
		}

		public static void Warn(object data)
		{
			logger.LogWarning((object)Format("AggroFix", data));
		}

		public static void Error(object data)
		{
			logger.LogError((object)Format("AggroFix", data));
		}
	}
}

plugins/Fusion/extra/net6/AmorLib_1.1.2.dll

Decompiled a week ago
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
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 System.Text.Json;
using System.Text.Json.Serialization;
using System.Text.RegularExpressions;
using AIGraph;
using AmorLib.API;
using AmorLib.Dependencies;
using AmorLib.Events;
using AmorLib.Utils;
using AmorLib.Utils.Extensions;
using AmorLib.Utils.JsonElementConverters;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Core.Logging.Interpolation;
using BepInEx.Logging;
using BepInEx.Unity.IL2CPP;
using CullingSystem;
using GTFO.API;
using GTFO.API.Extensions;
using GTFO.API.JSON;
using GTFO.API.Utilities;
using GameData;
using HarmonyLib;
using Il2CppInterop.Runtime.InteropTypes;
using Il2CppInterop.Runtime.InteropTypes.Arrays;
using Il2CppSystem;
using Il2CppSystem.Collections.Generic;
using InjectLib.JsonNETInjection.Supports;
using LevelGeneration;
using Localization;
using MTFO.Ext.PartialData;
using Microsoft.CodeAnalysis;
using SNetwork;
using SemanticVersioning;
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("AmorLib")]
[assembly: AssemblyConfiguration("Debug")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0+e55c20542f65f82551c50b400c7e279eccf15890")]
[assembly: AssemblyProduct("AmorLib")]
[assembly: AssemblyTitle("AmorLib")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.0.0.0")]
[module: UnverifiableCode]
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 AmorLib
{
	[AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = false)]
	internal sealed class CallConstructorOnLoadAttribute : Attribute
	{
	}
	[BepInPlugin("Amor.AmorLib", "AmorLib", "1.1.2")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	internal sealed class EntryPoint : BasePlugin
	{
		public override void Load()
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			new Harmony("Amor.AmorLib").PatchAll();
			CallAllAutoConstructors();
			Logger.Info("AmorLib is done loading!");
		}

		private void CallAllAutoConstructors()
		{
			IEnumerable<Type> enumerable = from t in AccessTools.GetTypesFromAssembly(((object)this).GetType().Assembly)
				where t.IsDefined(typeof(CallConstructorOnLoadAttribute), inherit: false)
				select t;
			foreach (Type item in enumerable)
			{
				RuntimeHelpers.RunClassConstructor(item.TypeHandle);
			}
		}
	}
	internal static class Logger
	{
		private static readonly ManualLogSource MLS;

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

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

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

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

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

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

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

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

		public static void Warn(string str)
		{
			MLS.LogWarning((object)str);
		}
	}
}
namespace AmorLib.Utils
{
	[CallConstructorOnLoad]
	public static class CourseNodeUtil
	{
		private class DimensionMap
		{
			private const float IndexSize = 4f;

			public List<AIG_CourseNode>?[,] BuildNodeMap;

			public AIG_CourseNode[,][] NodeMap;

			public (int x, int z) MinCellBound;

			public (int x, int z) MaxCellBound;

			public (int x, int z) MapSize;

			internal DimensionMap()
			{
				BuildNodeMap = null;
				NodeMap = null;
				MapSize = (0, 0);
				MinCellBound = (int.MaxValue, int.MaxValue);
				MaxCellBound = (int.MinValue, int.MinValue);
			}

			internal void UpdateBounds(Vector3 position)
			{
				//IL_0001: 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)
				int val = (int)(position.x / 4f);
				int val2 = (int)(position.z / 4f);
				MinCellBound = (Math.Min(val, MinCellBound.x), Math.Min(val2, MinCellBound.z));
				MaxCellBound = (Math.Max(val, MaxCellBound.x), Math.Max(val2, MaxCellBound.z));
			}

			internal void CreateNodeMap()
			{
				MapSize = (MaxCellBound.x - MinCellBound.x + 1, MaxCellBound.z - MinCellBound.z + 1);
				BuildNodeMap = new List<AIG_CourseNode>[MapSize.x, MapSize.z];
				NodeMap = new AIG_CourseNode[MapSize.x, MapSize.z][];
			}

			internal (int x, int z) GetMapPos(Vector3 position)
			{
				//IL_0001: 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)
				return (Math.Clamp((int)(position.x / 4f) - MinCellBound.x, 0, MapSize.x - 1), Math.Clamp((int)(position.z / 4f) - MinCellBound.z, 0, MapSize.z - 1));
			}

			internal List<AIG_CourseNode> GetBuildNodeList(Vector3 position)
			{
				//IL_0002: Unknown result type (might be due to invalid IL or missing references)
				(int x, int z) mapPos = GetMapPos(position);
				int item = mapPos.x;
				int item2 = mapPos.z;
				List<AIG_CourseNode> list = BuildNodeMap[item, item2];
				if (list == null)
				{
					list = (BuildNodeMap[item, item2] = new List<AIG_CourseNode>());
				}
				return list;
			}

			internal void FinishBuild()
			{
				for (int i = 0; i < MapSize.x; i++)
				{
					for (int j = 0; j < MapSize.z; j++)
					{
						NodeMap[i, j] = BuildNodeMap[i, j]?.ToArray();
					}
				}
				BuildNodeMap = null;
			}

			public AIG_CourseNode[] GetNodes(Vector3 position)
			{
				//IL_0002: 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_01c0: Expected O, but got Unknown
				//IL_01d3: Unknown result type (might be due to invalid IL or missing references)
				var (num, num2) = GetMapPos(position);
				if (NodeMap[num, num2] != null)
				{
					return NodeMap[num, num2];
				}
				float num3 = Math.Max(MapSize.x, MapSize.z);
				for (int i = 1; (float)i < num3; i++)
				{
					int num4 = Math.Max(num - i, 0);
					int num5 = Math.Min(num + i, MapSize.x - 1);
					int num6 = Math.Max(num2 - i, 0);
					int num7 = Math.Min(num2 + i, MapSize.z - 1);
					for (int j = num4; j <= num5; j++)
					{
						if (NodeMap[j, num6] != null)
						{
							return NodeMap[j, num6];
						}
						if (NodeMap[j, num7] != null)
						{
							return NodeMap[j, num7];
						}
					}
					for (int k = num6 + 1; k <= num7 - 1; k++)
					{
						if (NodeMap[num4, k] != null)
						{
							return NodeMap[num4, k];
						}
						if (NodeMap[num5, k] != null)
						{
							return NodeMap[num5, k];
						}
					}
				}
				bool flag = default(bool);
				BepInExErrorLogInterpolatedStringHandler val = new BepInExErrorLogInterpolatedStringHandler(66, 1, ref flag);
				if (flag)
				{
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral("Unable to get any node for (");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<Vector3>(position);
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral(")! How are you even playing the game?!");
				}
				Logger.Error(val);
				return null;
			}
		}

		private static readonly Dictionary<eDimensionIndex, DimensionMap> _maps;

		static CourseNodeUtil()
		{
			_maps = new Dictionary<eDimensionIndex, DimensionMap>();
			LevelAPI.OnAfterBuildBatch += OnAfterBuildBatch;
		}

		private static void OnAfterBuildBatch(BatchName batch)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0004: Invalid comparison between Unknown and I4
			//IL_0069: 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_00bc: Unknown result type (might be due to invalid IL or missing references)
			//IL_0177: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b5: Unknown result type (might be due to invalid IL or missing references)
			if ((int)batch != 38)
			{
				return;
			}
			_maps.Clear();
			Enumerator<AIG_NodeCluster> enumerator = AIG_NodeCluster.AllNodeClusters.GetEnumerator();
			while (enumerator.MoveNext())
			{
				AIG_NodeCluster current = enumerator.Current;
				object obj;
				if (current == null)
				{
					obj = null;
				}
				else
				{
					AIG_CourseNode courseNode = current.m_courseNode;
					obj = ((courseNode != null) ? courseNode.m_dimension : null);
				}
				if (obj != null)
				{
					if (!_maps.TryGetValue(current.m_courseNode.m_dimension.DimensionIndex, out DimensionMap value))
					{
						_maps.Add(current.m_courseNode.m_dimension.DimensionIndex, value = new DimensionMap());
					}
					Enumerator<AIG_INode> enumerator2 = current.m_nodes.GetEnumerator();
					while (enumerator2.MoveNext())
					{
						AIG_INode current2 = enumerator2.Current;
						value.UpdateBounds(current2.Position);
					}
				}
			}
			foreach (DimensionMap value2 in _maps.Values)
			{
				value2.CreateNodeMap();
			}
			Enumerator<AIG_NodeCluster> enumerator4 = AIG_NodeCluster.AllNodeClusters.GetEnumerator();
			while (enumerator4.MoveNext())
			{
				AIG_NodeCluster current4 = enumerator4.Current;
				object obj2;
				if (current4 == null)
				{
					obj2 = null;
				}
				else
				{
					AIG_CourseNode courseNode2 = current4.m_courseNode;
					obj2 = ((courseNode2 != null) ? courseNode2.m_dimension : null);
				}
				if (obj2 == null)
				{
					continue;
				}
				DimensionMap dimensionMap = _maps[current4.m_courseNode.m_dimension.DimensionIndex];
				int id = current4.CourseNode.NodeID;
				Enumerator<AIG_INode> enumerator5 = current4.m_nodes.GetEnumerator();
				while (enumerator5.MoveNext())
				{
					AIG_INode current5 = enumerator5.Current;
					List<AIG_CourseNode> buildNodeList = dimensionMap.GetBuildNodeList(current5.Position);
					if (!buildNodeList.Any((AIG_CourseNode node) => id == node.NodeID))
					{
						buildNodeList.Add(current4.CourseNode);
					}
				}
			}
			foreach (DimensionMap value3 in _maps.Values)
			{
				value3.FinishBuild();
			}
		}

		private static bool TryGetClosestNodeInCluster(AIG_NodeCluster cluster, Vector3 position, out AIG_INode node)
		{
			//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_001b: 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_00d4: 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_00da: Unknown result type (might be due to invalid IL or missing references)
			//IL_00df: Unknown result type (might be due to invalid IL or missing references)
			AIG_VoxelNodeVolume voxelNodeVolume = cluster.m_nodeVolume.m_voxelNodeVolume;
			if (voxelNodeVolume.TryGetCloseVoxelNode_Safe(position, position.y - 0.5f, position.y + 0.5f, ref node, false))
			{
				return true;
			}
			int num = default(int);
			int num2 = default(int);
			voxelNodeVolume.GetGridPosition(position, ref num, ref num2);
			num = Mathf.Clamp(num, 0, voxelNodeVolume.m_countX - 1);
			num2 = Mathf.Clamp(num2, 0, voxelNodeVolume.m_countZ - 1);
			float num3 = float.MaxValue;
			AIG_VoxelNode val = null;
			AIG_VoxelNodePillar val2 = default(AIG_VoxelNodePillar);
			for (int i = -1; i < 2; i++)
			{
				for (int j = -1; j < 2; j++)
				{
					if (!voxelNodeVolume.TryGetPillar(num + i, num2 + j, ref val2))
					{
						continue;
					}
					Enumerator<AIG_VoxelNode> enumerator = val2.m_nodes.GetEnumerator();
					while (enumerator.MoveNext())
					{
						AIG_VoxelNode current = enumerator.Current;
						if (current.ClusterID != cluster.ID)
						{
							continue;
						}
						Vector3 val3 = current.Position - position;
						float sqrMagnitude = ((Vector3)(ref val3)).sqrMagnitude;
						if (sqrMagnitude < num3)
						{
							val = current;
							num3 = sqrMagnitude;
							if (num3 < 0.55f)
							{
								node = ((Il2CppObjectBase)val).Cast<AIG_INode>();
								return true;
							}
						}
					}
				}
			}
			if (val != null)
			{
				node = ((Il2CppObjectBase)val).Cast<AIG_INode>();
				return true;
			}
			return false;
		}

		public static AIG_CourseNode ResolveCourseNode(AIG_CourseNode[] list, Vector3 position)
		{
			//IL_004c: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fd: Unknown result type (might be due to invalid IL or missing references)
			if (list == null)
			{
				return null;
			}
			if (list.Length == 1)
			{
				return list[0];
			}
			(AIG_CourseNode, AIG_INode)[] array = new(AIG_CourseNode, AIG_INode)[list.Length];
			int num = 0;
			foreach (AIG_CourseNode val in list)
			{
				if (!TryGetClosestNodeInCluster(val.m_nodeCluster, position, out AIG_INode node))
				{
					node = val.m_nodeCluster.m_nodes[0];
				}
				array[num++] = (val, node);
			}
			bool flag = false;
			float num2 = float.MaxValue;
			AIG_CourseNode result = null;
			(AIG_CourseNode, AIG_INode)[] array2 = array;
			for (int j = 0; j < array2.Length; j++)
			{
				var (val2, val3) = array2[j];
				if (val3 != null)
				{
					bool flag2 = val3.Position.y - 0.25f <= position.y;
					Vector3 val4 = position - val3.Position;
					float sqrMagnitude = ((Vector3)(ref val4)).sqrMagnitude;
					if ((!flag && flag2) || (flag == flag2 && sqrMagnitude < num2))
					{
						flag = flag2;
						num2 = sqrMagnitude;
						result = val2;
					}
				}
			}
			return result;
		}

		public static AIG_CourseNode GetCourseNode(Vector3 position)
		{
			//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_000f: Unknown result type (might be due to invalid IL or missing references)
			? val = position;
			Dimension dimensionFromPos = Dimension.GetDimensionFromPos(position);
			int num;
			if (dimensionFromPos == null)
			{
				num = 0;
				val = num;
				num = (int)val;
			}
			else
			{
				val = dimensionFromPos.DimensionIndex;
				num = (int)val;
			}
			return GetCourseNode((Vector3)num, (eDimensionIndex)val);
		}

		public static AIG_CourseNode GetCourseNode(Vector3 position, eDimensionIndex dimensionIndex)
		{
			//IL_0006: 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_001b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0021: Expected O, but got Unknown
			//IL_0031: Unknown result type (might be due to invalid IL or missing references)
			if (!_maps.TryGetValue(dimensionIndex, out DimensionMap value))
			{
				bool flag = default(bool);
				BepInExErrorLogInterpolatedStringHandler val = new BepInExErrorLogInterpolatedStringHandler(39, 1, ref flag);
				if (flag)
				{
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral("No Position-To-Node map for dimension ");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<eDimensionIndex>(dimensionIndex);
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral("!");
				}
				Logger.Error(val);
				return null;
			}
			return ResolveCourseNode(value.GetNodes(position), position);
		}

		public static AIG_CourseNode[] GetCourseNodes(Vector3 position, eDimensionIndex dimensionIndex)
		{
			//IL_0006: 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_001b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0021: Expected O, but got Unknown
			//IL_0031: Unknown result type (might be due to invalid IL or missing references)
			if (!_maps.TryGetValue(dimensionIndex, out DimensionMap value))
			{
				bool flag = default(bool);
				BepInExErrorLogInterpolatedStringHandler val = new BepInExErrorLogInterpolatedStringHandler(39, 1, ref flag);
				if (flag)
				{
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral("No Position-To-Node map for dimension ");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<eDimensionIndex>(dimensionIndex);
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral("!");
				}
				Logger.Error(val);
				return null;
			}
			return value.GetNodes(position);
		}
	}
	public static class DataBlockUtil
	{
		public static bool TryGetBlock<T>(string name, [MaybeNullWhen(false)] out T block) where T : GameDataBlockBase<T>
		{
			if (PData_Wrapper.TryGetGUID(name, out var guid))
			{
				return DataBlockUtil.TryGetBlock<T>(guid, out block);
			}
			block = GameDataBlockBase<T>.GetBlock(name);
			return block != null && ((GameDataBlockBase<T>)block).internalEnabled;
		}

		public static bool TryGetBlock<T>(uint id, [MaybeNullWhen(false)] out T block) where T : GameDataBlockBase<T>
		{
			block = GameDataBlockBase<T>.GetBlock(id);
			return block != null && ((GameDataBlockBase<T>)block).internalEnabled;
		}
	}
	public abstract class GlobalBase
	{
		private eDimensionIndex _dimIndex = (eDimensionIndex)0;

		private LG_LayerType _layerType = (LG_LayerType)0;

		private eLocalZoneIndex _localIndex = (eLocalZoneIndex)0;

		private GlobalZoneIndex _struct;

		private (int dim, int layer, int zone) _tuple;

		public Dimension? Dimension;

		public LG_Zone? Zone;

		private bool _isDirty = true;

		[JsonPropertyOrder(-10)]
		public eDimensionIndex DimensionIndex
		{
			get
			{
				//IL_0001: Unknown result type (might be due to invalid IL or missing references)
				return _dimIndex;
			}
			set
			{
				//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)
				_dimIndex = value;
				MarkDirty();
			}
		}

		[JsonPropertyOrder(-10)]
		public LG_LayerType Layer
		{
			get
			{
				//IL_0001: Unknown result type (might be due to invalid IL or missing references)
				return _layerType;
			}
			set
			{
				//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)
				_layerType = value;
				MarkDirty();
			}
		}

		[JsonPropertyOrder(-10)]
		public eLocalZoneIndex LocalIndex
		{
			get
			{
				//IL_0001: Unknown result type (might be due to invalid IL or missing references)
				return _localIndex;
			}
			set
			{
				//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)
				_localIndex = value;
				MarkDirty();
			}
		}

		[JsonIgnore]
		public GlobalZoneIndex GlobalZoneIndex
		{
			get
			{
				//IL_0009: Unknown result type (might be due to invalid IL or missing references)
				//IL_000e: Unknown result type (might be due to invalid IL or missing references)
				//IL_0011: Unknown result type (might be due to invalid IL or missing references)
				Refresh();
				return _struct;
			}
		}

		[JsonIgnore]
		public (int dimension, int layer, int zone) IntTuple
		{
			get
			{
				Refresh();
				return _tuple;
			}
		}

		protected GlobalBase()
		{
			//IL_0002: 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_0010: Unknown result type (might be due to invalid IL or missing references)
			Refresh();
			LevelAPI.OnAfterBuildBatch += OnAfterBuildBatch;
			LevelAPI.OnLevelCleanup += OnLevelCleanup;
		}

		private void OnAfterBuildBatch(BatchName batch)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0003: Invalid comparison between Unknown and I4
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			if ((int)batch == 8)
			{
				Dimension val = default(Dimension);
				Dimension = (Dimension.GetDimension(_dimIndex, ref val) ? val : null);
				Zone = (_tuple.TryGetZone(out LG_Zone zone) ? zone : null);
			}
		}

		private void OnLevelCleanup()
		{
			Dimension = null;
			Zone = null;
		}

		private void MarkDirty()
		{
			_isDirty = true;
		}

		private void Refresh()
		{
			//IL_0012: 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_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)
			//IL_0028: Unknown result type (might be due to invalid IL or missing references)
			//IL_002f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0035: Unknown result type (might be due to invalid IL or missing references)
			//IL_003b: Unknown result type (might be due to invalid IL or missing references)
			if (_isDirty)
			{
				_struct = GlobalIndexUtil.ToStruct(DimensionIndex, Layer, LocalIndex);
				_tuple = GlobalIndexUtil.ToIntTuple(DimensionIndex, Layer, LocalIndex);
				_isDirty = false;
			}
		}

		public override string ToString()
		{
			//IL_0019: 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_004f: Unknown result type (might be due to invalid IL or missing references)
			return $"({DimensionIndex}, {Layer}, {LocalIndex})";
		}
	}
	public static class GlobalIndexUtil
	{
		public static (int dimension, int layer, int zone) ToIntTuple(this LG_Zone zone)
		{
			//IL_0002: 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)
			return ToIntTuple(zone.DimensionIndex, zone.Layer.m_type, zone.LocalIndex);
		}

		public static (int dimension, int layer, int zone) ToIntTuple(this GlobalZoneIndex globalIndex)
		{
			//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_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)
			return ToIntTuple(globalIndex.Dimension, globalIndex.Layer, globalIndex.Zone);
		}

		public static (int dimension, int layer, int zone) ToIntTuple(eDimensionIndex dimension, LG_LayerType layer, eLocalZoneIndex zone)
		{
			//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_0003: Unknown result type (might be due to invalid IL or missing references)
			//IL_0009: Expected I4, but got Unknown
			//IL_0009: Expected I4, but got Unknown
			//IL_0009: Expected I4, but got Unknown
			return ((int)dimension, (int)layer, (int)zone);
		}

		public static GlobalZoneIndex ToStruct(this LG_Zone zone)
		{
			//IL_0002: 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_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_0020: Unknown result type (might be due to invalid IL or missing references)
			return ToStruct(zone.DimensionIndex, zone.Layer.m_type, zone.LocalIndex);
		}

		public static GlobalZoneIndex ToStruct(eDimensionIndex dimension, LG_LayerType layer, eLocalZoneIndex zone)
		{
			//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_0003: Unknown result type (might be due to invalid IL or missing references)
			//IL_0004: 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_000c: Unknown result type (might be due to invalid IL or missing references)
			return new GlobalZoneIndex(dimension, layer, zone);
		}

		public static bool TryGetZone(this (int, int, int) index, [MaybeNullWhen(false)] out LG_Zone zone)
		{
			return TryGetZone((eDimensionIndex)index.Item1, (LG_LayerType)(byte)index.Item2, (eLocalZoneIndex)index.Item3, out zone);
		}

		public static bool TryGetZone(this GlobalZoneIndex index, [MaybeNullWhen(false)] out LG_Zone zone)
		{
			//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_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)
			return TryGetZone(index.Dimension, index.Layer, index.Zone, out zone);
		}

		public static bool TryGetZone(eDimensionIndex dimension, LG_LayerType layer, eLocalZoneIndex localIndex, out LG_Zone? zone)
		{
			//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_001c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0022: Expected O, but got Unknown
			//IL_0032: 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_005a: Unknown result type (might be due to invalid IL or missing references)
			if (!Builder.CurrentFloor.TryGetZoneByLocalIndex(dimension, layer, localIndex, ref zone))
			{
				bool flag = default(bool);
				BepInExErrorLogInterpolatedStringHandler val = new BepInExErrorLogInterpolatedStringHandler(66, 3, ref flag);
				if (flag)
				{
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral("Unable to find zone in level! (Dimension: ");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<eDimensionIndex>(dimension);
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral(", Layer: ");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<LG_LayerType>(layer);
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral(", LocalIndex: ");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<eLocalZoneIndex>(localIndex);
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral(")");
				}
				Logger.Error(val);
				return false;
			}
			return true;
		}
	}
	public static class JsonSerializerUtil
	{
		public static JsonSerializerOptions CreateDefaultSettings(bool useLocalizedText = true, bool usePartialData = false, bool useInjectLib = false)
		{
			JsonSerializerOptions jsonSerializerOptions = new JsonSerializerOptions(useLocalizedText ? JsonSerializer.DefaultSerializerSettingsWithLocalizedText : JsonSerializer.DefaultSerializerSettings);
			if (usePartialData && PData_Wrapper.IsLoaded)
			{
				jsonSerializerOptions.Converters.Add(PData_Wrapper.PersistentIDConverter);
			}
			if (useInjectLib && InjectLib_Wrapper.IsLoaded)
			{
				jsonSerializerOptions.Converters.Add(InjectLib_Wrapper.InjectLibConverter);
			}
			return jsonSerializerOptions;
		}
	}
}
namespace AmorLib.Utils.JsonElementConverters
{
	[JsonConverter(typeof(BoolBaseConverter))]
	public struct BoolBase
	{
		public BoolMode Mode;

		public static readonly BoolBase False = new BoolBase(BoolMode.False);

		public static readonly BoolBase True = new BoolBase(BoolMode.True);

		public static readonly BoolBase Unchanged = new BoolBase(BoolMode.Unchanged);

		public BoolBase(bool mode)
		{
			Mode = (mode ? BoolMode.True : BoolMode.False);
		}

		public BoolBase(BoolMode mode)
		{
			Mode = mode;
		}

		public readonly bool GetValue(bool originalValue)
		{
			return Mode switch
			{
				BoolMode.True => true, 
				BoolMode.False => false, 
				_ => originalValue, 
			};
		}
	}
	public enum BoolMode
	{
		False,
		True,
		Unchanged
	}
	public sealed class BoolBaseConverter : JsonConverter<BoolBase>
	{
		public override bool HandleNull => false;

		public override bool CanConvert(Type objectType)
		{
			return objectType == typeof(BoolBase);
		}

		public override BoolBase Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
		{
			switch (reader.TokenType)
			{
			case JsonTokenType.String:
			{
				string text = reader.GetString()?.Trim();
				if (string.IsNullOrEmpty(text))
				{
					throw new JsonException("BoolBase string value is null or empty!");
				}
				if (text.EqualsAny(true, "Unchanged", "Ignore", "Keep", "Original", "KeepOriginal"))
				{
					return BoolBase.Unchanged;
				}
				if (bool.TryParse(text, out var result))
				{
					return new BoolBase(result);
				}
				throw new JsonException("Cannot parse BoolBase string: " + text + "! Are you sure it's in right format?");
			}
			case JsonTokenType.True:
				return BoolBase.True;
			case JsonTokenType.False:
				return BoolBase.False;
			default:
				throw new JsonException($"BoolBaseJson type: {reader.TokenType} is not implemented!");
			}
		}

		public override void Write(Utf8JsonWriter writer, BoolBase value, JsonSerializerOptions options)
		{
			switch (value.Mode)
			{
			case BoolMode.True:
				writer.WriteBooleanValue(value: true);
				break;
			case BoolMode.False:
				writer.WriteBooleanValue(value: false);
				break;
			case BoolMode.Unchanged:
				writer.WriteStringValue("Unchanged");
				break;
			}
			writer.WriteCommentValue("BoolBase");
		}
	}
	[JsonConverter(typeof(LocaleTextConverter))]
	public struct LocaleText : IEquatable<LocaleText>
	{
		public uint ID;

		public string RawText;

		public static readonly LocaleText Empty = new LocaleText(string.Empty);

		private readonly string TextFallback => (ID == 0) ? RawText : Text.Get(ID);

		public LocaleText(LocalizedText baseText)
		{
			RawText = ((Object)baseText).ToString();
			ID = baseText.Id;
		}

		public LocaleText(string text)
		{
			if (PData_Wrapper.TryGetGUID(text, out var guid))
			{
				RawText = string.Empty;
				ID = guid;
			}
			else
			{
				RawText = text;
				ID = 0u;
			}
		}

		public LocaleText(uint id)
		{
			RawText = string.Empty;
			ID = id;
		}

		public readonly LocalizedText ToLocalizedText()
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			//IL_0021: Expected O, but got Unknown
			return new LocalizedText
			{
				Id = ID,
				UntranslatedText = TextFallback
			};
		}

		public static explicit operator LocaleText(LocalizedText localizedText)
		{
			return new LocaleText(localizedText);
		}

		public static explicit operator LocaleText(string text)
		{
			return new LocaleText(text);
		}

		public static implicit operator LocalizedText(LocaleText localeText)
		{
			return localeText.ToLocalizedText();
		}

		public static implicit operator string(LocaleText localeText)
		{
			return localeText.ToString();
		}

		public override readonly string ToString()
		{
			return TextFallback;
		}

		public readonly bool Equals(LocaleText other)
		{
			return ID == other.ID && string.Equals(RawText, other.RawText, StringComparison.Ordinal);
		}

		public override readonly bool Equals(object? obj)
		{
			return obj is LocaleText other && Equals(other);
		}

		public override readonly int GetHashCode()
		{
			return HashCode.Combine(ID, RawText);
		}

		public static bool operator ==(LocaleText left, LocaleText right)
		{
			return left.Equals(right);
		}

		public static bool operator !=(LocaleText left, LocaleText right)
		{
			return !(left == right);
		}
	}
	public class LocaleTextConverter : JsonConverter<LocaleText>
	{
		public override bool HandleNull => true;

		public override LocaleText Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
		{
			return reader.TokenType switch
			{
				JsonTokenType.String => new LocaleText(reader.GetString()), 
				JsonTokenType.Number => new LocaleText(reader.GetUInt32()), 
				JsonTokenType.Null => LocaleText.Empty, 
				_ => throw new JsonException($"LocaleTextJson type: {reader.TokenType} is not implemented!"), 
			};
		}

		public override void Write(Utf8JsonWriter writer, LocaleText value, JsonSerializerOptions options)
		{
			if (value.ID != 0)
			{
				writer.WriteNumberValue(value.ID);
			}
			else
			{
				writer.WriteStringValue(value.RawText);
			}
		}
	}
	[JsonConverter(typeof(ValueBaseConverter))]
	public struct ValueBase
	{
		public float Value;

		public ValueMode Mode;

		public bool FromDefault;

		public static readonly ValueBase Unchanged = new ValueBase(1f, ValueMode.Rel, fromDefault: true);

		public static readonly ValueBase Zero = new ValueBase(0f, ValueMode.Abs, fromDefault: false);

		public ValueBase(float value = 1f, ValueMode mode = ValueMode.Rel, bool fromDefault = true)
		{
			Value = value;
			Mode = mode;
			FromDefault = fromDefault;
		}

		public readonly float GetAbsValue(float maxValue, float currentValue)
		{
			if (Mode == ValueMode.Rel)
			{
				return FromDefault ? (currentValue * Value) : (maxValue * Value);
			}
			return Value;
		}

		public readonly float GetAbsValue(float baseValue)
		{
			return (Mode == ValueMode.Abs) ? Value : (baseValue * Value);
		}

		public readonly int GetAbsValue(int maxValue, int currentValue)
		{
			return (int)Math.Round(GetAbsValue((float)maxValue, (float)currentValue));
		}

		public readonly int GetAbsValue(int baseValue)
		{
			return (int)Math.Round(GetAbsValue((float)baseValue));
		}

		public override readonly string ToString()
		{
			return $"[Mode: {Mode}, Value: {Value}]";
		}
	}
	public enum ValueMode
	{
		Rel,
		Abs
	}
	public sealed class ValueBaseConverter : JsonConverter<ValueBase>
	{
		public override bool HandleNull => false;

		public override bool CanConvert(Type objectType)
		{
			return objectType == typeof(ValueBase);
		}

		public override ValueBase Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
		{
			switch (reader.TokenType)
			{
			case JsonTokenType.Number:
				return new ValueBase(reader.GetSingle(), ValueMode.Abs);
			case JsonTokenType.StartObject:
			{
				ValueBase result3 = default(ValueBase);
				while (reader.Read())
				{
					if (reader.TokenType == JsonTokenType.EndObject)
					{
						return result3;
					}
					if (reader.TokenType != JsonTokenType.PropertyName)
					{
						throw new JsonException("Expected PropertyName token");
					}
					string @string = reader.GetString();
					reader.Read();
					switch (@string.ToLowerInvariant())
					{
					case "value":
						result3.Value = reader.GetSingle();
						break;
					case "mode":
					{
						if (Enum.TryParse<ValueMode>(reader.GetString(), out var result4))
						{
							result3.Mode = result4;
						}
						break;
					}
					case "fromdefault":
						result3.FromDefault = reader.GetBoolean();
						break;
					}
				}
				throw new JsonException("Expected EndObject token");
			}
			case JsonTokenType.String:
			{
				string text = reader.GetString()?.Trim();
				if (string.IsNullOrEmpty(text))
				{
					throw new JsonException("ValueBase string value is null or empty!");
				}
				bool fromDefault = false;
				if (text.EndsWith("of default", StringComparison.OrdinalIgnoreCase))
				{
					fromDefault = true;
					string text2 = text;
					text = text2.Substring(0, text2.Length - 10).TrimEnd();
				}
				if (text.EndsWith("%", StringComparison.InvariantCulture))
				{
					string text2 = text;
					if (float.TryParse(text2.Substring(0, text2.Length - 1).TrimEnd(), NumberStyles.Float | NumberStyles.AllowThousands, CultureInfo.InvariantCulture, out var result))
					{
						return new ValueBase(result / 100f, ValueMode.Rel, fromDefault);
					}
				}
				if (text.EqualsAny(true, "Unchanged", "Ignore", "Keep", "Original", "KeepOriginal"))
				{
					return new ValueBase(1f, ValueMode.Rel, fromDefault: false);
				}
				if (float.TryParse(text, NumberStyles.Float | NumberStyles.AllowThousands, CultureInfo.InvariantCulture, out var result2))
				{
					return new ValueBase(result2, ValueMode.Abs);
				}
				throw new JsonException("Cannot parse ValueBase string: " + text + "! Are you sure it's in right format?");
			}
			default:
				throw new JsonException($"ValueBaseJson type: {reader.TokenType} is not implemented!");
			}
		}

		public override void Write(Utf8JsonWriter writer, ValueBase value, JsonSerializerOptions options)
		{
			switch (value.Mode)
			{
			case ValueMode.Rel:
			{
				if (Mathf.Approximately(value.Value, 1f))
				{
					writer.WriteStringValue("Unchanged");
					break;
				}
				string format = (value.FromDefault ? "{0}% of default" : "{0}%");
				writer.WriteStringValue(string.Format(format, value.Value * 100f));
				break;
			}
			case ValueMode.Abs:
				writer.WriteStringValue(value.Value.ToString());
				break;
			}
			writer.WriteCommentValue("ValueBase");
		}
	}
}
namespace AmorLib.Utils.Extensions
{
	public static class CollectionExtensions
	{
		public static TValue GetOrAddNew<TKey, TValue>(this IDictionary<TKey, TValue> dict, TKey key) where TValue : new()
		{
			if (!dict.TryGetValue(key, out TValue value))
			{
				value = (dict[key] = new TValue());
			}
			return value;
		}

		public static void ForEachValue<TKey, TValue>(this IDictionary<TKey, TValue> dict, Action<TValue> action) where TKey : notnull
		{
			foreach (TValue value in dict.Values)
			{
				action(value);
			}
		}

		public static bool AnyAllValues<TKey, TCollection, TValue>(this IDictionary<TKey, TCollection> dict, Func<TValue, bool> predicate) where TCollection : IEnumerable<TValue>
		{
			foreach (TCollection value in dict.Values)
			{
				if (value.Any(predicate))
				{
					return true;
				}
			}
			return false;
		}

		public static TValue? FirstOrDefaultAllValues<TKey, TCollection, TValue>(this IDictionary<TKey, TCollection> dict, Func<TValue, bool> predicate) where TCollection : IEnumerable<TValue>
		{
			foreach (TCollection value in dict.Values)
			{
				foreach (TValue item in value)
				{
					if (predicate(item))
					{
						return item;
					}
				}
			}
			return default(TValue);
		}
	}
	public static class GameObjectPlusExtensions
	{
		public static bool TryAndGetComponent<T>(this GameObject go, out T component)
		{
			component = go.GetComponent<T>();
			return component != null;
		}

		public static T AddOrGetComponent<T>(this GameObject go) where T : Component
		{
			if (!go.TryAndGetComponent<T>(out var component))
			{
				return go.AddComponent<T>();
			}
			return component;
		}

		public static string GetFullPath(this GameObject go)
		{
			StringBuilder stringBuilder = new StringBuilder(((Object)go).name);
			Transform parent = go.transform.parent;
			while ((Object)(object)parent != (Object)null)
			{
				stringBuilder.Insert(0, ((Object)parent).name + "/");
				parent = parent.parent;
			}
			return stringBuilder.ToString();
		}

		public static GameObject ClonePrefabSpawners(this GameObject original, Vector3 position, Quaternion rotation, Transform parent)
		{
			//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_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_00b6: Unknown result type (might be due to invalid IL or missing references)
			GameObject val = Object.Instantiate<GameObject>(original, position, rotation, parent);
			foreach (LG_PrefabSpawner componentsInChild in val.GetComponentsInChildren<LG_PrefabSpawner>())
			{
				try
				{
					GameObject val2 = Object.Instantiate<GameObject>(componentsInChild.m_prefab, ((Component)componentsInChild).transform.position, ((Component)componentsInChild).transform.rotation, ((Component)componentsInChild).transform.parent);
					if (componentsInChild.m_disableCollision)
					{
						foreach (Collider componentsInChild2 in val2.GetComponentsInChildren<Collider>())
						{
							componentsInChild2.enabled = false;
						}
					}
					if (componentsInChild.m_applyScale)
					{
						val2.transform.localScale = ((Component)componentsInChild).transform.localScale;
					}
					val2.transform.SetParent(((Component)componentsInChild).transform);
				}
				catch
				{
				}
			}
			return val;
		}

		public static uint PostWithCleanup(this CellSoundPlayer soundPlayer, uint eventID, Vector3 pos, uint in_uFlags = 1u)
		{
			//IL_0003: Unknown result type (might be due to invalid IL or missing references)
			return soundPlayer.Post(eventID, pos, in_uFlags, EventCallback.op_Implicit((Action<Object, AkCallbackType, AkCallbackInfo>)SoundDoneCallback), (Object)(object)soundPlayer);
		}

		private static void SoundDoneCallback(Object in_pCookie, AkCallbackType in_type, AkCallbackInfo callbackInfo)
		{
			CellSoundPlayer val = ((Il2CppObjectBase)in_pCookie).Cast<CellSoundPlayer>();
			if (val != null)
			{
				val.Recycle();
			}
		}

		public static bool IsWithinSqrDistance(this Vector3 a, Vector3 b, float sqrThreshold, out float sqrDistance)
		{
			//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_0004: 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)
			Vector3 val = a - b;
			sqrDistance = ((Vector3)(ref val)).sqrMagnitude;
			return sqrDistance <= sqrThreshold;
		}

		public static bool IsWithinSqrDistance(this Vector3 a, Vector3 b, float sqrThreshold)
		{
			//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_0003: 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)
			Vector3 val = a - b;
			float sqrMagnitude = ((Vector3)(ref val)).sqrMagnitude;
			return sqrMagnitude <= sqrThreshold;
		}
	}
	public static class PluginInfoExtensions
	{
		public static bool VersionEquals(this PluginInfo pluginInfo, string verison)
		{
			int? num = CompareVersion(pluginInfo, verison);
			return num.HasValue && num.GetValueOrDefault() == 0;
		}

		public static bool VersionExceeds(this PluginInfo pluginInfo, string version)
		{
			int? num = CompareVersion(pluginInfo, version);
			return num.HasValue && num.GetValueOrDefault() > 0;
		}

		public static bool VersionAtLeast(this PluginInfo pluginInfo, string version)
		{
			int? num = CompareVersion(pluginInfo, version);
			return num.HasValue && num.GetValueOrDefault() >= 0;
		}

		private static int? CompareVersion(PluginInfo pluginInfo, string verison)
		{
			//IL_00cc: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d6: Expected O, but got Unknown
			object obj;
			if (pluginInfo == null)
			{
				obj = null;
			}
			else
			{
				BepInPlugin metadata = pluginInfo.Metadata;
				obj = ((metadata != null) ? metadata.Version : null);
			}
			if ((Version)obj == (Version)null)
			{
				Logger.Error("PluginInfo or Version.Metadata is null");
				return null;
			}
			Match match = Regex.Match(verison, "^(\\d+)\\.(\\d+)\\.(\\d+)$");
			if (!match.Success)
			{
				Logger.Error("Version string format is incorrect");
				return null;
			}
			int num = int.Parse(match.Groups[1].Value);
			int num2 = int.Parse(match.Groups[2].Value);
			int num3 = int.Parse(match.Groups[3].Value);
			return pluginInfo.Metadata.Version.CompareTo(new Version(num, num2, num3, (string)null, (string)null));
		}
	}
	public static class StringExtensions
	{
		public static bool EqualsAny(this string input, bool ignoreCase = false, params string[] args)
		{
			StringComparison comparisonType = (ignoreCase ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal);
			foreach (string value in args)
			{
				if (input.Equals(value, comparisonType))
				{
					return true;
				}
			}
			return false;
		}

		public static LocaleText ToLocaleText(this string input)
		{
			return new LocaleText(input);
		}
	}
}
namespace AmorLib.Patches.SNet
{
	[HarmonyPatch(typeof(CheckpointManager), "OnStateChange")]
	internal static class Patch_CheckpointState
	{
		[HarmonyPostfix]
		[HarmonyWrapSafe]
		public static void Post_CheckpointStateChange(pCheckpointState 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_0008: Invalid comparison between Unknown and I4
			if ((int)newState.lastInteraction == 2)
			{
				SNetEvents.CheckpointReloaded();
			}
		}
	}
	[HarmonyPatch(typeof(SNet_SyncManager), "OnRecallDone")]
	internal static class Patch_OnRecallDone
	{
		[HarmonyPostfix]
		[HarmonyWrapSafe]
		private static void Post_RecallDone()
		{
			SNetEvents.RecallDone();
		}
	}
	[HarmonyPatch(typeof(SNet_Capture))]
	internal static class Patch_SNet_Capture
	{
		[HarmonyPatch("TriggerCapture")]
		[HarmonyPrefix]
		[HarmonyWrapSafe]
		private static void Pre_TriggerCapture(SNet_Capture __instance)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			SNetEvents.BufferCaptured(__instance.PrimedBufferType);
		}

		[HarmonyPatch("RecallBuffer")]
		[HarmonyPostfix]
		[HarmonyWrapSafe]
		private static void Post_RecallBuffer(SNet_Capture __instance, eBufferType bufferType)
		{
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			if (!__instance.IsRecalling)
			{
				SNetEvents.BufferRecalled(bufferType);
			}
		}
	}
}
namespace AmorLib.Patches.LevelGen
{
	[HarmonyPatch]
	internal static class BuilderPatches
	{
		[HarmonyPatch(typeof(Builder), "BuildDone")]
		[HarmonyPostfix]
		[HarmonyBefore(new string[] { "dev.gtfomodding.gtfo-api" })]
		[HarmonyWrapSafe]
		private static void BuildDone_Early()
		{
			LevelEvents.BuildDoneEarly();
		}

		[HarmonyPatch(typeof(Builder), "BuildDone")]
		[HarmonyPostfix]
		[HarmonyAfter(new string[] { "dev.gtfomodding.gtfo-api" })]
		[HarmonyWrapSafe]
		private static void BuildDone_Late()
		{
			LevelEvents.BuildDoneLate();
		}
	}
	[HarmonyPatch(typeof(LG_BuildZoneLightsJob), "Build")]
	internal static class LightsPatches
	{
		[HarmonyPrefix]
		[HarmonyPriority(600)]
		[HarmonyWrapSafe]
		private static void Pre_ZoneBuild(LG_BuildZoneLightsJob __instance, out List<LightWorker>? __state)
		{
			LG_Zone zone = __instance.m_zone;
			if ((Object)(object)zone == (Object)null)
			{
				__state = null;
				return;
			}
			__state = new List<LightWorker>();
			Enumerator<AIG_CourseNode> enumerator = zone.m_courseNodes.GetEnumerator();
			while (enumerator.MoveNext())
			{
				AIG_CourseNode current = enumerator.Current;
				foreach (LG_Light componentsInChild in ((Component)current.m_area).GetComponentsInChildren<LG_Light>(false))
				{
					__state.Add(new LightWorker(zone, current, componentsInChild, ((Object)componentsInChild).GetInstanceID(), componentsInChild.m_intensity));
				}
			}
		}

		[HarmonyPostfix]
		[HarmonyPriority(600)]
		[HarmonyWrapSafe]
		private static void Post_ZoneBuild(LG_BuildZoneLightsJob __instance, bool __result, List<LightWorker>? __state)
		{
			if ((Object)(object)__instance.m_zone == (Object)null || !__result || __state == null)
			{
				return;
			}
			foreach (LightWorker item in __state)
			{
				item.Setup();
				LightAPI.AllLightsMap.TryAdd(item.InstanceID, item);
			}
		}
	}
	[HarmonyPatch]
	internal static class TerminalPatches
	{
		private static readonly Dictionary<(int, int, int), LG_ComputerTerminal> ReactorTerminals;

		static TerminalPatches()
		{
			ReactorTerminals = new Dictionary<(int, int, int), LG_ComputerTerminal>();
			LevelAPI.OnAfterBuildBatch += OnAfterBatchBuild;
			LevelAPI.OnLevelCleanup += OnLevelCleanup;
		}

		private static void OnAfterBatchBuild(BatchName batch)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0004: Invalid comparison between Unknown and I4
			if ((int)batch != 47)
			{
				return;
			}
			foreach (KeyValuePair<(int, int, int), LG_ComputerTerminal> kvp in ReactorTerminals)
			{
				if (kvp.Key.TryGetZone(out LG_Zone zone) && !ListExtensions.ToManaged<LG_ComputerTerminal>(zone.TerminalsSpawnedInZone).Any((LG_ComputerTerminal term) => term.SyncID == kvp.Value.SyncID))
				{
					zone.TerminalsSpawnedInZone.Add(kvp.Value);
					Logger.Debug("Appended reactor terminal to its TerminalsSpawnedInZone");
				}
			}
		}

		private static void OnLevelCleanup()
		{
			ReactorTerminals.Clear();
		}

		[HarmonyPatch(typeof(LG_ComputerTerminalCommandInterpreter), "ReceiveCommand")]
		[HarmonyPrefix]
		[HarmonyPriority(700)]
		[HarmonyWrapSafe]
		private static void HiddenCommandExecutionFix(LG_ComputerTerminalCommandInterpreter __instance, ref TERM_Command cmd)
		{
			//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_0019: 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_001c: Invalid comparison between Unknown and I4
			//IL_002b: 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_0030: Invalid comparison between Unknown and I4
			//IL_001e: 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_0037: Invalid comparison between Unknown and I4
			//IL_0023: 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: Invalid comparison between Unknown and I4
			//IL_003b: Unknown result type (might be due to invalid IL or missing references)
			//IL_003e: Invalid comparison between Unknown and I4
			if (((Il2CppArrayBase<TERM_Command>)(object)LG_ComputerTerminalCommandInterpreter.m_alwaysHiddenCommands).Contains(cmd))
			{
				return;
			}
			TERM_Command val = cmd;
			TERM_Command val2 = val;
			if ((int)val2 <= 6)
			{
				if ((int)val2 == 0 || val2 - 5 <= 1)
				{
					return;
				}
			}
			else if (val2 - 10 <= 1 || (int)val2 == 16 || (int)val2 == 31)
			{
				return;
			}
			if (__instance.m_terminal.CommandIsHidden(cmd))
			{
				cmd = (TERM_Command)10;
			}
		}

		[HarmonyPatch(typeof(LG_WardenObjective_Reactor), "Start")]
		[HarmonyPostfix]
		[HarmonyWrapSafe]
		private static void CustomReactorTerminalFix(LG_WardenObjective_Reactor __instance)
		{
			if (!((BaseChainloader<BasePlugin>)(object)IL2CPPChainloader.Instance).Plugins.ContainsKey("FlowGeos") && !((Object)(object)__instance.m_terminalPrefab != (Object)null))
			{
				Logger.Info("Resolving terminal prefab for reactor");
				GameObject loadedAsset = AssetAPI.GetLoadedAsset<GameObject>("Assets/AssetPrefabs/Complex/Generic/FunctionMarkers/Terminal_Floor.prefab");
				if ((Object)(object)loadedAsset == (Object)null)
				{
					Logger.Error("Failed to find terminal prefab loaded asset?");
				}
				else
				{
					__instance.m_terminalPrefab = loadedAsset;
				}
			}
		}

		[HarmonyPatch(/*Could not decode attribute arguments.*/)]
		[HarmonyPrefix]
		private static bool ReactorTerminalSpawnNodeFix(LG_ComputerTerminal __instance, ref AIG_CourseNode __result)
		{
			if ((Object)(object)__instance.ConnectedReactor != (Object)null && __instance.m_terminalItem.SpawnNode == null)
			{
				__result = __instance.ConnectedReactor.SpawnNode;
				return false;
			}
			return true;
		}

		[HarmonyPatch(typeof(LG_WardenObjective_Reactor), "GenericObjectiveSetup")]
		[HarmonyPostfix]
		[HarmonyWrapSafe]
		private static void ReactorTerminalInZoneFix(LG_WardenObjective_Reactor __instance)
		{
			if (__instance.SpawnNode.m_zone.TerminalsSpawnedInZone != null && (Object)(object)__instance.m_terminal != (Object)null)
			{
				ReactorTerminals.Add(__instance.SpawnNode.m_zone.ToIntTuple(), __instance.m_terminal);
			}
		}
	}
}
namespace AmorLib.Networking
{
	public struct LowResColor
	{
		public byte r;

		public byte g;

		public byte b;

		public byte a;

		private static Color _color = Color.black;

		public static implicit operator Color(LowResColor lowResColor)
		{
			//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)
			_color.r = (float)(int)lowResColor.r / 255f;
			_color.g = (float)(int)lowResColor.g / 255f;
			_color.b = (float)(int)lowResColor.b / 255f;
			_color.a = (float)(int)lowResColor.a / 255f;
			return _color;
		}

		public static implicit operator LowResColor(Color color)
		{
			//IL_000b: 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_0033: 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)
			LowResColor result = default(LowResColor);
			result.r = (byte)(color.r * 255f);
			result.g = (byte)(color.g * 255f);
			result.b = (byte)(color.b * 255f);
			result.a = (byte)(color.a * 255f);
			return result;
		}
	}
	public static class StateReplicatorManager
	{
		internal static readonly Dictionary<Type, HashSet<uint>> _reservedReplicators = new Dictionary<Type, HashSet<uint>>();

		public static void ReserveIDs<T>(params uint[] args)
		{
			//IL_0035: Unknown result type (might be due to invalid IL or missing references)
			//IL_003c: Expected O, but got Unknown
			HashSet<uint> orAddNew = _reservedReplicators.GetOrAddNew(typeof(T));
			bool flag = default(bool);
			foreach (uint num in args)
			{
				if (orAddNew.Contains(num))
				{
					BepInExErrorLogInterpolatedStringHandler val = new BepInExErrorLogInterpolatedStringHandler(41, 2, ref flag);
					if (flag)
					{
						((BepInExLogInterpolatedStringHandler)val).AppendLiteral("StateReplicator ");
						((BepInExLogInterpolatedStringHandler)val).AppendFormatted<Type>(typeof(T));
						((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" already has reserved ID ");
						((BepInExLogInterpolatedStringHandler)val).AppendFormatted<uint>(num);
					}
					Logger.Error(val);
				}
				else
				{
					orAddNew.Add(num);
				}
			}
		}

		public static void DeregisterIds<T>(params uint[] args)
		{
			if (_reservedReplicators.TryGetValue(typeof(T), out HashSet<uint> value))
			{
				foreach (uint item in args)
				{
					value.Remove(item);
				}
			}
		}
	}
	public abstract class SyncedEvent<S> where S : struct
	{
		public delegate void ReceiveHandler(S packet);

		public virtual string Prefix => string.Empty;

		public abstract string GUID { get; }

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


		public string EventName { get; private set; } = string.Empty;


		public event ReceiveHandler? OnReceive;

		public event ReceiveHandler? OnReceiveLocal;

		public void Setup()
		{
			if (!IsSetup)
			{
				EventName = (Utility.IsNullOrWhiteSpace(Prefix) ? ("SE-" + GUID) : ("SE-" + Prefix + "-" + GUID));
				NetworkAPI.RegisterEvent<S>(EventName, (Action<ulong, S>)ReceiveClient_Callback);
				IsSetup = true;
			}
		}

		public void Send(S packetData, SNet_Player? target = null, SNet_ChannelType priority = 4)
		{
			//IL_0027: 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)
			if ((Object)(object)target != (Object)null)
			{
				NetworkAPI.InvokeEvent<S>(EventName, packetData, target, priority);
			}
			else
			{
				NetworkAPI.InvokeEvent<S>(EventName, packetData, priority);
			}
			ReceiveLocal_Callback(packetData);
		}

		private void ReceiveLocal_Callback(S packet)
		{
			ReceiveLocal(packet);
			this.OnReceiveLocal?.Invoke(packet);
		}

		private void ReceiveClient_Callback(ulong sender, S packet)
		{
			Receive(packet);
			this.OnReceive?.Invoke(packet);
		}

		protected virtual void ReceiveLocal(S packet)
		{
		}

		protected virtual void Receive(S packet)
		{
		}
	}
	public abstract class SyncedEventMasterOnly<S> : SyncedEvent<S> where S : struct
	{
		public void Send(S packet, SNet_ChannelType priority = 4)
		{
			//IL_0014: Unknown result type (might be due to invalid IL or missing references)
			if (!SNet.IsMaster)
			{
				Send(packet, SNet.Master, priority);
			}
			else
			{
				Receive(packet);
			}
		}
	}
}
namespace AmorLib.Networking.StateReplicators
{
	public interface IStateReplicatorHolder<S> where S : struct
	{
		StateReplicator<S>? Replicator { get; }

		void OnStateChange(S oldState, S state, bool isRecall);
	}
	public struct Packet
	{
		public uint replicatorID;

		public PacketAction action;
	}
	public enum PacketAction : byte
	{
		Created,
		Destroyed,
		SyncRequest
	}
	internal sealed class ReplicatorHandshake
	{
		public delegate void ClientRequestedSyncDel(SNet_Player requestedPlayer);

		private readonly Dictionary<uint, (bool SetupOnHost, bool SetupOnClient)> _lookup = new Dictionary<uint, (bool, bool)>();

		public string EventName { get; private set; }

		public bool IsReadyToSync { get; private set; }

		public event ClientRequestedSyncDel? OnClientSyncRequested;

		public ReplicatorHandshake(string eventName)
		{
			EventName = eventName;
			NetworkAPI.RegisterEvent<Packet>(EventName, (Action<ulong, Packet>)OnSyncAction);
			SNetEvents.OnRecallDone += OnRecallDone;
		}

		private void OnRecallDone()
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: Expected O, but got Unknown
			bool flag = default(bool);
			BepInExWarningLogInterpolatedStringHandler val = new BepInExWarningLogInterpolatedStringHandler(42, 1, ref flag);
			if (flag)
			{
				((BepInExLogInterpolatedStringHandler)val).AppendLiteral("Handshake :: ");
				((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(EventName);
				((BepInExLogInterpolatedStringHandler)val).AppendLiteral(", Client sending sync request");
			}
			Logger.Warn(val);
			ClientSyncRequest();
		}

		private void ClientSyncRequest()
		{
			if (SNet.IsMaster)
			{
				return;
			}
			foreach (uint key in _lookup.Keys)
			{
				NetworkAPI.InvokeEvent<Packet>(EventName, new Packet
				{
					replicatorID = key,
					action = PacketAction.SyncRequest
				}, SNet.Master, (SNet_ChannelType)2);
			}
		}

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

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

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

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

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

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

		private void UpdateSyncState(uint id)
		{
			bool isReadyToSync = IsReadyToSync;
			IsReadyToSync = _lookup.TryGetValue(id, out (bool, bool) value) && value.Item1 && value.Item2;
			if (IsReadyToSync && IsReadyToSync != isReadyToSync && SNet.HasMaster && !SNet.IsMaster)
			{
				NetworkAPI.InvokeEvent<Packet>(EventName, new Packet
				{
					replicatorID = id,
					action = PacketAction.SyncRequest
				}, SNet.Master, (SNet_ChannelType)2);
			}
		}
	}
	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
	}
	internal delegate void OnReceiveDel<S>(ulong sender, uint replicatorID, S newState) where S : struct;
	internal interface IReplicatorEvent<S>
	{
		string EventName { get; }

		bool IsRegistered { get; }

		void Invoke(uint replicatorID, S data, SNet_Player? target = null, SNet_ChannelType priority = 2);
	}
	internal interface IStatePayload
	{
		uint ID { get; set; }

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

		void Set<S>(S stateData, Size size) where S : struct;
	}
	internal class ReplicatorPayload<S, P> : IReplicatorEvent<S> where S : struct where P : struct, IStatePayload
	{
		private readonly Size _payloadSize;

		public string EventName { get; private set; } = string.Empty;


		public bool IsRegistered => NetworkAPI.IsEventRegistered(EventName);

		public ReplicatorPayload(Size size, string eventName, OnReceiveDel<S> onReceiveCallback)
		{
			OnReceiveDel<S> onReceiveCallback2 = onReceiveCallback;
			base..ctor();
			ReplicatorPayload<S, P> replicatorPayload = this;
			NetworkAPI.RegisterEvent<P>(eventName, (Action<ulong, P>)delegate(ulong sender, P payload)
			{
				onReceiveCallback2?.Invoke(sender, payload.ID, payload.Get<S>(replicatorPayload._payloadSize));
			});
			EventName = eventName;
			_payloadSize = size;
		}

		public void Invoke(uint replicatorID, S data, SNet_Player? target, SNet_ChannelType priority)
		{
			//IL_0054: Unknown result type (might be due to invalid IL or missing references)
			//IL_0041: Unknown result type (might be due to invalid IL or missing references)
			P val = new P
			{
				ID = replicatorID
			};
			val.Set(data, _payloadSize);
			if ((Object)(object)target != (Object)null)
			{
				NetworkAPI.InvokeEvent<P>(EventName, val, target, priority);
			}
			else
			{
				NetworkAPI.InvokeEvent<P>(EventName, val, priority);
			}
		}
	}
	internal struct StatePayloadBytes : IStatePayload
	{
		public unsafe fixed byte PayloadBytes[256];

		public uint ID { get; set; }

		public unsafe S Get<S>(Size size) where S : struct
		{
			byte[] array = new byte[(int)size];
			fixed (byte* ptr = PayloadBytes)
			{
				Marshal.Copy((IntPtr)ptr, array, 0, (int)size);
			}
			return FromBytes<S>(array);
		}

		public unsafe void Set<S>(S stateData, Size size) where S : struct
		{
			byte[] array = ToBytes(stateData);
			if (array.Length > (int)size)
			{
				throw new ArgumentException($"Data size {array.Length} exceeds payload size {size}, unable to serialize {"S"}!");
			}
			fixed (byte* ptr = PayloadBytes)
			{
				Marshal.Copy(array, 0, (IntPtr)ptr, array.Length);
				for (int i = array.Length; i < (int)size; i++)
				{
					ptr[i] = 0;
				}
			}
		}

		private static byte[] ToBytes<S>(S data) where S : struct
		{
			int num = Marshal.SizeOf<S>();
			byte[] array = new byte[num];
			IntPtr intPtr = Marshal.AllocHGlobal(num);
			try
			{
				Marshal.StructureToPtr(data, intPtr, fDeleteOld: false);
				Marshal.Copy(intPtr, array, 0, num);
				return array;
			}
			finally
			{
				Marshal.FreeHGlobal(intPtr);
			}
		}

		private static S FromBytes<S>(byte[] arr) where S : struct
		{
			IntPtr intPtr = Marshal.AllocHGlobal(arr.Length);
			try
			{
				Marshal.Copy(arr, 0, intPtr, arr.Length);
				return Marshal.PtrToStructure<S>(intPtr);
			}
			finally
			{
				Marshal.FreeHGlobal(intPtr);
			}
		}
	}
	public enum LifeTimeType
	{
		Permanent,
		Session
	}
	public sealed class StateReplicator<S> where S : struct
	{
		internal 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 string HandshakeEventName;

		public static readonly int StateSize;

		public static readonly Size StateSizeType;

		private static readonly IReplicatorEvent<S>? _clientRequestEvent;

		private static readonly IReplicatorEvent<S>? _hostSetStateEvent;

		private static readonly IReplicatorEvent<S>? _hostSetRecallStateEvent;

		private static readonly ReplicatorHandshake? _handshake;

		internal 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 S LastState { get; private set; }

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


		public bool CanSendToClient => SNet.IsInLobby && SNet.IsMaster;

		public bool CanSendToHost => SNet.IsInLobby && !SNet.IsMaster && SNet.HasMaster && ClientSendStateAllowed;

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

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

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

		public void Unload()
		{
			if (IsValid)
			{
				_replicators.Remove(ID);
				_recallStateSnapshots.Clear();
				_handshake?.UpdateDestroyed(ID);
				ID = 0u;
			}
		}

		private void DoSync(S newState)
		{
			if (IsValid)
			{
				if (CanSendToClient)
				{
					_hostSetStateEvent?.Invoke(ID, newState, null, (SNet_ChannelType)2);
					Internal_ChangeState(newState, isRecall: false);
				}
				else if (CanSendToHost)
				{
					_clientRequestEvent?.Invoke(ID, newState, SNet.Master, (SNet_ChannelType)2);
				}
			}
		}

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

		private void SendDropInState(SNet_Player target)
		{
			//IL_001d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0023: Expected O, but got Unknown
			if (IsInvalid || (Object)(object)target == (Object)null)
			{
				bool flag = default(bool);
				BepInExErrorLogInterpolatedStringHandler val = new BepInExErrorLogInterpolatedStringHandler(35, 3, ref flag);
				if (flag)
				{
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral("IsInvalid: ");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<bool>(IsInvalid);
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral(", ");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>("SendDropInState");
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" :: Target was null? ");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<bool>((Object)(object)target == (Object)null);
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral("?");
				}
				Logger.Error(val);
			}
			else
			{
				_hostSetRecallStateEvent?.Invoke(ID, State, target, (SNet_ChannelType)2);
			}
		}

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

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

		private void RestoreSnapshot(eBufferType type)
		{
			//IL_001d: 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_005c: Expected O, but got Unknown
			//IL_0079: Unknown result type (might be due to invalid IL or missing references)
			if (!IsValid || !CanSendToClient)
			{
				return;
			}
			if (_recallStateSnapshots.TryGetValue(type, out var value))
			{
				_hostSetRecallStateEvent?.Invoke(ID, value, null, (SNet_ChannelType)2);
				Internal_ChangeState(value, isRecall: true);
				return;
			}
			bool flag = default(bool);
			BepInExErrorLogInterpolatedStringHandler val = new BepInExErrorLogInterpolatedStringHandler(31, 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 = GetSizeType(StateSize);
			using MD5 mD = MD5.Create();
			byte[] inArray = mD.ComputeHash(Encoding.UTF8.GetBytes(typeof(S).FullName));
			HashName = Convert.ToBase64String(inArray);
			ClientRequestEventName = "SRcr-" + Name + "-" + HashName;
			HostSetStateEventName = "SRhs-" + Name + "-" + HashName;
			HostSetRecallStateEventName = "SRre-" + Name + "-" + HashName;
			HandshakeEventName = "RH-" + Name + "-" + HashName;
			_clientRequestEvent = CreatePayloadEvent(ClientRequestEventName, ClientRequestEventCallback);
			_hostSetStateEvent = CreatePayloadEvent(HostSetStateEventName, HostSetStateEventCallback);
			_hostSetRecallStateEvent = CreatePayloadEvent(HostSetRecallStateEventName, HostSetRecallStateEventCallback);
			_handshake = CreateHandshakeEvent();
			SNetEvents.OnBufferCapture += BufferStored;
			SNetEvents.OnBufferRecall += BufferRecalled;
			LevelAPI.OnLevelCleanup += OnLevelCleanup;
		}

		public static StateReplicator<S>? Create(uint replicatorID, S startState, LifeTimeType lifeTime, IStateReplicatorHolder<S>? holder = null)
		{
			//IL_00a3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00aa: 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 = holder,
				State = startState
			};
			switch (lifeTime)
			{
			case LifeTimeType.Permanent:
				Logger.Debug("LifeTime is Permanent :: Handshaking is disabled");
				break;
			case LifeTimeType.Session:
				_handshake?.UpdateCreated(replicatorID);
				break;
			default:
			{
				bool flag = default(bool);
				BepInExErrorLogInterpolatedStringHandler val = new BepInExErrorLogInterpolatedStringHandler(21, 1, ref flag);
				if (flag)
				{
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral("LifeTime ");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<LifeTimeType>(lifeTime);
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" is invalid!");
				}
				Logger.Error(val);
				return null;
			}
			}
			_replicators[replicatorID] = stateReplicator;
			return stateReplicator;
		}

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

		private static IReplicatorEvent<S>? CreatePayloadEvent(string name, OnReceiveDel<S> callback)
		{
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_0017: Expected O, but got Unknown
			if (NetworkAPI.IsEventRegistered(name))
			{
				bool flag = default(bool);
				BepInExErrorLogInterpolatedStringHandler val = new BepInExErrorLogInterpolatedStringHandler(77, 3, ref flag);
				if (flag)
				{
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral("ReplicatorPayload<");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(Name);
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral(">.");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>("callback");
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" failed to initialize: Event name ");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(name);
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" is already registered!");
				}
				Logger.Error(val);
				return null;
			}
			return new ReplicatorPayload<S, StatePayloadBytes>(StateSizeType, name, callback);
		}

		private static ReplicatorHandshake? CreateHandshakeEvent()
		{
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			//IL_001b: Expected O, but got Unknown
			if (NetworkAPI.IsEventRegistered(HandshakeEventName))
			{
				bool flag = default(bool);
				BepInExErrorLogInterpolatedStringHandler val = new BepInExErrorLogInterpolatedStringHandler(78, 2, ref flag);
				if (flag)
				{
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral("ReplicatorHandshake<");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(Name);
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral("> failed to initialize: Event name ");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(HandshakeEventName);
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" is already registered!");
				}
				Logger.Error(val);
				return null;
			}
			ReplicatorHandshake replicatorHandshake = new ReplicatorHandshake(HandshakeEventName);
			replicatorHandshake.OnClientSyncRequested += ClientSyncRequested;
			return replicatorHandshake;
		}

		private static void ClientRequestEventCallback(ulong sender, uint replicatorID, S newState)
		{
			if (SNet.IsMaster && _replicators.TryGetValue(replicatorID, out StateReplicator<S> 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 StateReplicator<S> 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 StateReplicator<S> value))
			{
				value.Internal_ChangeState(newState, isRecall: true);
			}
		}

		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_0029: 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_0029: 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 OnLevelCleanup()
		{
			UnloadSessionReplicators();
		}

		public static void UnloadSessionReplicators()
		{
			List<uint> list = new List<uint>();
			foreach (StateReplicator<S> value in _replicators.Values)
			{
				if (value.LifeTime == LifeTimeType.Session)
				{
					list.Add(value.ID);
					value.Unload();
				}
			}
			foreach (uint item in list)
			{
				_replicators.Remove(item);
			}
			_handshake?.Reset();
		}
	}
}
namespace AmorLib.Events
{
	public static class LevelEvents
	{
		public static event Action? OnBuildDoneEarly;

		public static event Action? OnBuildDoneLate;

		internal static void BuildDoneEarly()
		{
			SafeInvoke.Invoke(LevelEvents.OnBuildDoneEarly);
		}

		internal static void BuildDoneLate()
		{
			SafeInvoke.Invoke(LevelEvents.OnBuildDoneLate);
		}
	}
	public static class SNetEvents
	{
		public static event Action<eBufferType>? OnBufferCapture;

		public static event Action<eBufferType>? OnBufferRecall;

		public static event Action? OnCheckpointReload;

		public static event Action? OnRecallDone;

		internal static void BufferCaptured(eBufferType bufferType)
		{
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			SafeInvoke.Invoke<eBufferType>(SNetEvents.OnBufferCapture, bufferType);
		}

		internal static void BufferRecalled(eBufferType bufferType)
		{
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			SafeInvoke.Invoke<eBufferType>(SNetEvents.OnBufferRecall, bufferType);
		}

		internal static void CheckpointReloaded()
		{
			SafeInvoke.Invoke(SNetEvents.OnCheckpointReload);
		}

		internal static void RecallDone()
		{
			SafeInvoke.Invoke(SNetEvents.OnRecallDone);
		}
	}
}
namespace AmorLib.Dependencies
{
	[CallConstructorOnLoad]
	public static class InjectLib_Wrapper
	{
		public const string PLUGIN_GUID = "GTFO.InjectLib";

		public static bool IsLoaded { get; private set; }

		public static JsonConverter? InjectLibConverter { get; private set; }

		static InjectLib_Wrapper()
		{
			//IL_0039: Unknown result type (might be due to invalid IL or missing references)
			//IL_003f: Expected O, but got Unknown
			IsLoaded = false;
			InjectLibConverter = null;
			if (((BaseChainloader<BasePlugin>)(object)IL2CPPChainloader.Instance).Plugins.ContainsKey("GTFO.InjectLib"))
			{
				IsLoaded = true;
				SetConverter();
			}
			bool flag = default(bool);
			BepInExDebugLogInterpolatedStringHandler val = new BepInExDebugLogInterpolatedStringHandler(21, 1, ref flag);
			if (flag)
			{
				((BepInExLogInterpolatedStringHandler)val).AppendLiteral("InjectLib is loaded: ");
				((BepInExLogInterpolatedStringHandler)val).AppendFormatted<bool>(IsLoaded);
			}
			Logger.Debug(val);
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		private static void SetConverter()
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_000b: Expected O, but got Unknown
			InjectLibConverter = (JsonConverter?)new InjectLibConnector();
		}
	}
	[CallConstructorOnLoad]
	public static class PData_Wrapper
	{
		public const string PLUGIN_GUID = "MTFO.Extension.PartialBlocks";

		public static bool IsLoaded { get; private set; }

		public static bool IsMainBranch { get; private set; }

		public static JsonConverter? PersistentIDConverter { get; private set; }

		static PData_Wrapper()
		{
			//IL_00af: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b6: Expected O, but got Unknown
			//IL_00e2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e9: Expected O, but got Unknown
			IsLoaded = false;
			IsMainBranch = false;
			PersistentIDConverter = null;
			bool flag = default(bool);
			if (((BaseChainloader<BasePlugin>)(object)IL2CPPChainloader.Instance).Plugins.TryGetValue("MTFO.Extension.PartialBlocks", out var value))
			{
				try
				{
					IsMainBranch = value.VersionAtLeast("1.5.2");
					Type type = AccessTools.TypeByName("MTFO.Ext.PartialData.JsonConverters.PersistentIDConverter");
					if (type != null && typeof(JsonConverter).IsAssignableFrom(type))
					{
						PersistentIDConverter = (JsonConverter)Activator.CreateInstance(type);
						IsLoaded = PersistentIDConverter != null;
					}
				}
				catch (Exception ex)
				{
					IsLoaded = false;
					IsMainBranch = false;
					PersistentIDConverter = null;
					BepInExErrorLogInterpolatedStringHandler val = new BepInExErrorLogInterpolatedStringHandler(54, 1, ref flag);
					if (flag)
					{
						((BepInExLogInterpolatedStringHandler)val).AppendLiteral("Exception thrown while reading data from PartialData:\n");
						((BepInExLogInterpolatedStringHandler)val).AppendFormatted<Exception>(ex);
					}
					Logger.Error(val);
				}
			}
			BepInExDebugLogInterpolatedStringHandler val2 = new BepInExDebugLogInterpolatedStringHandler(57, 2, ref flag);
			if (flag)
			{
				((BepInExLogInterpolatedStringHandler)val2).AppendLiteral("PartialData is loaded: ");
				((BepInExLogInterpolatedStringHandler)val2).AppendFormatted<bool>(IsLoaded);
				((BepInExLogInterpolatedStringHandler)val2).AppendLiteral(", Version >= 1.5.2 (main branch): ");
				((BepInExLogInterpolatedStringHandler)val2).AppendFormatted<bool>(IsMainBranch);
			}
			Logger.Debug(val2);
			if (IsLoaded && !IsMainBranch)
			{
				Logger.Warn("AWOPartialDataFixer (PartialDataModCompatible) is deprecated, or older version! It will still work but it's recommended to switch to the main branch of PartialData");
			}
		}

		public static bool TryGetGUID(string text, out uint guid)
		{
			if (IsLoaded && IsMainBranch)
			{
				guid = GetGUID(text);
				return guid != 0;
			}
			guid = 0u;
			return false;
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		private static uint GetGUID(string text)
		{
			uint result = default(uint);
			if (PersistentIDManager.TryGetId(text, ref result))
			{
				return result;
			}
			return 0u;
		}
	}
}
namespace AmorLib.API
{
	public interface ILightModifier
	{
		Color Color { get; set; }

		float Intensity { get; set; }

		bool Enabled { get; set; }

		int Priority { get; }

		bool Active { get; }

		void Set(Color color, float intensity, bool enabled)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			Color = color;
			Intensity = intensity;
			Enabled = enabled;
		}

		bool Register();

		void Remove();
	}
	[CallConstructorOnLoad]
	public static class LightAPI
	{
		internal static readonly ConcurrentDictionary<int, LightWorker> AllLightsMap;

		static LightAPI()
		{
			AllLightsMap = new ConcurrentDictionary<int, LightWorker>();
			LevelAPI.OnAfterBuildBatch += OnAfterZoneLightsBatch;
			LevelAPI.OnLevelCleanup += OnLevelCleanup;
		}

		private static void OnLevelCleanup()
		{
			AllLightsMap.Clear();
		}

		private static void OnAfterZoneLightsBatch(BatchName batch)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0004: Invalid comparison between Unknown and I4
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_0016: Expected O, but got Unknown
			if ((int)batch == 61)
			{
				bool flag = default(bool);
				BepInExDebugLogInterpolatedStringHandler val = new BepInExDebugLogInterpolatedStringHandler(35, 1, ref flag);
				if (flag)
				{
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral("All LightWorkers are setup. Count: ");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<int>(AllLightsMap.Count);
				}
				Logger.Debug(val);
			}
		}

		public static LightWorker? GetSpecificLightWorker(int instanceID)
		{
			LightWorker worker;
			return TryGetSpecificLightWorker(instanceID, out worker) ? worker : null;
		}

		public static bool TryGetSpecificLightWorker(int instanceID, [NotNullWhen(true)] out LightWorker? worker)
		{
			//IL_001a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0020: Expected O, but got Unknown
			if (!AllLightsMap.TryGetValue(instanceID, out worker))
			{
				bool flag = default(bool);
				BepInExErrorLogInterpolatedStringHandler val = new BepInExErrorLogInterpolatedStringHandler(65, 1, ref flag);
				if (flag)
				{
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral("Failed to find LightWorker: no LG_Light exists with instance id ");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<int>(instanceID);
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral("!");
				}
				Logger.Error(val);
				return false;
			}
			return true;
		}

		public static void ForEachWorker(this IEnumerable<LightWorker> lightWorkers, Action<LightWorker> action)
		{
			foreach (LightWorker lightWorker in lightWorkers)
			{
				action(lightWorker);
			}
		}

		public static IEnumerable<ILightModifier> AddLightModifiers(this IEnumerable<LightWorker> lightWorkers, Color color, float intensity, bool enabled, int priority = 1000)
		{
			//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 lightWorkers.Select((LightWorker worker) => worker.AddModifier(color, intensity, enabled, priority));
		}

		public static void ForEachMod(this IEnumerable<ILightModifier> lightModifiers, Action<ILightModifier> action)
		{
			foreach (ILightModifier lightModifier in lightModifiers)
			{
				action(lightModifier);
			}
		}

		public static IEnumerable<LightWorker> GetLightWorkersInDimension(params eDimensionIndex[] args)
		{
			eDimensionIndex[] args2 = args;
			return AllLightsMap.Values.Where((LightWorker light) => args2.Contains(light.OwnerZone.DimensionIndex));
		}

		public static IEnumerable<LightWorker> GetLightWorkersInZone(params (int, int, int)[] args)
		{
			(int, int, int)[] args2 = args;
			return AllLightsMap.Values.Where((LightWorker light) => args2.Contains<(int, int, int)>(light.OwnerZone.ToIntTuple()));
		}

		public static IEnumerable<LightWorker> GetLightWorkersInZone(params LG_Zone[] args)
		{
			(int, int, int)[] args2 = args.Select((LG_Zone z) => z.ToIntTuple()).Distinct().ToArray();
			return GetLightWorkersInZone(args2);
		}

		public static IEnumerable<LightWorker> GetLightWorkersInNode(params AIG_CourseNode[] args)
		{
			HashSet<ushort> nodes = args.Select((AIG_CourseNode n) => ((AIG_CourseGraphMember)n).m_searchID).ToHashSet();
			return AllLightsMap.Values.Where((LightWorker light) => nodes.Contains(((AIG_CourseGraphMember)light.SpawnNode).m_searchID));
		}

		public static IEnumerable<LightWorker> GetLightWorkersInRange(Vector3 position, float range)
		{
			//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)
			float sqrRange = range * range;
			return AllLightsMap.Values.Where((LightWorker light) => light.Position.IsWithinSqrDistance(position, sqrRange));
		}

		public static IEnumerable<LightWorker> GetLightWorkersInRange(eDimensionIndex dimension, Vector3 position, float range)
		{
			//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_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)
			float sqrRange = range * range;
			return AllLightsMap.Values.Where((LightWorker light) => light.OwnerZone.DimensionIndex == dimension && light.Position.IsWithinSqrDistance(position, sqrRange));
		}
	}
	public static class LightPriority
	{
		public const int Normal = 1000;

		public const int EMP = 2000;
	}
	public class LightWorker
	{
		private class LightModifier : ILightModifier
		{
			private Color _color;

			private float _intensity;

			private bool _enabled;

			private readonly LightWorker _worker;

			public Color Color
			{
				get
				{
					//IL_0001: Unknown result type (might be due to invalid IL or missing references)
					return _color;
				}
				set
				{
					//IL_0001: 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_0014: 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_002b: Unknown result type (might be due to invalid IL or missing references)
					if (!(value == _color))
					{
						_color = value;
						if (InUse)
						{
							_worker.ChangeLightColor(_color);
						}
					}
				}
			}

			public float Intensity
			{
				get
				{
					return _intensity;
				}
				set
				{
					if (value != _intensity)
					{
						_intensity = value;
						if (InUse)
						{
							_worker.ChangeLightIntensity(_intensity);
						}
					}
				}
			}

			public bool Enabled
			{
				get
				{
					return _enabled;
				}
				set
				{
					if (value != _enabled)
					{
						_enabled = value;
						if (InUse)
						{
							_worker.SetLightEnabled(_enabled);
						}
					}
				}
			}

			public int Priority { get; }

			public LinkedListNode<LightModifier>? Node { get; set; }

			public bool Active => Node != null && _worker != null;

			private bool InUse => Active && _worker._currentNode == Node;

			public LightModifier(Color color, float intensity, bool enabled, int priority, LightWorker worker)
			{
				//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)
				_color = color;
				_intensity = intensity;
				_enabled = enabled;
				Priority = priority;
				_worker = worker;
			}

			public bool Register()
			{
				if (_worker == null)
				{
					return false;
				}
				if (Active)
				{
					_worker._priorityDict[Priority].Remove(Node);
				}
				_worker.AddModifier(this);
				return true;
			}

			public void Apply()
			{
				//IL_0008: Unknown result type (might be due to invalid IL or missing references)
				_worker.ChangeLightColor(_color);
				_worker.ChangeLightIntensity(_intensity);
				_worker.SetLightEnabled(_enabled);
			}

			public void Remove()
			{
				if (Active)
				{
					_worker.RemoveModifier(this);
				}
			}
		}

		public readonly LG_Zone OwnerZone;

		public readonly AIG_CourseNode SpawnNode;

		public readonly LG_Light Light;

		public readonly int InstanceID;

		public readonly float PrefabIntensity;

		public LG_LightAnimator? Animator;

		public Color OrigColor;

		public float OrigIntensity;

		public bool OrigEnabled;

		private readonly SortedDictionary<int, LinkedList<LightModifier>> _priorityDict = new SortedDictionary<int, LinkedList<LightModifier>>();

		private LinkedListNode<LightModifier>? _currentNode;

		public const int OrigPriority = -1000;

		private ILightModifier _origLightMod = null;

		public Vector3 Position => Light.GetPosition();

		public Color CurrentColor => Light.m_color;

		public float CurrentIntensity => Light.m_intensity;

		public bool CurrentEnabled { get; private set; }

		public LightWorker(LG_Zone zone, AIG_CourseNode node, LG_Light light, int id, float intensity)
		{
			OwnerZone = zone;
			SpawnNode = node;
			Light = light;
			InstanceID = id;
			PrefabIntensity = intensity;
		}

		internal void Setup()
		{
			//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)
			//IL_006a: Unknown result type (might be due to invalid IL or missing references)
			Animator = ((Component)Light).gameObject.GetComponent<LG_LightAnimator>();
			OrigColor = Light.m_color;
			OrigIntensity = Light.m_intensity;
			OrigEnabled = !Light.DisabledFromSettings && ((Behaviour)Light).isActiveAndEnabled;
			CurrentEnabled = OrigEnabled;
			_origLightMod = AddModifier(OrigColor, OrigIntensity, OrigEnabled, -1000);
		}

		public bool IsEMPActive()
		{
			LinkedList<LightModifier> value;
			return _priorityDict.TryGetValue(2000, out value) && value.Count > 0;
		}

		private void ChangeLightColor(Color color)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			Light.ChangeColor(color);
		}

		private void ChangeLightIntensity(float intensity)
		{
			Light.ChangeIntensity(intensity);
		}

		private void SetLightEnabled(bool enabled)
		{
			Light.SetEnabled(enabled);
			CurrentEnabled = enabled;
		}

		public bool ToggleLightFlicker(bool enabled)
		{
			if ((Object)(object)Animator == (Object)null)
			{
				return false;
			}
			C_Light c_Light = Light.GetC_Light();
			if (enabled)
			{
				Animator.ResetRamp(c_Light);
			}
			else
			{
				Animator.m_inRamp = false;
				Animator.m_startTime = float.MaxValue;
				Animator.m_absTime = 1f;
				Animator.FeedLight(c_Light);
			}
			return true;
		}

		public ILightModifier AddModifier(Color color, float intensity, bool enabled, int priority = 1000)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			LightModifier lightModifier = new LightModifier(color, intensity, enabled, priority, this);
			AddModifier(lightModifier);
			return lightModifier;
		}

		private void AddModifier(LightModifier modifier)
		{
			LinkedList<LightModifier> orAddNew = _priorityDict.GetOrAddNew(modifier.Priority);
			modifier.Node = orAddNew.AddLast(modifier);
			if (_currentNode == null || _currentNode.Value.Priority <= modifier.Priority)
			{
				_currentNode = modifier.Node;
				modifier.Apply();
			}
		}

		private void RemoveModifier(LightModifier modifier)
		{
			if (!_priorityDict.TryGetValue(modifier.Priority, out LinkedList<LightModifier> value))
			{
				return;
			}
			bool flag = _currentNode == modifier.Node;
			value.Remove(modifier.Node);
			modifier.Node = null;
			if (value.Count == 0)
			{
				_priorityDict.Remove(modifier.Priority);
			}
			if (!flag)
			{
				return;
			}
			if (_priorityDict.Count == 0)
			{
				_currentNode = null;
				return;
			}
			LinkedList<LightModifier> linkedList = _priorityDict.Values.Last((LinkedList<LightModifier> list) => list.Count > 0);
			_currentNode = linkedList.Last;
			_currentNode.Value.Apply();
		}

		internal void Reset()
		{
			List<LightModifier> list2 = _priorityDict.Values.SelectMany((LinkedList<LightModifier> list) => list).ToList();
			foreach (LightModifier item in list2)
			{
				item.Remove();
			}
			_priorityDict.Clear();
			_origLightMod.Register();
		}
	}
}

plugins/Fusion/extra/net6/BoosterPack.dll

Decompiled a week 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/Fusion/extra/net6/CleanerRundownMenu.dll

Decompiled a week ago
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 System.Text.RegularExpressions;
using BepInEx;
using BepInEx.Core.Logging.Interpolation;
using BepInEx.Logging;
using BepInEx.Unity.IL2CPP;
using CellMenu;
using GTFO.API.JSON;
using HarmonyLib;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETCoreApp,Version=v6.0", FrameworkDisplayName = "")]
[assembly: AssemblyCompany("CleanerRundownMenu")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0")]
[assembly: AssemblyProduct("CleanerRundownMenu")]
[assembly: AssemblyTitle("CleanerRundownMenu")]
[assembly: AssemblyVersion("1.0.0.0")]
namespace CleanerRundownMenu;

[BepInPlugin("com.Untilted.CleanerRundownMenu", "CleanerRundownMenu", "1.0.0")]
[BepInDependency(/*Could not decode attribute arguments.*/)]
public class Loader : BasePlugin
{
	public const string MODNAME = "CleanerRundownMenu";

	public const string AUTHOR = "Untilted";

	public const string GUID = "com.Untilted.CleanerRundownMenu";

	public const string VERSION = "1.0.0";

	public static ManualLogSource Logger;

	public override void Load()
	{
		//IL_0020: Unknown result type (might be due to invalid IL or missing references)
		Logger = ((BasePlugin)this).Log;
		((BasePlugin)this).Log.LogMessage((object)"Loading CleanerRundownMenu");
		new Harmony("CleanerRundownMenu").PatchAll(typeof(MenuPatches));
		((BasePlugin)this).Log.LogMessage((object)"Loaded CleanerRundownMenu");
	}
}
public class MenuData : VPersistentData<MenuData>
{
	[JsonIgnore]
	public override string PersistentDataVersion { get; set; } = "1.0.0";


	public bool ShowVanityDrops { get; set; }

	public bool ShowSectorSummary { get; set; }

	public bool ShowIntel { get; set; }

	public MenuData()
	{
		ShowVanityDrops = false;
		ShowSectorSummary = true;
		ShowIntel = true;
	}
}
internal class MenuPatches
{
	[HarmonyPatch(typeof(CM_PageRundown_New), "PlaceRundown")]
	[HarmonyPostfix]
	public static void PlaceRundown()
	{
		//IL_0021: 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_004a: 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_007f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0089: 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)
		//IL_00be: Unknown result type (might be due to invalid IL or missing references)
		if (!VPersistentData<MenuData>.CurrentData.ShowVanityDrops)
		{
			Transform transform = ((Component)MainMenuGuiLayer.Current.PageRundownNew.m_buttonVanityItemDrops).transform;
			transform.position *= 20f;
			Transform transform2 = ((Component)MainMenuGuiLayer.Current.PageRundownNew.m_vanityItemDropsNext).transform;
			transform2.position *= 20f;
		}
		if (!VPersistentData<MenuData>.CurrentData.ShowSectorSummary)
		{
			Transform transform3 = ((Component)MainMenuGuiLayer.Current.PageRundownNew.m_tierMarkerSectorSummary).transform;
			transform3.position *= 20f;
		}
		if (!VPersistentData<MenuData>.CurrentData.ShowIntel)
		{
			Transform transform4 = ((Component)MainMenuGuiLayer.Current.PageRundownNew.m_rundownIntelButton).transform;
			transform4.position *= 20f;
		}
	}
}
public class VPersistentData<T> where T : VPersistentData<T>, new()
{
	private const string VERSION_REGEX = "\"PersistentDataVersion\": \"(.+?)\"";

	private static T s_CurrentData;

	private static readonly string s_fullPath = GetFullPath();

	public static T CurrentData
	{
		get
		{
			if (s_CurrentData != null)
			{
				return s_CurrentData;
			}
			s_CurrentData = Load();
			return s_CurrentData;
		}
		set
		{
			s_CurrentData = value;
		}
	}

	protected static string persistentPath => Path.Combine("PersistentData", typeof(T).Assembly.GetName().Name, typeof(T).Name + ".json");

	public virtual string PersistentDataVersion { get; set; } = "1.0.0";


	[JsonIgnore]
	public bool LoadingFailed { get; private set; }

	private static string GetFullPath()
	{
		//IL_0094: Unknown result type (might be due to invalid IL or missing references)
		//IL_009b: Expected O, but got Unknown
		string TPersistentPath = persistentPath;
		PropertyInfo property = typeof(T).GetProperty("persistentPath", BindingFlags.Static | BindingFlags.NonPublic);
		if (property != null)
		{
			TPersistentPath = (string)property.GetValue(null, null);
		}
		if (Path.IsPathFullyQualified(TPersistentPath))
		{
			return TPersistentPath;
		}
		string fileName = Path.GetFileName(TPersistentPath);
		string text = Directory.GetFiles(Paths.PluginPath, fileName, SearchOption.AllDirectories).FirstOrDefault((string f) => f.EndsWith(TPersistentPath));
		if (string.IsNullOrEmpty(text))
		{
			ManualLogSource logger = Loader.Logger;
			bool flag = default(bool);
			BepInExDebugLogInterpolatedStringHandler val = new BepInExDebugLogInterpolatedStringHandler(32, 1, ref flag);
			if (flag)
			{
				((BepInExLogInterpolatedStringHandler)val).AppendLiteral("Couldn't find existing data for ");
				((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(typeof(T).Name);
			}
			logger.LogDebug(val);
			return Path.Combine(Paths.PluginPath, TPersistentPath);
		}
		return text;
	}

	public static T Load()
	{
		return Load(s_fullPath);
	}

	public static T Load(string path)
	{
		//IL_000a: Unknown result type (might be due to invalid IL or missing references)
		//IL_0010: Expected O, but got Unknown
		//IL_015c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0163: Expected O, but got Unknown
		//IL_00be: Unknown result type (might be due to invalid IL or missing references)
		//IL_00c5: Expected O, but got Unknown
		ManualLogSource logger = Loader.Logger;
		bool flag = default(bool);
		BepInExDebugLogInterpolatedStringHandler val = new BepInExDebugLogInterpolatedStringHandler(14, 2, ref flag);
		if (flag)
		{
			((BepInExLogInterpolatedStringHandler)val).AppendLiteral("Loading ");
			((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(typeof(T).Name);
			((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" from ");
			((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(path);
		}
		logger.LogDebug(val);
		T val2 = new T();
		if (File.Exists(path))
		{
			string text = File.ReadAllText(path);
			string text2 = "1.0.0";
			Match match = Regex.Match(text, "\"PersistentDataVersion\": \"(.+?)\"");
			if (match.Success)
			{
				text2 = match.Groups[1].Value ?? "";
			}
			if (text2 != val2.PersistentDataVersion)
			{
				ManualLogSource logger2 = Loader.Logger;
				BepInExWarningLogInterpolatedStringHandler val3 = new BepInExWarningLogInterpolatedStringHandler(48, 3, ref flag);
				if (flag)
				{
					((BepInExLogInterpolatedStringHandler)val3).AppendFormatted<string>(typeof(T).Name);
					((BepInExLogInterpolatedStringHandler)val3).AppendLiteral(" PersistentDataVersion mismatch: expected ");
					((BepInExLogInterpolatedStringHandler)val3).AppendFormatted<string>(val2.PersistentDataVersion);
					((BepInExLogInterpolatedStringHandler)val3).AppendLiteral(", got ");
					((BepInExLogInterpolatedStringHandler)val3).AppendFormatted<string>(text2);
				}
				logger2.LogWarning(val3);
				File.WriteAllText(Path.ChangeExtension(path, null) + "-" + text2 + ".json", text);
				val2.Save(path);
				return val2;
			}
			T val4;
			try
			{
				val4 = JsonSerializer.Deserialize<T>(text, (JsonSerializerOptions)null);
			}
			catch (JsonException ex)
			{
				ManualLogSource logger3 = Loader.Logger;
				BepInExErrorLogInterpolatedStringHandler val5 = new BepInExErrorLogInterpolatedStringHandler(23, 2, ref flag);
				if (flag)
				{
					((BepInExLogInterpolatedStringHandler)val5).AppendLiteral("Failed to deserialize ");
					((BepInExLogInterpolatedStringHandler)val5).AppendFormatted<string>(typeof(T).Name);
					((BepInExLogInterpolatedStringHandler)val5).AppendLiteral("\n");
					((BepInExLogInterpolatedStringHandler)val5).AppendFormatted<JsonException>(ex);
				}
				logger3.LogError(val5);
				val2.LoadingFailed = true;
				return val2;
			}
			val2 = val4;
		}
		else
		{
			val2.Save(path);
		}
		return val2;
	}

	public void Save()
	{
		Save(s_fullPath);
	}

	public void Save(string path)
	{
		string contents = JsonSerializer.Serialize((object)(T)this, (JsonSerializerOptions)null);
		string directoryName = Path.GetDirectoryName(path);
		if (!Directory.Exists(directoryName))
		{
			Directory.CreateDirectory(directoryName);
		}
		File.WriteAllText(path, contents);
	}
}

plugins/Fusion/extra/net6/ExtraWeaponCustomization.dll

Decompiled a week ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
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.Configuration;
using BepInEx.Logging;
using BepInEx.Unity.IL2CPP;
using BepInEx.Unity.IL2CPP.Hook;
using BepInEx.Unity.IL2CPP.Utils.Collections;
using CharacterDestruction;
using CullingSystem;
using EWC.API;
using EWC.CustomWeapon;
using EWC.CustomWeapon.KillTracker;
using EWC.CustomWeapon.ObjectWrappers;
using EWC.CustomWeapon.Properties;
using EWC.CustomWeapon.Properties.Effects;
using EWC.CustomWeapon.Properties.Effects.Heal;
using EWC.CustomWeapon.Properties.Effects.Hit.CustomFoam;
using EWC.CustomWeapon.Properties.Effects.Hit.DOT;
using EWC.CustomWeapon.Properties.Effects.Hit.DOT.DOTGlowFX;
using EWC.CustomWeapon.Properties.Effects.Hit.Explosion;
using EWC.CustomWeapon.Properties.Effects.Hit.Explosion.EEC_ExplosionFX;
using EWC.CustomWeapon.Properties.Effects.Hit.Explosion.EEC_ExplosionFX.Handlers;
using EWC.CustomWeapon.Properties.Effects.Triggers;
using EWC.CustomWeapon.Properties.Traits;
using EWC.CustomWeapon.Properties.Traits.CustomProjectile;
using EWC.CustomWeapon.Properties.Traits.CustomProjectile.Components;
using EWC.CustomWeapon.Properties.Traits.CustomProjectile.Managers;
using EWC.CustomWeapon.WeaponContext;
using EWC.CustomWeapon.WeaponContext.Contexts;
using EWC.CustomWeapon.WeaponContext.Contexts.Triggers;
using EWC.Dependencies;
using EWC.JSON;
using EWC.JSON.Converters;
using EWC.Networking;
using EWC.Patches;
using EWC.Patches.Melee;
using EWC.Patches.Native;
using EWC.Patches.Player;
using EWC.Utils;
using EWC.Utils.Log;
using EndskApi.Api;
using EndskApi.Enums.EnemyKill;
using EndskApi.Information.EnemyKill;
using Enemies;
using ExtraRecoilData.API;
using ExtraRecoilData.CustomRecoil;
using FX_EffectSystem;
using FirstPersonItem;
using GTFO.API;
using GTFO.API.JSON.Converters;
using GTFO.API.Utilities;
using GTFuckingXP.Extensions;
using GTFuckingXP.Information.Level;
using GameData;
using Gear;
using HarmonyLib;
using Il2CppInterop.Runtime.Attributes;
using Il2CppInterop.Runtime.Injection;
using Il2CppInterop.Runtime.InteropTypes;
using Il2CppInterop.Runtime.InteropTypes.Arrays;
using Il2CppInterop.Runtime.Runtime;
using Il2CppSystem;
using Il2CppSystem.Collections;
using Il2CppSystem.Collections.Generic;
using KillIndicatorFix;
using LevelGeneration;
using LevelGeneration.Core;
using MTFO.API;
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("ExtraWeaponCustomization")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0+6ad3732cfa7352e970b4a9d88f2992c961b9243c")]
[assembly: AssemblyProduct("ExtraWeaponCustomization")]
[assembly: AssemblyTitle("ExtraWeaponCustomization")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.0.0.0")]
[module: UnverifiableCode]
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 EWC
{
	internal static class Configuration
	{
		private static readonly ConfigEntry<bool> _showExplosionEffect;

		private static readonly ConfigEntry<bool> _playExplosionSFX;

		private static readonly ConfigEntry<float> _explosionSFXCooldown;

		private static readonly ConfigEntry<int> _explosionSFXShotOverride;

		private static readonly ConfigEntry<bool> _playExplosionShake;

		private static readonly ConfigEntry<float> _autoAimTickDelay;

		private static readonly ConfigEntry<float> _homingTickDelay;

		private static readonly ConfigFile configFile;

		private static ConfigEntry<bool> ForceCreateTemplate { get; set; }

		public static bool ShowExplosionEffect => _showExplosionEffect.Value;

		public static bool PlayExplosionSFX => _playExplosionSFX.Value;

		public static float ExplosionSFXCooldown => _explosionSFXCooldown.Value;

		public static int ExplosionSFXShotOverride => _explosionSFXShotOverride.Value;

		public static bool PlayExplosionShake => _playExplosionShake.Value;

		public static float AutoAimTickDelay => _autoAimTickDelay.Value;

		public static float HomingTickDelay => _homingTickDelay.Value;

		static Configuration()
		{
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_001a: Expected O, but got Unknown
			configFile = new ConfigFile(Path.Combine(Paths.ConfigPath, "ExtraWeaponCustomization.cfg"), true);
			string text = "Auto Aim Settings";
			_autoAimTickDelay = configFile.Bind<float>(text, "Search Cooldown", 0.1f, "Time between attempted searches to acquire targets.");
			text = "Explosion Settings";
			_showExplosionEffect = configFile.Bind<bool>(text, "Show Effect", true, "Enables explosion visual FX.");
			_playExplosionSFX = configFile.Bind<bool>(text, "Play Sound", true, "Enables explosion sound FX.");
			_explosionSFXCooldown = configFile.Bind<float>(text, "SFX Cooldown", 0.08f, "Minimum time between explosion sound effects, to prevent obnoxiously loud sounds.");
			_explosionSFXShotOverride = configFile.Bind<int>(text, "Shots to Override SFX Cooldown", 8, "Amount of shots fired before another explosion sound effect is forced, regardless of cooldown.\nSmaller numbers let fast-firing weapons and shotguns make more sounds in a short span of time.");
			_playExplosionShake = configFile.Bind<bool>(text, "Play Screen Shake", true, "Enables explosion screen shake. Doesn't bypass the global screen shake settings modifier.");
			text = "Projectile Settings";
			_homingTickDelay = configFile.Bind<float>(text, "Homing Search Cooldown", 0.1f, "Minimum time between attempted searches to acquire a new target.");
			text = "Tools";
			ForceCreateTemplate = configFile.Bind<bool>(text, "Force Create Template", false, "Creates the template file again.");
		}

		internal static void Init()
		{
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			//IL_0021: Expected O, but got Unknown
			LiveEdit.CreateListener(Paths.ConfigPath, "ExtraWeaponCustomization.cfg", false).FileChanged += new LiveEditEventHandler(OnFileChanged);
		}

		private static void OnFileChanged(LiveEditEventArgs _)
		{
			configFile.Reload();
			CheckAndRefreshTemplate();
		}

		private static void CheckAndRefreshTemplate()
		{
			if (ForceCreateTemplate.Value)
			{
				ForceCreateTemplate.Value = false;
				CustomWeaponManager.Current.CreateTemplate();
				configFile.Save();
			}
		}
	}
	[BepInPlugin("Dinorush.ExtraWeaponCustomization", "ExtraWeaponCustomization", "2.18.4")]
	[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.*/)]
	internal sealed class EntryPoint : BasePlugin
	{
		public const string MODNAME = "ExtraWeaponCustomization";

		public static bool Loaded { get; private set; }

		public override void Load()
		{
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			//IL_002d: Expected O, but got Unknown
			EWCLogger.Log("Loading ExtraWeaponCustomization");
			if (!MTFOAPIWrapper.HasCustomContent)
			{
				EWCLogger.Error("No MTFO datablocks detected. Not loading EWC...");
				return;
			}
			Loaded = true;
			Harmony val = new Harmony("ExtraWeaponCustomization");
			val.PatchAll();
			EnemyDetectionPatches.ApplyNativePatch();
			if (!CCAPIWrapper.HasCC)
			{
				val.PatchAll(typeof(PlayerDamagePatches));
			}
			Configuration.Init();
			LevelAPI.OnLevelCleanup += LevelAPI_OnLevelCleanup;
			LevelAPI.OnEnterLevel += LevelAPI_OnLevelEnter;
			AssetAPI.OnStartupAssetsLoaded += AssetAPI_OnStartupAssetsLoaded;
			EWCLogger.Log("Loaded ExtraWeaponCustomization");
		}

		private void LevelAPI_OnLevelCleanup()
		{
			CustomWeaponManager.Current.ResetCWCs(activate: false);
			EWCProjectileManager.Reset();
			DOTDamageManager.Reset();
		}

		private void LevelAPI_OnLevelEnter()
		{
			CustomWeaponManager.Current.ActivateCWCs();
		}

		private void AssetAPI_OnStartupAssetsLoaded()
		{
			ClassInjector.RegisterTypeInIl2Cpp<DOTGlowHandler>();
			ClassInjector.RegisterTypeInIl2Cpp<ExplosionEffectHandler>();
			ClassInjector.RegisterTypeInIl2Cpp<CustomWeaponComponent>();
			ClassInjector.RegisterTypeInIl2Cpp<EWCProjectileComponentBase>();
			ClassInjector.RegisterTypeInIl2Cpp<EWCProjectileComponentShooter>();
			LayerUtil.Init();
			ExplosionManager.Init();
			DOTDamageManager.Init();
			FoamActionManager.Init();
			HealManager.Init();
			TriggerManager.Init();
			KillAPIWrapper.Init();
			EWCProjectileManager.Init();
			RuntimeHelpers.RunClassConstructor(typeof(CustomWeaponManager).TypeHandle);
		}
	}
}
namespace EWC.Utils
{
	internal static class DamageableUtil
	{
		private static IntPtr _cachedExpedition = default(IntPtr);

		private static float _cachedHealth = 15f;

		public static float LockHealth
		{
			get
			{
				if (RundownManager.ActiveExpedition != null && ((Il2CppObjectBase)RundownManager.ActiveExpedition).Pointer != _cachedExpedition)
				{
					_cachedExpedition = ((Il2CppObjectBase)RundownManager.ActiveExpedition).Pointer;
					_cachedHealth = RundownManager.ActiveExpeditionBalanceData.WeakDoorLockHealth;
				}
				return _cachedHealth;
			}
		}

		public static IDamageable? GetDamageableFromRayHit(RaycastHit rayHit)
		{
			if (!((Object)(object)((RaycastHit)(ref rayHit)).collider == (Object)null))
			{
				return GetDamageableFromCollider(((RaycastHit)(ref rayHit)).collider);
			}
			return null;
		}

		public static IDamageable? GetDamageableFromCollider(Collider? collider)
		{
			if (!((Object)(object)collider == (Object)null))
			{
				return GetDamageableFromGO(((Component)collider).gameObject);
			}
			return null;
		}

		public static IDamageable? GetDamageableFromGO(GameObject? go)
		{
			if ((Object)(object)go == (Object)null)
			{
				return null;
			}
			ColliderMaterial component = go.GetComponent<ColliderMaterial>();
			IDamageable val = ((component != null) ? component.Damageable : null);
			if (val != null)
			{
				return val;
			}
			return go.GetComponent<IDamageable>();
		}

		public static bool IsValid([NotNullWhen(true)] this IDamageable? damageable)
		{
			if (damageable == null)
			{
				return false;
			}
			if (!((Object)(object)damageable.GetBaseAgent() != (Object)null))
			{
				return (Object)(object)((Il2CppObjectBase)damageable).TryCast<LG_WeakLockDamage>() != (Object)null;
			}
			return true;
		}

		public static bool IsEnemy([NotNullWhen(true)] this IDamageable? damageable)
		{
			//IL_001e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0024: Invalid comparison between Unknown and I4
			if (damageable == null)
			{
				return false;
			}
			Agent baseAgent = damageable.GetBaseAgent();
			if ((Object)(object)baseAgent != (Object)null && baseAgent.Alive)
			{
				return (int)baseAgent.Type == 1;
			}
			return false;
		}
	}
	public sealed class DelayedCallback
	{
		private readonly Func<float> _getDelay;

		private readonly Action? _onStart;

		private readonly Action? _onRefresh;

		private readonly Action? _onEnd;

		private float _endTime;

		private Coroutine? _routine;

		public DelayedCallback(Func<float> getDelay, Action? onEnd)
		{
			_getDelay = getDelay;
			_onEnd = onEnd;
		}

		public DelayedCallback(Func<float> getDelay, Action? onStart, Action? onEnd)
		{
			_getDelay = getDelay;
			_onStart = onStart;
			_onEnd = onEnd;
		}

		public DelayedCallback(Func<float> getDelay, Action? onStart, Action? onRefresh, Action? onEnd)
		{
			_getDelay = getDelay;
			_onStart = onStart;
			_onRefresh = onRefresh;
			_onEnd = onEnd;
		}

		public void Start()
		{
			_endTime = Clock.Time + _getDelay();
			_onRefresh?.Invoke();
			if (_routine == null)
			{
				_routine = CoroutineManager.StartCoroutine(CollectionExtensions.WrapToIl2Cpp(Update()), (Action)null);
			}
		}

		public IEnumerator Update()
		{
			_onStart?.Invoke();
			while (_endTime > Clock.Time)
			{
				yield return (object)new WaitForSeconds(_endTime - Clock.Time);
			}
			_routine = null;
			_onEnd?.Invoke();
		}

		public void Stop()
		{
			if (_routine != null)
			{
				CoroutineManager.StopCoroutine(_routine);
				_routine = null;
				_onEnd?.Invoke();
			}
		}

		public void Cancel()
		{
			if (_routine != null)
			{
				CoroutineManager.StopCoroutine(_routine);
				_routine = null;
			}
		}
	}
	internal static class DictExtensions
	{
		public static bool TryGetValueAs<Key, Value, ValueAs>(this IDictionary<Key, Value> dict, Key key, [MaybeNullWhen(false)] out ValueAs valueAs) where Key : notnull where ValueAs : Value
		{
			if (dict.TryGetValue(key, out Value value))
			{
				valueAs = (ValueAs)(object)value;
				return true;
			}
			valueAs = default(ValueAs);
			return false;
		}
	}
	public sealed class HitData
	{
		public float damage;

		public Vector2 damageFalloff;

		public float falloff;

		public float precisionMulti;

		public float staggerMulti;

		public float maxRayDist;

		public PlayerAgent owner;

		public Vector3 fireDir;

		public Vector3 hitPos;

		public IDamageable? damageable;

		public Collider collider;

		private RaycastHit _rayHit;

		private WeaponHitData? _weaponHitData;

		private MeleeWeaponFirstPerson? _meleeWeapon;

		public RaycastHit RayHit
		{
			get
			{
				//IL_0001: Unknown result type (might be due to invalid IL or missing references)
				return _rayHit;
			}
			set
			{
				//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_000e: 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_002b: Unknown result type (might be due to invalid IL or missing references)
				_rayHit = value;
				hitPos = ((RaycastHit)(ref _rayHit)).point;
				collider = ((RaycastHit)(ref _rayHit)).collider;
				damageable = DamageableUtil.GetDamageableFromRayHit(_rayHit);
			}
		}

		public HitData(WeaponHitData hitData, float additionalDist = 0f)
		{
			Setup(hitData, additionalDist);
		}

		public HitData(MeleeWeaponFirstPerson melee, MeleeWeaponDamageData hitData)
		{
			Setup(melee, hitData);
		}

		public HitData()
		{
		}

		public void Setup(WeaponHitData hitData, float additionalDist = 0f)
		{
			//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_004c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0051: Unknown result type (might be due to invalid IL or missing references)
			//IL_0064: Unknown result type (might be due to invalid IL or missing references)
			_weaponHitData = hitData;
			_meleeWeapon = null;
			damage = hitData.damage;
			damageFalloff = hitData.damageFalloff;
			precisionMulti = hitData.precisionMulti;
			staggerMulti = hitData.staggerMulti;
			owner = hitData.owner;
			fireDir = hitData.fireDir;
			maxRayDist = hitData.maxRayDist;
			RayHit = hitData.rayHit;
			SetFalloff(additionalDist);
		}

		public void Setup(MeleeWeaponFirstPerson melee, MeleeWeaponDamageData hitData)
		{
			//IL_003f: 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_004f: 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_005b: Unknown result type (might be due to invalid IL or missing references)
			_weaponHitData = null;
			_meleeWeapon = melee;
			damage = melee.m_damageToDeal;
			precisionMulti = melee.m_precisionMultiToDeal;
			staggerMulti = melee.m_staggerMultiToDeal;
			falloff = 1f;
			fireDir = hitData.hitPos - hitData.sourcePos;
			hitPos = hitData.hitPos;
			damageable = DamageableUtil.GetDamageableFromGO(hitData.damageGO);
		}

		public void Apply()
		{
			if (_weaponHitData != null)
			{
				Apply(_weaponHitData);
			}
			else if ((Object)(object)_meleeWeapon != (Object)null)
			{
				Apply(_meleeWeapon);
			}
		}

		public WeaponHitData Apply(WeaponHitData hitData)
		{
			//IL_0032: 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)
			hitData.owner = owner;
			hitData.damage = damage;
			hitData.precisionMulti = precisionMulti;
			hitData.staggerMulti = staggerMulti;
			hitData.rayHit = RayHit;
			hitData.fireDir = fireDir;
			hitData.maxRayDist = maxRayDist;
			return hitData;
		}

		public MeleeWeaponFirstPerson Apply(MeleeWeaponFirstPerson melee)
		{
			melee.m_damageToDeal = damage;
			melee.m_precisionMultiToDeal = precisionMulti;
			melee.m_staggerMultiToDeal = staggerMulti;
			return melee;
		}

		public void SetFalloff(float additionalDist = 0f)
		{
			//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)
			RaycastHit rayHit = RayHit;
			falloff = (((RaycastHit)(ref rayHit)).distance + additionalDist).Map(damageFalloff.x, damageFalloff.y, 1f, BulletWeapon.s_falloffMin);
		}

		public WeaponHitData ToWeaponHitData()
		{
			//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_0011: 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_001d: 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_0035: Unknown result type (might be due to invalid IL or missing references)
			//IL_0041: Unknown result type (might be due to invalid IL or missing references)
			//IL_0043: 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_004f: 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_0066: Expected O, but got Unknown
			return new WeaponHitData
			{
				damage = damage,
				damageFalloff = damageFalloff,
				precisionMulti = precisionMulti,
				staggerMulti = staggerMulti,
				owner = owner,
				rayHit = RayHit,
				fireDir = fireDir,
				maxRayDist = maxRayDist
			};
		}
	}
	public static class LayerUtil
	{
		public static int MaskDynamic { get; private set; }

		public static int MaskEntityAndWorld { get; private set; }

		public static int MaskEntityAndWorld3P { get; private set; }

		public static int MaskWorld { get; private set; }

		public static int MaskWorldExcProj { get; private set; }

		public static int MaskDecalValid { get; private set; }

		public static int MaskEntityDynamic3P { get; private set; }

		public static int MaskEntity { get; private set; }

		public static int MaskEntity3P { get; private set; }

		public static int MaskOwner { get; private set; }

		public static int MaskFriendly { get; private set; }

		public static int MaskEnemy { get; private set; }

		public static int MaskEnemyDynamic { get; private set; }

		internal static void Init()
		{
			MaskOwner = LayerMask.GetMask(new string[1] { "PlayerMover" });
			MaskFriendly = LayerMask.GetMask(new string[1] { "PlayerSynced" });
			MaskEnemy = LayerMask.GetMask(new string[1] { "EnemyDamagable" });
			MaskDynamic = LayerMask.GetMask(new string[1] { "Dynamic" });
			MaskEnemyDynamic = MaskEnemy | MaskDynamic;
			MaskEntity3P = MaskFriendly | MaskEnemy;
			MaskEntity = MaskOwner | MaskEntity3P;
			MaskDecalValid = LayerMask.GetMask(new string[3] { "Default", "Default_NoGraph", "Default_BlockGraph" });
			MaskWorldExcProj = MaskDecalValid | MaskDynamic;
			MaskWorld = MaskWorldExcProj | LayerMask.GetMask(new string[1] { "ProjectileBlocker" });
			MaskEntityAndWorld = MaskEntity | MaskWorld;
			MaskEntityDynamic3P = MaskEntity3P | MaskDynamic;
			MaskEntityAndWorld3P = MaskEntity3P | MaskWorld;
		}
	}
	internal static class NumExtensions
	{
		public static float Map(this float orig, float fromMin, float fromMax, float toMin, float toMax, float exponent = 1f)
		{
			if (fromMin == fromMax)
			{
				if (!(orig < fromMin))
				{
					return toMax;
				}
				return toMin;
			}
			orig = Math.Clamp(orig, fromMin, fromMax);
			if (exponent != 1f)
			{
				return (float)Math.Pow((orig - fromMin) / (fromMax - fromMin), exponent) * (toMax - toMin) + toMin;
			}
			return (orig - fromMin) / (fromMax - fromMin) * (toMax - toMin) + toMin;
		}

		public static float MapInverted(this float orig, float fromMin, float fromMax, float toMax, float toMin, float exponent = 1f)
		{
			if (fromMin == fromMax)
			{
				if (!(orig < fromMin))
				{
					return toMin;
				}
				return toMax;
			}
			orig = Math.Clamp(orig, fromMin, fromMax);
			if (exponent != 1f)
			{
				return (float)Math.Pow((fromMax - orig) / (fromMax - fromMin), exponent) * (toMax - toMin) + toMin;
			}
			return (fromMax - orig) / (fromMax - fromMin) * (toMax - toMin) + toMin;
		}

		public static float Lerp(this float t, float min, float max)
		{
			return (max - min) * Math.Clamp(t, 0f, 1f) + min;
		}

		public static float Lerp(this double t, float min, float max)
		{
			return (max - min) * (float)Math.Clamp(t, 0.0, 1.0) + min;
		}
	}
	[Flags]
	internal enum SearchSetting
	{
		None = 0,
		Alloc = 1,
		CacheHit = 2,
		CheckLOS = 4,
		CheckDoors = 8,
		CheckOwner = 0x10,
		CheckFriendly = 0x20,
		IgnoreDupes = 0x40
	}
	internal static class SearchUtil
	{
		private static readonly List<EnemyAgent> s_enemyCache = new List<EnemyAgent>();

		private static readonly List<(EnemyAgent, RaycastHit)> s_combinedCache = new List<(EnemyAgent, RaycastHit)>();

		private static readonly List<(PlayerAgent, RaycastHit)> s_combinedCachePlayer = new List<(PlayerAgent, RaycastHit)>();

		private static readonly Queue<AIG_CourseNode> s_nodeQueue = new Queue<AIG_CourseNode>();

		private static readonly List<RaycastHit> s_lockCache = new List<RaycastHit>();

		public static HashSet<IntPtr>? DupeCheckSet;

		public static int SightBlockLayer = 0;

		public const float WeakspotBufferDist = 0.1f;

		private static Ray s_ray;

		private static RaycastHit s_rayHit;

		private const float Epsilon = 1E-05f;

		private static Vector3 ClosestPointOnBounds(Bounds bounds, Vector3 point)
		{
			//IL_0000: 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_0014: 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_002b: 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_0046: Unknown result type (might be due to invalid IL or missing references)
			//IL_004e: 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_0069: Unknown result type (might be due to invalid IL or missing references)
			return new Vector3(Math.Clamp(point.x, ((Bounds)(ref bounds)).min.x, ((Bounds)(ref bounds)).max.x), Math.Clamp(point.y, ((Bounds)(ref bounds)).min.y, ((Bounds)(ref bounds)).max.y), Math.Clamp(point.z, ((Bounds)(ref bounds)).min.z, ((Bounds)(ref bounds)).max.z));
		}

		private static bool PortalInRange(Ray ray, float range, float angle, AIG_CoursePortal portal)
		{
			//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_000c: 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_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_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_0022: 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_0043: 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_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_0068: 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_006c: 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_008e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0093: 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_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_00a8: 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_0120: Unknown result type (might be due to invalid IL or missing references)
			//IL_0121: Unknown result type (might be due to invalid IL or missing references)
			//IL_0122: Unknown result type (might be due to invalid IL or missing references)
			//IL_0127: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f5: 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)
			Bounds portalBounds = portal.m_cullPortal.m_portalBounds;
			Vector3 val = ClosestPointOnBounds(portalBounds, ((Ray)(ref ray)).origin);
			Vector3 val2 = ((Ray)(ref ray)).origin - val;
			if (((Vector3)(ref val2)).sqrMagnitude > range * range)
			{
				return false;
			}
			if (angle >= 180f || ((Bounds)(ref portalBounds)).Contains(((Ray)(ref ray)).origin))
			{
				return true;
			}
			Vector3 val3 = portal.m_cullPortal.m_center - ((Ray)(ref ray)).origin;
			float num = Vector3.Dot(val3, ((Ray)(ref ray)).direction);
			if (angle == 90f)
			{
				return num >= 0f;
			}
			val = Vector3.Project(val3, ((Ray)(ref ray)).direction);
			Bounds portalBounds2 = portal.m_cullPortal.m_portalBounds;
			val2 = ((Bounds)(ref portalBounds2)).extents;
			float magnitude = ((Vector3)(ref val2)).magnitude;
			float num2 = ((Vector3)(ref val)).magnitude * (float)Math.Tan(angle * (MathF.PI / 180f));
			if (num2 < 0f)
			{
				if (num >= 0f)
				{
					return true;
				}
				num2 = Math.Max(0f, num2 + magnitude);
				val2 = val3 - val;
				return ((Vector3)(ref val2)).sqrMagnitude >= num2 * num2;
			}
			if (num <= 0f)
			{
				return false;
			}
			num2 += magnitude;
			val2 = val3 - val;
			return ((Vector3)(ref val2)).sqrMagnitude <= num2 * num2;
		}

		private static bool RaycastEnsured(Collider collider, Vector3 backupOrigin, float range, out RaycastHit hit)
		{
			//IL_0001: 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_0013: Unknown result type (might be due to invalid IL or missing references)
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			//IL_001e: 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_0026: 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_002e: 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_003a: 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_0042: Unknown result type (might be due to invalid IL or missing references)
			//IL_0047: Unknown result type (might be due to invalid IL or missing references)
			//IL_0048: 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_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0064: 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_007f: Unknown result type (might be due to invalid IL or missing references)
			if (collider.Raycast(s_ray, ref hit, range))
			{
				return true;
			}
			Vector3 val = collider.ClosestPoint(backupOrigin);
			Bounds bounds = collider.bounds;
			Vector3 val2 = val - ((Bounds)(ref bounds)).center;
			Vector3 normalized = ((Vector3)(ref val2)).normalized;
			bounds = collider.bounds;
			((Ray)(ref s_ray)).origin = ((Bounds)(ref bounds)).center + val2 + normalized * Math.Min(0.1f, range / 2f);
			((Ray)(ref s_ray)).direction = -normalized;
			return collider.Raycast(s_ray, ref hit, range);
		}

		private static bool TryGetClosestHit(Ray ray, float range, float angle, Agent agent, out RaycastHit hit, SearchSetting settings)
		{
			//IL_0002: 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_0031: Unknown result type (might be due to invalid IL or missing references)
			//IL_0037: Invalid comparison between Unknown and I4
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cb: Invalid comparison between Unknown and I4
			//IL_00f2: Unknown result type (might be due to invalid IL or missing references)
			//IL_0109: Unknown result type (might be due to invalid IL or missing references)
			//IL_010e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0113: 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_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_0123: Unknown result type (might be due to invalid IL or missing references)
			//IL_0138: Unknown result type (might be due to invalid IL or missing references)
			//IL_013e: Invalid comparison between Unknown and I4
			//IL_016a: Unknown result type (might be due to invalid IL or missing references)
			//IL_016f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0173: Unknown result type (might be due to invalid IL or missing references)
			//IL_0178: Unknown result type (might be due to invalid IL or missing references)
			//IL_02b4: Unknown result type (might be due to invalid IL or missing references)
			//IL_019e: 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_026e: 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_020f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0214: Unknown result type (might be due to invalid IL or missing references)
			//IL_0223: Unknown result type (might be due to invalid IL or missing references)
			//IL_022a: Unknown result type (might be due to invalid IL or missing references)
			//IL_022f: Unknown result type (might be due to invalid IL or missing references)
			//IL_023d: Unknown result type (might be due to invalid IL or missing references)
			//IL_024e: Unknown result type (might be due to invalid IL or missing references)
			hit = default(RaycastHit);
			if ((Object)(object)agent == (Object)null || !agent.Alive)
			{
				return false;
			}
			if (settings.HasFlag(SearchSetting.IgnoreDupes))
			{
				if ((int)agent.Type == 1)
				{
					HashSet<IntPtr>? dupeCheckSet = DupeCheckSet;
					if (dupeCheckSet != null && dupeCheckSet.Contains(((Il2CppObjectBase)((Il2CppObjectBase)agent).Cast<EnemyAgent>().Damage).Pointer))
					{
						return false;
					}
				}
				if ((int)agent.Type == 0)
				{
					HashSet<IntPtr>? dupeCheckSet2 = DupeCheckSet;
					if (dupeCheckSet2 != null && dupeCheckSet2.Contains(((Il2CppObjectBase)((Il2CppObjectBase)agent).Cast<PlayerAgent>().Damage).Pointer))
					{
						return false;
					}
				}
			}
			((Ray)(ref s_ray)).origin = ((Ray)(ref ray)).origin;
			float num = range * range;
			float num2 = num;
			Collider val = null;
			bool flag = false;
			foreach (Collider componentsInChild in ((Component)agent).GetComponentsInChildren<Collider>())
			{
				Dam_EnemyDamageLimb val2 = null;
				if ((int)agent.Type == 1)
				{
					val2 = ((Component)componentsInChild).GetComponent<Dam_EnemyDamageLimb>();
					if ((Object)(object)val2 == (Object)null || val2.IsDestroyed)
					{
						continue;
					}
				}
				else if ((int)agent.Type == 0 && ((Component)componentsInChild).GetComponent<IDamageable>() == null)
				{
					continue;
				}
				Vector3 val3 = componentsInChild.ClosestPoint(((Ray)(ref ray)).origin);
				Vector3 direction = val3 - ((Ray)(ref ray)).origin;
				float num3 = ((Vector3)(ref direction)).sqrMagnitude;
				float num4 = num3;
				if (val2 != null && (int)val2.m_type == 1 && num3 < num)
				{
					float num5 = Math.Max(((Vector3)(ref direction)).magnitude - 0.1f, 0f);
					num3 = num5 * num5;
				}
				if (!(num3 < num2) || !(Vector3.Angle(((Ray)(ref ray)).direction, val3 - ((Ray)(ref ray)).origin) <= angle) || (settings.HasFlag(SearchSetting.CheckLOS) && Physics.Linecast(((Ray)(ref ray)).origin, val3, SightBlockLayer)))
				{
					continue;
				}
				num2 = num3;
				val = componentsInChild;
				if (!settings.HasFlag(SearchSetting.CacheHit))
				{
					break;
				}
				if (num2 < 1E-05f)
				{
					if (!(num4 > 1E-05f))
					{
						((Ray)(ref s_ray)).origin = ((Ray)(ref s_ray)).origin - ((Ray)(ref ray)).direction * Math.Min(0.1f, range / 2f);
						((Ray)(ref s_ray)).direction = val3 - ((Ray)(ref s_ray)).origin;
						if (RaycastEnsured(componentsInChild, ((Ray)(ref ray)).origin, range, out hit))
						{
							((RaycastHit)(ref hit)).point = val3;
							((RaycastHit)(ref hit)).distance = 0f;
							flag = true;
						}
						else
						{
							val = null;
						}
					}
					break;
				}
				((Ray)(ref s_ray)).direction = direction;
			}
			if ((Object)(object)val == (Object)null)
			{
				return false;
			}
			if (settings.HasFlag(SearchSetting.CacheHit) && !flag && !RaycastEnsured(val, ((Ray)(ref ray)).origin, range, out hit))
			{
				return false;
			}
			return true;
		}

		private static void CacheEnemiesInRange(Ray ray, float range, float angle, AIG_CourseNode origin, SearchSetting settings)
		{
			//IL_0083: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ff: Unknown result type (might be due to invalid IL or missing references)
			//IL_0104: Unknown result type (might be due to invalid IL or missing references)
			//IL_010b: 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_0115: Unknown result type (might be due to invalid IL or missing references)
			//IL_0121: Unknown result type (might be due to invalid IL or missing references)
			//IL_013b: Unknown result type (might be due to invalid IL or missing references)
			AIG_SearchID.IncrementSearchID();
			ushort searchID = AIG_SearchID.SearchID;
			float num = range * range;
			s_nodeQueue.Enqueue(origin);
			((AIG_CourseGraphMember)origin).m_searchID = searchID;
			s_combinedCache.Clear();
			AIG_CourseNode result;
			while (s_nodeQueue.TryDequeue(out result))
			{
				Enumerator<AIG_CoursePortal> enumerator = result.m_portals.GetEnumerator();
				while (enumerator.MoveNext())
				{
					AIG_CoursePortal current = enumerator.Current;
					AIG_CourseNode oppositeNode = current.GetOppositeNode(result);
					if ((!settings.HasFlag(SearchSetting.CheckDoors) || current.IsTraversable) && ((AIG_CourseGraphMember)oppositeNode).m_searchID != searchID && PortalInRange(ray, range, angle, current))
					{
						((AIG_CourseGraphMember)oppositeNode).m_searchID = searchID;
						s_nodeQueue.Enqueue(oppositeNode);
					}
				}
				Enumerator<EnemyAgent> enumerator2 = result.m_enemiesInNode.GetEnumerator();
				while (enumerator2.MoveNext())
				{
					EnemyAgent current2 = enumerator2.Current;
					if (!((Object)(object)current2 == (Object)null) && ((Agent)current2).Alive && !(((Dam_SyncedDamageBase)current2.Damage).Health <= 0f))
					{
						Vector3 val = ClosestPointOnBounds(((C_Cullable)current2.MovingCuller.Culler).Bounds, ((Ray)(ref ray)).origin) - ((Ray)(ref ray)).origin;
						if (!(((Vector3)(ref val)).sqrMagnitude > num) && TryGetClosestHit(ray, range, angle, (Agent)(object)current2, out s_rayHit, settings))
						{
							s_combinedCache.Add((current2, s_rayHit));
						}
					}
				}
			}
		}

		public static List<EnemyAgent> GetEnemiesInRange(Ray ray, float range, float angle, AIG_CourseNode origin, SearchSetting settings = SearchSetting.None)
		{
			//IL_003a: Unknown result type (might be due to invalid IL or missing references)
			s_enemyCache.Clear();
			if (range == 0f || angle == 0f)
			{
				if (!settings.HasFlag(SearchSetting.Alloc))
				{
					return s_enemyCache;
				}
				return new List<EnemyAgent>();
			}
			CacheEnemiesInRange(ray, range, angle, origin, settings);
			if (settings.HasFlag(SearchSetting.Alloc))
			{
				return s_combinedCache.ConvertAll(((EnemyAgent, RaycastHit) pair) => pair.Item1);
			}
			foreach (var item2 in s_combinedCache)
			{
				EnemyAgent item = item2.Item1;
				s_enemyCache.Add(item);
			}
			return s_enemyCache;
		}

		public static List<(EnemyAgent enemy, RaycastHit hit)> GetEnemyHitsInRange(Ray ray, float range, float angle, AIG_CourseNode origin, SearchSetting settings = SearchSetting.CacheHit)
		{
			//IL_0040: Unknown result type (might be due to invalid IL or missing references)
			if (range == 0f || angle == 0f)
			{
				s_combinedCache.Clear();
				if (!settings.HasFlag(SearchSetting.Alloc))
				{
					return s_combinedCache;
				}
				return new List<(EnemyAgent, RaycastHit)>();
			}
			settings |= SearchSetting.CacheHit;
			CacheEnemiesInRange(ray, range, angle, origin, settings);
			if (settings.HasFlag(SearchSetting.Alloc))
			{
				return new List<(EnemyAgent, RaycastHit)>(s_combinedCache);
			}
			return s_combinedCache;
		}

		public static List<RaycastHit> GetLockHitsInRange(Ray ray, float range, float angle, SearchSetting settings = SearchSetting.None)
		{
			//IL_003b: 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_0057: 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_010c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0111: Unknown result type (might be due to invalid IL or missing references)
			//IL_011c: 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_00c5: Unknown result type (might be due to invalid IL or missing references)
			//IL_012c: 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_013f: Unknown result type (might be due to invalid IL or missing references)
			s_lockCache.Clear();
			if (range == 0f || angle == 0f)
			{
				if (!settings.HasFlag(SearchSetting.Alloc))
				{
					return s_lockCache;
				}
				return new List<RaycastHit>();
			}
			Collider[] array = Il2CppArrayBase<Collider>.op_Implicit((Il2CppArrayBase<Collider>)(object)Physics.OverlapSphere(((Ray)(ref ray)).origin, range, LayerUtil.MaskDynamic));
			Vector3 direction = ((Ray)(ref ray)).direction;
			Collider[] array2 = array;
			foreach (Collider val in array2)
			{
				IDamageable damageableFromCollider = DamageableUtil.GetDamageableFromCollider(val);
				if (damageableFromCollider == null)
				{
					continue;
				}
				if (settings.HasFlag(SearchSetting.IgnoreDupes))
				{
					HashSet<IntPtr>? dupeCheckSet = DupeCheckSet;
					if (dupeCheckSet != null && dupeCheckSet.Contains(((Il2CppObjectBase)damageableFromCollider.GetBaseDamagable()).Pointer))
					{
						continue;
					}
				}
				if (!settings.HasFlag(SearchSetting.CheckLOS) || !Physics.Linecast(((Ray)(ref ray)).origin, damageableFromCollider.DamageTargetPos, ref s_rayHit, SightBlockLayer) || !(((Il2CppObjectBase)((Component)((RaycastHit)(ref s_rayHit)).collider).gameObject).Pointer != ((Il2CppObjectBase)((Component)val).gameObject).Pointer))
				{
					((Ray)(ref ray)).direction = damageableFromCollider.DamageTargetPos - ((Ray)(ref ray)).origin;
					if (val.Raycast(ray, ref s_rayHit, range) && Vector3.Angle(((Ray)(ref ray)).direction, direction) < angle)
					{
						s_lockCache.Add(s_rayHit);
					}
				}
			}
			if (settings.HasFlag(SearchSetting.Alloc))
			{
				return new List<RaycastHit>(s_lockCache);
			}
			return s_lockCache;
		}

		public static List<(PlayerAgent, RaycastHit)> GetPlayerHitsInRange(Ray ray, float range, float angle, SearchSetting settings = SearchSetting.CheckOwner | SearchSetting.CheckFriendly)
		{
			//IL_0076: 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_0082: Unknown result type (might be due to invalid IL or missing references)
			//IL_0089: 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_0093: Unknown result type (might be due to invalid IL or missing references)
			//IL_0153: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ca: Unknown result type (might be due to invalid IL or missing references)
			//IL_00df: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00eb: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fb: Unknown result type (might be due to invalid IL or missing references)
			//IL_016a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0122: Unknown result type (might be due to invalid IL or missing references)
			//IL_012c: Unknown result type (might be due to invalid IL or missing references)
			s_combinedCachePlayer.Clear();
			if (range == 0f || angle == 0f)
			{
				if (!settings.HasFlag(SearchSetting.Alloc))
				{
					return s_combinedCachePlayer;
				}
				return new List<(PlayerAgent, RaycastHit)>();
			}
			float num = range * range;
			Enumerator<PlayerAgent> enumerator = PlayerManager.PlayerAgentsInLevel.GetEnumerator();
			while (enumerator.MoveNext())
			{
				PlayerAgent current = enumerator.Current;
				if ((Object)(object)current == (Object)null || !((Agent)current).Alive)
				{
					continue;
				}
				Vector3 val = ClosestPointOnBounds(((C_Cullable)current.m_movingCuller.Culler).Bounds, ((Ray)(ref ray)).origin) - ((Ray)(ref ray)).origin;
				if (((Vector3)(ref val)).sqrMagnitude > num)
				{
					continue;
				}
				if (((Agent)current).IsLocallyOwned)
				{
					if (!settings.HasFlag(SearchSetting.CheckOwner))
					{
						continue;
					}
					((Ray)(ref s_ray)).origin = ((Ray)(ref ray)).origin;
					((Ray)(ref s_ray)).direction = ((Dam_SyncedDamageBase)current.Damage).DamageTargetPos - ((Ray)(ref ray)).origin;
					if (!((Component)current).GetComponent<Collider>().Raycast(s_ray, ref s_rayHit, range) || (settings.HasFlag(SearchSetting.CheckLOS) && Physics.Linecast(((Ray)(ref ray)).origin, ((RaycastHit)(ref s_rayHit)).point, SightBlockLayer)))
					{
						continue;
					}
				}
				else if (!settings.HasFlag(SearchSetting.CheckFriendly) || !TryGetClosestHit(ray, range, angle, (Agent)(object)current, out s_rayHit, settings))
				{
					continue;
				}
				s_combinedCachePlayer.Add((current, s_rayHit));
			}
			if (settings.HasFlag(SearchSetting.Alloc))
			{
				return new List<(PlayerAgent, RaycastHit)>(s_combinedCachePlayer);
			}
			return s_combinedCachePlayer;
		}

		private static bool HasCluster(AIG_VoxelNodePillar pillar)
		{
			Enumerator<AIG_VoxelNode> enumerator = pillar.m_nodes.GetEnumerator();
			AIG_NodeCluster val = default(AIG_NodeCluster);
			while (enumerator.MoveNext())
			{
				AIG_VoxelNode current = enumerator.Current;
				if (current.ClusterID != 0 && AIG_NodeCluster.TryGetNodeCluster(current.ClusterID, ref val))
				{
					return true;
				}
			}
			return false;
		}

		public static AIG_CourseNode GetCourseNode(Vector3 position, Agent agent)
		{
			//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_0007: 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_001a: 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_003b: 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_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_004d: 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_007a: 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_0060: 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_0066: Unknown result type (might be due to invalid IL or missing references)
			Vector3 position2 = agent.Position;
			Dimension dimensionFromPos = Dimension.GetDimensionFromPos(position);
			if (dimensionFromPos != null && TryGetGeomorphVolumeSilent(dimensionFromPos.DimensionIndex, position, out AIG_GeomorphNodeVolume resultingGeoVolume))
			{
				position.y = ((AIG_NodeVolume)resultingGeoVolume).Position.y;
				position2.y = position.y;
				Vector3 val = position2 - position;
				Vector3 normalized = ((Vector3)(ref val)).normalized;
				AIG_VoxelNodePillar val2 = null;
				for (int i = 0; i < 10; i++)
				{
					if (((AIG_NodeVolume)resultingGeoVolume).m_voxelNodeVolume.TryGetPillar(position, ref val2) && HasCluster(val2))
					{
						break;
					}
					position += normalized;
				}
				if (val2 == null)
				{
					return agent.CourseNode;
				}
				Enumerator<AIG_VoxelNode> enumerator = val2.m_nodes.GetEnumerator();
				AIG_NodeCluster val3 = default(AIG_NodeCluster);
				while (enumerator.MoveNext())
				{
					AIG_VoxelNode current = enumerator.Current;
					if (current.ClusterID != 0 && AIG_NodeCluster.TryGetNodeCluster(current.ClusterID, ref val3) && val3.CourseNode != null)
					{
						return val3.CourseNode;
					}
				}
			}
			return agent.CourseNode;
		}

		private static bool TryGetGeomorphVolumeSilent(eDimensionIndex dimensionIndex, Vector3 pos, [MaybeNullWhen(false)] out AIG_GeomorphNodeVolume resultingGeoVolume)
		{
			//IL_001a: 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)
			resultingGeoVolume = null;
			LG_Floor currentFloor = Builder.Current.m_currentFloor;
			if ((Object)(object)currentFloor == (Object)null)
			{
				return false;
			}
			Dimension val = default(Dimension);
			if (!currentFloor.GetDimension(dimensionIndex, ref val))
			{
				return false;
			}
			if (val.Grid == null || !TryGetCell(val.Grid, pos, out LG_Cell cell))
			{
				return false;
			}
			if (((CellBase<LG_Tile, LG_Cell>)(object)cell).m_grouping == null || (Object)(object)((CellBase<LG_Tile, LG_Cell>)(object)cell).m_grouping.m_geoRoot == (Object)null)
			{
				return false;
			}
			resultingGeoVolume = ((Il2CppObjectBase)((CellBase<LG_Tile, LG_Cell>)(object)cell).m_grouping.m_geoRoot.m_nodeVolume).TryCast<AIG_GeomorphNodeVolume>();
			return (Object)(object)resultingGeoVolume != (Object)null;
		}

		private static bool TryGetCell(LG_Grid grid, Vector3 pos, [MaybeNullWhen(false)] out LG_Cell cell)
		{
			//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_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_000e: 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)
			pos -= ((CellGridBase<LG_Grid, LG_Tile, LG_Cell>)(object)grid).m_gridPosition;
			int num = (int)Math.Round((pos.x - ((CellGridBase<LG_Grid, LG_Tile, LG_Cell>)(object)grid).m_cellDimHalf) / ((CellGridBase<LG_Grid, LG_Tile, LG_Cell>)(object)grid).m_cellDim);
			int num2 = (int)Math.Round((pos.z - ((CellGridBase<LG_Grid, LG_Tile, LG_Cell>)(object)grid).m_cellDimHalf) / ((CellGridBase<LG_Grid, LG_Tile, LG_Cell>)(object)grid).m_cellDim);
			if (num < 0 || num2 < 0 || num >= ((CellGridBase<LG_Grid, LG_Tile, LG_Cell>)(object)grid).m_sizeX || num2 >= ((CellGridBase<LG_Grid, LG_Tile, LG_Cell>)(object)grid).m_sizeZ)
			{
				cell = null;
				return false;
			}
			cell = ((CellGridBase<LG_Grid, LG_Tile, LG_Cell>)(object)grid).GetCell(num, num2);
			return true;
		}
	}
	internal static class SortUtil
	{
		private static List<(RaycastHit hit, float distance)> s_limbCache = new List<(RaycastHit, float)>();

		private static List<(EnemyAgent enemy, float value)> s_enemyTupleCache = new List<(EnemyAgent, float)>();

		public static int Rayhit(RaycastHit x, RaycastHit y)
		{
			if (((RaycastHit)(ref x)).distance == ((RaycastHit)(ref y)).distance)
			{
				return 0;
			}
			if (!(((RaycastHit)(ref x)).distance < ((RaycastHit)(ref y)).distance))
			{
				return 1;
			}
			return -1;
		}

		public static int EnemyRayhit((EnemyAgent, RaycastHit hit) x, (EnemyAgent, RaycastHit hit) y)
		{
			if (((RaycastHit)(ref x.hit)).distance == ((RaycastHit)(ref y.hit)).distance)
			{
				return 0;
			}
			if (!(((RaycastHit)(ref x.hit)).distance < ((RaycastHit)(ref y.hit)).distance))
			{
				return 1;
			}
			return -1;
		}

		public static void SortWithWeakspotBuffer(IList<RaycastHit> list)
		{
			//IL_000a: 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_0010: 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_0059: 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_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)
			foreach (RaycastHit item in list)
			{
				RaycastHit current = item;
				IDamageable? damageableFromRayHit = DamageableUtil.GetDamageableFromRayHit(current);
				int num;
				if (damageableFromRayHit == null)
				{
					num = 0;
				}
				else
				{
					Dam_EnemyDamageLimb obj = ((Il2CppObjectBase)damageableFromRayHit).TryCast<Dam_EnemyDamageLimb>();
					num = ((((obj != null) ? new eLimbDamageType?(obj.m_type) : null) == (eLimbDamageType?)1) ? 1 : 0);
				}
				bool flag = (byte)num != 0;
				s_limbCache.Add((current, flag ? Math.Max(((RaycastHit)(ref current)).distance - 0.1f, 0f) : ((RaycastHit)(ref current)).distance));
			}
			s_limbCache.Sort(FloatTuple);
			CopySortedList(s_limbCache, list);
			s_limbCache.Clear();
		}

		public static void CopySortedList<T>(IList<(T, float)> sortedList, IList<T> list)
		{
			for (int i = 0; i < list.Count; i++)
			{
				list[i] = sortedList[i].Item1;
			}
		}

		public static void CopySortedList<T>(IList<(T, float, float)> sortedList, IList<T> list)
		{
			for (int i = 0; i < list.Count; i++)
			{
				list[i] = sortedList[i].Item1;
			}
		}

		public static int FloatTuple<T>((T, float val) x, (T, float val) y)
		{
			if (x.val == y.val)
			{
				return 0;
			}
			if (!(x.val < y.val))
			{
				return 1;
			}
			return -1;
		}

		public static int FloatTuple<T>((T, float val1, float val2) x, (T, float val1, float val2) y)
		{
			if (x.val1 == y.val1)
			{
				if (x.val2 == y.val2)
				{
					return 0;
				}
				if (!(x.val2 < y.val2))
				{
					return 1;
				}
				return -1;
			}
			if (!(x.val1 < y.val1))
			{
				return 1;
			}
			return -1;
		}
	}
	internal static class StringExtensions
	{
		public static T ToEnum<T>(this string? value, T defaultValue) where T : struct
		{
			if (string.IsNullOrEmpty(value))
			{
				return defaultValue;
			}
			if (!Enum.TryParse<T>(value.Replace(" ", null), ignoreCase: true, out var result))
			{
				return defaultValue;
			}
			return result;
		}
	}
}
namespace EWC.Utils.Log
{
	internal static class EWCLogger
	{
		private static ManualLogSource logger = Logger.CreateLogSource("ExtraWeaponCustomization");

		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 EWC.Patches
{
	[HarmonyPatch]
	internal static class WeaponPatches
	{
		private static uint s_lastSearchID = 0u;

		private static float s_origHitDamage = 0f;

		private static float s_origHitPrecision = 0f;

		private static readonly HitData s_hitData = new HitData();

		private static ContextController? _cachedHitCC = null;

		public static ContextController? CachedHitCC
		{
			get
			{
				return _cachedHitCC;
			}
			set
			{
				_cachedHitCC = value;
				CachedBypassTumorCap = false;
			}
		}

		public static bool CachedBypassTumorCap { get; private set; } = false;


		[HarmonyPatch(typeof(BulletWeapon), "OnGearSpawnComplete")]
		[HarmonyWrapSafe]
		[HarmonyPostfix]
		private static void SetupCallback(BulletWeapon __instance)
		{
			CustomWeaponManager.Current.AddWeaponListener((ItemEquippable)(object)__instance);
			if (CustomWeaponManager.TryGetCustomGunData(((GameDataBlockBase<ArchetypeDataBlock>)(object)((ItemEquippable)__instance).ArchetypeData).persistentID, out CustomWeaponData data) && !((Object)(object)((Component)__instance).gameObject.GetComponent<CustomWeaponComponent>() != (Object)null))
			{
				((Component)__instance).gameObject.AddComponent<CustomWeaponComponent>().Register(data);
			}
		}

		[HarmonyPatch(typeof(BulletWeapon), "OnWield")]
		[HarmonyWrapSafe]
		[HarmonyPostfix]
		private static void UpdateCurrentWeapon(BulletWeapon __instance)
		{
			CustomWeaponComponent component = ((Component)__instance).GetComponent<CustomWeaponComponent>();
			if (!((Object)(object)component == (Object)null))
			{
				component.Invoke(StaticContext<WeaponWieldContext>.Instance);
				component.RefreshSoundDelay();
				s_lastSearchID = 0u;
			}
		}

		[HarmonyPatch(typeof(BulletWeapon), "OnUnWield")]
		[HarmonyWrapSafe]
		[HarmonyPostfix]
		private static void UpdateWeaponUnwielded(BulletWeapon __instance)
		{
			CustomWeaponComponent component = ((Component)__instance).GetComponent<CustomWeaponComponent>();
			if (!((Object)(object)component == (Object)null))
			{
				component.Invoke(StaticContext<WeaponUnWieldContext>.Instance);
			}
		}

		[HarmonyPatch(typeof(BulletWeapon), "BulletHit")]
		[HarmonyPriority(200)]
		[HarmonyWrapSafe]
		[HarmonyPrefix]
		private static void HitCallback(ref WeaponHitData weaponRayData, bool doDamage, float additionalDis, uint damageSearchID, ref bool allowDirectionalBonus)
		{
			CachedHitCC = null;
			if (!allowDirectionalBonus || weaponRayData.vfxBulletHit != null || !doDamage || !((Agent)weaponRayData.owner).IsLocallyOwned)
			{
				return;
			}
			s_hitData.Setup(weaponRayData, additionalDis);
			IDamageable damageable = s_hitData.damageable;
			IDamageable val = ((damageable != null) ? damageable.GetBaseDamagable() : damageable);
			if ((val != null && val.GetHealthRel() <= 0f) || (damageSearchID != 0 && val != null && val.TempSearchID == damageSearchID))
			{
				return;
			}
			ItemEquippable wieldedItem = s_hitData.owner.Inventory.WieldedItem;
			CustomWeaponComponent customWeaponComponent = ((wieldedItem != null) ? ((Component)wieldedItem).GetComponent<CustomWeaponComponent>() : null);
			if ((Object)(object)customWeaponComponent == (Object)null)
			{
				if (damageable.IsEnemy())
				{
					KillTrackerManager.ClearHit(((Il2CppObjectBase)damageable.GetBaseAgent()).Cast<EnemyAgent>());
				}
				return;
			}
			if (damageable != null && damageSearchID != 0)
			{
				if (s_lastSearchID != damageSearchID)
				{
					s_lastSearchID = damageSearchID;
					s_origHitDamage = s_hitData.damage;
					s_origHitPrecision = s_hitData.precisionMulti;
				}
				s_hitData.damage = s_origHitDamage;
				s_hitData.precisionMulti = s_origHitPrecision;
			}
			ApplyEWCHit(customWeaponComponent, s_hitData, damageSearchID != 0, ref s_origHitDamage, out allowDirectionalBonus);
		}

		public static void ApplyEWCHit(CustomWeaponComponent cwc, HitData hitData, bool pierce, ref float pierceDamage, out bool doBackstab)
		{
			ApplyEWCHit(cwc.GetContextController(), cwc.Weapon, hitData, pierce, ref pierceDamage, out doBackstab);
		}

		public static void ApplyEWCHit(ContextController cc, ItemEquippable weapon, HitData hitData, bool pierce, ref float pierceDamage, out bool doBackstab)
		{
			//IL_0059: Unknown result type (might be due to invalid IL or missing references)
			//IL_005f: Invalid comparison between Unknown and I4
			//IL_0077: Unknown result type (might be due to invalid IL or missing references)
			//IL_0082: Unknown result type (might be due to invalid IL or missing references)
			doBackstab = true;
			CachedHitCC = cc;
			IDamageable damageable = hitData.damageable;
			if (damageable.IsValid() && damageable.GetBaseDamagable().GetHealthRel() > 0f)
			{
				float num = 1f;
				float num2 = 1f;
				Agent baseAgent = damageable.GetBaseAgent();
				Dam_EnemyDamageLimb val = null;
				int num3;
				if ((Object)(object)baseAgent != (Object)null && baseAgent.Alive)
				{
					num3 = (((int)baseAgent.Type == 1) ? 1 : 0);
					if (num3 != 0)
					{
						val = ((Il2CppObjectBase)damageable).Cast<Dam_EnemyDamageLimb>();
						num2 = val.ApplyDamageFromBehindBonus(1f, hitData.hitPos, ((Vector3)(ref hitData.fireDir)).normalized, 1f);
						num = num2.Map(1f, 2f, 1f, cc.Invoke(new WeaponBackstabContext()).Value);
					}
				}
				else
				{
					num3 = 0;
				}
				cc.Invoke(new WeaponPreHitDamageableContext(hitData, num, DamageType.Bullet));
				WeaponDamageContext weaponDamageContext = new WeaponDamageContext(hitData.damage, hitData.precisionMulti, damageable);
				cc.Invoke(weaponDamageContext);
				hitData.damage = weaponDamageContext.Damage.Value;
				hitData.precisionMulti = weaponDamageContext.Precision.Value;
				CachedBypassTumorCap = weaponDamageContext.BypassTumorCap;
				if (pierce)
				{
					WeaponPierceContext weaponPierceContext = new WeaponPierceContext(pierceDamage, damageable);
					cc.Invoke(weaponPierceContext);
					pierceDamage = weaponPierceContext.Value;
				}
				if (num3 != 0)
				{
					WeaponHitDamageableContext weaponHitDamageableContext = new WeaponHitDamageableContext(hitData, CachedBypassTumorCap, num, val, DamageType.Bullet);
					cc.Invoke(weaponHitDamageableContext);
					KillTrackerManager.RegisterHit(weapon, weaponHitDamageableContext);
					if (num > 1f)
					{
						hitData.damage *= num / num2;
					}
					else
					{
						doBackstab = false;
					}
				}
				else
				{
					cc.Invoke(new WeaponHitDamageableContext(hitData, DamageType.Bullet));
				}
			}
			else
			{
				cc.Invoke(new WeaponHitContext(hitData));
			}
			hitData.Apply();
		}
	}
}
namespace EWC.Patches.Player
{
	internal static class PlayerDamagePatches
	{
		private static bool _ignoreCall;

		[HarmonyPatch(typeof(Dam_PlayerDamageBase), "OnIncomingDamage")]
		[HarmonyWrapSafe]
		[HarmonyPrefix]
		private static void Pre_TakeDamage(Dam_PlayerDamageBase __instance, float damage)
		{
			_ignoreCall = damage <= 0f || ((Dam_SyncedDamageBase)__instance).Health <= 0f;
		}

		[HarmonyPatch(typeof(Dam_PlayerDamageBase), "OnIncomingDamage")]
		[HarmonyWrapSafe]
		[HarmonyPostfix]
		private static void Post_TakeDamage(Dam_PlayerDamageBase __instance, float damage)
		{
			PlayerBackpack val = default(PlayerBackpack);
			if (!_ignoreCall && PlayerBackpackManager.TryGetBackpack(__instance.Owner.Owner, ref val))
			{
				BackpackItem val2 = default(BackpackItem);
				if (val.TryGetBackpackItem((InventorySlot)1, ref val2))
				{
					Item instance = val2.Instance;
					((instance != null) ? ((Component)instance).GetComponent<CustomWeaponComponent>() : null)?.Invoke(new WeaponDamageTakenContext(damage));
				}
				BackpackItem val3 = default(BackpackItem);
				if (val.TryGetBackpackItem((InventorySlot)2, ref val3))
				{
					Item instance2 = val3.Instance;
					((instance2 != null) ? ((Component)instance2).GetComponent<CustomWeaponComponent>() : null)?.Invoke(new WeaponDamageTakenContext(damage));
				}
			}
		}
	}
	[HarmonyPatch]
	internal static class PlayerLocalPatches
	{
		[HarmonyPatch(typeof(PUI_LocalPlayerStatus), "UpdateHealth")]
		[HarmonyWrapSafe]
		[HarmonyPrefix]
		private static void UpdateHealth(PUI_LocalPlayerStatus __instance, float health, bool meleeBuffActive)
		{
			if (__instance.m_lastHealthVal <= 0.14f && health > 0.14f && __instance.m_warningRoutine != null)
			{
				__instance.m_healthWarningLooping = true;
			}
		}
	}
}
namespace EWC.Patches.Native
{
	internal static class EnemyDetectionPatches
	{
		private unsafe delegate void d_DetectOnNoise(IntPtr _this, IntPtr agentTarget, float movementDetectionDistance, float shootDetectionDistance, float delta, out float output, Il2CppMethodInfo* methodInfo);

		private struct CWCHolder
		{
			public CustomWeaponComponent? primary;

			public bool hasPrimary;

			public CustomWeaponComponent? special;

			public bool hasSpecial;

			public readonly bool IsValid
			{
				get
				{
					if ((Object)(object)primary != (Object)null == hasPrimary)
					{
						return (Object)(object)special != (Object)null == hasSpecial;
					}
					return false;
				}
			}
		}

		private static INativeDetour? DetectOnNoiseDetour;

		private static d_DetectOnNoise? orig_DetectOnNoise;

		private static readonly Dictionary<int, CWCHolder> s_cachedCWCs = new Dictionary<int, CWCHolder>();

		internal unsafe static void ApplyNativePatch()
		{
			DetectOnNoiseDetour = INativeDetour.CreateAndApply<d_DetectOnNoise>((IntPtr)(nint)Il2CppAPI.GetIl2CppMethod<EnemyDetection>("DetectOnNoiseDistance_Conditional_AnimatedWindow", typeof(void).Name, false, new string[5]
			{
				"AgentTarget",
				typeof(float).Name,
				typeof(float).Name,
				typeof(float).Name,
				typeof(float).MakeByRefType().Name
			}), (d_DetectOnNoise)DetectOnNoisePatch, ref orig_DetectOnNoise);
			NativePatchAPI.AddDetectPostfix(Post_DetectAgentNoise);
		}

		private unsafe static void DetectOnNoisePatch(IntPtr _this, IntPtr agentTarget, float movementDetectionDistance, float shootDetectionDistance, float delta, out float output, Il2CppMethodInfo* methodInfo)
		{
			//IL_0009: 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: Expected O, but got Unknown
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			//IL_0022: Expected O, but got Unknown
			//IL_0044: Expected O, but got Unknown
			output = 0f;
			EnemyDetection val = new EnemyDetection(_this);
			AgentTarget agentTarget2 = new AgentTarget(agentTarget);
			if (NativePatchAPI.RunDetectPrefix(val, agentTarget2, movementDetectionDistance, shootDetectionDistance, delta, ref output))
			{
				orig_DetectOnNoise(_this, agentTarget, movementDetectionDistance, shootDetectionDistance, delta, out output, methodInfo);
			}
			NativePatchAPI.RunDetectPostfix(val, agentTarget2, movementDetectionDistance, shootDetectionDistance, delta, ref output);
		}

		private static void UpdateCache()
		{
			if (s_cachedCWCs.Count == PlayerManager.PlayerAgentsInLevel.Count && !s_cachedCWCs.Values.Any((CWCHolder holder) => !holder.IsValid))
			{
				return;
			}
			s_cachedCWCs.Clear();
			Enumerator<PlayerAgent> enumerator = PlayerManager.PlayerAgentsInLevel.GetEnumerator();
			PlayerBackpack val = default(PlayerBackpack);
			BackpackItem val2 = default(BackpackItem);
			BackpackItem val3 = default(BackpackItem);
			while (enumerator.MoveNext())
			{
				PlayerAgent current = enumerator.Current;
				if (PlayerBackpackManager.TryGetBackpack(current.Owner, ref val) && val.TryGetBackpackItem((InventorySlot)1, ref val2) && val.TryGetBackpackItem((InventorySlot)2, ref val3))
				{
					Item instance = val2.Instance;
					CustomWeaponComponent customWeaponComponent = ((instance != null) ? ((Component)instance).GetComponent<CustomWeaponComponent>() : null);
					Item instance2 = val3.Instance;
					CustomWeaponComponent customWeaponComponent2 = ((instance2 != null) ? ((Component)instance2).GetComponent<CustomWeaponComponent>() : null);
					s_cachedCWCs.Add(((Agent)current).GlobalID, new CWCHolder
					{
						primary = customWeaponComponent,
						hasPrimary = ((Object)(object)customWeaponComponent != (Object)null),
						special = customWeaponComponent2,
						hasSpecial = ((Object)(object)customWeaponComponent2 != (Object)null)
					});
				}
			}
		}

		private static void Post_DetectAgentNoise(EnemyDetection __instance, AgentTarget agentTarget, float _mv, float _wp, float _delta, ref float output)
		{
			UpdateCache();
			if (s_cachedCWCs.TryGetValue(agentTarget.m_globalID, out var value) && (value.hasPrimary || value.hasSpecial))
			{
				WeaponStealthUpdateContext weaponStealthUpdateContext = new WeaponStealthUpdateContext(__instance.m_ai.m_enemyAgent, __instance.m_noiseDetectionOn, output);
				value.primary?.Invoke(weaponStealthUpdateContext);
				value.special?.Invoke(weaponStealthUpdateContext);
				output = weaponStealthUpdateContext.Output;
			}
		}
	}
}
namespace EWC.Patches.Melee
{
	[HarmonyPatch]
	internal static class MeleePatches
	{
		private static readonly HitData s_hitData = new HitData();

		private static float s_origHitDamage = 0f;

		private static float s_origHitPrecision = 0f;

		public static float CachedCharge { get; private set; } = 0f;


		[HarmonyPatch(typeof(MeleeWeaponFirstPerson), "SetupMeleeAnimations")]
		[HarmonyWrapSafe]
		[HarmonyPostfix]
		private static void SetupCallback(MeleeWeaponFirstPerson __instance)
		{
			CachedCharge = 0f;
			CustomWeaponManager.Current.AddWeaponListener((ItemEquippable)(object)__instance);
			if (CustomWeaponManager.TryGetCustomMeleeData(((GameDataBlockBase<MeleeArchetypeDataBlock>)(object)((ItemEquippable)__instance).MeleeArchetypeData).persistentID, out CustomWeaponData data) && !((Object)(object)((Component)__instance).gameObject.GetComponent<CustomWeaponComponent>() != (Object)null))
			{
				((Component)__instance).gameObject.AddComponent<CustomWeaponComponent>().Register(data);
			}
		}

		[HarmonyPatch(typeof(MeleeWeaponFirstPerson), "OnWield")]
		[HarmonyWrapSafe]
		[HarmonyPostfix]
		private static void UpdateCurrentWeapon(MeleeWeaponFirstPerson __instance)
		{
			CachedCharge = 0f;
			CustomWeaponComponent component = ((Component)__instance).GetComponent<CustomWeaponComponent>();
			if (!((Object)(object)component == (Object)null))
			{
				component.Invoke(StaticContext<WeaponWieldContext>.Instance);
			}
		}

		[HarmonyPatch(typeof(MeleeWeaponFirstPerson), "OnUnWield")]
		[HarmonyWrapSafe]
		[HarmonyPostfix]
		private static void ClearCharge(MeleeWeaponFirstPerson __instance)
		{
			CachedCharge = 0f;
			CustomWeaponComponent component = ((Component)__instance).GetComponent<CustomWeaponComponent>();
			if (!((Object)(object)component == (Object)null))
			{
				component.Invoke(StaticContext<WeaponUnWieldContext>.Instance);
			}
		}

		[HarmonyPatch(typeof(MeleeWeaponFirstPerson), "SetNextDamageToDeal")]
		[HarmonyWrapSafe]
		[HarmonyPostfix]
		private static void SetDamageCallback(MeleeWeaponFirstPerson __instance, eMeleeWeaponDamage dam, float scale)
		{
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			//IL_0018: Invalid comparison between Unknown and I4
			s_origHitDamage = __instance.m_damageToDeal;
			s_origHitPrecision = __instance.m_precisionMultiToDeal;
			CachedCharge = (((int)dam == 2) ? ((float)Math.Cbrt(scale)) : 0f);
		}

		[HarmonyPatch(typeof(MeleeWeaponFirstPerson), "DoAttackDamage")]
		[HarmonyWrapSafe]
		[HarmonyPrefix]
		private static void HitCallback(MeleeWeaponFirstPerson __instance, MeleeWeaponDamageData data, bool isPush)
		{
			//IL_0060: Unknown result type (might be due to invalid IL or missing references)
			//IL_0066: Invalid comparison between Unknown and I4
			if (isPush)
			{
				return;
			}
			s_hitData.Setup(__instance, data);
			IDamageable damageable = s_hitData.damageable;
			IDamageable val = ((damageable != null) ? damageable.GetBaseDamagable() : null);
			if (val != null && val.GetHealthRel() <= 0f)
			{
				return;
			}
			CustomWeaponComponent component = ((Component)__instance).GetComponent<CustomWeaponComponent>();
			if ((Object)(object)component == (Object)null)
			{
				Agent val2 = ((damageable != null) ? damageable.GetBaseAgent() : null);
				if ((Object)(object)val2 != (Object)null && (int)val2.Type == 1 && val2.Alive)
				{
					KillTrackerManager.ClearHit(((Il2CppObjectBase)val2).Cast<EnemyAgent>());
				}
				WeaponPatches.CachedHitCC = null;
			}
			else
			{
				s_hitData.damage = s_origHitDamage;
				s_hitData.precisionMulti = s_origHitPrecision;
				WeaponPatches.ApplyEWCHit(component, s_hitData, pierce: false, ref s_origHitDamage, out var _);
			}
		}
	}
	[HarmonyPatch]
	internal static class MWSPatches
	{
		[HarmonyPatch(typeof(MWS_ChargeUp), "Enter")]
		[HarmonyWrapSafe]
		[HarmonyPostfix]
		private static void ChargeCallback(MWS_ChargeUp __instance)
		{
			CustomWeaponComponent component = ((Component)((MWS_Base)__instance).m_weapon).GetComponent<CustomWeaponComponent>();
			if (!((Object)(object)component == (Object)null))
			{
				WeaponFireRateContext weaponFireRateContext = new WeaponFireRateContext(1f);
				component.Invoke(weaponFireRateContext);
				__instance.m_maxDamageTime /= weaponFireRateContext.Value;
			}
		}

		[HarmonyPatch(typeof(MWS_Push), "Enter")]
		[HarmonyWrapSafe]
		[HarmonyPostfix]
		private static void PushCallback(MWS_Push __instance)
		{
			CustomWeaponComponent component = ((Component)((MWS_Base)__instance).m_weapon).GetComponent<CustomWeaponComponent>();
			if (!((Object)(object)component == (Object)null))
			{
				WeaponFireRateContext weaponFireRateContext = new WeaponFireRateContext(1f);
				component.Invoke(weaponFireRateContext);
				Animator weaponAnimator = ((MWS_Base)__instance).m_weapon.WeaponAnimator;
				weaponAnimator.speed *= weaponFireRateContext.Value;
			}
		}

		[HarmonyPatch(typeof(MWS_AttackSwingBase), "Enter")]
		[HarmonyWrapSafe]
		[HarmonyPostfix]
		private static void PreSwingCallback(MWS_AttackSwingBase __instance)
		{
			CustomWeaponComponent component = ((Component)((MWS_Base)__instance).m_weapon).GetComponent<CustomWeaponComponent>();
			if (!((Object)(object)component == (Object)null))
			{
				component.Invoke(StaticContext<WeaponPreFireContext>.Instance);
			}
		}

		[HarmonyPatch(typeof(MWS_AttackSwingBase), "Exit")]
		[HarmonyWrapSafe]
		[HarmonyPostfix]
		private static void PostSwingCallback(MWS_AttackSwingBase __instance)
		{
			CustomWeaponComponent component = ((Component)((MWS_Base)__instance).m_weapon).GetComponent<CustomWeaponComponent>();
			if (!((Object)(object)component == (Object)null))
			{
				component.Invoke(StaticContext<WeaponPostFireContext>.Instance);
			}
		}
	}
}
namespace EWC.Patches.Gun
{
	[HarmonyPatch]
	internal static class FPISPatches
	{
		private static CustomWeaponComponent? _cachedCWC;

		[HarmonyPatch(typeof(FPIS_Aim), "Enter")]
		[HarmonyWrapSafe]
		[HarmonyPostfix]
		private static void Post_AimEnter(FPIS_Aim __instance)
		{
			_cachedCWC = ((Component)((FPItemState)__instance).Holder.WieldedItem).GetComponent<CustomWeaponComponent>();
			if (!((Object)(object)_cachedCWC == (Object)null))
			{
				_cachedCWC.Invoke(StaticContext<WeaponAimContext>.Instance);
			}
		}

		[HarmonyPatch(typeof(FPIS_Aim), "Exit")]
		[HarmonyWrapSafe]
		[HarmonyPostfix]
		private static void Post_AimExit()
		{
			if (!((Object)(object)_cachedCWC == (Object)null))
			{
				_cachedCWC.Invoke(StaticContext<WeaponAimEndContext>.Instance);
			}
		}
	}
	[HarmonyPatch]
	internal static class PlayerInventoryPatches
	{
		private static bool _allowReload = true;

		[HarmonyPatch(typeof(PUI_Inventory), "SetSlotAmmo")]
		[HarmonyWrapSafe]
		[HarmonyPrefix]
		private static void SetAmmoUICallback(PUI_Inventory __instance, InventorySlot slot, ref int clipAbs, ref int inPackAbs, ref float inPackRel)
		{
			//IL_0000: 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)
			if ((int)slot == 0)
			{
				return;
			}
			SNet_Player owner = __instance.m_owner;
			object obj;
			if (owner == null)
			{
				obj = null;
			}
			else
			{
				SNet_IPlayerAgent playerAgent = owner.PlayerAgent;
				if (playerAgent == null)
				{
					obj = null;
				}
				else
				{
					PlayerAgent obj2 = ((Il2CppObjectBase)playerAgent).TryCast<PlayerAgent>();
					if (obj2 == null)
					{
						obj = null;
					}
					else
					{
						FirstPersonItemHolder fPItemHolder = obj2.FPItemHolder;
						if (fPItemHolder == null)
						{
							obj = null;
						}
						else
						{
							ItemEquippable wieldedItem = fPItemHolder.WieldedItem;
							if (wieldedItem == null)
							{
								obj = null;
							}
							else
							{
								BulletWeapon obj3 = ((Il2CppObjectBase)wieldedItem).TryCast<BulletWeapon>();
								obj = ((obj3 != null) ? ((Component)obj3).GetComponent<CustomWeaponComponent>() : null);
							}
						}
					}
				}
			}
			CustomWeaponComponent customWeaponComponent = (CustomWeaponComponent)obj;
			if (!((Object)(object)customWeaponComponent == (Object)null))
			{
				PUI_InventoryItem val = __instance.m_inventorySlots[slot];
				WeaponPreAmmoUIContext weaponPreAmmoUIContext = new WeaponPreAmmoUIContext(clipAbs, inPackAbs, inPackRel, val.ShowAmmoClip, val.ShowAmmoPack, val.ShowAmmoTotalRel, val.ShowAmmoInfinite);
				customWeaponComponent.Invoke(weaponPreAmmoUIContext);
				clipAbs = weaponPreAmmoUIContext.Clip;
				inPackAbs = weaponPreAmmoUIContext.Reserve;
				inPackRel = weaponPreAmmoUIContext.TotalRel;
				val.ShowAmmoClip = weaponPreAmmoUIContext.ShowClip;
				val.ShowAmmoPack = weaponPreAmmoUIContext.ShowReserve;
				val.ShowAmmoTotalRel = weaponPreAmmoUIContext.ShowRel;
				val.ShowAmmoInfinite = weaponPreAmmoUIContext.ShowInfinite;
			}
		}

		private static InventorySlot AmmoToSlot(AmmoType ammo)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0012: Expected I4, but got Unknown
			//IL_0015: 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_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_0021: Unknown result type (might be due to invalid IL or missing references)
			return (InventorySlot)((int)ammo switch
			{
				0 => 1, 
				1 => 2, 
				2 => 3, 
				_ => 0, 
			});
		}

		[HarmonyPatch(typeof(PlayerAmmoStorage), "PickupAmmo")]
		[HarmonyWrapSafe]
		[HarmonyPrefix]
		private static void AmmoPackCallback(PlayerAmmoStorage __instance, AmmoType ammoType, ref float ammoAmount)
		{
			//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)
			BackpackItem val = default(BackpackItem);
			if (__instance.m_playerBackpack.TryGetBackpackItem(AmmoToSlot(ammoType), ref val))
			{
				Item instance = val.Instance;
				CustomWeaponComponent customWeaponComponent = ((instance != null) ? ((Component)instance).GetComponent<CustomWeaponComponent>() : null);
				if ((Object)(object)customWeaponComponent != (Object)null)
				{
					ammoAmount = customWeaponComponent.Invoke(new WeaponPreAmmoPackContext(ammoAmount)).AmmoAmount;
				}
			}
		}

		[HarmonyPatch(typeof(PlayerAmmoStorage), "PickupAmmo")]
		[HarmonyWrapSafe]
		[HarmonyPostfix]
		private static void PostAmmoPackCallback(PlayerAmmoStorage __instance, AmmoType ammoType)
		{
			//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)
			BackpackItem val = default(BackpackItem);
			if (__instance.m_playerBackpack.TryGetBackpackItem(AmmoToSlot(ammoType), ref val))
			{
				Item instance = val.Instance;
				((instance != null) ? ((Component)instance).GetComponent<CustomWeaponComponent>() : null)?.Invoke(new WeaponPostAmmoPackContext(__instance));
			}
		}

		[HarmonyPatch(typeof(PlayerInventoryLocal), "DoReload")]
		[HarmonyPatch(typeof(PlayerInventoryBase), "DoReload")]
		[HarmonyWrapSafe]
		[HarmonyPostfix]
		private static void ReloadCallback(PlayerInventoryBase __instance)
		{
			ItemEquippable wieldedItem = __instance.m_wieldedItem;
			CustomWeaponComponent customWeaponComponent = ((wieldedItem != null) ? ((Component)wieldedItem).GetComponent<CustomWeaponComponent>() : null);
			if (!((Object)(object)customWeaponComponent == (Object)null))
			{
				customWeaponComponent.Invoke(StaticContext<WeaponPostReloadContext>.Instance);
			}
		}

		[HarmonyPatch(typeof(PlayerInventoryLocal), "TriggerReload")]
		[HarmonyWrapSafe]
		[HarmonyPrefix]
		private static bool ReloadPreStartCallback(PlayerInventoryLocal __instance)
		{
			_allowReload = true;
			ItemEquippable wieldedItem = ((PlayerInventoryBase)__instance).m_wieldedItem;
			CustomWeaponComponent customWeaponComponent = ((wieldedItem != null) ? ((Component)wieldedItem).GetComponent<CustomWeaponComponent>() : null);
			if ((Object)(object)customWeaponComponent == (Object)null)
			{
				return true;
			}
			_allowReload = customWeaponComponent.Invoke(new WeaponPreReloadContext()).Allow;
			return _allowReload;
		}

		[HarmonyPatch(typeof(PlayerInventoryLocal), "TriggerReload")]
		[HarmonyWrapSafe]
		[HarmonyPostfix]
		private static void ReloadStartCallback(PlayerInventoryLocal __instance)
		{
			if (_allowReload)
			{
				ItemEquippable wieldedItem = ((PlayerInventoryBase)__instance).m_wieldedItem;
				CustomWeaponComponent customWeaponComponent = ((wieldedItem != null) ? ((Component)wieldedItem).GetComponent<CustomWeaponComponent>() : null);
				if (!((Object)(object)customWeaponComponent == (Object)null) && customWeaponComponent.Weapon.IsReloading)
				{
					customWeaponComponent.Invoke(StaticContext<WeaponReloadStartContext>.Instance);
				}
			}
		}

		[HarmonyPatch(typeof(PlayerAmmoStorage), "FillAllClips")]
		[HarmonyWrapSafe]
		[HarmonyPostfix]
		private static void PostFillAllClipsCallback(PlayerAmmoStorage __instance)
		{
			BackpackItem val = default(BackpackItem);
			if (__instance.m_playerBackpack.TryGetBackpackItem((InventorySlot)1, ref val))
			{
				Item instance = val.Instance;
				((instance != null) ? ((Component)instance).GetComponent<CustomWeaponComponent>() : null)?.Invoke(new WeaponPostAmmoInitContext(__instance, __instance.StandardAmmo));
			}
			BackpackItem val2 = default(BackpackItem);
			if (__instance.m_playerBackpack.TryGetBackpackItem((InventorySlot)2, ref val2))
			{
				Item instance2 = val2.Instance;
				((instance2 != null) ? ((Component)instance2).GetComponent<CustomWeaponComponent>() : null)?.Invoke(new WeaponPostAmmoInitContext(__instance, __instance.SpecialAmmo));
			}
		}
	}
	[HarmonyPatch]
	internal static class ShotgunPatches
	{
		[HarmonyPatch(typeof(Shotgun), "Fire")]
		[HarmonyWrapSafe]
		[HarmonyPrefix]
		private static void Pre_Fire(Shotgun __instance)
		{
			WeaponRayPatches.CachedWeapon = (BulletWeapon?)(object)__instance;
		}

		[HarmonyPatch(typeof(Shotgun), "Fire")]
		[HarmonyWrapSafe]
		[HarmonyPostfix]
		private static void Post_Fire(Shotgun __instance)
		{
			WeaponRayPatches.CachedWeapon = null;
		}
	}
	[HarmonyPatch]
	internal static class WeaponArchetypePatches
	{
		[HarmonyPatch(typeof(BulletWeaponArchetype), "SetOwner")]
		[HarmonyWrapSafe]
		[HarmonyPostfix]
		private static void SetupCallback(BulletWeaponArchetype __instance, PlayerAgent owner)
		{
			if (!((Object)(object)owner == (Object)null))
			{
				CustomWeaponComponent component = ((Component)__instance.m_weapon).GetComponent<CustomWeaponComponent>();
				if (!((Object)(object)component == (Object)null))
				{
					component.OwnerInit();
				}
			}
		}

		[HarmonyPatch(typeof(BWA_Burst), "OnStartFiring")]
		[HarmonyPatch(typeof(BWA_Auto), "OnStartFiring")]
		[HarmonyPatch(typeof(BulletWeaponArchetype), "OnStartFiring")]
		[HarmonyWrapSafe]
		[HarmonyPrefix]
		private static bool StartFireCallback(BulletWeaponArchetype __instance)
		{
			BulletWeapon weapon = __instance.m_weapon;
			CustomWeaponComponent customWeaponComponent = ((weapon != null) ? ((Component)weapon).GetComponent<CustomWeaponComponent>() : null);
			if ((Object)(object)customWeaponComponent == (Object)null)
			{
				return true;
			}
			customWeaponComponent.CancelShot = false;
			WeaponPreStartFireContext weaponPreStartFireContext = new WeaponPreStartFireContext();
			customWeaponComponent.Invoke(weaponPreStartFireContext);
			customWeaponComponent.UpdateStoredFireRate();
			if (!weaponPreStartFireContext.Allow)
			{
				customWeaponComponent.StoreCancelShot();
			}
			return weaponPreStartFireContext.Allow;
		}

		[HarmonyPatch(typeof(BWA_Burst), "OnStartFiring")]
		[HarmonyPatch(typeof(BWA_Auto), "OnStartFiring")]
		[HarmonyPatch(typeof(BulletWeaponArchetype), "OnStartFiring")]
		[HarmonyWrapSafe]
		[HarmonyPostfix]
		private static void PostStartFireCallback(BulletWeaponArchetype __instance)
		{
			BulletWeapon weapon = __instance.m_weapon;
			CustomWeaponComponent customWeaponComponent = ((weapon != null) ? ((Component)weapon).GetComponent<CustomWeaponComponent>() : null);
			if (!((Object)(object)customWeaponComponent == (Object)null))
			{
				if (customWeaponComponent.ResetShotIfCancel(__instance))
				{
					customWeaponComponent.CancelShot = false;
					__instance.m_readyToFire = false;
				}
				else
				{
					customWeaponComponent.Invoke(StaticContext<WeaponPostStartFireContext>.Instance);
				}
			}
		}

		[HarmonyPatch(typeof(BWA_Auto), "OnFireShot")]
		[HarmonyPatch(typeof(BWA_Burst), "OnFireShot")]
		[HarmonyPatch(typeof(BWA_Semi), "OnFireShot")]
		[HarmonyWrapSafe]
		[HarmonyPrefix]
		private static bool PreFireCallback(BulletWeaponArchetype __instance)
		{
			BulletWeapon weapon = __instance.m_weapon;
			CustomWeaponComponent customWeaponComponent = ((weapon != null) ? ((Component)weapon).GetComponent<CustomWeaponComponent>() : null);
			if ((Object)(object)customWeaponComponent == (Object)null)
			{
				return true;
			}
			if (customWeaponComponent.CancelShot)
			{
				return false;
			}
			WeaponFireCancelContext weaponFireCancelContext = new WeaponFireCancelContext();
			customWeaponComponent.Invoke(weaponFireCancelContext);
			if (!weaponFireCancelContext.Allow)
			{
				customWeaponComponent.StoreCancelShot();
			}
			else
			{
				customWeaponComponent.Invoke(StaticContext<WeaponPreFireContext>.Instance);
			}
			return weaponFireCancelContext.Allow;
		}

		[HarmonyPatch(typeof(BWA_Auto), "OnFireShot")]
		[HarmonyPatch(typeof(BWA_Burst), "OnFireShot")]
		[HarmonyPatch(typeof(BWA_Semi), "OnFireShot")]
		[HarmonyWrapSafe]
		[HarmonyPostfix]
		private static void PostFireCallback(BulletWeaponArchetype __instance)
		{
			BulletWeapon weapon = __instance.m_weapon;
			CustomWeaponComponent customWeaponComponent = ((weapon != null) ? ((Component)weapon).GetComponent<CustomWeaponComponent>() : null);
			if (!((Object)(object)customWeaponComponent == (Object)null) && !customWeaponComponent.CancelShot)
			{
				customWeaponComponent.NotifyShotFired();
				customWeaponComponent.Invoke(StaticContext<WeaponPostFireContext>.Instance);
			}
		}

		[HarmonyPatch(typeof(BulletWeaponArchetype), "PostFireCheck")]
		[HarmonyWrapSafe]
		[HarmonyPrefix]
		private static void PrePostFireCallback(BulletWeaponArchetype __instance)
		{
			BulletWeapon weapon = __instance.m_weapon;
			CustomWeaponComponent customWeaponComponent = ((weapon != null) ? ((Component)weapon).GetComponent<CustomWeaponComponent>() : null);
			if (!((Object)(object)customWeaponComponent == (Object)null))
			{
				customWeaponComponent.ResetShotIfCancel(__instance);
			}
		}

		[HarmonyPatch(typeof(BulletWeaponArchetype), "PostFireCheck")]
		[HarmonyWrapSafe]
		[HarmonyPostfix]
		private static void PostPostFireCallback(BulletWeaponArchetype __instance)
		{
			BulletWeapon weapon = __instance.m_weapon;
			CustomWeaponComponent customWeaponComponent = ((weapon != null) ? ((Component)weapon).GetComponent<CustomWeaponComponent>() : null);
			if (!((Object)(object)customWeaponComponent == (Object)null))
			{
				if (customWeaponComponent.CancelShot)
				{
					customWeaponComponent.ModifyFireRate();
					customWeaponComponent.CancelShot = false;
				}
				else
				{
					customWeaponComponent.UpdateStoredFireRate();
					customWeaponComponent.ModifyFireRate();
				}
			}
		}

		[HarmonyPatch(typeof(BWA_Burst), "OnStopFiring")]
		[HarmonyPatch(typeof(BWA_Auto), "OnStopFiring")]
		[HarmonyPatch(typeof(BulletWeaponArchetype), "OnStopFiring")]
		[HarmonyWrapSafe]
		[HarmonyPostfix]
		private static void StopFiringCallback(BulletWeaponArchetype __instance)
		{
			BulletWeapon weapon = __instance.m_weapon;
			CustomWeaponComponent customWeaponComponent = ((weapon != null) ? ((Component)weapon).GetComponent<CustomWeaponComponent>() : null);
			if (!((Object)(object)customWeaponComponent == (Object)null))
			{
				customWeaponComponent.Invoke(StaticContext<WeaponPostStopFiringContext>.Instance);
			}
		}
	}
	[HarmonyPatch]
	internal static class WeaponRayPatches
	{
		public static BulletWeapon? CachedWeapon = null;

		private static HitData s_hitData = new HitData();

		private static CustomWeaponComponent? _cachedCWC = null;

		private static IntPtr _cachedData = IntPtr.Zero;

		[HarmonyTargetMethod]
		private static MethodBase FindWeaponRayFunc(Harmony harmony)
		{
			return AccessTools.Method(typeof(Weapon), "CastWeaponRay", new Type[4]
			{
				typeof(Transform),
				typeof(WeaponHitData).MakeByRefType(),
				typeof(Vector3),
				typeof(int)
			}, (Type[])null);
		}

		[HarmonyWrapSafe]
		[HarmonyPrefix]
		private static void PreRayCallback(ref WeaponHitData weaponRayData, Vector3 originPos, int altRayCastMask)
		{
			//IL_0094: Unknown result type (might be due to invalid IL or missing references)
			if (altRayCastMask != -1 || _cachedData == ((Il2CppObjectBase)weaponRayData).Pointer)
			{
				return;
			}
			_cachedData = ((Il2CppObjectBase)weaponRayData).Pointer;
			if ((Object)(object)CachedWeapon != (Object)null)
			{
				_cachedCWC = ((Component)CachedWeapon).GetComponent<CustomWeaponComponent>();
			}
			else
			{
				PlayerAgent owner = weaponRayData.owner;
				object cachedCWC;
				if (owner == null)
				{
					cachedCWC = null;
				}
				else
				{
					ItemEquippable wieldedItem = owner.Inventory.WieldedItem;
					cachedCWC = ((wieldedItem != null) ? ((Component)wieldedItem).GetComponent<CustomWeaponComponent>() : null);
				}
				_cachedCWC = (CustomWeaponComponent?)cachedCWC;
			}
			if (!((Object)(object)_cachedCWC == (Object)null))
			{
				s_hitData.Setup(weaponRayData);
				_cachedCWC.Invoke(new WeaponPreRayContext(s_hitData, originPos));
				s_hitData.Apply();
			}
		}

		[HarmonyWrapSafe]
		[HarmonyPostfix]
		private static void PostRayCallback(ref WeaponHitData weaponRayData, Vector3 originPos, int altRayCastMask, ref bool __result)
		{
			//IL_0029: 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)
			if (!((Object)(object)_cachedCWC == (Object)null))
			{
				s_hitData.Setup(weaponRayData);
				if (!_cachedCWC.Invoke(new WeaponCancelRayContext(s_hitData, originPos)).Result)
				{
					__result = false;
					return;
				}
				__result = _cachedCWC.Invoke(new WeaponPostRayContext(s_hitData, originPos, __result, (IntPtr)0)).Result;
				s_hitData.Apply();
				_cachedCWC = null;
			}
		}
	}
	[HarmonyPatch]
	internal static class WeaponRecoilPatches
	{
		private static BulletWeapon? _cachedWeapon;

		private static CustomWeaponComponent? _cachedComponent;

		[HarmonyPatch(typeof(BulletWeapon), "OnWield")]
		[HarmonyWrapSafe]
		[HarmonyPostfix]
		private static void UpdateCurrentWeapon(BulletWeapon __instance)
		{
			PlayerAgent owner = ((Item)__instance).Owner;
			if (owner != null && ((Agent)owner).IsLocallyOwned)
			{
				_cachedWeapon = __instance;
				_cachedComponent = ((Component)__instance).GetComponent<CustomWeaponComponent>();
			}
		}

		[HarmonyAfter(new string[] { "Dinorush.ExtraRecoilData" })]
		[HarmonyPatch(typeof(FPS_RecoilSystem), "ApplyRecoil")]
		[HarmonyWrapSafe]
		[HarmonyPostfix]
		private static void PostApplyRecoilCallback(FPS_RecoilSystem __instance, bool resetSimilarity, RecoilDataBlock recoilData)
		{
			//IL_0031: 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_0066: 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_0075: Unknown result type (might be due to invalid IL or missing references)
			//IL_0093: 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_00ae: 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_00d0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ea: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fc: Unknown result type (might be due to invalid IL or missing references)
			//IL_0113: Unknown result type (might be due to invalid IL or missing references)
			//IL_011a: Unknown result type (might be due to invalid IL or missing references)
			if (!((Object)(object)_cachedComponent == (Object)null))
			{
				WeaponRecoilContext weaponRecoilContext = new WeaponRecoilContext();
				_cachedComponent.Invoke(weaponRecoilContext);
				if (weaponRecoilContext.Value != 1f)
				{
					Vector2 val = default(Vector2);
					((Vector2)(ref val))..ctor(__instance.recoilDir.x * (weaponRecoilContext.Value - 1f), __instance.recoilDir.y * (weaponRecoilContext.Value - 1f));
					Vector2 currentRecoilForce = __instance.currentRecoilForce;
					currentRecoilForce.x -= val.x * (1f - recoilData.worldToViewSpaceBlendVertical);
					currentRecoilForce.y -= val.y * (1f - recoilData.worldToViewSpaceBlendHorizontal);
					Vector2 currentRecoilForceVP = __instance.currentRecoilForceVP;
					currentRecoilForceVP.x -= val.x * recoilData.worldToViewSpaceBlendVertical;
					currentRecoilForceVP.y -= val.y * recoilData.worldToViewSpaceBlendHorizontal;
					Vector2 recoilDir = __instance.recoilDir;
					((Vector2)(ref recoilDir)).Set(__instance.recoilDir.x * weaponRecoilContext.Value, __instance.recoilDir.y * weaponRecoilContext.Value);
					__instance.currentRecoilForce = currentRecoilForce;
					__instance.currentRecoilForceVP = currentRecoilForceVP;
				}
			}
		}
	}
	[HarmonyPatch]
	internal static class WeaponSyncPatches
	{
		[HarmonyPatch(typeof(BulletWeaponSynced), "OnGearSpawnComplete")]
		[HarmonyWrapSafe]
		[HarmonyPostfix]
		private static void Post_SetupSynced(BulletWeaponSynced __instance)
		{
			CustomWeaponComponent component = ((Component)__instance).GetComponent<CustomWeaponComponent>();
			if (!((Object)(object)component == (Object)null))
			{
				component.SetToSync();
			}
		}

		[HarmonyPatch(typeof(ShotgunSynced), "Fire")]
		[HarmonyPatch(typeof(BulletWeaponSynced), "Fire")]
		[HarmonyWrapSafe]
		[HarmonyPrefix]
		private static void Pre_FireSynced(BulletWeaponSynced __instance)
		{
			CustomWeaponComponent component = ((Component)__instance).GetComponent<CustomWeaponComponent>();
			if (!((Object)(object)component == (Object)null))
			{
				component.Invoke(StaticContext<WeaponPreFireContextSync>.Instance);
			}
		}

		[HarmonyPatch(typeof(ShotgunSynced), "Fire")]
		[HarmonyPatch(typeof(BulletWeaponSynced), "Fire")]
		[HarmonyWrapSafe]
		[HarmonyPostfix]
		private static void Post_FireSynced(BulletWeaponSynced __instance)
		{
			CustomWeaponComponent component = ((Component)__instance).GetComponent<CustomWeaponComponent>();
			if (!((Object)(object)component == (Object)null))
			{
				component.NotifyShotFired();
				component.UpdateStoredFireRate();
				component.ModifyFireRateSynced(__instance);
				component.Invoke(StaticContext<WeaponPostFireContextSync>.Instance);
			}
		}
	}
}
namespace EWC.Patches.Enemy
{
	[HarmonyPatch]
	internal static class EnemyFoamPatches
	{
		[HarmonyPatch(typeof(Dam_EnemyDamageBase), "AddToTotalGlueVolume")]
		[HarmonyPriority(200)]
		[HarmonyWrapSafe]
		[HarmonyPostfix]
		private static void SyncWithFoamManager(Dam_EnemyDamageBase __instance, GlueGunProjectile? proj, GlueVolumeDesc volume)
		{
			//IL_0018: 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)
			float num = (((Object)(object)proj != (Object)null) ? proj.EffectMultiplier : 1f);
			FoamManager.AddFoam(__instance, (volume.volume + volume.expandVolume) * num, FoamManager.GetProjProperty(proj));
		}
	}
	[HarmonyPatch]
	internal static class EnemyLimbPatches
	{
		private static float _cachedArmor;

		[HarmonyPatch(typeof(Dam_EnemyDamageLimb), "BulletDamage")]
		[HarmonyPatch(typeof(Dam_EnemyDamageLimb), "MeleeDamage")]
		[HarmonyWrapSafe]
		[HarmonyPrefix]
		private static void Pre_Damage(Dam_EnemyDamageLimb __instance)
		{
			//IL_000a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0010: Invalid comparison between Unknown and I4
			ContextController cachedHitCC = WeaponPatches.CachedHitCC;
			if (cachedHitCC != null && (int)__instance.m_type == 2)
			{
				_cachedArmor = __instance.m_armorDamageMulti;
				__instance.m_armorDamageMulti = cachedHitCC.Invoke(new WeaponArmorContext(_cachedArmor)).ArmorMulti;
			}
		}

		[HarmonyPatch(typeof(Dam_EnemyDamageLimb), "BulletDamage")]
		[HarmonyPatch(typeof(Dam_EnemyDamageLimb), "MeleeDamage")]
		[HarmonyWrapSafe]
		[HarmonyPostfix]
		private static void Post_Damage(Dam_EnemyDamageLimb __instance)
		{
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			//IL_000e: Invalid comparison between Unknown and I4
			if (WeaponPatches.CachedHitCC != null && (int)__instance.m_type == 2)
			{
				__instance.m_armorDamageMulti = _cachedArmor;
			}
		}

		[HarmonyPatch(typeof(Dam_EnemyDamageLimb_Custom), "ApplyWeakspotAndArmorModifiers")]
		[HarmonyWrapSafe]
		[HarmonyPrefix]
		private static bool Pre_WeakspotModifiers(Dam_EnemyDamageLimb_Custom __instance, float dam, float precisionMulti, ref float __result)
		{
			if (!WeaponPatches.CachedBypassTumorCap)
			{
				return true;
			}
			__result = dam * Math.Max(((Dam_EnemyDamageLimb)__instance).m_weakspotDamageMulti * precisionMulti, 1f) * ((Dam_EnemyDamageLimb)__instance).m_armorDamageMulti;
			return false;
		}
	}
}
namespace EWC.Networking
{
	public abstract class SyncedEvent<T> where T : struct
	{
		public delegate void ReceiveHandler(T packet);

		private bool _isSetup;

		public abstract string GUID { get; }

		public bool IsSetup => _isSetup;

		public string EventName { get; private set; } = string.Empty;


		public event ReceiveHandler? OnReceive;

		public event ReceiveHandler? OnReceiveLocal;

		public void Setup()
		{
			if (!_isSetup)
			{
				EventName = "EWC" + GUID

plugins/Fusion/extra/net6/Fusion.dll

Decompiled a week 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.InteropServices;
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 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=#A78E44>Fusion</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.5")]
	public class EntryPoint : BasePlugin
	{
		public const string AUTHOR = "Inas";

		public const string RUNDOWN_NAME = "LEGACY";

		public const string VERSION = "4.4.5";

		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
	{
		[CompilerGenerated]
		private sealed class <DoEaseLocalPos>d__1 : IEnumerator<object>, IEnumerator, IDisposable
		{
			private int <>1__state;

			private object <>2__current;

			public Transform trans;

			public Vector3 sourcePos;

			public Vector3 targetPos;

			public float startTime;

			public float duration;

			public EasingFunction ease;

			public Action onDone;

			public BoolCheck checkAbort;

			private bool <doAbort>5__1;

			private float <t>5__2;

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

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

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

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

			private bool MoveNext()
			{
				//IL_00e2: 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_0086: 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)
				switch (<>1__state)
				{
				default:
					return false;
				case 0:
					<>1__state = -1;
					<doAbort>5__1 = false;
					break;
				case 1:
					<>1__state = -1;
					break;
				}
				if (Clock.Time < startTime + duration && !<doAbort>5__1)
				{
					<doAbort>5__1 = checkAbort != null && checkAbort();
					<t>5__2 = ease(Clock.Time - startTime, 0f, 1f, duration);
					trans.localPosition = Vector3.Lerp(sourcePos, targetPos, <t>5__2);
					<>2__current = null;
					<>1__state = 1;
					return true;
				}
				trans.localPosition = targetPos;
				if (!<doAbort>5__1 && onDone != null)
				{
					onDone();
				}
				return false;
			}

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

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

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

			private object <>2__current;

			public Transform trans;

			public Vector3 sourceEuler;

			public Vector3 targetEuler;

			public float startTime;

			public float duration;

			public EasingFunction ease;

			public Action onDone;

			public BoolCheck checkAbort;

			private bool <doAbort>5__1;

			private float <t>5__2;

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

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

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

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

			private bool MoveNext()
			{
				//IL_00e2: 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_0086: 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)
				switch (<>1__state)
				{
				default:
					return false;
				case 0:
					<>1__state = -1;
					<doAbort>5__1 = false;
					break;
				case 1:
					<>1__state = -1;
					break;
				}
				if (Clock.Time < startTime + duration && !<doAbort>5__1)
				{
					<doAbort>5__1 = checkAbort != null && checkAbort();
					<t>5__2 = ease(Clock.Time - startTime, 0f, 1f, duration);
					trans.localEulerAngles = Vector3.Lerp(sourceEuler, targetEuler, <t>5__2);
					<>2__current = null;
					<>1__state = 1;
					return true;
				}
				trans.localEulerAngles = targetEuler;
				if (!<doAbort>5__1 && onDone != null)
				{
					onDone();
				}
				return false;
			}

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

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

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

			private object <>2__current;

			public Transform trans;

			public Vector3 startScale;

			public Vector3 targetScale;

			public float startTime;

			public float duration;

			public EasingFunction ease;

			public Action onDone;

			public BoolCheck checkAbort;

			private bool <doAbort>5__1;

			private float <t>5__2;

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

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

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

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

			private bool MoveNext()
			{
				//IL_00e2: 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_0086: 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)
				switch (<>1__state)
				{
				default:
					return false;
				case 0:
					<>1__state = -1;
					<doAbort>5__1 = false;
					break;
				case 1:
					<>1__state = -1;
					break;
				}
				if (Clock.Time < startTime + duration && !<doAbort>5__1)
				{
					<doAbort>5__1 = checkAbort != null && checkAbort();
					<t>5__2 = ease(Clock.Time - startTime, 0f, 1f, duration);
					trans.localScale = Vector3.Lerp(startScale, targetScale, <t>5__2);
					<>2__current = null;
					<>1__state = 1;
					return true;
				}
				trans.localScale = targetScale;
				if (!<doAbort>5__1 && onDone != null)
				{
					onDone();
				}
				return false;
			}

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

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

		[IteratorStateMachine(typeof(<DoEaseLocalScale>d__0))]
		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)
			//yield-return decompiler failed: Unexpected instruction in Iterator.Dispose()
			return new <DoEaseLocalScale>d__0(0)
			{
				trans = trans,
				startScale = startScale,
				targetScale = targetScale,
				startTime = startTime,
				duration = duration,
				ease = ease,
				onDone = onDone,
				checkAbort = checkAbort
			};
		}

		[IteratorStateMachine(typeof(<DoEaseLocalPos>d__1))]
		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)
			//yield-return decompiler failed: Unexpected instruction in Iterator.Dispose()
			return new <DoEaseLocalPos>d__1(0)
			{
				trans = trans,
				sourcePos = sourcePos,
				targetPos = targetPos,
				startTime = startTime,
				duration = duration,
				ease = ease,
				onDone = onDone,
				checkAbort = checkAbort
			};
		}

		[IteratorStateMachine(typeof(<DoEaseLocalRot>d__2))]
		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)
			//yield-return decompiler failed: Unexpected instruction in Iterator.Dispose()
			return new <DoEaseLocalRot>d__2(0)
			{
				trans = trans,
				sourceEuler = sourceEuler,
				targetEuler = targetEuler,
				startTime = startTime,
				duration = duration,
				ease = ease,
				onDone = onDone,
				checkAbort = checkAbort
			};
		}

		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_0069: 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)
			//IL_0105: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)Assets.RestartPage == (Object)null)
			{
				return;
			}
			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
	{
		[CompilerGenerated]
		private sealed class <BlinkMarker>d__61 : IEnumerator<object>, IEnumerator, IDisposable
		{
			private int <>1__state;

			private object <>2__current;

			public ResourceStation <>4__this;

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

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

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

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

			private bool MoveNext()
			{
				//IL_004d: Unknown result type (might be due to invalid IL or missing references)
				//IL_0057: Expected O, but got Unknown
				switch (<>1__state)
				{
				default:
					return false;
				case 0:
					<>1__state = -1;
					break;
				case 1:
					<>1__state = -1;
					break;
				}
				<>4__this.StationMarkerGO.SetActive(!<>4__this.StationMarkerGO.active);
				<>2__current = (object)new WaitForSeconds(0.5f);
				<>1__state = 1;
				return true;
			}

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

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

		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;
			}
			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);
			}
		}

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

		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.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 RundownSelectionCustomization
	{
		[CompilerGenerated]
		private sealed class <reverseReveal>d__6 : IEnumerator<object>, IEnumerator, IDisposable
		{
			private int <>1__state;

			private object <>2__current;

			public CM_PageRundown_New p;

			public bool hosting;

			public Transform guixSurfaceTransform;

			private float <arrowScale>5__1;

			private float <tierMarkerDelay>5__2;

			private int <k>5__3;

			private int <m>5__4;

			private int <l>5__5;

			private int <j>5__6;

			private int <i>5__7;

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

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

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

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

			private bool MoveNext()
			{
				//IL_011a: Unknown result type (might be due to invalid IL or missing references)
				//IL_0124: Expected O, but got Unknown
				//IL_01b9: Unknown result type (might be due to invalid IL or missing references)
				//IL_01c3: Expected O, but got Unknown
				//IL_01f3: Unknown result type (might be due to invalid IL or missing references)
				//IL_0207: 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_02a0: Expected O, but got Unknown
				//IL_02d0: Unknown result type (might be due to invalid IL or missing references)
				//IL_02db: Unknown result type (might be due to invalid IL or missing references)
				//IL_0356: Unknown result type (might be due to invalid IL or missing references)
				//IL_036a: Unknown result type (might be due to invalid IL or missing references)
				//IL_03c3: Unknown result type (might be due to invalid IL or missing references)
				//IL_03cd: Expected O, but got Unknown
				//IL_040f: Unknown result type (might be due to invalid IL or missing references)
				//IL_0419: Expected O, but got Unknown
				//IL_0459: Unknown result type (might be due to invalid IL or missing references)
				//IL_046e: Unknown result type (might be due to invalid IL or missing references)
				//IL_015e: Unknown result type (might be due to invalid IL or missing references)
				//IL_0172: Unknown result type (might be due to invalid IL or missing references)
				//IL_00fa: Unknown result type (might be due to invalid IL or missing references)
				//IL_0104: Expected O, but got Unknown
				//IL_023b: Unknown result type (might be due to invalid IL or missing references)
				//IL_024f: 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_032f: Expected O, but got Unknown
				//IL_04ca: Unknown result type (might be due to invalid IL or missing references)
				//IL_04d4: Expected O, but got Unknown
				//IL_05aa: Unknown result type (might be due to invalid IL or missing references)
				//IL_05b4: Expected O, but got Unknown
				//IL_068c: Unknown result type (might be due to invalid IL or missing references)
				//IL_0696: Expected O, but got Unknown
				//IL_076e: Unknown result type (might be due to invalid IL or missing references)
				//IL_0778: Expected O, but got Unknown
				//IL_0850: Unknown result type (might be due to invalid IL or missing references)
				//IL_085a: Expected O, but got Unknown
				//IL_0932: Unknown result type (might be due to invalid IL or missing references)
				//IL_093c: Expected O, but got Unknown
				switch (<>1__state)
				{
				default:
					return false;
				case 0:
					<>1__state = -1;
					<arrowScale>5__1 = p.m_tierSpacing * 5f * p.m_tierSpaceToArrowScale;
					if (hosting)
					{
						CoroutineManager.BlinkIn(p.m_buttonConnect, 0f, (Transform)null);
						<>2__current = (object)new WaitForSeconds(0.1f);
						<>1__state = 1;
						return true;
					}
					goto IL_0147;
				case 1:
					<>1__state = -1;
					<>2__current = (object)new WaitForSeconds(0.24f);
					<>1__state = 2;
					return true;
				case 2:
					<>1__state = -1;
					((RectTransformComp)p.m_buttonConnect).SetVisible(false);
					goto IL_0147;
				case 3:
					<>1__state = -1;
					<>2__current = (object)new WaitForSeconds(0.1f);
					<>1__state = 4;
					return true;
				case 4:
					<>1__state = -1;
					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);
					<>2__current = CoroutineEase.EaseLocalScale(guixSurfaceTransform, Vector3.one, new Vector3(0.2f, 0.2f, 0.2f), 0.2f, (EasingFunction)Easing.LinearTween, (Action)null, (BoolCheck)null);
					<>1__state = 5;
					return true;
				case 5:
					<>1__state = -1;
					<>2__current = (object)new WaitForSeconds(0.1f);
					<>1__state = 6;
					return true;
				case 6:
					<>1__state = -1;
					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);
					<>2__current = (object)new WaitForSeconds(0.2f);
					<>1__state = 7;
					return true;
				case 7:
					<>1__state = -1;
					CM_PageBase.PostSound(EVENTS.MENU_SURFACE_LEVEL_TURN, "");
					<>2__current = CoroutineEase.EaseLocalRot(guixSurfaceTransform, Vector3.zero, new Vector3(70f, 0f, 0f), 0.3f, (EasingFunction)Easing.LinearTween, (Action)null, (BoolCheck)null);
					<>1__state = 8;
					return true;
				case 8:
					<>1__state = -1;
					p.m_verticalArrow.SetActive(true);
					<>2__current = (object)new WaitForSeconds(0.5f);
					<>1__state = 9;
					return true;
				case 9:
					<>1__state = -1;
					CoroutineManager.BlinkIn(((Component)p.m_tierMarkerSectorSummary).gameObject, 0f);
					CM_PageBase.PostSound(EVENTS.MENU_RUNDOWN_DISC_APPEAR_5, "");
					<>2__current = (object)new WaitForSeconds(0.5f);
					<>1__state = 10;
					return true;
				case 10:
					<>1__state = -1;
					CM_PageBase.PostSound(EVENTS.MENU_RUNDOWN_SPINE_START, "");
					CoroutineEase.EaseLocalScale(p.m_verticalArrow.transform, new Vector3(1f, 0f, 1f), new Vector3(1f, <arrowScale>5__1, 1f), 4.3f, (EasingFunction)Easing.LinearTween, (Action)delegate
					{
						CM_PageBase.PostSound(EVENTS.MENU_RUNDOWN_SPINE_STOP, "");
					}, (BoolCheck)null);
					<tierMarkerDelay>5__2 = 0.6f;
					<>2__current = (object)new WaitForSeconds(0.2f);
					<>1__state = 11;
					return true;
				case 11:
					<>1__state = -1;
					CM_PageBase.PostSound(EVENTS.MENU_RUNDOWN_DISC_APPEAR_3, "");
					((Component)p.m_guix_Tier3).gameObject.SetActive(true);
					<k>5__3 = 0;
					while (<k>5__3 < p.m_expIconsTier3.Count)
					{
						CoroutineManager.BlinkIn(((Component)p.m_expIconsTier3[<k>5__3]).gameObject, (float)<k>5__3 * 0.1f);
						<k>5__3++;
					}
					if (p.m_expIconsTier3.Count > 0)
					{
						p.m_tierMarker3.SetVisible(true, <tierMarkerDelay>5__2);
					}
					<>2__current = (object)new WaitForSeconds(1f);
					<>1__state = 12;
					return true;
				case 12:
					<>1__state = -1;
					CM_PageBase.PostSound(EVENTS.MENU_RUNDOWN_DISC_APPEAR_5, "");
					((Component)p.m_guix_Tier5).gameObject.SetActive(true);
					<m>5__4 = 0;
					while (<m>5__4 < p.m_expIconsTier5.Count)
					{
						CoroutineManager.BlinkIn(((Component)p.m_expIconsTier5[<m>5__4]).gameObject, (float)<m>5__4 * 0.1f);
						<m>5__4++;
					}
					if (p.m_expIconsTier5.Count > 0)
					{
						p.m_tierMarker5.SetVisible(true, <tierMarkerDelay>5__2);
					}
					<>2__current = (object)new WaitForSeconds(1f);
					<>1__state = 13;
					return true;
				case 13:
					<>1__state = -1;
					CM_PageBase.PostSound(EVENTS.MENU_RUNDOWN_DISC_APPEAR_4, "");
					((Component)p.m_guix_Tier4).gameObject.SetActive(true);
					<l>5__5 = 0;
					while (<l>5__5 < p.m_expIconsTier4.Count)
					{
						CoroutineManager.BlinkIn(((Component)p.m_expIconsTier4[<l>5__5]).gameObject, (float)<l>5__5 * 0.1f);
						<l>5__5++;
					}
					if (p.m_expIconsTier4.Count > 0)
					{
						p.m_tierMarker4.SetVisible(true, <tierMarkerDelay>5__2);
					}
					<>2__current = (object)new WaitForSeconds(1f);
					<>1__state = 14;
					return true;
				case 14:
					<>1__state = -1;
					CM_PageBase.PostSound(EVENTS.MENU_RUNDOWN_DISC_APPEAR_2, "");
					((Component)p.m_guix_Tier2).gameObject.SetActive(true);
					<j>5__6 = 0;
					while (<j>5__6 < p.m_expIconsTier2.Count)
					{
						CoroutineManager.BlinkIn(((Component)p.m_expIconsTier2[<j>5__6]).gameObject, (float)<j>5__6 * 0.1f);
						<j>5__6++;
					}
					if (p.m_expIconsTier2.Count > 0)
					{
						p.m_tierMarker2.SetVisible(true, <tierMarkerDelay>5__2);
					}
					<>2__current = (object)new WaitForSeconds(1f);
					<>1__state = 15;
					return true;
				case 15:
					<>1__state = -1;
					CM_PageBase.PostSound(EVENTS.MENU_RUNDOWN_DISC_APPEAR_1, "");
					((Component)p.m_guix_Tier1).gameObject.SetActive(true);
					<i>5__7 = 0;
					while (<i>5__7 < p.m_expIconsTier1.Count)
					{
						CoroutineManager.BlinkIn(((Component)p.m_expIconsTier1[<i>5__7]).gameObject, (float)<i>5__7 * 0.1f);
						<i>5__7++;
					}
					if (p.m_expIconsTier1.Count > 0)
					{
						p.m_tierMarker1.SetVisible(true, <tierMarkerDelay>5__2);
					}
					<>2__current = (object)new WaitForSeconds(1f);
					<>1__state = 16;
					return true;
				case 16:
					{
						<>1__state = -1;
						((Component)p.m_joinOnServerIdText).gameObject.SetActive(true);
						CoroutineMa

plugins/Fusion/extra/net6/Inas07.ThermalSights.dll

Decompiled a week 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/Fusion/extra/net6/LGTuner_1.1.8.dll

Decompiled a week 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.Security;
using System.Security.Permissions;
using System.Text.Json;
using System.Text.Json.Serialization;
using AIGraph;
using AssetShards;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Logging;
using BepInEx.Unity.IL2CPP;
using Expedition;
using GTFO.API;
using GTFO.API.Utilities;
using GameData;
using HarmonyLib;
using Il2CppInterop.Runtime.InteropTypes;
using Il2CppInterop.Runtime.InteropTypes.Arrays;
using Il2CppSystem;
using Il2CppSystem.Collections.Generic;
using LGTuner.Configs;
using LGTuner.Manager;
using LGTuner.Utils;
using LevelGeneration;
using LevelGeneration.Core;
using LogUtils;
using Microsoft.CodeAnalysis;
using SNetwork;
using UnityEngine;
using UnityEngine.SceneManagement;
using XXHashing;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETCoreApp,Version=v6.0", FrameworkDisplayName = ".NET 6.0")]
[assembly: AssemblyCompany("LGTuner")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0+git3a752d0-dirty-master.3a752d0c2c0a7a0392ad2fa80b66e7cffc6b6b13")]
[assembly: AssemblyProduct("LGTuner")]
[assembly: AssemblyTitle("LGTuner")]
[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 LGTuner
{
	public static class BuilderInfo
	{
		private static readonly List<Complex> _extraComplexResourceToLoad = new List<Complex>();

		public static IEnumerable<Complex> ExtraComplexResourceToLoad => _extraComplexResourceToLoad;

		public static ComplexResourceSetDataBlock ComplexResourceSet { get; private set; }

		public static int GridSize { get; private set; }

		public static int GridCenter { get; private set; }

		public static int GridZeroOffset { get; private set; }

		public static float AltitudeOffset { get; private set; }

		public static LayoutConfig MainLayer { get; private set; }

		public static LayoutConfig SecondaryLayer { get; private set; }

		public static LayoutConfig ThirdLayer { get; private set; }

		public static LayoutConfig[] DimensionLayer { get; private set; } = Array.Empty<LayoutConfig>();


		internal static void OnResourceSetSelected()
		{
			//IL_0156: Unknown result type (might be due to invalid IL or missing references)
			ComplexResourceSet = Builder.ComplexResourceSetBlock;
			GridSize = ComplexResourceSet.LevelGenConfig.GridSize;
			GridCenter = GridSize / 2;
			GridZeroOffset = -GridCenter;
			AltitudeOffset = ComplexResourceSet.LevelGenConfig.AltitudeOffset;
			MainLayer = null;
			SecondaryLayer = null;
			ThirdLayer = null;
			DimensionLayer = new LayoutConfig[Enum.GetValues(typeof(eDimensionIndex)).Length];
			_extraComplexResourceToLoad.Clear();
			ExpeditionInTierData activeExpedition = RundownManager.ActiveExpedition;
			if (ConfigManager.TryGetConfig(activeExpedition.LevelLayoutData, out var config))
			{
				MainLayer = config;
			}
			if (activeExpedition.SecondaryLayerEnabled && ConfigManager.TryGetConfig(activeExpedition.SecondaryLayout, out var config2))
			{
				SecondaryLayer = config2;
			}
			if (activeExpedition.ThirdLayerEnabled && ConfigManager.TryGetConfig(activeExpedition.ThirdLayout, out var config3))
			{
				ThirdLayer = config3;
			}
			Enumerator<Dimension> enumerator = Builder.CurrentFloor.m_dimensions.GetEnumerator();
			while (enumerator.MoveNext())
			{
				Dimension current = enumerator.Current;
				if (!current.IsMainDimension && !current.DimensionData.IsStaticDimension)
				{
					LevelLayoutDataBlock block = GameDataBlockBase<LevelLayoutDataBlock>.GetBlock(current.DimensionData.LevelLayoutData);
					if (block != null && ConfigManager.TryGetConfig(((GameDataBlockBase<LevelLayoutDataBlock>)(object)block).persistentID, out var config4))
					{
						Logger.Info("loysimme dimension ja levellayoutin");
						config4.Reset(((CellGridBase<LG_Grid, LG_Tile, LG_Cell>)(object)current.Grid).m_sizeX);
						DimensionLayer[current.DimensionIndex] = config4;
					}
				}
			}
			MainLayer?.Reset(GridSize);
			SecondaryLayer?.Reset(GridSize);
			ThirdLayer?.Reset(GridSize);
			AddExtraShard(MainLayer);
			AddExtraShard(SecondaryLayer);
			AddExtraShard(ThirdLayer);
			Array.ForEach(DimensionLayer, delegate(LayoutConfig x)
			{
				AddExtraShard(x);
			});
		}

		private static void AddExtraShard(LayoutConfig layerConfig)
		{
			//IL_0012: 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_0025: Unknown result type (might be due to invalid IL or missing references)
			if (layerConfig == null)
			{
				return;
			}
			Complex[] extraComplexResourceToLoad = layerConfig.ExtraComplexResourceToLoad;
			foreach (Complex item in extraComplexResourceToLoad)
			{
				if (!_extraComplexResourceToLoad.Contains(item))
				{
					_extraComplexResourceToLoad.Add(item);
				}
			}
		}

		public static bool TryGetConfig(LG_Zone zone, out LayoutConfig config)
		{
			//IL_0001: 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_0032: Unknown result type (might be due to invalid IL or missing references)
			//IL_0044: Expected I4, but got Unknown
			//IL_0116: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ff: Unknown result type (might be due to invalid IL or missing references)
			Dimension val = default(Dimension);
			if (!Dimension.GetDimension(zone.DimensionIndex, ref val))
			{
				Logger.Info("dimension getter failed");
				config = null;
				return false;
			}
			if (val.IsMainDimension)
			{
				LG_LayerType type = zone.Layer.m_type;
				switch ((int)type)
				{
				case 0:
					config = MainLayer;
					return MainLayer != null;
				case 1:
					config = SecondaryLayer;
					return SecondaryLayer != null;
				case 2:
					config = ThirdLayer;
					return ThirdLayer != null;
				}
			}
			else if (!val.DimensionData.IsStaticDimension)
			{
				Enumerator<Dimension> enumerator = Builder.CurrentFloor.m_dimensions.GetEnumerator();
				while (enumerator.MoveNext())
				{
					Dimension current = enumerator.Current;
					if (!current.IsMainDimension && !current.DimensionData.IsStaticDimension)
					{
						LevelLayoutDataBlock block = GameDataBlockBase<LevelLayoutDataBlock>.GetBlock(current.DimensionData.LevelLayoutData);
						if (block != null && ConfigManager.TryGetConfig(((GameDataBlockBase<LevelLayoutDataBlock>)(object)block).persistentID, out var config2))
						{
							Logger.Info("found a dimension + levellayout");
							config2.Reset(((CellGridBase<LG_Grid, LG_Tile, LG_Cell>)(object)current.Grid).m_sizeX);
							DimensionLayer[current.DimensionIndex] = config2;
						}
					}
				}
				config = DimensionLayer[zone.DimensionIndex];
				return config != null;
			}
			config = null;
			return false;
		}

		public static GameObject GetRandomPlug(uint seed, int plugHeight, SubComplex subcomplex, bool withGate)
		{
			//IL_002d: 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_0065: Unknown result type (might be due to invalid IL or missing references)
			ComplexResourceSetDataBlock complexResourceSet = ComplexResourceSet;
			return (GameObject)(plugHeight switch
			{
				0 => complexResourceSet.GetRandomPrefab(seed, withGate ? complexResourceSet.m_straightPlugsWithGates : complexResourceSet.m_straightPlugsNoGates, subcomplex), 
				1 => complexResourceSet.GetRandomPrefab(seed, withGate ? complexResourceSet.m_singleDropPlugsWithGates : complexResourceSet.m_singleDropPlugsNoGates, subcomplex), 
				2 => complexResourceSet.GetRandomPrefab(seed, withGate ? complexResourceSet.m_doubleDropPlugsWithGates : complexResourceSet.m_doubleDropPlugsNoGates, subcomplex), 
				_ => null, 
			});
		}

		public static uint GetLayoutIdOfZone(LG_Zone zone)
		{
			//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_0036: Expected I4, but got Unknown
			//IL_006e: Unknown result type (might be due to invalid IL or missing references)
			Dimension dimension = zone.Dimension;
			if (dimension.IsMainDimension)
			{
				LG_LayerType type = zone.Layer.m_type;
				ExpeditionInTierData activeExpedition = RundownManager.ActiveExpedition;
				return (int)type switch
				{
					0 => activeExpedition.LevelLayoutData, 
					1 => activeExpedition.SecondaryLayout, 
					2 => activeExpedition.ThirdLayout, 
					_ => throw new NotSupportedException($"LayerType: {type} is not supported!"), 
				};
			}
			return dimension.DimensionData.LevelLayoutData;
		}
	}
	[BepInPlugin("LGTuner", "LGTuner", "1.1.8")]
	[BepInProcess("GTFO.exe")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	public class EntryPoint : BasePlugin
	{
		public static bool AssetsFixed;

		public Harmony HarmonyInstance { get; private set; }

		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
			HarmonyInstance = new Harmony("LGTuner");
			HarmonyInstance.PatchAll();
			ConfigManager.Init();
			AssetShardManager.OnSharedAsssetLoaded += Action.op_Implicit((Action)ConfigManager.LoadShardForFixingAssets);
		}
	}
	public static class LGExtensions
	{
		public static bool IsSame(this LG_GridPosition position, LG_GridPosition other)
		{
			//IL_0000: 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_000e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0014: Unknown result type (might be due to invalid IL or missing references)
			if (position.x == other.x)
			{
				return position.z == other.z;
			}
			return false;
		}

		public static LG_GridPosition ToNormalGrid(this LG_Tile tile, int gridSize)
		{
			//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)
			return tile.m_shape.m_gridPosition.GetNormal(gridSize);
		}

		public static LG_GridPosition GetNormal(this LG_GridPosition position, int gridSize)
		{
			//IL_003a: 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_0051: 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_0006: 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)
			//IL_0021: 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)
			LG_GridPosition result;
			if (gridSize < 0)
			{
				result = default(LG_GridPosition);
				result.x = position.x + BuilderInfo.GridZeroOffset;
				result.z = position.z + BuilderInfo.GridZeroOffset;
				return result;
			}
			int num = gridSize / 2;
			result = default(LG_GridPosition);
			result.x = position.x - num;
			result.z = position.z - num;
			return result;
		}

		public static Vector3 GetPositionNormal(this LG_Grid grid, int x, int z, int gridSize)
		{
			//IL_0024: 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)
			if (gridSize < 0)
			{
				return ((CellGridBase<LG_Grid, LG_Tile, LG_Cell>)(object)grid).GetPosition(x - BuilderInfo.GridZeroOffset, z - BuilderInfo.GridZeroOffset);
			}
			int num = gridSize / 2;
			return ((CellGridBase<LG_Grid, LG_Tile, LG_Cell>)(object)grid).GetPosition(x + num, z + num);
		}

		public static int GetGridSize(this Dimension dimension)
		{
			return ((CellGridBase<LG_Grid, LG_Tile, LG_Cell>)(object)dimension.Grid).m_sizeX;
		}

		public static bool TryGetDimension(this LG_Floor floor, int dimensionIndex, out Dimension dimension)
		{
			if (Enum.IsDefined(typeof(eDimensionIndex), dimensionIndex))
			{
				return floor.GetDimension((eDimensionIndex)dimensionIndex, ref dimension);
			}
			dimension = null;
			return false;
		}

		public static bool TryGetDimension(this LG_Floor floor, eDimensionIndex dimensionIndex, out Dimension dimension)
		{
			//IL_000a: 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)
			if (Enum.IsDefined(typeof(eDimensionIndex), dimensionIndex))
			{
				return floor.GetDimension(dimensionIndex, ref dimension);
			}
			dimension = null;
			return false;
		}
	}
	public static class RandomExtensions
	{
		public static uint NextUint(this Random random)
		{
			int num = random.Next(1073741824);
			uint num2 = (uint)random.Next(4);
			return (uint)(num << 2) | num2;
		}

		public static float NextFloat(this Random random)
		{
			return Mathf.Clamp01((float)random.NextDouble());
		}

		public static int ToSeed(this uint seed)
		{
			return (int)seed;
		}
	}
	internal static class Logger
	{
		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("LGTuner");
			Logger.Sources.Add((ILogSource)(object)_logger);
		}

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

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

		public static void Verbose(object data)
		{
		}

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

		public static void Error(object data)
		{
			_logger.LogError((object)Format(data));
		}
	}
	public enum DirectionType
	{
		Unknown,
		Forward,
		Backward,
		Left,
		Right
	}
	public enum RotateType
	{
		None,
		Flip,
		MoveTo_Left,
		MoveTo_Right,
		Towards_Random,
		Towards_Forward,
		Towards_Backward,
		Towards_Left,
		Towards_Right
	}
	public struct LG_PlugInfo
	{
		public static readonly Quaternion NoRotation = Quaternion.AngleAxis(0f, Vector3.up);

		public static readonly Quaternion RightRotation = Quaternion.AngleAxis(90f, Vector3.up);

		public static readonly Quaternion BackwardRotation = Quaternion.AngleAxis(180f, Vector3.up);

		public static readonly Quaternion LeftRotation = Quaternion.AngleAxis(270f, Vector3.up);

		public static readonly Vector3 FrontPlugPosition = Vector3.forward * 32f;

		public static readonly Vector3 BackPlugPosition = Vector3.back * 32f;

		public static readonly Vector3 LeftPlugPosition = Vector3.left * 32f;

		public static readonly Vector3 RightPlugPosition = Vector3.right * 32f;

		public bool IsValid { get; private set; }

		public DirectionType StartDirection { get; private set; }

		public int Count { get; private set; }

		public bool HasFront { get; private set; }

		public bool HasBack { get; private set; }

		public bool HasLeft { get; private set; }

		public bool HasRight { get; private set; }

		public bool TryGetNewRotation(uint seed, RotateType rotate, out Quaternion rotation)
		{
			//IL_0062: Unknown result type (might be due to invalid IL or missing references)
			//IL_0067: 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)
			DirectionType newDirection = GetNewDirection(seed, StartDirection, rotate);
			if (Count >= 4)
			{
				rotation = GetRotationOfDirection(newDirection);
				return true;
			}
			Logger.Info($"You are rotating {Count} side Geomorph, this could lead to level gen crash!");
			rotation = GetRotationOfDirection(newDirection);
			return true;
		}

		public bool HasPlug(DirectionType direction)
		{
			if (!IsValid)
			{
				return false;
			}
			if (Count >= 4)
			{
				return true;
			}
			return direction switch
			{
				DirectionType.Forward => HasFront, 
				DirectionType.Backward => HasBack, 
				DirectionType.Left => HasLeft, 
				DirectionType.Right => HasRight, 
				_ => false, 
			};
		}

		public static LG_PlugInfo BuildPlugInfo(GameObject geoObject, Quaternion rotation)
		{
			//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_0065: 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_007e: Expected I4, but got Unknown
			//IL_011f: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)geoObject.GetComponent<LG_Geomorph>() == (Object)null)
			{
				return default(LG_PlugInfo);
			}
			Il2CppArrayBase<LG_Plug> componentsInChildren = geoObject.GetComponentsInChildren<LG_Plug>();
			if (componentsInChildren == null)
			{
				return default(LG_PlugInfo);
			}
			if (componentsInChildren.Length < 1)
			{
				return default(LG_PlugInfo);
			}
			LG_PlugInfo result = default(LG_PlugInfo);
			foreach (LG_Plug item in componentsInChildren)
			{
				LG_PlugDir dir = item.m_dir;
				switch (dir - 2)
				{
				case 0:
					result.HasBack = true;
					result.Count++;
					break;
				case 2:
					result.HasFront = true;
					result.Count++;
					break;
				case 3:
					result.HasLeft = true;
					result.Count++;
					break;
				case 1:
					result.HasRight = true;
					result.Count++;
					break;
				}
			}
			result.IsValid = result.Count > 0;
			float num = Mathf.Round(((Quaternion)(ref rotation)).eulerAngles.y);
			Logger.Verbose($"angle: {num}");
			num = Mathf.Repeat(num, 360f);
			result.StartDirection = Mathf.RoundToInt(num / 90f) switch
			{
				0 => DirectionType.Forward, 
				1 => DirectionType.Right, 
				2 => DirectionType.Backward, 
				3 => DirectionType.Left, 
				_ => DirectionType.Unknown, 
			};
			return result;
		}

		public static DirectionType GetNewDirection(uint seed, DirectionType direction, RotateType rotate)
		{
			if (direction == DirectionType.Unknown)
			{
				return DirectionType.Unknown;
			}
			if (rotate == RotateType.Towards_Random)
			{
				rotate = new Random(seed.ToSeed()).Next(4) switch
				{
					0 => RotateType.Towards_Forward, 
					1 => RotateType.Towards_Backward, 
					2 => RotateType.Towards_Left, 
					3 => RotateType.Towards_Right, 
					_ => throw new IndexOutOfRangeException("Towards_Random: nextIndex was out of range?!"), 
				};
			}
			return rotate switch
			{
				RotateType.None => direction, 
				RotateType.Flip => direction switch
				{
					DirectionType.Forward => DirectionType.Backward, 
					DirectionType.Backward => DirectionType.Forward, 
					DirectionType.Left => DirectionType.Right, 
					DirectionType.Right => DirectionType.Left, 
					_ => throw new ArgumentOutOfRangeException("direction"), 
				}, 
				RotateType.MoveTo_Left => direction switch
				{
					DirectionType.Forward => DirectionType.Left, 
					DirectionType.Backward => DirectionType.Right, 
					DirectionType.Left => DirectionType.Backward, 
					DirectionType.Right => DirectionType.Forward, 
					_ => throw new ArgumentOutOfRangeException("direction"), 
				}, 
				RotateType.MoveTo_Right => direction switch
				{
					DirectionType.Forward => DirectionType.Right, 
					DirectionType.Backward => DirectionType.Left, 
					DirectionType.Left => DirectionType.Forward, 
					DirectionType.Right => DirectionType.Backward, 
					_ => throw new ArgumentOutOfRangeException("direction"), 
				}, 
				RotateType.Towards_Forward => DirectionType.Forward, 
				RotateType.Towards_Backward => DirectionType.Backward, 
				RotateType.Towards_Left => DirectionType.Left, 
				RotateType.Towards_Right => DirectionType.Right, 
				_ => throw new ArgumentOutOfRangeException("direction"), 
			};
		}

		public static Quaternion GetRotationOfDirection(DirectionType direction)
		{
			//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_0022: 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_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_0032: 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_0045: Unknown result type (might be due to invalid IL or missing references)
			return (Quaternion)(direction switch
			{
				DirectionType.Forward => NoRotation, 
				DirectionType.Backward => BackwardRotation, 
				DirectionType.Left => LeftRotation, 
				DirectionType.Right => RightRotation, 
				_ => throw new ArgumentOutOfRangeException("direction"), 
			});
		}
	}
	[GeneratedCode("VersionInfoGenerator", "2.0.0+git50a4b1a-master")]
	[CompilerGenerated]
	internal static class VersionInfo
	{
		public const string RootNamespace = "LGTuner";

		public const string Version = "1.0.0";

		public const string VersionPrerelease = null;

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

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

		public const string GitRevShort = "3a752d0-dirty";

		public const string GitRevLong = "3a752d0c2c0a7a0392ad2fa80b66e7cffc6b6b13-dirty";

		public const string GitBranch = "master";

		public const string GitTag = null;

		public const bool GitIsDirty = true;
	}
}
namespace LGTuner.Utils
{
	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());
			if (MTFOPartialDataUtil.IsLoaded && MTFOPartialDataUtil.Initialized)
			{
				_setting.Converters.Add(MTFOPartialDataUtil.PersistentIDConverter);
				Logger.Info("PartialData 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(object value, Type type)
		{
			return JsonSerializer.Serialize(value, type, _setting);
		}
	}
	public static class MTFOPartialDataUtil
	{
		public const string PLUGIN_GUID = "MTFO.Extension.PartialBlocks";

		public static JsonConverter PersistentIDConverter { 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;
			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 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);
				IsLoaded = true;
			}
			catch (Exception value2)
			{
				Logger.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)
			{
				Logger.Error($"Exception thrown while reading path from DataDumper (MTFO): \n{value2}");
			}
		}
	}
}
namespace LGTuner.Manager
{
	public static class ConfigManager
	{
		[CompilerGenerated]
		private static class <>O
		{
			public static LiveEditEventHandler <0>__LiveEdit_FileChanged;
		}

		private static readonly List<LayoutConfig> _layouts = new List<LayoutConfig>();

		private static readonly Dictionary<uint, LayoutConfig> _lookup = new Dictionary<uint, LayoutConfig>();

		private static readonly Dictionary<string, LayoutConfig> _fileNameLookup = new Dictionary<string, LayoutConfig>();

		public static IEnumerable<LayoutConfig> Layouts => _layouts;

		public static void LoadShardForFixingAssets()
		{
			AssetShardManager.LoadShard(AssetShardManager.GetShardName((AssetBundleName)4, (AssetBundleShard)5), (LoadSceneMode)1);
			AssetShardManager.LoadShard(AssetShardManager.GetShardName((AssetBundleName)3, (AssetBundleShard)9), (LoadSceneMode)1);
		}

		public static void Init()
		{
			//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_0135: Expected O, but got Unknown
			if (!MTFOUtil.HasCustomContent)
			{
				return;
			}
			string text = Path.Combine(MTFOUtil.CustomPath, "LGTuner");
			FileInfo[] files = Directory.CreateDirectory(text).GetFiles();
			foreach (FileInfo fileInfo in files)
			{
				string extension = fileInfo.Extension;
				bool flag = extension.Equals(".json", StringComparison.InvariantCultureIgnoreCase);
				bool flag2 = extension.Equals(".jsonc", StringComparison.InvariantCultureIgnoreCase);
				if (flag || flag2)
				{
					LayoutConfig layoutConfig = JSON.Deserialize<LayoutConfig>(File.ReadAllText(fileInfo.FullName));
					if (_lookup.ContainsKey(layoutConfig.LevelLayoutID))
					{
						Logger.Error($"Duplicated ID found!: {fileInfo.Name}, {layoutConfig.LevelLayoutID}");
					}
					else
					{
						_layouts.Add(layoutConfig);
						_lookup.Add(layoutConfig.LevelLayoutID, layoutConfig);
						_fileNameLookup.Add(fileInfo.Name.ToLowerInvariant(), layoutConfig);
					}
				}
			}
			LiveEditListener obj = LiveEdit.CreateListener(text, "*.*", true);
			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;
			obj.StartListen();
		}

		private static void LiveEdit_FileChanged(LiveEditEventArgs e)
		{
			string key = Path.GetFileName(e.FullPath).ToLowerInvariant();
			string extension = Path.GetExtension(e.FullPath);
			if (!extension.Equals(".json", StringComparison.InvariantCulture) && !extension.Equals(".jsonc", StringComparison.InvariantCulture))
			{
				return;
			}
			Logger.Error($"File Edited: '{key}' '{e.FullPath}'");
			try
			{
				LayoutConfig data = _fileNameLookup[key];
				uint oldID = data.LevelLayoutID;
				LiveEdit.TryReadFileContent(e.FullPath, (Action<string>)delegate(string json)
				{
					try
					{
						LayoutConfig layoutConfig = JSON.Deserialize<LayoutConfig>(json);
						layoutConfig.LevelLayoutID = oldID;
						_fileNameLookup.Remove(key);
						_lookup.Remove(oldID);
						_layouts.Remove(data);
						_layouts.Add(layoutConfig);
						_lookup.Add(oldID, layoutConfig);
						_fileNameLookup.Add(key, layoutConfig);
					}
					catch (Exception value2)
					{
						Logger.Error($"Error while reading LGTuner Config: {value2}");
					}
				});
			}
			catch (Exception value)
			{
				Logger.Error($"Error while reading LGTuner Config: {value}");
			}
		}

		private static void DumpLevel()
		{
		}

		private static void DumpLayerToConfig()
		{
		}

		public static bool TryGetConfig(uint layoutID, out LayoutConfig config)
		{
			return _lookup.TryGetValue(layoutID, out config);
		}
	}
}
namespace LGTuner.Inject
{
	[HarmonyPatch]
	internal static class Inject_CreateDimension
	{
		[HarmonyPatch(typeof(LG_Floor), "CreateAllDimensions")]
		[HarmonyPrefix]
		private static bool Dim250(LG_Floor __instance, uint seed, bool skipMainDimension = true)
		{
			//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_005d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0064: Invalid comparison between Unknown and I4
			//IL_01a0: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a7: Invalid comparison between Unknown and I4
			//IL_0205: Unknown result type (might be due to invalid IL or missing references)
			//IL_020a: 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_0091: 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_00c1: 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_00d2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00da: 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_0115: Unknown result type (might be due to invalid IL or missing references)
			//IL_012d: 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_0246: Invalid comparison between Unknown and I4
			//IL_0286: 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_02b3: Unknown result type (might be due to invalid IL or missing references)
			//IL_03d3: Unknown result type (might be due to invalid IL or missing references)
			//IL_03d6: Unknown result type (might be due to invalid IL or missing references)
			//IL_03db: Unknown result type (might be due to invalid IL or missing references)
			//IL_03df: Unknown result type (might be due to invalid IL or missing references)
			//IL_03e4: Unknown result type (might be due to invalid IL or missing references)
			//IL_03e9: Unknown result type (might be due to invalid IL or missing references)
			//IL_03f3: Unknown result type (might be due to invalid IL or missing references)
			//IL_03f8: Unknown result type (might be due to invalid IL or missing references)
			//IL_040d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0417: Unknown result type (might be due to invalid IL or missing references)
			//IL_042f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0431: Unknown result type (might be due to invalid IL or missing references)
			//IL_0439: Unknown result type (might be due to invalid IL or missing references)
			//IL_0470: Unknown result type (might be due to invalid IL or missing references)
			//IL_0485: Unknown result type (might be due to invalid IL or missing references)
			//IL_03bf: Unknown result type (might be due to invalid IL or missing references)
			int num = 40;
			if (Builder.LevelGenExpedition.DimensionDatas == null || Builder.LevelGenExpedition.DimensionDatas.Count <= 0)
			{
				Dimension.CalculateAllDimensionBounds();
				return false;
			}
			XXHashSequence val = default(XXHashSequence);
			((XXHashSequence)(ref val))..ctor(seed, true);
			Vector3 up = Vector3.up;
			int num2 = 0;
			float num3 = 150f;
			DimensionDataBlock val3 = default(DimensionDataBlock);
			for (int i = 0; i < Builder.LevelGenExpedition.DimensionDatas.Count; i++)
			{
				DimensionInExpeditionData val2 = Builder.LevelGenExpedition.DimensionDatas[i];
				if ((int)val2.DimensionIndex != 22 && val2.TryGetDimensionData(ref val3))
				{
					DimensionData dimensionData = val3.DimensionData;
					if (val2.Enabled && (!skipMainDimension || (int)val2.DimensionIndex != 0) && !__instance.m_createdDimensionSet.Contains(val2.DimensionIndex))
					{
						num3 += dimensionData.VerticalExtentsDown;
						Vector3 val4 = up * num3;
						__instance.CreateDimension(((XXHashSequence)(ref val)).NextSubSeed(), val2.DimensionIndex, false, dimensionData, val4, num, 64f);
						__instance.m_createdDimensionSet.Add(val2.DimensionIndex);
						Logger.Info($"created dim {val2.DimensionIndex} pos {val4} ..");
						num3 += dimensionData.VerticalExtentsUp;
						num2++;
					}
				}
			}
			float num4 = 0f;
			float num5 = 0f;
			DimensionDataBlock val6 = default(DimensionDataBlock);
			for (int j = 0; j < Builder.LevelGenExpedition.DimensionDatas.Count; j++)
			{
				DimensionInExpeditionData val5 = Builder.LevelGenExpedition.DimensionDatas[j];
				if ((int)val5.DimensionIndex == 22 && val5.TryGetDimensionData(ref val6))
				{
					num = 10;
					if (val6.DimensionData.VerticalExtentsDown > num4)
					{
						num4 = val6.DimensionData.VerticalExtentsDown;
					}
					if (val6.DimensionData.VerticalExtentsUp > num4)
					{
						num5 = num4;
					}
				}
			}
			int num6 = 0;
			Vector3 right = Vector3.right;
			DimensionDataBlock val8 = default(DimensionDataBlock);
			Bounds val10 = default(Bounds);
			for (int k = 0; k < ((Il2CppArrayBase<SNet_Slot>)(object)SNet.Slots.PlayerSlots).Length; k++)
			{
				num3 += num4;
				float num7 = 0f;
				for (int l = 0; l < Builder.LevelGenExpedition.DimensionDatas.Count; l++)
				{
					DimensionInExpeditionData val7 = Builder.LevelGenExpedition.DimensionDatas[l];
					if ((int)val7.DimensionIndex != 22)
					{
						continue;
					}
					if (!val7.TryGetDimensionData(ref val8))
					{
						Debug.LogError(Object.op_Implicit("Could not find datablock for arena: datablockID: " + val7.DimensionData));
						continue;
					}
					eDimensionIndex val9 = (eDimensionIndex)(21 - (num6 + 1));
					if (__instance.m_createdDimensionSet.Contains(val9))
					{
						DebugLog.LogPrefixError((Object)(object)__instance, $"Enemy dimension ({val9}) had already been created! If there are dimension enemies in the level, dimensionIndex {17}-{20} needs to be free (one for each player slot).");
						continue;
					}
					DimensionData dimensionData2 = val8.DimensionData;
					if (val7.Enabled)
					{
						GameObject customGeomorph = GameDataBlockBase<ComplexResourceSetDataBlock>.GetBlock(dimensionData2.DimensionResourceSetID).GetCustomGeomorph(dimensionData2.DimensionGeomorph);
						if ((Object)(object)customGeomorph == (Object)null)
						{
							DebugLog.LogPrefixError((Object)(object)__instance, $"The dimension geomorph for ({((GameDataBlockBase<DimensionDataBlock>)(object)val8).persistentID}) {((GameDataBlockBase<DimensionDataBlock>)(object)val8).name} could not be found!");
							continue;
						}
						float num8 = 32f;
						LG_Dimension component = customGeomorph.GetComponent<LG_Dimension>();
						if ((Object)(object)component != (Object)null && component.TryGetDimensionBounds(ref val10))
						{
							num8 += ((Bounds)(ref val10)).extents.x;
						}
						num7 += num8;
						Vector3 val11 = up * num3 + right * num7;
						__instance.CreateDimension(((XXHashSequence)(ref val)).NextSubSeed(), val9, true, dimensionData2, val11, 10, 64f);
						__instance.m_createdDimensionSet.Add(val9);
						DimensionSlotIndex val12 = default(DimensionSlotIndex);
						val12.DimensionDataBlockID = 14u;
						val12.PlayerSlotIndex = (uint)k;
						DimensionSlotIndex val13 = val12;
						__instance.m_dimensionArenaMap.Add(val13, __instance.m_dimensions[__instance.m_dimensions.Count - 1]);
						Logger.Info($"created dim {val9} pos {val11} ..");
						num2++;
						num7 += num8;
					}
					num6++;
				}
				num3 += num5;
			}
			Dimension.CalculateAllDimensionBounds();
			Logger.Info($"Found ({num2}) unique dimension references in GameData for this expedition and created ({num6}) enemy dimensions.");
			return false;
		}

		[HarmonyPatch(typeof(LG_Floor), "CreateDimension")]
		[HarmonyPrefix]
		private static bool Prefix(LG_Floor __instance, uint seed, eDimensionIndex dimensionIndex, bool arenaDimension, ref DimensionData dimensionData, Vector3 position, ref int __result, int gridSize, float cellSize = 64f)
		{
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b3: 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_00c5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ca: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cf: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e0: 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_0110: Unknown result type (might be due to invalid IL or missing references)
			//IL_0113: Unknown result type (might be due to invalid IL or missing references)
			//IL_011a: Expected O, but got Unknown
			//IL_0133: Unknown result type (might be due to invalid IL or missing references)
			//IL_0281: Unknown result type (might be due to invalid IL or missing references)
			//IL_0283: Unknown result type (might be due to invalid IL or missing references)
			//IL_0252: Unknown result type (might be due to invalid IL or missing references)
			//IL_02c2: Unknown result type (might be due to invalid IL or missing references)
			//IL_0321: Unknown result type (might be due to invalid IL or missing references)
			//IL_0399: Unknown result type (might be due to invalid IL or missing references)
			//IL_03a7: Unknown result type (might be due to invalid IL or missing references)
			//IL_04c6: Unknown result type (might be due to invalid IL or missing references)
			//IL_03dd: 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)
			if (arenaDimension)
			{
				return true;
			}
			gridSize = 40;
			_ = Builder.LayerBuildDatas[0].m_zoneBuildDatas[0].SubComplex;
			if (dimensionData.IsStaticDimension)
			{
				return true;
			}
			LayoutConfig config = null;
			LevelLayoutDataBlock block = GameDataBlockBase<LevelLayoutDataBlock>.GetBlock(dimensionData.LevelLayoutData);
			ConfigManager.TryGetConfig(((GameDataBlockBase<LevelLayoutDataBlock>)(object)block).persistentID, out config);
			if (config == null)
			{
				return true;
			}
			if (config.TileOverrides.Length == 0)
			{
				return true;
			}
			Logger.Info($"in createdim prefix gridsize {gridSize} ..");
			cellSize = 64f;
			GameObject val = null;
			XXHashSequence val2 = default(XXHashSequence);
			((XXHashSequence)(ref val2))..ctor(seed, true);
			Vector3 val3 = position - new Vector3(cellSize, 0f, cellSize) * (float)gridSize * 0.5f;
			LG_TileShape val4 = __instance.CreateTileShape((LG_TileShapeType)1, cellSize, ref val3);
			LG_Grid val5 = CellGridBase<LG_Grid, LG_Tile, LG_Cell>.Create(cellSize, val3);
			((CellGridBase<LG_Grid, LG_Tile, LG_Cell>)(object)val5).SetupCells(gridSize, gridSize);
			((CellGridBase<LG_Grid, LG_Tile, LG_Cell>)(object)val5).InititalizeCells();
			int count = __instance.m_dimensions.Count;
			Dimension val6 = new Dimension(val5, dimensionIndex, count, dimensionData, position, arenaDimension);
			DebugLog.LogPrefix((Object)(object)__instance, $"Created Dimension (Index: {dimensionIndex}, gridSize: {gridSize}, cellSize: {cellSize}).");
			val = val6.ResourceData.GetCustomGeomorph(dimensionData.DimensionGeomorph);
			if (block != null && config.TileOverrides[0].X == 0 && config.TileOverrides[0].Z == 0 && !string.IsNullOrEmpty(config.TileOverrides[0].Geomorph))
			{
				Object loadedAsset = AssetAPI.GetLoadedAsset(config.TileOverrides[0].Geomorph);
				val = ((loadedAsset != null) ? ((Il2CppObjectBase)loadedAsset).Cast<GameObject>() : null);
				Logger.Info($" - dim {dimensionIndex} elevator overriden! {((Object)val).name}");
			}
			if ((Object)(object)val == (Object)null)
			{
				DebugLog.LogPrefixError((Object)(object)__instance, $"<b><color=red>NULL ERROR</color></b> Could not get the Dimension Geomorph prefab for dimension {dimensionIndex}, are you using a resource set in the DimensionDataBlock that contains the Dimension Geomorph prefab under the \"Custom Geomorphs_Objective_1x1\" header?");
				__result = count;
				return false;
			}
			LG_FloorTransition val7 = __instance.CreateFloorTransition(((XXHashSequence)(ref val2)).NextSubSeed(), val6, position, Quaternion.identity, val, val6.DimensionData.IsStaticDimension);
			if ((Object)(object)val7 == (Object)null)
			{
				DebugLog.LogPrefixError((Object)(object)__instance, $"<b><color=red>NULL ERROR</color></b> The LG_FloorTransition of dimension {dimensionIndex} was null! Does the dimension prefab have a LG_FloorTransition component on its root?");
				__result = count;
				return false;
			}
			LG_Dimension val8 = ((Component)val7).GetComponent<LG_Dimension>();
			if ((Object)(object)val8 == (Object)null)
			{
				val8 = ((Component)val7).gameObject.AddComponent<LG_Dimension>();
				DebugLog.LogPrefixError((Object)(object)__instance, $"<b><color=red>NULL ERROR</color></b> The dimension {dimensionIndex} had no {typeof(LG_Dimension).Name} component, so added one automatically!");
			}
			val6.DimensionLevel = val8;
			if (val7.m_spawnPoints != null && ((Il2CppArrayBase<Transform>)(object)val7.m_spawnPoints).Length != 0)
			{
				val8.AddSpawnPoints(val7.m_spawnPoints);
			}
			val4.m_gridPosition = new LG_GridPosition(gridSize / 2, gridSize / 2);
			val4.m_type = val7.m_shapeType;
			AIG_GeomorphNodeVolume component = ((Component)val7).GetComponent<AIG_GeomorphNodeVolume>();
			if ((Object)(object)component == (Object)null)
			{
				DebugLog.LogPrefixError((Object)(object)__instance, $"<b><color=red>NULL ERROR</color></b> The Dimension Geomorph for {dimensionIndex} did not have a {typeof(AIG_GeomorphNodeVolume).Name} component on it!");
				__result = count;
				return false;
			}
			((LG_Geomorph)val7).m_nodeVolume = (AIG_NodeVolume)(object)component;
			((AIG_NodeVolume)component).ConstructVoxelNodeVolume();
			((LG_Geomorph)val7).ScanChildrenAreas();
			val6.m_startTile = LG_Tile.Create(val5, val4);
			val6.m_startTile.m_geoRoot = (LG_Geomorph)(object)val7;
			val6.m_startTile.m_geoRoot.m_tile = val6.m_startTile;
			((Component)val7).transform.SetParent(((Component)val6.DimensionRootTemp).transform);
			((LG_Geomorph)val7).m_tile = val6.m_startTile;
			val6.m_startTransition = val7;
			val6.Tiles.Add(val6.m_startTile);
			__instance.m_dimensions.Add(val6);
			__instance.m_indexToDimensionMap[dimensionIndex] = val6;
			__result = count;
			return false;
		}
	}
	[HarmonyPatch(typeof(LG_SetupFloor), "Build")]
	internal static class Inject_SetupFloor
	{
		private static LayoutConfig _configContext;

		[HarmonyPrefix]
		private static bool Prefix(LG_SetupFloor __instance, ref bool __result)
		{
			//IL_0089: 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)
			//IL_005f: 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_0160: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a1: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ca: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f4: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ff: Expected O, but got Unknown
			LayoutConfig config = null;
			Debug.Log(Object.op_Implicit(Deb.LG("LG_SetupFloor.Build", 0f)));
			GameObject val = null;
			uint num = 0u;
			if (Builder.LayerBuildDatas[0].m_zoneBuildDatas != null && Builder.LayerBuildDatas[0].m_zoneBuildDatas.Count > 0)
			{
				_ = Builder.LayerBuildDatas[0].m_zoneBuildDatas[0].SubComplex;
				num = (uint)Builder.LayerBuildDatas[0].m_zoneBuildDatas[0].SubSeed;
			}
			XXHashSeed seed = __instance.m_rnd.Seed;
			XXHashSequence val2 = default(XXHashSequence);
			((XXHashSequence)(ref val2))..ctor(((XXHashSeed)(ref seed)).SubSeed(num), true);
			ConfigManager.TryGetConfig(RundownManager.ActiveExpedition.LevelLayoutData, out config);
			if (config == null)
			{
				return true;
			}
			LG_GridPosition val3 = default(LG_GridPosition);
			val3.x = 0;
			val3.z = 0;
			if (config.TileOverrides.Length == 0)
			{
				return true;
			}
			if (config.TileOverrides[0].X != 0 || config.TileOverrides[0].Z != 0)
			{
				return true;
			}
			if (!string.IsNullOrEmpty(config.TileOverrides[0].Geomorph))
			{
				Object loadedAsset = AssetAPI.GetLoadedAsset(config.TileOverrides[0].Geomorph);
				val = ((loadedAsset != null) ? ((Il2CppObjectBase)loadedAsset).Cast<GameObject>() : null);
				if ((Object)(object)val == (Object)null)
				{
					Logger.Info("LGTuner failed to override elevator!");
					return true;
				}
				Logger.Info(" - elevator overriden! " + ((Object)val).name);
				LG_FloorTransition val4 = GOUtil.SpawnChildAndGetComp<LG_FloorTransition>(val, __instance.m_position, __instance.m_rotation);
				((LG_Geomorph)val4).m_geoPrefab = val;
				((LG_Geomorph)val4).SetupAreas(((XXHashSequence)(ref val2)).NextSubSeed());
				((LG_Geomorph)val4).SetPlaced();
				__instance.m_floor.Setup(((XXHashSequence)(ref val2)).NextSubSeed(), (LG_FloorType)0, Builder.ComplexResourceSetBlock.LevelGenConfig.TransitionDirection, val4);
				for (int i = 0; i < __instance.m_floor.m_dimensions.Count; i++)
				{
					__instance.m_floor.InjectJobs(__instance.m_floor.m_dimensions[i].DimensionIndex);
				}
				LG_Factory.InjectJob((LG_FactoryJob)new LG_BuildFloorJob(__instance.m_floor), (BatchName)7);
				__result = true;
				return false;
			}
			return true;
		}
	}
	[HarmonyPatch(typeof(LG_BuildPlugBaseJob), "SpawnPlug")]
	internal static class Inject_BuildPlug
	{
		private static void Prefix(LG_Plug plug, ref GameObject prefab)
		{
			//IL_0023: 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_00b5: 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_00bc: 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_010f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0111: 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_012a: Expected I4, but got Unknown
			//IL_0253: Unknown result type (might be due to invalid IL or missing references)
			Logger.Info($"found plug for zone: {((LG_ZoneExpander)plug).m_linksFrom.m_zone.LocalIndex}{((Object)((LG_ZoneExpander)plug).m_linksFrom).name}->{((LG_ZoneExpander)plug).m_linksTo.m_zone.LocalIndex}{((Object)((LG_ZoneExpander)plug).m_linksTo).name}");
			if (!BuilderInfo.TryGetConfig(((LG_ZoneExpander)plug).m_linksFrom.m_zone, out var config))
			{
				return;
			}
			LG_GridPosition normal = ((LG_ZoneExpander)plug).m_linksFrom.m_geomorph.m_tile.m_shape.m_gridPosition.GetNormal(config.GridSize);
			if (!config.TryGetTileData(normal, out var overrideData))
			{
				return;
			}
			ZoneOverrideData zoneData = overrideData.ZoneData;
			if (zoneData != null && zoneData.OverridePlugs && TryGetPlugPrefab(overrideData.ZoneData.GetNextPlug(), out var prefab2))
			{
				Logger.Info(" - Prefab Replaced by Zone OverridePlugs! " + ((Object)prefab2).name);
				prefab = prefab2;
			}
			LG_PlugDir dir = plug.m_dir;
			GameObject prefab3;
			switch (dir - 2)
			{
			case 0:
				if (TryGetPlugPrefab(overrideData.BackwardPlug, out prefab3))
				{
					Logger.Info(" - Prefab Replaced by BackwardPlug setting! " + ((Object)prefab3).name);
					prefab = prefab3;
					return;
				}
				break;
			case 2:
				if (TryGetPlugPrefab(overrideData.ForwardPlug, out prefab3))
				{
					Logger.Info(" - Prefab Replaced by ForwardPlug setting! " + ((Object)prefab3).name);
					prefab = prefab3;
					return;
				}
				break;
			case 3:
				if (TryGetPlugPrefab(overrideData.LeftPlug, out prefab3))
				{
					Logger.Info(" - Prefab Replaced by LeftPlug setting! " + ((Object)prefab3).name);
					prefab = prefab3;
					return;
				}
				break;
			case 1:
				if (TryGetPlugPrefab(overrideData.RightPlug, out prefab3))
				{
					Logger.Info(" - Prefab Replaced by RightPlug setting! " + ((Object)prefab3).name);
					prefab = prefab3;
					return;
				}
				break;
			}
			if (overrideData.OverridePlugWithNoGateChance)
			{
				Random random = new Random(((LG_ZoneExpander)plug).m_linksFrom.AreaSeed.ToSeed());
				bool withGate = ((LG_ZoneExpander)plug).m_isZoneSource || (!(overrideData.PlugWithNoGateChance >= 1f) && (overrideData.PlugWithNoGateChance <= 0f || random.NextFloat() >= overrideData.PlugWithNoGateChance));
				int dropHeight = GetDropHeight(plug);
				GameObject randomPlug = BuilderInfo.GetRandomPlug(random.NextUint(), dropHeight, GetSubComplexOfPlug(plug), withGate);
				if ((Object)(object)randomPlug == (Object)null)
				{
					Logger.Error($"Plug was null! - Height: {dropHeight}");
				}
				else
				{
					prefab = randomPlug;
				}
			}
		}

		private static SubComplex GetSubComplexOfPlug(LG_Plug plug)
		{
			//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_0008: 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_001c: 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)
			SubComplex result = ((LG_ZoneExpander)plug).m_subComplex;
			if (((LG_ZoneExpander)plug).m_subComplex != ((LG_ZoneExpander)plug.m_pariedWith).m_subComplex)
			{
				result = (SubComplex)8;
			}
			return result;
		}

		private static bool TryGetPlugPrefab(string prefabPath, out GameObject prefab)
		{
			if (string.IsNullOrEmpty(prefabPath))
			{
				prefab = null;
				return false;
			}
			Object loadedAsset = AssetAPI.GetLoadedAsset(prefabPath);
			prefab = ((loadedAsset != null) ? ((Il2CppObjectBase)loadedAsset).Cast<GameObject>() : null);
			return (Object)(object)prefab != (Object)null;
		}

		private static int GetDropHeight(LG_Plug plug)
		{
			//IL_0006: 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)
			return Mathf.RoundToInt(Mathf.Abs(((Component)plug).transform.position.y - ((Component)plug.m_pariedWith).transform.position.y) / BuilderInfo.AltitudeOffset);
		}
	}
	[HarmonyPatch(typeof(LG_BuildPlugJob), "Build")]
	internal class Inject_BuildPlugJob
	{
		[HarmonyWrapSafe]
		private static bool Prefix(LG_BuildPlugJob __instance)
		{
			//IL_0022: 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_0054: 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: Invalid comparison between Unknown and I4
			//IL_00b6: 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_00c6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c8: 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_00da: Unknown result type (might be due to invalid IL or missing references)
			//IL_00dc: Unknown result type (might be due to invalid IL or missing references)
			//IL_00df: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f5: Expected I4, but got Unknown
			//IL_01cc: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e8: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ed: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f5: Unknown result type (might be due to invalid IL or missing references)
			//IL_01fa: 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_01ff: Unknown result type (might be due to invalid IL or missing references)
			GameObject val = null;
			LG_Plug plug = __instance.m_plug;
			Logger.Info($"buildplugjob plug in complex {((LG_ZoneExpander)plug).m_subComplex} plug status {((LG_ZoneExpander)plug).ExpanderStatus} plug direction {plug.m_dir} ..");
			if ((int)((LG_ZoneExpander)plug).ExpanderStatus == 1)
			{
				return true;
			}
			if (((LG_ZoneExpander)plug).m_isZoneSource)
			{
				return true;
			}
			if (!BuilderInfo.TryGetConfig(((LG_ZoneExpander)plug).m_linksFrom.m_zone, out var config))
			{
				return true;
			}
			LG_GridPosition normal = ((LG_ZoneExpander)plug).m_linksFrom.m_geomorph.m_tile.m_shape.m_gridPosition.GetNormal(config.GridSize);
			if (!config.TryGetTileData(normal, out var overrideData))
			{
				return true;
			}
			LG_PlugDir dir = plug.m_dir;
			GameObject prefab;
			switch (dir - 2)
			{
			case 0:
				if (TryGetPlugPrefab(overrideData.BackwardPlug, out prefab))
				{
					Logger.Info(" - Prefab Replaced by BackwardPlug setting! " + ((Object)prefab).name);
					val = prefab;
				}
				break;
			case 2:
				if (TryGetPlugPrefab(overrideData.ForwardPlug, out prefab))
				{
					Logger.Info(" - Prefab Replaced by ForwardPlug setting! " + ((Object)prefab).name);
					val = prefab;
				}
				break;
			case 3:
				if (TryGetPlugPrefab(overrideData.LeftPlug, out prefab))
				{
					Logger.Info(" - Prefab Replaced by LeftPlug setting! " + ((Object)prefab).name);
					val = prefab;
				}
				break;
			case 1:
				if (TryGetPlugPrefab(overrideData.RightPlug, out prefab))
				{
					Logger.Info(" - Prefab Replaced by RightPlug setting! " + ((Object)prefab).name);
					val = prefab;
				}
				break;
			}
			if ((Object)(object)val != (Object)null)
			{
				Logger.Info($"we shall replace a cap going {plug.m_dir}");
				Vector3 position = ((Component)plug).transform.position;
				Quaternion rotation = ((Component)plug).transform.rotation;
				GameObject val2 = Object.Instantiate<GameObject>(val, position, rotation);
				val2.transform.SetParent(((Component)plug).transform, true);
				LG_Factory.FindAndBuildSelectorsAndSpawners(val2, RandomExtensions.NextSubSeed(__instance.m_rnd.Random), false);
				__instance.ProcessDivider(plug, val2, false, RandomExtensions.NextSubSeed(__instance.m_rnd.Random));
				((LG_ZoneExpander)plug).m_wasProcessed = true;
			}
			return true;
		}

		private static bool TryGetPlugPrefab(string prefabPath, out GameObject prefab)
		{
			if (string.IsNullOrEmpty(prefabPath))
			{
				prefab = null;
				return false;
			}
			prefab = ((Il2CppObjectBase)AssetAPI.GetLoadedAsset(prefabPath)).Cast<GameObject>();
			return (Object)(object)prefab != (Object)null;
		}
	}
	[HarmonyPatch(typeof(LG_LevelBuilder), "PlaceRoot")]
	internal static class Inject_BuildGeomorph
	{
		private static LayoutConfig _configContext;

		private static RotateType _nextRotateType;

		[HarmonyPostfix]
		[HarmonyWrapSafe]
		[HarmonyPatch("BuildFloor")]
		private static void Post_BuildFloor()
		{
			BuilderInfo.OnResourceSetSelected();
		}

		[HarmonyPrefix]
		[HarmonyWrapSafe]
		[HarmonyPatch("PlaceRoot")]
		private static void Pre_PlaceRoot(LG_Tile tile, ref GameObject tilePrefab, ref bool forceAlignToVector, ref Vector3 alignVector, LG_Zone zone)
		{
			//IL_000e: 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_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_004b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0064: 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_00b3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00dd: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ee: Unknown result type (might be due to invalid IL or missing references)
			_configContext = null;
			_nextRotateType = RotateType.None;
			forceAlignToVector = alignVector != Vector3.zero;
			int gridSize = zone.Dimension.GetGridSize();
			LG_GridPosition val = tile.ToNormalGrid(gridSize);
			Logger.Info($"tile info: {val.x} {val.z} {((Object)tilePrefab).name} for {zone.LocalIndex} : {zone.DimensionIndex}");
			if (!BuilderInfo.TryGetConfig(zone, out _configContext))
			{
				return;
			}
			if (!_configContext.TryGetTileData(val, out var overrideData))
			{
				overrideData = _configContext.PopulateTileOverrideForZone(zone, val);
				if (overrideData == null)
				{
					return;
				}
			}
			if (!string.IsNullOrEmpty(overrideData.Geomorph))
			{
				if (overrideData.X == 0 && overrideData.Z == 0)
				{
					return;
				}
				Object loadedAsset = AssetAPI.GetLoadedAsset(overrideData.Geomorph);
				GameObject val2 = ((loadedAsset != null) ? ((Il2CppObjectBase)loadedAsset).Cast<GameObject>() : null);
				if ((Object)(object)val2 != (Object)null)
				{
					Logger.Info(" - tile overriden! " + ((Object)val2).name);
					tilePrefab = val2;
				}
			}
			if (overrideData.Rotation != 0)
			{
				_nextRotateType = overrideData.Rotation;
			}
		}

		[HarmonyPostfix]
		[HarmonyWrapSafe]
		[HarmonyPatch("GetTilePosition")]
		private static void Post_GetTilePosition(LG_Tile tile, LG_Floor floor, int dimensionIndex, ref Vector3 __result)
		{
			//IL_0021: Unknown result type (might be due to invalid IL or missing references)
			//IL_0026: 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_0045: 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_0052: 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_0059: 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)
			//IL_007c: 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_0081: Unknown result type (might be due to invalid IL or missing references)
			if (_configContext != null && floor.TryGetDimension(dimensionIndex, out var dimension))
			{
				int gridSize = _configContext.GridSize;
				LG_GridPosition val = tile.ToNormalGrid(gridSize);
				if (_configContext.TryGetTileData(val, out var overrideData) && overrideData.OverrideAltitude)
				{
					Vector3 positionNormal = dimension.Grid.GetPositionNormal(val.x, val.z, gridSize);
					positionNormal += new Vector3(0f, (float)overrideData.Altitude * BuilderInfo.AltitudeOffset, 0f);
					__result = positionNormal;
				}
			}
		}

		[HarmonyPostfix]
		[HarmonyWrapSafe]
		[HarmonyPatch("PlaceRoot")]
		private static void Post_PlaceRoot(LG_Tile tile, LG_Zone zone, LG_Geomorph __result)
		{
			//IL_0099: 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_00a4: 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_007f: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ee: Unknown result type (might be due to invalid IL or missing references)
			//IL_01fa: Expected O, but got Unknown
			//IL_01ff: Unknown result type (might be due to invalid IL or missing references)
			//IL_020b: Expected O, but got Unknown
			if (_configContext == null)
			{
				return;
			}
			if (_nextRotateType != 0)
			{
				GameObject gameObject = ((Component)__result).gameObject;
				LG_PlugInfo lG_PlugInfo = LG_PlugInfo.BuildPlugInfo(gameObject, gameObject.transform.rotation);
				Logger.Info($" - TRYING ROTATION! PLUG COUNT: {lG_PlugInfo.Count}");
				if (lG_PlugInfo.TryGetNewRotation(zone.m_subSeed, _nextRotateType, out var rotation))
				{
					Logger.Info(" - Done!");
					gameObject.transform.rotation = rotation;
				}
				__result.SetPlaced();
			}
			int gridSize = _configContext.GridSize;
			LG_GridPosition normalGridPosition = tile.ToNormalGrid(gridSize);
			if (!_configContext.TryGetTileData(normalGridPosition, out var overrideData))
			{
				return;
			}
			if (overrideData.OverrideAreaSeeds)
			{
				if (overrideData.AreaSeeds.Length == ((Il2CppArrayBase<LG_Area>)(object)__result.m_areas).Length)
				{
					int length = ((Il2CppArrayBase<LG_Area>)(object)__result.m_areas).Length;
					for (int i = 0; i < length; i++)
					{
						uint num = overrideData.AreaSeeds[i];
						if (num != 0)
						{
							((Il2CppArrayBase<LG_Area>)(object)__result.m_areas)[i].AreaSeed = num;
							Logger.Info($" - new area seed: {((Il2CppArrayBase<LG_Area>)(object)__result.m_areas)[i].m_navInfo}, {num}");
						}
					}
				}
				else
				{
					Logger.Error($" - Area count and AreaSeeds item count mismatched! (CFG: {overrideData.AreaSeeds.Length} != AREA: {((Il2CppArrayBase<LG_Area>)(object)__result.m_areas).Length}) Area seed will not be applied!");
				}
			}
			if (!zone.m_settings.HasCustomGeomorphPrefab)
			{
				iLG_CustomGeomorphLogic[] array = Il2CppArrayBase<iLG_CustomGeomorphLogic>.op_Implicit(((Component)__result).GetComponentsInChildren<iLG_CustomGeomorphLogic>());
				for (int j = 0; j < array.Length; j++)
				{
					array[j].SpawnedOnFloor();
					LG_Factory.InjectJob((LG_FactoryJob)new LG_CustomGeomorphBuildJob(array[j]), (BatchName)45);
					LG_Factory.InjectJob((LG_FactoryJob)new LG_CustomGeomorphPostCullingJob(array[j]), (BatchName)64);
				}
			}
		}
	}
	[HarmonyPatch(typeof(LG_LoadComplexDataSetResourcesJob), "Build")]
	internal static class Inject_LoadComplexShard
	{
		private static int _waitingShared;

		private static void Prefix(LG_LoadComplexDataSetResourcesJob __instance)
		{
			//IL_004b: 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_0064: Unknown result type (might be due to invalid IL or missing references)
			//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_01bb: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ce: Expected I4, but got Unknown
			//IL_01d1: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d6: Unknown result type (might be due to invalid IL or missing references)
			//IL_01db: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e2: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e4: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e6: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e0: 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_01ea: 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)
			if (__instance.m_loadingStarted)
			{
				return;
			}
			if (!EntryPoint.AssetsFixed)
			{
				if (!((BaseChainloader<BasePlugin>)(object)IL2CPPChainloader.Instance).Plugins.TryGetValue("StairsFix", out var _))
				{
					Transform transform = ((Component)AssetAPI.GetLoadedAsset<GameObject>("Assets/AssetPrefabs/Complex/Dimensions/Desert/Dimension_Desert_Mining_Shaft.prefab").GetComponentsInChildren<LG_Ladder>()[2]).gameObject.transform;
					transform.position += new Vector3(0f, 0f, -1.5f);
					Logger.Info("navmesh fix on Dimension_Desert_Mining_Shaft.prefab (StairsFix) done");
				}
				foreach (Transform componentsInChild in AssetAPI.GetLoadedAsset<GameObject>("Assets/AssetPrefabs/Complex/Service/Geomorphs/Maintenance/geo_64x64_service_floodways_hub_SF_01.prefab").GetComponentsInChildren<Transform>())
				{
					if (((Object)componentsInChild).name == "AIGraphSource")
					{
						componentsInChild.position = new Vector3(5f, 2f, -16f);
					}
				}
				Logger.Info("navmesh fix on geo_64x64_service_floodways_hub_SF_01.prefab done");
				foreach (LG_PrefabSpawner componentsInChild2 in AssetAPI.GetLoadedAsset<GameObject>("Assets/AssetPrefabs/Complex/Tech/Geomorphs/geo_64x64_tech_lab_HA_05.prefab").GetComponentsInChildren<LG_PrefabSpawner>())
				{
					if (!((Object)((Component)componentsInChild2).transform).name.Contains("prop_generic_duct_d_2m_tile_001"))
					{
						continue;
					}
					foreach (Transform componentsInChild3 in componentsInChild2.m_prefab.GetComponentsInChildren<Transform>())
					{
						if (((Object)componentsInChild3).name == "Capsulecollider")
						{
							((Component)componentsInChild3).transform.localScale = new Vector3(0.5f, 1f, 0.5f);
						}
					}
				}
				Logger.Info("collider fix on geo_64x64_tech_lab_HA_05.prefab done");
				EntryPoint.AssetsFixed = true;
			}
			foreach (Complex item in BuilderInfo.ExtraComplexResourceToLoad)
			{
				AssetBundleName val = (AssetBundleName)((int)item switch
				{
					0 => 2, 
					1 => 4, 
					2 => 3, 
					_ => 0, 
				});
				if ((int)val != 0)
				{
					AssetShardManager.LoadAllShardsForBundleAsync(val, Action.op_Implicit((Action)Loaded), 1, (LoadSceneMode)1);
					_waitingShared++;
				}
			}
		}

		private static void Loaded()
		{
			_waitingShared--;
		}

		[HarmonyWrapSafe]
		private static void Postfix(LG_LoadComplexDataSetResourcesJob __instance, ref bool __result)
		{
			if (_waitingShared >= 1)
			{
				__result = false;
			}
		}
	}
}
namespace LGTuner.Configs
{
	public sealed class LayoutConfig
	{
		private TileOverrideData[,] _builtTileOverrides = new TileOverrideData[0, 0];

		public uint LevelLayoutID { get; set; }

		public Complex[] ExtraComplexResourceToLoad { get; set; } = Array.Empty<Complex>();


		public ZoneOverrideData[] ZoneOverrides { get; set; } = Array.Empty<ZoneOverrideData>();


		public TileOverrideData[] TileOverrides { get; set; } = Array.Empty<TileOverrideData>();


		[JsonIgnore]
		public int GridSize { get; private set; }

		[JsonIgnore]
		public int GridSizeHalf { get; private set; }

		public void Reset(int gridSize)
		{
			Array.ForEach(ZoneOverrides, delegate(ZoneOverrideData item)
			{
				item.Clear();
			});
			Array.Clear(_builtTileOverrides, 0, _builtTileOverrides.Length);
			GridSize = gridSize;
			GridSizeHalf = gridSize / 2;
			_builtTileOverrides = new TileOverrideData[GridSize, GridSize];
			TileOverrideData[] tileOverrides = TileOverrides;
			foreach (TileOverrideData tileOverrideData in tileOverrides)
			{
				if (_builtTileOverrides[tileOverrideData.X + GridSizeHalf, tileOverrideData.Z + GridSizeHalf] == null)
				{
					PutOverrideData(tileOverrideData);
					continue;
				}
				Logger.Error($"Duplicate tile data in layout: {LevelLayoutID}, ({tileOverrideData.X}, {tileOverrideData.Z})!");
			}
		}

		public bool TryGetTileData(LG_GridPosition normalGridPosition, out TileOverrideData overrideData)
		{
			//IL_0000: 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)
			int num = normalGridPosition.x + GridSizeHalf;
			if (num >= GridSize)
			{
				Logger.Error($"TryGetTileData grid x was out of range! {num}:{GridSize}");
				overrideData = null;
				return false;
			}
			int num2 = normalGridPosition.z + GridSizeHalf;
			if (num2 >= GridSize)
			{
				Logger.Error($"TryGetTileData grid Z was out of range! {num2}:{GridSize}");
				overrideData = null;
				return false;
			}
			overrideData = _builtTileOverrides[num, num2];
			return overrideData != null;
		}

		public void PutOverrideData(TileOverrideData data)
		{
			_builtTileOverrides[data.X + GridSizeHalf, data.Z + GridSizeHalf] = data;
		}

		public TileOverrideData PopulateTileOverrideForZone(LG_Zone zone, LG_GridPosition normalGridPosition)
		{
			//IL_0002: 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_003b: 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)
			if (!TryGetZoneOverride(zone.LocalIndex, out var data))
			{
				return null;
			}
			if (TryGetTileData(normalGridPosition, out var overrideData))
			{
				overrideData.ZoneData = data;
				TryApplyOverrides(data, overrideData);
				return overrideData;
			}
			TileOverrideData tileOverrideData = new TileOverrideData
			{
				ZoneData = data,
				X = normalGridPosition.x,
				Z = normalGridPosition.z,
				OverridePlugWithNoGateChance = data.OverridePlugWithNoGateChance,
				PlugWithNoGateChance = data.PlugWithNoGateChance
			};
			TryApplyOverrides(data, tileOverrideData);
			PutOverrideData(tileOverrideData);
			return tileOverrideData;
		}

		private void TryApplyOverrides(ZoneOverrideData zoneOverrideData, TileOverrideData tileOverrideData)
		{
			if (zoneOverrideData.OverrideGeomorphs && string.IsNullOrEmpty(tileOverrideData.Geomorph))
			{
				ZoneOverrideData.GeomorphData? nextGeo = zoneOverrideData.GetNextGeo();
				if (nextGeo.HasValue)
				{
					tileOverrideData.Geomorph = nextGeo.Value.Geomorph;
					if (tileOverrideData.Rotation == RotateType.None)
					{
						tileOverrideData.Rotation = ZoneOverrideData.DirectionToRotate(nextGeo.Value.Direction);
					}
				}
			}
			if (zoneOverrideData.OverrideAltitudes && !tileOverrideData.OverrideAltitude)
			{
				int? nextAltitude = zoneOverrideData.GetNextAltitude();
				if (nextAltitude.HasValue)
				{
					tileOverrideData.OverrideAltitude = true;
					tileOverrideData.Altitude = nextAltitude.Value;
				}
			}
		}

		public bool TryGetZoneOverride(eLocalZoneIndex localIndex, out ZoneOverrideData data)
		{
			//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)
			data = ZoneOverrides.SingleOrDefault((ZoneOverrideData z) => z.LocalIndex == localIndex);
			return data != null;
		}
	}
	public sealed class TileOverrideData
	{
		public int X { get; set; }

		public int Z { get; set; }

		public bool OverrideAreaSeeds { get; set; }

		public uint[] AreaSeeds { get; set; } = Array.Empty<uint>();


		public RotateType Rotation { get; set; }

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


		public bool OverrideAltitude { get; set; }

		public int Altitude { get; set; }

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


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


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


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


		public bool OverridePlugWithNoGateChance { get; set; }

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


		[JsonIgnore]
		public ZoneOverrideData ZoneData { get; set; }
	}
	public sealed class ZoneOverrideData
	{
		public enum Direction
		{
			Unchanged,
			Random,
			Forward,
			Backward,
			Left,
			Right
		}

		public struct GeomorphData
		{
			public string Geomorph { get; set; }

			public Direction Direction { get; set; }
		}

		private int _curGeomorphIndex;

		private int _curAltitudeIndex;

		private int _curPlugIndex;

		public eLocalZoneIndex LocalIndex { get; set; }

		public bool OverrideGeomorphs { get; set; }

		public GeomorphData[] Geomorphs { get; set; } = Array.Empty<GeomorphData>();


		public bool OverrideAltitudes { get; set; }

		public int[] Altitudes { get; set; } = Array.Empty<int>();


		public bool OverridePlugs { get; set; }

		public string[] Plugs { get; set; } = Array.Empty<string>();


		public bool OverridePlugWithNoGateChance { get; set; }

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


		public void Clear()
		{
			_curGeomorphIndex = 0;
			_curAltitudeIndex = 0;
			_curPlugIndex = 0;
		}

		public GeomorphData? GetNextGeo()
		{
			if (Geomorphs == null || Geomorphs.Length == 0)
			{
				return null;
			}
			return Geomorphs[_curGeomorphIndex++ % Geomorphs.Length];
		}

		public int? GetNextAltitude()
		{
			if (Altitudes == null || Altitudes.Length == 0)
			{
				return null;
			}
			return Altitudes[_curAltitudeIndex++ % Altitudes.Length];
		}

		public string GetNextPlug()
		{
			if (Plugs == null || Plugs.Length == 0)
			{
				return string.Empty;
			}
			return Plugs[_curPlugIndex++ % Plugs.Length];
		}

		public static RotateType DirectionToRotate(Direction direction)
		{
			return direction switch
			{
				Direction.Unchanged => RotateType.None, 
				Direction.Random => RotateType.Towards_Random, 
				Direction.Forward => RotateType.Towards_Forward, 
				Direction.Backward => RotateType.Towards_Backward, 
				Direction.Left => RotateType.Towards_Left, 
				Direction.Right => RotateType.Towards_Right, 
				_ => throw new NotImplementedException($"DirectionType: {direction} is not supported"), 
			};
		}
	}
}

plugins/Fusion/extra/net6/PortalPuzzleChanger.dll

Decompiled a week 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/Fusion/extra/Oxygen/Oxygen.dll

Decompiled a week 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;
			}
		}
	}
}