Decompiled source of Natural selection v0.4.5

DLLs/fandovec03.NaturalSelection.dll

Decompiled a day ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using System.Text;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Configuration;
using BepInEx.Logging;
using CleaningCompany;
using EnhancedMonsters.Monobehaviours;
using GameNetcodeStuff;
using HarmonyLib;
using LethalNetworkAPI;
using LobbyCompatibility.Enums;
using LobbyCompatibility.Features;
using Microsoft.CodeAnalysis;
using NaturalSelection.Compatibility;
using NaturalSelection.EnemyPatches;
using NaturalSelection.Generics;
using NaturalSelectionLib;
using ReXuvination.src.Patches;
using Unity.Netcode;
using UnityEngine;
using UnityEngine.AI;

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

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

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

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

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace NaturalSelection
{
	[BepInPlugin("fandovec03.NaturalSelection", "NaturalSelection", "0.4.1")]
	[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.*/)]
	public class Script : BaseUnityPlugin
	{
		public static ManualLogSource Logger = null;

		internal static bool stableToggle;

		private static bool isExperimental = false;

		private static bool isPrerelease = false;

		private static bool debugBool = false;

		private static bool spammyLogs = false;

		private static bool debugNetworking = false;

		private static bool debugLibrary = false;

		private static bool debugTriggerFlags = false;

		private static bool debugGiants = false;

		private static bool debugHygrodere = false;

		private static bool debugNutcrackers = false;

		private static bool debugRedBees = false;

		private static bool debugSandworms = false;

		private static bool debugSpiders = false;

		private static bool debugSpiderWebs = false;

		private static bool debugUnspecified = false;

		internal static bool enhancedMonstersPresent = false;

		internal static bool sellBodiesPresent = false;

		internal static bool rexuvinationPresent = false;

		internal static bool CompatibilityAutoToggle = false;

		internal static bool LobbyCompatibilityPresent = false;

		internal static Dictionary<string, bool> Bools = new Dictionary<string, bool>();

		internal static List<EnemyAI> loadedEnemyList = new List<EnemyAI>();

		public static Action<string, bool>? OnConfigSettingChanged;

		public static Script Instance { get; private set; } = null;


		internal static Harmony? Harmony { get; set; }

		internal static MyModConfig BoundingConfig { get; set; } = null;


		private static void SubscribeDebugConfigBools(ConfigEntry<bool> entryKey, bool boolParam, string entry)
		{
			ConfigEntry<bool> entryKey2 = entryKey;
			string entry2 = entry;
			entryKey2.SettingChanged += delegate
			{
				boolParam = entryKey2.Value;
				Logger.LogMessage((object)$"Updating with entry.Value {entryKey2.Value}. Result: {boolParam}");
				OnConfigSettingChanged?.Invoke(entry2, entryKey2.Value);
			};
		}

		private void Awake()
		{
			Logger = ((BaseUnityPlugin)this).Logger;
			Instance = this;
			BoundingConfig = new MyModConfig(((BaseUnityPlugin)this).Config);
			stableToggle = BoundingConfig.stableMode.Value;
			Bools.Add("debugBool", debugBool);
			Bools.Add("spammyLogs", spammyLogs);
			Bools.Add("debugNetworking", debugNetworking);
			Bools.Add("debugLibrary", debugLibrary);
			Bools.Add("debugTriggerFlags", debugTriggerFlags);
			Bools.Add("debugGiants", debugGiants);
			Bools.Add("debugHygrodere", debugHygrodere);
			Bools.Add("debugNutcrackers", debugNutcrackers);
			Bools.Add("debugRedBees", debugRedBees);
			Bools.Add("debugSandworms", debugSandworms);
			Bools.Add("debugSpiders", debugSpiders);
			Bools.Add("debugSpiderWebs", debugSpiderWebs);
			Bools.Add("debugUnspecified", debugUnspecified);
			CompatibilityAutoToggle = BoundingConfig.CompatibilityAutoToggle.Value;
			foreach (KeyValuePair<string, ConfigEntry<bool>> debugEntry in BoundingConfig.debugEntries)
			{
				if (Bools.ContainsKey(debugEntry.Key))
				{
					Bools[debugEntry.Key] = debugEntry.Value.Value;
					SubscribeDebugConfigBools(debugEntry.Value, Bools[debugEntry.Key], debugEntry.Key);
				}
				else
				{
					Logger.LogError((object)("Failed to find bool for config entry " + debugEntry.Key));
				}
			}
			char[] array = "0.4.1".ToCharArray();
			if ((array[0] == '9' && array[1] == '9') || (array[0] == '8' && array[1] == '8'))
			{
				if (array[0] == '9' && array[1] == '9')
				{
					isExperimental = true;
				}
				if (array[0] == '8' && array[1] == '8')
				{
					isPrerelease = true;
				}
				array[0] = '0';
				array[1] = '0';
			}
			Patch();
			StringBuilder stringBuilder = new StringBuilder();
			stringBuilder.Append(array);
			Logger.LogInfo((object)string.Format("{0} v{1} has loaded!", "fandovec03.NaturalSelection", stringBuilder));
		}

		internal static void Patch()
		{
			//IL_000c: 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_0017: Expected O, but got Unknown
			if (Harmony == null)
			{
				Harmony = new Harmony("fandovec03.NaturalSelection");
			}
			Logger.LogInfo((object)"Patching NaturalSelection...");
			foreach (KeyValuePair<string, PluginInfo> pluginInfo in Chainloader.PluginInfos)
			{
				string text = "";
				if (!CompatibilityAutoToggle)
				{
					break;
				}
				switch (pluginInfo.Key)
				{
				case "com.velddev.enhancedmonsters":
					enhancedMonstersPresent = true;
					text = "Found Enhanced Monsters";
					break;
				case "Entity378.sellbodies":
					sellBodiesPresent = true;
					text = "Found SellbodiesFixed";
					break;
				case "XuuXiaolan.ReXuvination":
					rexuvinationPresent = true;
					text = "Found ReXuvination";
					break;
				case "BMX.LobbyCompatibility":
					LobbyCompatibilityPresent = true;
					text = "Found LobbyCompatibility";
					break;
				}
				if (text != "")
				{
					Logger.LogInfo((object)(text + ". Automatically loading compatibility."));
				}
			}
			try
			{
				LobbyCompCompatibility.RegisterLobbyComp("fandovec03.NaturalSelection", Version.Parse("0.4.1"));
			}
			catch
			{
			}
			foreach (KeyValuePair<string, ConfigEntry<bool>> compatibilityEntry in BoundingConfig.CompatibilityEntries)
			{
				string text2 = "";
				if (compatibilityEntry.Value.Value)
				{
					switch (compatibilityEntry.Key)
					{
					case "com.velddev.enhancedmonsters":
						enhancedMonstersPresent = true;
						break;
					case "Entity378.sellbodies":
						sellBodiesPresent = true;
						break;
					case "XuuXiaolan.ReXuvination":
						rexuvinationPresent = true;
						break;
					}
					text2 = "Manually enabling compatibility for " + compatibilityEntry.Key + ".";
				}
				if (text2 != "")
				{
					Logger.LogInfo((object)text2);
				}
			}
			if (isExperimental)
			{
				Logger.LogFatal((object)("LOADING EXPERIMENTAL BUILD OF " + "NaturalSelection".ToUpper() + ", DOWNLOAD NATURAL SELECTION INSTEAD FOR MORE STABLE EXPERIENCE!"));
			}
			if (isPrerelease)
			{
				Logger.LogWarning((object)("LOADING PRERELASE BUILD OF " + "NaturalSelection".ToUpper() + ", DOWNLOAD NATURAL SELECTION INSTEAD FOR MORE STABLE EXPERIENCE!"));
			}
			Harmony.PatchAll(typeof(AICollisionDetectPatch));
			Harmony.PatchAll(typeof(EnemyAIPatch));
			Harmony.PatchAll(typeof(Networking));
			Harmony.PatchAll(typeof(NetworkingMethods));
			Harmony.PatchAll(typeof(InitializeGamePatch));
			try
			{
				NaturalSelectionLib.SetLibraryLoggers(Logger, spammyLogs, debugLibrary);
				Logger.LogMessage((object)("Library successfully setup! Version " + NaturalSelectionLib.ReturnVersion()));
			}
			catch
			{
				Logger.LogError((object)"Failed to setup library!");
			}
			Harmony.PatchAll(typeof(RoundManagerPatch));
			if (BoundingConfig.enableLeviathan.Value)
			{
				Harmony.PatchAll(typeof(SandWormAIPatch));
			}
			if (BoundingConfig.enableSlime.Value)
			{
				Harmony.PatchAll(typeof(BlobAIPatch));
			}
			if (BoundingConfig.enableHoardingBug.Value)
			{
				Harmony.PatchAll(typeof(HoarderBugPatch));
			}
			if (BoundingConfig.enableRedBees.Value)
			{
				Harmony.PatchAll(typeof(BeeAIPatch));
			}
			if (BoundingConfig.enableGiant.Value)
			{
				Harmony.PatchAll(typeof(ForestGiantPatch));
			}
			if (BoundingConfig.enableSpiderWebs.Value)
			{
				Harmony.PatchAll(typeof(SandSpiderWebTrapPatch));
			}
			if (BoundingConfig.enableSpider.Value)
			{
				Harmony.PatchAll(typeof(SandSpiderAIPatch));
			}
			if (enhancedMonstersPresent)
			{
				Harmony.PatchAll(typeof(EnhancedMonstersCompatibility));
				Logger.LogInfo((object)"Loading compatibility for Enhanced Monsters");
			}
			if (sellBodiesPresent)
			{
				SellBodiesFixedCompatibility.AddTracerScriptToPrefabs();
				Logger.LogInfo((object)"Loading compatibility for SellbodiesFixed");
			}
			if (rexuvinationPresent)
			{
				Harmony.PatchAll(typeof(ReXuvinationPatch));
				Logger.LogInfo((object)"Loading compatibility for Rexuvination");
			}
			if (!stableToggle)
			{
				if (isExperimental)
				{
					if (BoundingConfig.enableNutcracker.Value)
					{
						Harmony.PatchAll(typeof(NutcrackerAIPatch));
					}
					if (BoundingConfig.enableSporeLizard.Value)
					{
						Harmony.PatchAll(typeof(PufferAIPatch));
					}
				}
				else
				{
					Logger.LogWarning((object)"Limited access. Some patches cannot be enabled in stable branch.");
				}
				Logger.LogInfo((object)"Stable mode off. Loaded all patches.");
			}
			else
			{
				Logger.LogInfo((object)"Stable mode on. Excluded unstable and WIP patches from loading.");
			}
			Logger.LogInfo((object)"Finished patching NaturalSelection !");
		}

		internal static void Unpatch()
		{
			Logger.LogDebug((object)"Unpatching...");
			Harmony? harmony = Harmony;
			if (harmony != null)
			{
				harmony.UnpatchSelf();
			}
			Logger.LogDebug((object)"Finished unpatching!");
		}
	}
	public static class MyPluginInfo
	{
		public const string PLUGIN_GUID = "fandovec03.NaturalSelection";

		public const string PLUGIN_NAME = "NaturalSelection";

		public const string PLUGIN_VERSION = "0.4.1";
	}
}
namespace NaturalSelection.Generics
{
	internal class InitializeGamePatch
	{
		private static bool finishedLoading = false;

		private static List<string> loadedEnemyNamesFromConfig = new List<string>();

		private static List<string> beeBlacklistList = Script.BoundingConfig.beeBlacklist.Value.Split(',', StringSplitOptions.RemoveEmptyEntries).ToList();

		private static List<string> blobBlacklistList = Script.BoundingConfig.blobBlacklist.Value.Split(',', StringSplitOptions.RemoveEmptyEntries).ToList();

		private static List<string> sandwormBlacklistList = Script.BoundingConfig.sandwormBlacklist.Value.Split(',', StringSplitOptions.RemoveEmptyEntries).ToList();

		private static List<string> spiderWebBlacklistList = Script.BoundingConfig.spiderWebBlacklist.Value.Split(',', StringSplitOptions.RemoveEmptyEntries).ToList();

		private static List<string> speedModifierList = Script.BoundingConfig.speedModifierList.Value.Split(',', StringSplitOptions.RemoveEmptyEntries).ToList();

		private static List<string> spiderBlacklistList = Script.BoundingConfig.spiderBlacklist.Value.Split(',', StringSplitOptions.RemoveEmptyEntries).ToList();

		private static List<string> customSizeOverrideListList = Script.BoundingConfig.customSizeOverrideList.Value.Split(',', StringSplitOptions.RemoveEmptyEntries).ToList();

		private static Dictionary<string, bool> beeBlacklistrDictionay = new Dictionary<string, bool>();

		private static Dictionary<string, bool> blobBlacklistDictionay = new Dictionary<string, bool>();

		private static Dictionary<string, bool> sandwormBlacklistDictionay = new Dictionary<string, bool>();

		private static Dictionary<string, bool> spiderWebBlacklistDictionay = new Dictionary<string, bool>();

		public static Dictionary<string, float> speedModifierDictionay = new Dictionary<string, float>();

		private static Dictionary<string, bool> spiderBlacklistDictionay = new Dictionary<string, bool>();

		public static Dictionary<string, int> customSizeOverrideListDictionary = new Dictionary<string, int>();

		public static List<string> beeBlacklistFinal = new List<string>();

		public static List<string> blobBlacklistFinal = new List<string>();

		public static List<string> sandwormBlacklistFinal = new List<string>();

		public static List<string> spiderWebBlacklistFinal = new List<string>();

		public static List<string> spiderBlacklistFinal = new List<string>();

		public static List<EnemyAI> tryFindLater = new List<EnemyAI>();

		[HarmonyPatch(typeof(InitializeGame), "Start")]
		[HarmonyPostfix]
		public static void InitializeGameStartPatch()
		{
			Script.loadedEnemyList = Resources.FindObjectsOfTypeAll<EnemyAI>().ToList();
			if (!finishedLoading)
			{
				Script.Logger.Log((LogLevel)8, (object)"Reading/Checking/Writing entries for enemies.");
				ReadConfigLists();
				CheckConfigLists(Script.loadedEnemyList);
				WriteToConfigLists();
			}
			LibraryCalls.SubscribeToConfigChanges();
			Networking.SubscribeToConfigChanges();
			finishedLoading = true;
		}

		[HarmonyPatch(typeof(StartOfRound), "Awake")]
		[HarmonyPostfix]
		public static void StartOfRoundPatch()
		{
			if (tryFindLater.Count > 0)
			{
				Script.Logger.Log((LogLevel)8, (object)"Secondary list is not empty. Checking/Writing entries for skipped enemies");
				try
				{
					CheckConfigLists(tryFindLater);
					WriteToConfigLists();
					tryFindLater.Clear();
				}
				catch
				{
					Script.Logger.Log((LogLevel)2, (object)"An error has occured while working with the list.");
					tryFindLater.Clear();
				}
			}
		}

		public static void ReadConfigLists()
		{
			foreach (string speedModifier in speedModifierList)
			{
				try
				{
					string text = speedModifier.Split(":")[0];
					float num = float.Parse(speedModifier.Split(":")[1].Replace(".", ","));
					speedModifierDictionay.Add(text, num);
					Script.Logger.Log((LogLevel)32, (object)$"Found {text}, {num}");
				}
				catch (Exception ex)
				{
					Script.Logger.Log((LogLevel)2, (object)"Failed to add enemy into speedModifierDictionary");
					Script.Logger.Log((LogLevel)2, (object)speedModifier);
					Script.Logger.Log((LogLevel)2, (object)speedModifier.Split(":")[0]);
					Script.Logger.Log((LogLevel)2, (object)speedModifier.Split(":")[1]);
					Script.Logger.Log((LogLevel)2, (object)ex);
				}
			}
			foreach (string beeBlacklist in beeBlacklistList)
			{
				try
				{
					string text2 = beeBlacklist.Split(":")[0];
					bool flag = bool.Parse(beeBlacklist.Split(":")[1]);
					if (flag)
					{
						beeBlacklistFinal.Add(text2);
					}
					beeBlacklistrDictionay.Add(text2, flag);
					Script.Logger.Log((LogLevel)32, (object)$"Found {text2}, {flag}");
				}
				catch (Exception ex2)
				{
					Script.Logger.Log((LogLevel)2, (object)"Failed to add enemy into beeBlacklistrDictionay");
					Script.Logger.Log((LogLevel)2, (object)beeBlacklist);
					Script.Logger.Log((LogLevel)2, (object)beeBlacklist.Split(":")[0]);
					Script.Logger.Log((LogLevel)2, (object)beeBlacklist.Split(":")[1]);
					Script.Logger.Log((LogLevel)2, (object)ex2);
				}
			}
			foreach (string blobBlacklist in blobBlacklistList)
			{
				try
				{
					string text3 = blobBlacklist.Split(":")[0];
					bool flag2 = bool.Parse(blobBlacklist.Split(":")[1]);
					if (flag2)
					{
						blobBlacklistFinal.Add(text3);
					}
					blobBlacklistDictionay.Add(text3, flag2);
					Script.Logger.Log((LogLevel)32, (object)$"Found {text3}, {flag2}");
				}
				catch (Exception ex3)
				{
					Script.Logger.Log((LogLevel)2, (object)"Failed to add enemy into blobBlacklistDictionay");
					Script.Logger.Log((LogLevel)2, (object)blobBlacklist);
					Script.Logger.Log((LogLevel)2, (object)blobBlacklist.Split(":")[0]);
					Script.Logger.Log((LogLevel)2, (object)blobBlacklist.Split(":")[1]);
					Script.Logger.Log((LogLevel)2, (object)ex3);
				}
			}
			foreach (string sandwormBlacklist in sandwormBlacklistList)
			{
				try
				{
					string text4 = sandwormBlacklist.Split(":")[0];
					bool flag3 = bool.Parse(sandwormBlacklist.Split(":")[1]);
					if (flag3)
					{
						sandwormBlacklistFinal.Add(text4);
					}
					sandwormBlacklistDictionay.Add(text4, flag3);
					Script.Logger.Log((LogLevel)32, (object)$"Found {text4}, {flag3}");
				}
				catch (Exception ex4)
				{
					Script.Logger.Log((LogLevel)2, (object)"Failed to add enemy into sandwormBlacklistDictionay");
					Script.Logger.Log((LogLevel)2, (object)sandwormBlacklist);
					Script.Logger.Log((LogLevel)2, (object)sandwormBlacklist.Split(":")[0]);
					Script.Logger.Log((LogLevel)2, (object)sandwormBlacklist.Split(":")[1]);
					Script.Logger.Log((LogLevel)2, (object)ex4);
				}
			}
			foreach (string spiderWebBlacklist in spiderWebBlacklistList)
			{
				try
				{
					string text5 = spiderWebBlacklist.Split(":")[0];
					bool flag4 = bool.Parse(spiderWebBlacklist.Split(":")[1]);
					if (flag4)
					{
						spiderWebBlacklistFinal.Add(text5);
					}
					spiderWebBlacklistDictionay.Add(text5, flag4);
					Script.Logger.Log((LogLevel)32, (object)$"Found {text5}, {flag4}");
				}
				catch (Exception ex5)
				{
					Script.Logger.Log((LogLevel)2, (object)"Failed to add enemy into spiderWebBlacklistDictionay");
					Script.Logger.Log((LogLevel)2, (object)spiderWebBlacklist);
					Script.Logger.Log((LogLevel)2, (object)spiderWebBlacklist.Split(":")[0]);
					Script.Logger.Log((LogLevel)2, (object)spiderWebBlacklist.Split(":")[1]);
					Script.Logger.Log((LogLevel)2, (object)ex5);
				}
			}
			foreach (string spiderBlacklist in spiderBlacklistList)
			{
				try
				{
					string text6 = spiderBlacklist.Split(":")[0];
					bool flag5 = bool.Parse(spiderBlacklist.Split(":")[1]);
					if (flag5)
					{
						spiderBlacklistFinal.Add(text6);
					}
					spiderBlacklistDictionay.Add(text6, flag5);
					Script.Logger.Log((LogLevel)32, (object)$"Found {text6}, {flag5}");
				}
				catch (Exception ex6)
				{
					Script.Logger.Log((LogLevel)2, (object)"Failed to add enemy into spiderBlacklistDictionay");
					Script.Logger.Log((LogLevel)2, (object)spiderBlacklist);
					Script.Logger.Log((LogLevel)2, (object)spiderBlacklist.Split(":")[0]);
					Script.Logger.Log((LogLevel)2, (object)spiderBlacklist.Split(":")[1]);
					Script.Logger.Log((LogLevel)2, (object)ex6);
				}
			}
			foreach (string customSizeOverrideList in customSizeOverrideListList)
			{
				try
				{
					string text7 = customSizeOverrideList.Split(":")[0];
					int num2 = int.Parse(customSizeOverrideList.Split(":")[1]);
					if (num2 < 0 || num2 > 5)
					{
						Script.Logger.Log((LogLevel)2, (object)$"Invalid size value {num2}. Defaulting to (0 || {CustomEnemySize.Undefined})");
						num2 = 0;
					}
					customSizeOverrideListDictionary.Add(text7, num2);
					Script.Logger.Log((LogLevel)32, (object)$"Found {text7}, {(CustomEnemySize)num2}");
				}
				catch (Exception ex7)
				{
					Script.Logger.Log((LogLevel)2, (object)"Failed to add enemy into customSizeOverrideListList");
					Script.Logger.Log((LogLevel)2, (object)customSizeOverrideList);
					Script.Logger.Log((LogLevel)2, (object)customSizeOverrideList.Split(":")[0]);
					Script.Logger.Log((LogLevel)2, (object)customSizeOverrideList.Split(":")[1]);
					Script.Logger.Log((LogLevel)2, (object)ex7);
				}
			}
		}

		public static void CheckConfigLists(List<EnemyAI> listOfEnemies)
		{
			//IL_0069: Unknown result type (might be due to invalid IL or missing references)
			//IL_006e: Unknown result type (might be due to invalid IL or missing references)
			//IL_006f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0081: Expected I4, but got Unknown
			foreach (EnemyAI listOfEnemy in listOfEnemies)
			{
				string enemyName;
				try
				{
					enemyName = listOfEnemy.enemyType.enemyName;
				}
				catch
				{
					Script.Logger.Log((LogLevel)4, (object)("Failed to get enemy name from " + ((Object)listOfEnemy).name + ". Adding to list for 2nd attempt."));
					tryFindLater.Add(listOfEnemy);
					continue;
				}
				if (customSizeOverrideListList.Count < 1)
				{
					EnemySize enemySize = listOfEnemy.enemyType.EnemySize;
					switch ((int)enemySize)
					{
					case 0:
						if (!listOfEnemy.enemyType.canDie)
						{
							customSizeOverrideListDictionary[enemyName] = 0;
						}
						else if (listOfEnemy is FlowerSnakeEnemy || listOfEnemy is DoublewingAI || listOfEnemy is RedLocustBees || listOfEnemy is DocileLocustBeesAI || listOfEnemy is ButlerBeesEnemyAI)
						{
							customSizeOverrideListDictionary[enemyName] = 1;
						}
						else if (listOfEnemy.enemyHP <= 3)
						{
							customSizeOverrideListDictionary[enemyName] = 2;
						}
						else if (listOfEnemy.enemyHP <= 15)
						{
							customSizeOverrideListDictionary[enemyName] = 3;
						}
						else if (listOfEnemy.enemyHP <= 30)
						{
							customSizeOverrideListDictionary[enemyName] = 4;
						}
						else if (listOfEnemy.enemyHP > 30)
						{
							customSizeOverrideListDictionary[enemyName] = 5;
						}
						else
						{
							customSizeOverrideListDictionary[enemyName] = 0;
						}
						break;
					case 2:
						customSizeOverrideListDictionary[enemyName] = 3;
						break;
					case 1:
						customSizeOverrideListDictionary[enemyName] = 5;
						break;
					default:
						customSizeOverrideListDictionary[enemyName] = 0;
						break;
					}
				}
				if (!loadedEnemyNamesFromConfig.Contains(enemyName))
				{
					loadedEnemyNamesFromConfig.Add(enemyName);
				}
			}
			foreach (string item in loadedEnemyNamesFromConfig)
			{
				Script.Logger.Log((LogLevel)16, (object)("Checking config entries for enemy: " + item));
				if (!speedModifierDictionay.Keys.Contains(item))
				{
					Script.Logger.Log((LogLevel)32, (object)("Generating new web speed modifier entry for " + item));
					speedModifierDictionay.Add(item, 1f);
				}
				if (!beeBlacklistrDictionay.Keys.Contains(item))
				{
					Script.Logger.Log((LogLevel)32, (object)("Generating new bee blacklist entry for " + item));
					bool value = false;
					if (beeBlacklistrDictionay.Keys.Contains("Earth Leviathan") || beeBlacklistrDictionay.Keys.Contains("Docile Locust Bees"))
					{
						value = true;
					}
					beeBlacklistrDictionay.Add(item, value);
				}
				if (!blobBlacklistDictionay.Keys.Contains(item))
				{
					Script.Logger.Log((LogLevel)32, (object)("Generating new blob blacklist entry for " + item));
					blobBlacklistDictionay.Add(item, value: false);
				}
				if (!sandwormBlacklistDictionay.Keys.Contains(item))
				{
					Script.Logger.Log((LogLevel)32, (object)("Generating new Sandworm blacklist entry for " + item));
					sandwormBlacklistDictionay.Add(item, value: false);
				}
				if (!spiderWebBlacklistDictionay.Keys.Contains(item))
				{
					Script.Logger.Log((LogLevel)32, (object)("Generating new spider web blacklist entry for " + item));
					spiderWebBlacklistDictionay.Add(item, value: false);
				}
				if (!spiderBlacklistDictionay.Keys.Contains(item))
				{
					Script.Logger.Log((LogLevel)32, (object)("Generating new spider blacklist entry for " + item));
					spiderBlacklistDictionay.Add(item, value: false);
				}
				if (!customSizeOverrideListDictionary.Keys.Contains(item))
				{
					Script.Logger.Log((LogLevel)32, (object)("Generating new custom enemy size entry for " + item));
					customSizeOverrideListDictionary.Add(item, 0);
				}
			}
			if (!Script.BoundingConfig.debugBool.Value)
			{
				return;
			}
			foreach (string item2 in beeBlacklistFinal)
			{
				Script.Logger.Log((LogLevel)32, (object)("checking final blacklist beeBlacklistFinal -> " + item2));
			}
			foreach (string item3 in sandwormBlacklistFinal)
			{
				Script.Logger.Log((LogLevel)32, (object)("checking final blacklist sandwormBlacklistFinal -> " + item3));
			}
			foreach (string item4 in spiderWebBlacklistFinal)
			{
				Script.Logger.Log((LogLevel)32, (object)("checking final blacklist spiderWebBlacklistFinal -> " + item4));
			}
			foreach (string item5 in spiderBlacklistFinal)
			{
				Script.Logger.Log((LogLevel)32, (object)("checking final blacklist spiderBlacklistFinal -> " + item5));
			}
			foreach (KeyValuePair<string, float> item6 in speedModifierDictionay)
			{
				Script.Logger.Log((LogLevel)32, (object)string.Format("checking final speed modifier list {0} -> {1}, {2}", "speedModifierDictionay", item6.Key, item6.Value));
			}
		}

		public static void WriteToConfigLists()
		{
			string text = "";
			string text2 = "";
			string text3 = "";
			string text4 = "";
			string text5 = "";
			string text6 = "";
			string text7 = "";
			try
			{
				foreach (KeyValuePair<string, float> item in speedModifierDictionay)
				{
					text = $"{text}{item.Key}:{item.Value},";
				}
				Script.BoundingConfig.speedModifierList.Value = text;
				foreach (KeyValuePair<string, bool> item2 in beeBlacklistrDictionay)
				{
					text2 = $"{text2}{item2.Key}:{item2.Value},";
				}
				Script.BoundingConfig.beeBlacklist.Value = text2;
				foreach (KeyValuePair<string, bool> item3 in blobBlacklistDictionay)
				{
					text3 = $"{text3}{item3.Key}:{item3.Value},";
				}
				Script.BoundingConfig.blobBlacklist.Value = text3;
				foreach (KeyValuePair<string, bool> item4 in sandwormBlacklistDictionay)
				{
					text4 = $"{text4}{item4.Key}:{item4.Value},";
				}
				Script.BoundingConfig.sandwormBlacklist.Value = text4;
				foreach (KeyValuePair<string, bool> item5 in spiderWebBlacklistDictionay)
				{
					text5 = $"{text5}{item5.Key}:{item5.Value},";
				}
				Script.BoundingConfig.spiderWebBlacklist.Value = text5;
				foreach (KeyValuePair<string, bool> item6 in spiderBlacklistDictionay)
				{
					text6 = $"{text6}{item6.Key}:{item6.Value},";
				}
				Script.BoundingConfig.spiderBlacklist.Value = text6;
				foreach (KeyValuePair<string, int> item7 in customSizeOverrideListDictionary)
				{
					text7 = $"{text7}{item7.Key}:{item7.Value},";
				}
				Script.BoundingConfig.customSizeOverrideList.Value = text7;
				Script.Logger.Log((LogLevel)16, (object)"Finished generating configucations.");
			}
			catch (Exception ex)
			{
				Script.Logger.Log((LogLevel)2, (object)"Failed to generate configucations.");
				Script.Logger.Log((LogLevel)2, (object)ex);
			}
		}
	}
	public class LibraryCalls
	{
		private static bool debugSpam = Script.Bools["spammyLogs"];

		private static bool debugTriggerFlag = Script.Bools["debugTriggerFlags"];

		private static bool debugLibraryCalls = Script.Bools["debugLibrary"];

		private static void Event_OnConfigSettingChanged(string entryKey, bool value)
		{
			if (entryKey == "debugTriggerFlags")
			{
				debugTriggerFlag = value;
			}
			if (entryKey == "spammyLogs")
			{
				debugSpam = value;
				NaturalSelectionLib.SetLibraryLoggers(Script.Logger, value, debugLibraryCalls);
			}
			if (entryKey == "debugLibrary")
			{
				debugLibraryCalls = value;
				NaturalSelectionLib.SetLibraryLoggers(Script.Logger, debugSpam, value);
			}
		}

		public static void SubscribeToConfigChanges()
		{
			Script.OnConfigSettingChanged = (Action<string, bool>)Delegate.Combine(Script.OnConfigSettingChanged, new Action<string, bool>(Event_OnConfigSettingChanged));
		}

		public static string DebugStringHead(EnemyAI? instance, bool shortFormat = true)
		{
			if (debugLibraryCalls && debugSpam && debugTriggerFlag)
			{
				Script.Logger.Log((LogLevel)16, (object)"Called library DebugStringHead!");
			}
			return NaturalSelectionLib.DebugStringHead(instance, shortFormat);
		}

		public static List<EnemyAI> GetCompleteList(EnemyAI instance, bool FilterThemselves = true, int includeOrReturnThedDead = 0)
		{
			if (debugLibraryCalls && debugSpam && debugTriggerFlag)
			{
				Script.Logger.Log((LogLevel)16, (object)"Called library GetCompleteList!");
			}
			return NaturalSelectionLib.GetCompleteList(instance, FilterThemselves, includeOrReturnThedDead);
		}

		public static void GetInsideOrOutsideEnemyList(ref List<EnemyAI> importEnemyList, EnemyAI instance)
		{
			if (debugLibraryCalls && debugSpam && debugTriggerFlag)
			{
				Script.Logger.Log((LogLevel)16, (object)"Called library GetInsideOrOutsideEnemyList!");
			}
			NaturalSelectionLib.GetInsideOrOutsideEnemyList(ref importEnemyList, instance);
		}

		public static EnemyAI? FindClosestEnemy(ref List<EnemyAI> importEnemyList, EnemyAI? importClosestEnemy, EnemyAI instance, bool includeTheDead = false)
		{
			if (debugLibraryCalls && debugSpam && debugTriggerFlag)
			{
				Script.Logger.Log((LogLevel)16, (object)"Called library findClosestEnemy!");
			}
			return NaturalSelectionLib.FindClosestEnemy(ref importEnemyList, importClosestEnemy, instance, includeTheDead);
		}

		public static void FilterEnemyList(ref List<EnemyAI> importEnemyList, List<string>? blacklist, EnemyAI instance, bool filterOutImmortal = true, bool filterTheSameType = true)
		{
			if (debugLibraryCalls && debugSpam && debugTriggerFlag)
			{
				Script.Logger.LogInfo((object)"Called library filterEnemyList!");
			}
			if (debugLibraryCalls && debugSpam && debugTriggerFlag)
			{
				Script.Logger.Log((LogLevel)16, (object)"Called library filterEnemyList!");
			}
			NaturalSelectionLib.FilterEnemyList(ref importEnemyList, blacklist, instance, filterOutImmortal, filterTheSameType);
		}

		public static void FilterEnemySizes(ref Dictionary<EnemyAI, int> importEnemySizeDict, int[] enemySizes, EnemyAI instance, bool inverseToggle = false)
		{
			if (debugLibraryCalls && debugSpam && debugTriggerFlag)
			{
				Script.Logger.LogInfo((object)"Called library FilterEnemySizes!");
			}
			if (debugLibraryCalls && debugSpam && debugTriggerFlag)
			{
				Script.Logger.Log((LogLevel)16, (object)"Called library FilterEnemySizes!");
			}
			NaturalSelectionLib.FilterEnemySizes(ref importEnemySizeDict, enemySizes, instance, inverseToggle);
		}

		public static void FilterEnemySizes(ref List<EnemyAI> importEnemySizeDict, EnemySize[] enemySizes, EnemyAI instance, bool inverseToggle = false)
		{
			if (debugLibraryCalls && debugSpam && debugTriggerFlag)
			{
				Script.Logger.LogInfo((object)"Called library FilterEnemySizes!");
			}
			if (debugLibraryCalls && debugSpam && debugTriggerFlag)
			{
				Script.Logger.Log((LogLevel)16, (object)"Called library FilterEnemySizes!");
			}
			NaturalSelectionLib.FilterEnemySizes(ref importEnemySizeDict, enemySizes, instance, inverseToggle);
		}

		public static Dictionary<EnemyAI, float> GetEnemiesInLOS(EnemyAI instance, ref List<EnemyAI> importEnemyList, float width = 45f, int importRange = 0, float proximityAwareness = -1f, float importRadius = 0f, Vector3? importEyePosition = null)
		{
			if (debugLibraryCalls && debugSpam && debugTriggerFlag)
			{
				Script.Logger.Log((LogLevel)16, (object)"Called library GetEnemiesInLOS!");
			}
			return NaturalSelectionLib.GetEnemiesInLOS(instance, ref importEnemyList, width, (float)importRange, proximityAwareness, importRadius, importEyePosition);
		}

		public static Dictionary<EnemyAI, float> GetEnemiesInLOS(EnemyAI instance, float width = 45f, int importRange = 0, float proximityAwareness = -1f, float importRadius = 0f, Vector3? importEyePosition = null)
		{
			if (debugLibraryCalls && debugSpam && debugTriggerFlag)
			{
				Script.Logger.Log((LogLevel)16, (object)"Called library GetEnemiesInLOS!");
			}
			return NaturalSelectionLib.GetEnemiesInLOS(instance, width, (float)importRange, proximityAwareness, importRadius, importEyePosition);
		}
	}
	internal class MyModConfig
	{
		public readonly ConfigEntry<bool> sandwormCollisionOverride;

		public readonly ConfigEntry<bool> blobAICantOpenDoors;

		public readonly ConfigEntry<bool> stableMode;

		public readonly ConfigEntry<bool> IgnoreImmortalEnemies;

		public readonly ConfigEntry<float> agentRadiusModifier;

		public readonly ConfigEntry<float> globalListsUpdateInterval;

		public readonly ConfigEntry<string> customSizeOverrideList;

		public readonly ConfigEntry<bool> enableSpider;

		public readonly ConfigEntry<bool> enableSlime;

		public readonly ConfigEntry<bool> enableLeviathan;

		public readonly ConfigEntry<bool> enableSporeLizard;

		public readonly ConfigEntry<bool> enableRedBees;

		public readonly ConfigEntry<bool> enableNutcracker;

		public readonly ConfigEntry<bool> enableGiant;

		public readonly ConfigEntry<bool> enableHoardingBug;

		public readonly ConfigEntry<float> beesSetGiantsOnFireMinChance;

		public readonly ConfigEntry<float> beesSetGiantsOnFireMaxChance;

		public readonly ConfigEntry<int> giantExtinguishChance;

		public readonly ConfigEntry<bool> blobConsumesCorpses;

		public readonly ConfigEntry<bool> blobPathfindToCorpses;

		public readonly ConfigEntry<bool> blobPathfind;

		public readonly ConfigEntry<bool> sandwormDoNotEatPlayersInsideLeavingShip;

		public readonly ConfigEntry<bool> enableSpiderWebs;

		public readonly ConfigEntry<string> speedModifierList;

		public readonly ConfigEntry<float> webStrength;

		public readonly ConfigEntry<float> chaseAfterEnemiesModifier;

		public readonly ConfigEntry<string> beeBlacklist;

		public readonly ConfigEntry<string> blobBlacklist;

		public readonly ConfigEntry<string> sandwormBlacklist;

		public readonly ConfigEntry<string> spiderWebBlacklist;

		public readonly ConfigEntry<string> spiderBlacklist;

		public ConfigEntry<bool> debugBool;

		public ConfigEntry<bool> spammyLogs;

		public ConfigEntry<bool> debugTriggerFlags;

		public ConfigEntry<bool> debugNetworking;

		public ConfigEntry<bool> debugRedBees;

		public ConfigEntry<bool> debugSandworms;

		public ConfigEntry<bool> debugHygrodere;

		public ConfigEntry<bool> debugNutcrackers;

		public ConfigEntry<bool> debugSpiders;

		public ConfigEntry<bool> debugGiants;

		public ConfigEntry<bool> debugUnspecified;

		public ConfigEntry<bool> debugLibrary;

		public ConfigEntry<bool> debugSpiderWebs;

		public Dictionary<string, ConfigEntry<bool>> debugEntries = new Dictionary<string, ConfigEntry<bool>>();

		public Dictionary<string, ConfigEntry<bool>> CompatibilityEntries = new Dictionary<string, ConfigEntry<bool>>();

		public ConfigEntry<bool> CompatibilityAutoToggle;

		public ConfigEntry<bool> enhancedMonstersCompToggle;

		public ConfigEntry<bool> sellBodiesFixedCompToggle;

		public ConfigEntry<bool> ReXuvinationCompToggle;

		public MyModConfig(ConfigFile cfg)
		{
			//IL_020f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0219: Expected O, but got Unknown
			//IL_0248: Unknown result type (might be due to invalid IL or missing references)
			//IL_0252: Expected O, but got Unknown
			//IL_0281: Unknown result type (might be due to invalid IL or missing references)
			//IL_028b: Expected O, but got Unknown
			cfg.SaveOnConfigSet = false;
			sandwormCollisionOverride = cfg.Bind<bool>("Experimental Fixes", "Sandworm collision override", false, "Override vanilla sandworm collisions. May fix lag when sandworm collides with multiple enemies at once. \n \n May be removed in the future.");
			blobAICantOpenDoors = cfg.Bind<bool>("Experimental Fixes", "Blob cannot open doors", true, "Blob can't open doors.");
			stableMode = cfg.Bind<bool>("General Settings", "Toggle stable mode", true, "When true, the mod will exlude patches that are WIP or are experimental from loading. Requires restart.");
			IgnoreImmortalEnemies = cfg.Bind<bool>("General Settings", "Ignore Immortal Enemies", false, "All immortal enemies will be ignored by majority of entities.");
			agentRadiusModifier = cfg.Bind<float>("General Settings", "Agent radius modifier", 0.5f, "Modifies agent radius of entities for more reliable collisions.");
			globalListsUpdateInterval = cfg.Bind<float>("General Settings", "Global lists update interval", 1f, "Set a period how often are global lists updated. Default is one second.");
			customSizeOverrideList = cfg.Bind<string>("DEV", "Custom size override list", "", "Set what size the enemy is considered as. Generates automatically.");
			enableSpider = cfg.Bind<bool>("Entity settings", "Enable spider", true, "Enable changes to apply to to spider and modify it's behavior.");
			enableSlime = cfg.Bind<bool>("Entity settings", "Enable slime", true, "Enable changes to apply to to slime and modify it's behavior.");
			enableLeviathan = cfg.Bind<bool>("Entity settings", "Enable leviathan", true, "Enable changes to apply to to leviathan and modify it's behavior.");
			enableSporeLizard = cfg.Bind<bool>("DEV", "Enable SporeLizard", false, "Enable changes to apply to to spore lizard. \n\n Early build. DEV ONLY");
			enableRedBees = cfg.Bind<bool>("Entity settings", "Enable Red bees (Circuit bees)", true, "Enable changes to apply to red bees and modify it's behavior.");
			enableNutcracker = cfg.Bind<bool>("DEV", "Enable Nutcracker", false, "Enable changes to nutcracker to apply to and modify its behavior. \n\n Early build. DEV ONLY");
			enableGiant = cfg.Bind<bool>("Entity settings", "Enable Giant", true, "Enable changes to apply to to forest giant.");
			enableHoardingBug = cfg.Bind<bool>("DEV", "Enable Hoarding bug", false, "Enable changes to apply to to hoarding bug");
			enableSpiderWebs = cfg.Bind<bool>("Entity settings", "Enable Spider Webs", true, "Enables changes to apply to to spider webs. Webs will stick to and slow down enemies.");
			giantExtinguishChance = cfg.Bind<int>("Entity settings | Giant", "Extinguish chance", 33, new ConfigDescription("Chance of giants extinguishing themselves in percent.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 100), Array.Empty<object>()));
			beesSetGiantsOnFireMinChance = cfg.Bind<float>("Entity settings | Giant", "Ignite giants min chace", 1.5f, new ConfigDescription("The minimum chance bees will set giant on fire on hit in percent. Applies to calm bees.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 100f), Array.Empty<object>()));
			beesSetGiantsOnFireMaxChance = cfg.Bind<float>("Entity settings | Giant", "Ignite giants max chace", 8f, new ConfigDescription("The minimum chance bees will set giant on fire on hit in percent. Applies to angry bees.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 100f), Array.Empty<object>()));
			blobConsumesCorpses = cfg.Bind<bool>("Entity settings | Hygrodere", "Consume corpses", true, "Hygrodere consume dead enemy corpses.");
			blobPathfindToCorpses = cfg.Bind<bool>("Entity settings | Hygrodere", "Pathfind to corpses", true, "Hygrodere move towards corpses to consume.");
			blobPathfind = cfg.Bind<bool>("Entity settings | Hygrodere", "Pathfind", true, "Pathfind to other entities.");
			sandwormDoNotEatPlayersInsideLeavingShip = cfg.Bind<bool>("Entity settings | Sandworm", "Do not eat players inside leaving ship", false, "Worms do not eat players inside ship leaving moon.");
			chaseAfterEnemiesModifier = cfg.Bind<float>("Entity settings | Spider/Spider Web", "Chase after enemies modifier", 3f, "Modifies chase timer for chasing enemies. When chasing another enemy, hunter's chase timer is divided by set number.");
			speedModifierList = cfg.Bind<string>("Entity settings | Spider/Spider Web", "Web speed modifiers", "", "Modifies final speed of enemy caught in web. \n \n [The ',' acts as a separator between each entry. Entry format: EnemyName:Speed ] \n This config generates automatically.");
			webStrength = cfg.Bind<float>("Entity settings | Spider/Spider Web", "Spider Web Strenght", 1.3f, "Strength of spider webs. Stronger spider web slows enemies more.");
			beeBlacklist = cfg.Bind<string>("Blacklists", "Bees Blacklist", "", "Any enemy with set value to true will be ignored by circuit bees. \n \n [The ',' acts as a separator between each entry. Entry format: EnemyName:True/False] \n This config generates automatically.");
			blobBlacklist = cfg.Bind<string>("Blacklists", "Blob Blacklist", "", "Any enemy with set value to true will be ignored by hygroderes. \n \n [The ',' acts as a separator between each entry. Entry format: EnemyName:True/False ] \n This config generates automatically.");
			sandwormBlacklist = cfg.Bind<string>("Blacklists", "Sandworm Blacklist", "", "Any enemy with set value to true will be ignored by sandworms. \n \n [The ',' acts as a separator between each entry. Entry format: EnemyName:True/False] \n This config generates automatically.");
			spiderWebBlacklist = cfg.Bind<string>("Blacklists", "Web blacklist", "", "Any enemy with set value to true will be ignored by webs. \n \n [The ',' acts as a separator between each entry. Entry format: EnemyName:True/False] \n This config generates automatically.");
			spiderBlacklist = cfg.Bind<string>("Blacklists", "Spider blacklist", "", "Any enemy with set value to true will be ignored by spider. \n \n [The ',' acts as a separator between each entry. Entry format: EnemyName:True/False] \n This config generates automatically.");
			debugBool = cfg.Bind<bool>("Debug", "Debug mode", false, "Enables debug mode for more debug logs. Can be changed at runtime via config mods.");
			debugEntries.Add("debugBool", debugBool);
			spammyLogs = cfg.Bind<bool>("Debug", "Spammy logs", false, "Enables spammy logs for extra logs. Can be changed at runtime via config mods.");
			debugEntries.Add("spammyLogs", spammyLogs);
			debugNetworking = cfg.Bind<bool>("Debug", "Debug networking", false, "Enables debug logs for networking. Can be changed at runtime via config mods.");
			debugEntries.Add("debugNetworking", debugNetworking);
			debugTriggerFlags = cfg.Bind<bool>("Debug", "Trigger flags", false, "Enables logs with trigger flag.");
			debugEntries.Add("debugTriggerFlags", debugTriggerFlags);
			debugUnspecified = cfg.Bind<bool>("Debug", "Log unspecified", false, "Enables logs for unspecified. Can be changed at runtime via config mods.");
			debugEntries.Add("debugUnspecified", debugUnspecified);
			debugLibrary = cfg.Bind<bool>("Debug", "Log library", false, "Enables logs for the library. Can be changed at runtime via config mods.");
			debugEntries.Add("debugLibrary", debugLibrary);
			debugRedBees = cfg.Bind<bool>("Debug", "Log bees", false, "Enables logs for bees. Can be changed at runtime via config mods.");
			debugEntries.Add("debugRedBees", debugRedBees);
			debugSandworms = cfg.Bind<bool>("Debug", "Log sandworms", false, "Enables logs for sandowrms. Can be changed at runtime via config mods.");
			debugEntries.Add("debugSandworms", debugSandworms);
			debugHygrodere = cfg.Bind<bool>("Debug", "Log hydrogere", false, "Enables logs for hydrogere. Can be changed at runtime via config mods.");
			debugEntries.Add("debugHygrodere", debugHygrodere);
			debugNutcrackers = cfg.Bind<bool>("Debug", "Log nutcrackers", false, "Enables logs for nutcrackers. Can be changed at runtime via config mods.");
			debugEntries.Add("debugNutcrackers", debugNutcrackers);
			debugSpiders = cfg.Bind<bool>("Debug", "Log spiders", false, "Enables logs for spiders. Can be changed at runtime via config mods.");
			debugEntries.Add("debugSpiders", debugSpiders);
			debugGiants = cfg.Bind<bool>("Debug", "Log giants", false, "Enables logs for giants. Can be changed at runtime via config mods.");
			debugEntries.Add("debugGiants", debugGiants);
			debugSpiderWebs = cfg.Bind<bool>("Debug", "Log spider webs", false, "Enables logs for spider webs. Can be changed at runtime via config mods.");
			debugEntries.Add("debugSpiderWebs", debugSpiderWebs);
			CompatibilityAutoToggle = cfg.Bind<bool>("Compatibility toggles", "Auto load compatibilities", true, "Automatically load compatibilites for detected mods");
			ReXuvinationCompToggle = cfg.Bind<bool>("Compatibility toggles", "ReXuvination compatibility", false, "Manually toggles compatibility patches for ReXuvination.");
			CompatibilityEntries.Add("XuuXiaolan.ReXuvination", ReXuvinationCompToggle);
			enhancedMonstersCompToggle = cfg.Bind<bool>("Compatibility toggles", "Enhanced monsters compatibility", false, "Manually toggles compatibility patches for Enhanced monsters.");
			CompatibilityEntries.Add("com.velddev.enhancedmonsters", enhancedMonstersCompToggle);
			sellBodiesFixedCompToggle = cfg.Bind<bool>("Compatibility toggles", "Sellbodiesfixed compatibility", false, "Manually toggles compatibility patches for Sellbodiesfixed.");
			CompatibilityEntries.Add("Entity378.sellbodies", sellBodiesFixedCompToggle);
			ClearOrphanedEntries(cfg);
			cfg.Save();
			cfg.SaveOnConfigSet = true;
		}

		public void ClearOrphanedEntries(ConfigFile cfg)
		{
			PropertyInfo propertyInfo = AccessTools.Property(typeof(ConfigFile), "OrphanedEntries");
			Dictionary<ConfigDefinition, string> dictionary = (Dictionary<ConfigDefinition, string>)propertyInfo.GetValue(cfg);
			foreach (KeyValuePair<ConfigDefinition, string> item in dictionary)
			{
				Script.Logger.LogWarning((object)("Found orphaned entry of " + item.Key.Section + ": " + item.Key.Key + ", " + item.Value + ". Make sure your configuration was not altered."));
			}
			dictionary.Clear();
		}
	}
	internal class Networking_New : NetworkBehaviour
	{
	}
	public class Networking
	{
		public static Dictionary<string, Type> NetworkingDictionary = new Dictionary<string, Type>();

		private static bool logNetworking = Script.Bools["debugNetworking"];

		private static void Event_OnConfigSettingChanged(string entryKey, bool value)
		{
			if (entryKey == "debugNetworking")
			{
				logNetworking = value;
			}
		}

		public static void SubscribeToConfigChanges()
		{
			Script.OnConfigSettingChanged = (Action<string, bool>)Delegate.Combine(Script.OnConfigSettingChanged, new Action<string, bool>(Event_OnConfigSettingChanged));
		}

		public static LNetworkVariable<T> NSEnemyNetworkVariable<T>(string NWID)
		{
			if (!NetworkingDictionary.ContainsKey(NWID))
			{
				NetworkingDictionary.Add(NWID, typeof(T));
			}
			return LNetworkVariable<T>.Connect(NWID, default(T), (LNetworkVariableWritePerms)0, (Action<T, T>)null);
		}

		public static LNetworkEvent NSEnemyNetworkEvent(string NWID)
		{
			if (!NetworkingDictionary.ContainsKey(NWID))
			{
				NetworkingDictionary.Add(NWID, typeof(LNetworkEvent));
			}
			return LNetworkEvent.Connect(NWID, (Action<ulong>)null, (Action)null, (Action<ulong>)null);
		}

		public static void ClearSubscribtionsInDictionary()
		{
			foreach (KeyValuePair<string, Type> item in NetworkingDictionary)
			{
				if (item.Value == typeof(LNetworkEvent))
				{
					if (logNetworking)
					{
						Script.Logger.Log((LogLevel)32, (object)("Clearing subscriptions of event " + item.Key));
					}
					LNetworkEvent.Connect(item.Key, (Action<ulong>)null, (Action)null, (Action<ulong>)null).ClearSubscriptions();
					continue;
				}
				if (logNetworking)
				{
					Script.Logger.Log((LogLevel)32, (object)$"Disposing of network {item.Value} {item.Key}");
				}
				if (item.Value == typeof(int))
				{
					LNetworkVariable<int>.Connect(item.Key, 0, (LNetworkVariableWritePerms)0, (Action<int, int>)null).Dispose();
				}
				else if (item.Value == typeof(float))
				{
					LNetworkVariable<float>.Connect(item.Key, 0f, (LNetworkVariableWritePerms)0, (Action<float, float>)null).Dispose();
				}
				else if (item.Value == typeof(bool))
				{
					LNetworkVariable<bool>.Connect(item.Key, false, (LNetworkVariableWritePerms)0, (Action<bool, bool>)null).Dispose();
				}
				else
				{
					Script.Logger.Log((LogLevel)4, (object)$"Unsupported type {item.Value}");
				}
			}
			Script.Logger.Log((LogLevel)16, (object)"/Networking/ Finished clearing dictionary.");
			NetworkingDictionary.Clear();
		}
	}
	internal class NetworkingMethods
	{
		[HarmonyPatch(typeof(GameNetworkManager), "ResetGameValuesToDefault")]
		[HarmonyPostfix]
		private static void ResetGameValuesToDefaultPatch()
		{
			Script.Logger.Log((LogLevel)16, (object)"/Networking-ResetGameValuesToDefault/ Clearing all subscribtions and globalEnemyLists.");
			Networking.ClearSubscribtionsInDictionary();
			NaturalSelectionLib.globalEnemyLists.Clear();
		}

		[HarmonyPatch(typeof(RoundManager), "ResetEnemyVariables")]
		[HarmonyPostfix]
		private static void ResetEnemyVariablesPatch()
		{
			Script.Logger.Log((LogLevel)16, (object)"/Networking-ResetEnemyVariables/ Clearing all subscribtions and globalEnemyLists.");
			Networking.ClearSubscribtionsInDictionary();
			NaturalSelectionLib.globalEnemyLists.Clear();
		}
	}
	[HarmonyPatch(typeof(RoundManager))]
	internal class RoundManagerPatch
	{
		private static float nextUpdate = 0f;

		private static float updateTime = 0f;

		private static Dictionary<Type, List<EnemyAI>> checkedTypes = new Dictionary<Type, List<EnemyAI>>();

		public static float updateListInterval = Script.BoundingConfig.globalListsUpdateInterval.Value;

		private static bool logSpam = Script.Bools["spammyLogs"];

		private static bool logUnspecified = Script.Bools["debugNetworking"];

		public static List<GameObject> deadEnemiesList = new List<GameObject>();

		private static void Event_OnConfigSettingChanged(string entryKey, bool value)
		{
			if (entryKey == "debugNetworking")
			{
				logUnspecified = value;
			}
			if (entryKey == "spammyLogs")
			{
				logSpam = value;
			}
		}

		[HarmonyPatch("Awake")]
		[HarmonyPostfix]
		private static void AwakePostfixPatch()
		{
			Script.OnConfigSettingChanged = (Action<string, bool>)Delegate.Combine(Script.OnConfigSettingChanged, new Action<string, bool>(Event_OnConfigSettingChanged));
		}

		[HarmonyPatch("Update")]
		[HarmonyPrefix]
		private static void UpdatePatch()
		{
			if (!(Time.realtimeSinceStartup >= nextUpdate))
			{
				return;
			}
			foreach (Type item in checkedTypes.Keys.ToList())
			{
				List<EnemyAI> list = checkedTypes[item];
				NaturalSelectionLib.UpdateListInsideDictionrary(item, ref list);
			}
			checkedTypes.Clear();
			nextUpdate = Time.realtimeSinceStartup + updateListInterval;
		}

		public static bool RequestUpdate(EnemyAI instance)
		{
			if (!checkedTypes.ContainsKey(((object)instance).GetType()) && ((NetworkBehaviour)instance).IsOwner)
			{
				checkedTypes.Add(((object)instance).GetType(), new List<EnemyAI>());
				if (logUnspecified && logSpam)
				{
					Script.Logger.Log((LogLevel)8, (object)$"/RoundManager/ request was Accepted. Requested by {LibraryCalls.DebugStringHead(instance)} at {Time.realtimeSinceStartup}");
				}
				return true;
			}
			if (logUnspecified && logSpam && !((NetworkBehaviour)instance).IsOwner)
			{
				Script.Logger.Log((LogLevel)32, (object)"/RoundManager/ request was Denied. Not owner of the instance.");
			}
			else if (logUnspecified && logSpam)
			{
				Script.Logger.Log((LogLevel)32, (object)$"/RoundManager/ request was Denied. Requested by {LibraryCalls.DebugStringHead(instance)} at {Time.realtimeSinceStartup}");
			}
			return false;
		}

		public static void ScheduleGlobalListUpdate(EnemyAI instance, ref List<EnemyAI> list)
		{
			if (checkedTypes.ContainsKey(((object)instance).GetType()))
			{
				checkedTypes[((object)instance).GetType()] = list;
			}
			if (!NaturalSelectionLib.globalEnemyLists.ContainsKey(((object)instance).GetType()))
			{
				List<EnemyAI> list2 = checkedTypes[((object)instance).GetType()];
				Script.Logger.Log((LogLevel)4, (object)(LibraryCalls.DebugStringHead(instance) + "global enemy list for this enemy does not exist! Creating a new one."));
				NaturalSelectionLib.UpdateListInsideDictionrary(((object)instance).GetType(), ref list2);
			}
		}
	}
}
namespace NaturalSelection.EnemyPatches
{
	internal class BeeValues
	{
		internal EnemyAI? closestEnemy;

		internal EnemyAI? targetEnemy;

		internal Vector3 lastKnownEnemyPosition = Vector3.zero;

		internal int customBehaviorStateIndex;

		internal Dictionary<EnemyAI, float> hitRegistry = new Dictionary<EnemyAI, float>();

		internal float LostLOSOfEnemy;

		internal float delayTimer = 0.2f;
	}
	[HarmonyPatch(typeof(RedLocustBees))]
	internal class BeeAIPatch
	{
		private static Dictionary<RedLocustBees, BeeValues> beeList = new Dictionary<RedLocustBees, BeeValues>();

		private static bool logBees = Script.Bools["debugRedBees"];

		private static bool debugSpam = Script.Bools["spammyLogs"];

		private static bool debugTriggers = Script.Bools["debugTriggerFlags"];

		private static List<string> beeBlacklist = InitializeGamePatch.beeBlacklistFinal;

		private static void Event_OnConfigSettingChanged(string entryKey, bool value)
		{
			if (entryKey == "debugRedBees")
			{
				logBees = value;
			}
			if (entryKey == "spammyLogs")
			{
				debugSpam = value;
			}
			if (entryKey == "debugTriggerFlags")
			{
				debugTriggers = value;
			}
		}

		[HarmonyPatch("Start")]
		[HarmonyPostfix]
		private static void StartPatch(RedLocustBees __instance)
		{
			if (!beeList.ContainsKey(__instance))
			{
				Script.Logger.Log((LogLevel)16, (object)("Creating data container for " + LibraryCalls.DebugStringHead((EnemyAI?)(object)__instance)));
				beeList.Add(__instance, new BeeValues());
			}
			BeeValues beeValues = beeList[__instance];
			Script.OnConfigSettingChanged = (Action<string, bool>)Delegate.Combine(Script.OnConfigSettingChanged, new Action<string, bool>(Event_OnConfigSettingChanged));
		}

		[HarmonyPatch("Update")]
		[HarmonyPostfix]
		private static void UpdatePatch(RedLocustBees __instance)
		{
			if (!beeList.ContainsKey(__instance))
			{
				Script.Logger.Log((LogLevel)1, (object)("Critical failule. Failed to get data for " + LibraryCalls.DebugStringHead((EnemyAI?)(object)__instance) + ". Attempting to fix..."));
				beeList.Add(__instance, new BeeValues());
			}
			BeeValues beeValues = beeList[__instance];
			if (RoundManagerPatch.RequestUpdate((EnemyAI)(object)__instance))
			{
				List<EnemyAI> importEnemyList = LibraryCalls.GetCompleteList((EnemyAI)(object)__instance);
				LibraryCalls.FilterEnemyList(ref importEnemyList, beeBlacklist, (EnemyAI)(object)__instance, Script.BoundingConfig.IgnoreImmortalEnemies.Value);
				RoundManagerPatch.ScheduleGlobalListUpdate((EnemyAI)(object)__instance, ref importEnemyList);
			}
			foreach (KeyValuePair<EnemyAI, float> item in new Dictionary<EnemyAI, float>(beeValues.hitRegistry))
			{
				if (item.Value > 1.7f)
				{
					beeValues.hitRegistry.Remove(item.Key);
				}
				else
				{
					beeValues.hitRegistry[item.Key] += Time.deltaTime;
				}
			}
		}

		[HarmonyPatch("DoAIInterval")]
		[HarmonyPrefix]
		private static bool DoAIIntervalPrefixPatch(RedLocustBees __instance)
		{
			//IL_0071: Unknown result type (might be due to invalid IL or missing references)
			CheckDataIntegrityBees(__instance);
			BeeValues beeValues = beeList[__instance];
			if ((Object)(object)beeValues.targetEnemy != (Object)null && !((EnemyAI)__instance).movingTowardsTargetPlayer && beeValues.customBehaviorStateIndex != 0)
			{
				if (logBees && debugSpam && debugTriggers)
				{
					Script.Logger.Log((LogLevel)32, (object)(LibraryCalls.DebugStringHead((EnemyAI?)(object)__instance) + " DoAIInterval: Prefix triggered false"));
				}
				if (((EnemyAI)__instance).moveTowardsDestination)
				{
					((EnemyAI)__instance).agent.SetDestination(((EnemyAI)__instance).destination);
				}
				((EnemyAI)__instance).SyncPositionToClients();
				return false;
			}
			if (logBees && debugSpam && debugTriggers)
			{
				Script.Logger.Log((LogLevel)32, (object)(LibraryCalls.DebugStringHead((EnemyAI?)(object)__instance) + " DoAIInterval: Prefix triggered true"));
			}
			return true;
		}

		[HarmonyPatch("DoAIInterval")]
		[HarmonyPostfix]
		private static void DoAIIntervalPostfixPatch(RedLocustBees __instance)
		{
			//IL_00da: 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_00f3: Unknown result type (might be due to invalid IL or missing references)
			//IL_0268: Unknown result type (might be due to invalid IL or missing references)
			//IL_0278: Unknown result type (might be due to invalid IL or missing references)
			//IL_036d: Unknown result type (might be due to invalid IL or missing references)
			//IL_03f7: Unknown result type (might be due to invalid IL or missing references)
			//IL_03fc: Unknown result type (might be due to invalid IL or missing references)
			//IL_0406: Unknown result type (might be due to invalid IL or missing references)
			//IL_040b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0410: 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_0187: Unknown result type (might be due to invalid IL or missing references)
			//IL_0659: Unknown result type (might be due to invalid IL or missing references)
			//IL_0686: Unknown result type (might be due to invalid IL or missing references)
			//IL_0447: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a9: Unknown result type (might be due to invalid IL or missing references)
			//IL_0794: Unknown result type (might be due to invalid IL or missing references)
			//IL_0799: Unknown result type (might be due to invalid IL or missing references)
			//IL_07a0: Unknown result type (might be due to invalid IL or missing references)
			//IL_04ec: Unknown result type (might be due to invalid IL or missing references)
			//IL_04fc: Unknown result type (might be due to invalid IL or missing references)
			//IL_086f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0833: Unknown result type (might be due to invalid IL or missing references)
			//IL_051a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0563: Unknown result type (might be due to invalid IL or missing references)
			if (((EnemyAI)__instance).isEnemyDead)
			{
				return;
			}
			CheckDataIntegrityBees(__instance);
			BeeValues beeValues = beeList[__instance];
			Type type = ((object)__instance).GetType();
			List<EnemyAI> importEnemyList = NaturalSelectionLib.globalEnemyLists[type];
			LibraryCalls.GetInsideOrOutsideEnemyList(ref importEnemyList, (EnemyAI)(object)__instance);
			Dictionary<EnemyAI, float> enemyDictionary = new Dictionary<EnemyAI, float>(LibraryCalls.GetEnemiesInLOS((EnemyAI)(object)__instance, ref importEnemyList, 360f, 16, 1f));
			switch (((EnemyAI)__instance).currentBehaviourStateIndex)
			{
			case 0:
				if (enemyDictionary.Count > 0)
				{
					beeValues.targetEnemy = enemyDictionary.Keys.First();
					if (logBees)
					{
						Script.Logger.Log((LogLevel)16, (object)(LibraryCalls.DebugStringHead((EnemyAI?)(object)__instance) + " case0: Checked LOS for enemies. Enemy found: " + LibraryCalls.DebugStringHead(beeValues.targetEnemy)));
					}
				}
				if (__instance.wasInChase)
				{
					__instance.wasInChase = false;
				}
				if (Vector3.Distance(((Component)__instance).transform.position, __instance.lastKnownHivePosition) > 2f)
				{
					((EnemyAI)__instance).SetDestinationToPosition(__instance.lastKnownHivePosition, true);
				}
				if (__instance.IsHiveMissing() || (Object)(object)__instance.hive.parentObject != (Object)null)
				{
					((EnemyAI)__instance).SwitchToBehaviourState(2);
					beeValues.customBehaviorStateIndex = 2;
					if (logBees)
					{
						Script.Logger.Log((LogLevel)16, (object)$"{LibraryCalls.DebugStringHead((EnemyAI?)(object)__instance)} case0: HIVE IS MISSING! CustomBehaviorStateIndex changed: {beeValues.customBehaviorStateIndex}");
					}
				}
				else if ((Object)(object)beeValues.targetEnemy != (Object)null && Vector3.Distance(((Component)beeValues.targetEnemy).transform.position, ((Component)__instance.hive).transform.position) < (float)__instance.defenseDistance)
				{
					((EnemyAI)__instance).SetDestinationToPosition(((Component)beeValues.targetEnemy).transform.position, true);
					if (logBees)
					{
						Script.Logger.Log((LogLevel)16, (object)$"{LibraryCalls.DebugStringHead((EnemyAI?)(object)__instance)} case0: Moving towards {beeValues.targetEnemy}");
					}
					beeValues.customBehaviorStateIndex = 1;
					((EnemyAI)__instance).SwitchToBehaviourState(1);
					beeValues.LostLOSOfEnemy = 0f;
					if (logBees)
					{
						Script.Logger.Log((LogLevel)32, (object)$"{LibraryCalls.DebugStringHead((EnemyAI?)(object)__instance)} case0: CustomBehaviorStateIndex changed: {beeValues.customBehaviorStateIndex}");
					}
				}
				break;
			case 1:
				if ((Object)(object)((EnemyAI)__instance).targetPlayer != (Object)null && ((EnemyAI)__instance).movingTowardsTargetPlayer)
				{
					break;
				}
				if ((Object)(object)beeValues.targetEnemy == (Object)null || beeValues.targetEnemy.isEnemyDead || Vector3.Distance(((Component)beeValues.targetEnemy).transform.position, ((Component)__instance.hive).transform.position) > (float)__instance.defenseDistance + 5f)
				{
					beeValues.targetEnemy = null;
					__instance.wasInChase = false;
					if (__instance.IsHiveMissing() || (Object)(object)__instance.hive.parentObject != (Object)null)
					{
						beeValues.customBehaviorStateIndex = 2;
						((EnemyAI)__instance).SwitchToBehaviourState(2);
						if (logBees)
						{
							Script.Logger.Log((LogLevel)16, (object)$"{LibraryCalls.DebugStringHead((EnemyAI?)(object)__instance)} case1: HIVE IS MISSING! CustomBehaviorStateIndex changed: {beeValues.customBehaviorStateIndex}");
						}
					}
					else
					{
						beeValues.customBehaviorStateIndex = 0;
						((EnemyAI)__instance).SwitchToBehaviourState(0);
						if (logBees)
						{
							Script.Logger.Log((LogLevel)32, (object)$"{LibraryCalls.DebugStringHead((EnemyAI?)(object)__instance)} case1: CustomBehaviorStateIndex changed: {beeValues.customBehaviorStateIndex}");
						}
					}
				}
				else if ((Object)(object)__instance.hive.parentObject != (Object)null)
				{
					beeValues.customBehaviorStateIndex = 2;
					((EnemyAI)__instance).SwitchToBehaviourState(2);
				}
				else
				{
					((EnemyAI)__instance).SetDestinationToPosition(((Component)beeValues.targetEnemy).transform.position, true);
				}
				break;
			case 2:
			{
				if ((Object)(object)((EnemyAI)__instance).targetPlayer != (Object)null || ((EnemyAI)__instance).movingTowardsTargetPlayer)
				{
					if (logBees && debugSpam)
					{
						Script.Logger.Log((LogLevel)32, (object)(LibraryCalls.DebugStringHead((EnemyAI?)(object)__instance) + " case2: target player found or moving towards target player"));
					}
					break;
				}
				if (__instance.IsHivePlacedAndInLOS() && !Object.op_Implicit((Object)(object)__instance.hive.parentObject))
				{
					if (__instance.wasInChase)
					{
						__instance.wasInChase = false;
					}
					__instance.lastKnownHivePosition = ((Component)__instance.hive).transform.position + Vector3.up * 0.5f;
					if (logBees)
					{
						Script.Logger.Log((LogLevel)32, (object)(LibraryCalls.DebugStringHead((EnemyAI?)(object)__instance) + " case2: IsHivePlacedAndInLOS triggered"));
					}
					EnemyAI val = null;
					Collider[] array = Physics.OverlapSphere(((Component)__instance.hive).transform.position, (float)__instance.defenseDistance, StartOfRound.Instance.collidersAndRoomMaskAndDefault, (QueryTriggerInteraction)2);
					if (array != null && array.Length != 0)
					{
						for (int i = 0; i < array.Length; i++)
						{
							EnemyAI component = ((Component)array[i]).gameObject.GetComponent<EnemyAI>();
							if ((Object)(object)component != (Object)null && (Object)(object)component != (Object)(object)__instance)
							{
								val = component;
								if (logBees)
								{
									Script.Logger.Log((LogLevel)16, (object)(LibraryCalls.DebugStringHead((EnemyAI?)(object)__instance) + " case2: CollisionArray triggered. Enemy found: " + LibraryCalls.DebugStringHead(val)));
								}
								break;
							}
						}
					}
					if ((Object)(object)val != (Object)null && Vector3.Distance(((Component)val).transform.position, ((Component)__instance.hive).transform.position) < (float)__instance.defenseDistance)
					{
						((EnemyAI)__instance).SetDestinationToPosition(((Component)val).transform.position, true);
						if (logBees)
						{
							Script.Logger.Log((LogLevel)16, (object)$"{LibraryCalls.DebugStringHead((EnemyAI?)(object)__instance)} case2: Moving towards: {val}");
						}
						beeValues.customBehaviorStateIndex = 1;
						((EnemyAI)__instance).SwitchToBehaviourState(1);
						__instance.syncedLastKnownHivePosition = false;
						__instance.SyncLastKnownHivePositionServerRpc(__instance.lastKnownHivePosition);
						beeValues.LostLOSOfEnemy = 0f;
						if (logBees)
						{
							Script.Logger.Log((LogLevel)32, (object)$"{LibraryCalls.DebugStringHead((EnemyAI?)(object)__instance)} case2: CustomBehaviorStateIndex changed: {beeValues.customBehaviorStateIndex}");
						}
					}
					else
					{
						beeValues.customBehaviorStateIndex = 0;
						((EnemyAI)__instance).SwitchToBehaviourState(0);
						if (logBees)
						{
							Script.Logger.Log((LogLevel)32, (object)$"{LibraryCalls.DebugStringHead((EnemyAI?)(object)__instance)} case2: CustomBehaviorStateIndex changed: {beeValues.customBehaviorStateIndex}");
						}
					}
					break;
				}
				bool flag = false;
				EnemyAI val2 = ChaseEnemyWithPriorities(ref enemyDictionary, __instance);
				if (logBees)
				{
					Script.Logger.Log((LogLevel)32, (object)$"{LibraryCalls.DebugStringHead((EnemyAI?)(object)__instance)} case2: {val2} is closest to hive.");
				}
				if ((Object)(object)val2 != (Object)null && (Object)(object)beeValues.targetEnemy != (Object)(object)val2)
				{
					flag = true;
					__instance.wasInChase = false;
					beeValues.targetEnemy = val2;
					((EnemyAI)__instance).SetDestinationToPosition(((Component)beeValues.targetEnemy).transform.position, true);
					((EnemyAI)__instance).StopSearch(__instance.searchForHive, true);
					__instance.syncedLastKnownHivePosition = false;
					beeValues.LostLOSOfEnemy = 0f;
					__instance.SyncLastKnownHivePositionServerRpc(__instance.lastKnownHivePosition);
					if (logBees)
					{
						Script.Logger.Log((LogLevel)16, (object)$"{LibraryCalls.DebugStringHead((EnemyAI?)(object)__instance)} case2: Targeting {val2}. Synced hive position");
					}
					break;
				}
				if ((Object)(object)beeValues.targetEnemy != (Object)null)
				{
					((EnemyAI)__instance).agent.acceleration = 16f;
					if (!flag && enemyDictionary.Count == 0)
					{
						if (logBees && debugSpam)
						{
							Script.Logger.Log((LogLevel)32, (object)$"{LibraryCalls.DebugStringHead((EnemyAI?)(object)__instance)} case2: lost LOS of {beeValues.targetEnemy}, started timer.");
						}
						beeValues.LostLOSOfEnemy += ((EnemyAI)__instance).AIIntervalTime;
						if (beeValues.LostLOSOfEnemy >= 4.5f)
						{
							beeValues.targetEnemy = null;
							beeValues.LostLOSOfEnemy = 0f;
							if (logBees)
							{
								Script.Logger.Log((LogLevel)32, (object)$"{LibraryCalls.DebugStringHead((EnemyAI?)(object)__instance)} case2: lost LOS of {beeValues.targetEnemy}, Stopped and reset timer.");
							}
						}
					}
					else
					{
						__instance.wasInChase = true;
						beeValues.lastKnownEnemyPosition = ((Component)beeValues.targetEnemy).transform.position;
						((EnemyAI)__instance).SetDestinationToPosition(beeValues.lastKnownEnemyPosition, true);
						beeValues.LostLOSOfEnemy = 0f;
						if (logBees)
						{
							Script.Logger.Log((LogLevel)32, (object)$"{LibraryCalls.DebugStringHead((EnemyAI?)(object)__instance)} case2: lost {beeValues.targetEnemy}");
						}
					}
					break;
				}
				((EnemyAI)__instance).agent.acceleration = 13f;
				if (__instance.searchForHive.inProgress)
				{
					break;
				}
				if (logBees)
				{
					Script.Logger.Log((LogLevel)16, (object)(LibraryCalls.DebugStringHead((EnemyAI?)(object)__instance) + " case2: set new search for hive"));
				}
				if (__instance.wasInChase)
				{
					((EnemyAI)__instance).StartSearch(beeValues.lastKnownEnemyPosition, __instance.searchForHive);
					if (logBees)
					{
						Script.Logger.Log((LogLevel)32, (object)(LibraryCalls.DebugStringHead((EnemyAI?)(object)__instance) + " case2: Started search for hive."));
					}
				}
				else
				{
					((EnemyAI)__instance).StartSearch(((Component)__instance).transform.position, __instance.searchForHive);
					if (logBees)
					{
						Script.Logger.Log((LogLevel)32, (object)(LibraryCalls.DebugStringHead((EnemyAI?)(object)__instance) + " case2: Started search for hive."));
					}
				}
				break;
			}
			}
		}

		private static LNetworkVariable<float> NSSetOnFireChance(RedLocustBees instance)
		{
			string nWID = "NSSetOnFireChance" + ((NetworkBehaviour)instance).NetworkObjectId;
			return Networking.NSEnemyNetworkVariable<float>(nWID);
		}

		private static LNetworkVariable<float> NSSetOnFireMaxChance(RedLocustBees instance)
		{
			string nWID = "NSSetOnFireMaxChance" + ((NetworkBehaviour)instance).NetworkObjectId;
			return Networking.NSEnemyNetworkVariable<float>(nWID);
		}

		private static LNetworkEvent NetworkSetGiantOnFire(ForestGiantAI forestGiantAI)
		{
			string nWID = "NSSetGiantOnFire" + ((NetworkBehaviour)forestGiantAI).NetworkObjectId;
			return Networking.NSEnemyNetworkEvent(nWID);
		}

		public static void CheckDataIntegrityBees(RedLocustBees __instance)
		{
			if (!beeList.ContainsKey(__instance))
			{
				Script.Logger.Log((LogLevel)1, (object)("Critical failule. Failed to get data for " + LibraryCalls.DebugStringHead((EnemyAI?)(object)__instance) + ". Attempting to fix..."));
				beeList.Add(__instance, new BeeValues());
			}
		}

		public static void OnCustomEnemyCollision(RedLocustBees __instance, EnemyAI mainscript2)
		{
			//IL_0246: Unknown result type (might be due to invalid IL or missing references)
			//IL_024c: Expected O, but got Unknown
			if (((object)mainscript2).GetType() == typeof(RedLocustBees) || !beeList.ContainsKey(__instance) || beeBlacklist.Contains(mainscript2.enemyType.enemyName) || (((beeList[__instance].hitRegistry.ContainsKey(mainscript2) && !(beeList[__instance].hitRegistry[mainscript2] > 1.7f)) || ((EnemyAI)__instance).currentBehaviourStateIndex <= 0 || mainscript2.isEnemyDead) && ((beeList[__instance].hitRegistry.ContainsKey(mainscript2) && !(beeList[__instance].hitRegistry[mainscript2] > 1.2f)) || ((EnemyAI)__instance).currentBehaviourStateIndex != 2 || mainscript2.isEnemyDead)))
			{
				return;
			}
			mainscript2.HitEnemy(1, (PlayerControllerB)null, true, -1);
			if (!beeList[__instance].hitRegistry.ContainsKey(mainscript2))
			{
				beeList[__instance].hitRegistry.Add(mainscript2, 0f);
			}
			else
			{
				beeList[__instance].hitRegistry[mainscript2] = 0f;
			}
			if (!(mainscript2 is ForestGiantAI) || mainscript2.currentBehaviourStateIndex == 2)
			{
				return;
			}
			if (((NetworkBehaviour)__instance).IsOwner)
			{
				NSSetOnFireChance(__instance).Value = Random.Range(0f, 100f);
				if (((EnemyAI)__instance).currentBehaviourStateIndex != 2)
				{
					NSSetOnFireMaxChance(__instance).Value = Script.BoundingConfig.beesSetGiantsOnFireMinChance.Value;
				}
				else
				{
					NSSetOnFireMaxChance(__instance).Value = Script.BoundingConfig.beesSetGiantsOnFireMaxChance.Value;
				}
				Script.Logger.Log((LogLevel)16, (object)$"{LibraryCalls.DebugStringHead((EnemyAI?)(object)__instance)} OnCustomEnemyCollision: Giant hit. Chance to set on fire: {NSSetOnFireMaxChance(__instance).Value} , rolled {NSSetOnFireChance(__instance)}");
			}
			else if (logBees)
			{
				Script.Logger.Log((LogLevel)8, (object)"Client not elligible to determine chance to set giant on fire");
			}
			if (NSSetOnFireChance(__instance).Value <= NSSetOnFireMaxChance(__instance).Value && ((NetworkBehaviour)__instance).IsOwner)
			{
				Script.Logger.Log((LogLevel)16, (object)$"{LibraryCalls.DebugStringHead((EnemyAI?)(object)__instance)} OnCustomEnemyCollision: SET GIANT ON FIRE! Random number: {NSSetOnFireChance(__instance).Value}");
				ForestGiantAI forestGiantAI = (ForestGiantAI)mainscript2;
				NetworkSetGiantOnFire(forestGiantAI).InvokeServer();
			}
		}

		public static EnemyAI? ChaseEnemyWithPriorities(ref Dictionary<EnemyAI, float> enemyDictionary, RedLocustBees instance)
		{
			//IL_0153: Unknown result type (might be due to invalid IL or missing references)
			//IL_0163: Unknown result type (might be due to invalid IL or missing references)
			//IL_0173: Unknown result type (might be due to invalid IL or missing references)
			//IL_0183: Unknown result type (might be due to invalid IL or missing references)
			EnemyAI val = null;
			if (enemyDictionary.Count < 1)
			{
				return null;
			}
			foreach (KeyValuePair<EnemyAI, float> item in enemyDictionary)
			{
				if ((Object)(object)item.Key == (Object)(object)instance)
				{
					continue;
				}
				IVisibleThreat component = ((Component)item.Key).GetComponent<IVisibleThreat>();
				if (component != null && (Object)(object)component.GetHeldObject() != (Object)null && (Object)(object)component.GetHeldObject() == (Object)(object)instance.hive && !component.IsThreatDead())
				{
					if (debugTriggers)
					{
						Script.Logger.Log((LogLevel)16, (object)("ChaseEnemiesWithPriorities: Returning " + LibraryCalls.DebugStringHead(item.Key) + " |threatComp|"));
					}
					return item.Key;
				}
				if ((Object)(object)instance.hive.parentObject != (Object)null && (Object)(object)((Component)instance.hive.parentObject).gameObject.GetComponentInParent<EnemyAI>() == (Object)(object)item.Key)
				{
					if (debugTriggers)
					{
						Script.Logger.Log((LogLevel)16, (object)("ChaseEnemiesWithPriorities: Returning " + LibraryCalls.DebugStringHead(item.Key) + " |GetComponentInParent|"));
					}
					return item.Key;
				}
				if (instance.IsHivePlacedAndInLOS() && !item.Key.isEnemyDead)
				{
					if ((Object)(object)val == (Object)null)
					{
						val = item.Key;
					}
					else if (Vector3.Distance(((Component)item.Key).transform.position, ((Component)instance.hive).transform.position) < Vector3.Distance(((Component)val).transform.position, ((Component)instance.hive).transform.position))
					{
						val = item.Key;
					}
				}
			}
			if (!Object.op_Implicit((Object)(object)val))
			{
				val = enemyDictionary.Keys.First();
			}
			if (debugTriggers)
			{
				Script.Logger.Log((LogLevel)16, (object)("ChaseEnemiesWithPriorities: Returning " + LibraryCalls.DebugStringHead(val) + " |returnEnemy|"));
			}
			return val;
		}
	}
	internal class BlobData
	{
		internal EnemyAI? closestEnemy;

		internal bool playSound;

		internal Dictionary<EnemyAI, float> hitRegistry = new Dictionary<EnemyAI, float>();
	}
	[HarmonyPatch(typeof(BlobAI))]
	internal class BlobAIPatch
	{
		private static Dictionary<BlobAI, BlobData> slimeList = new Dictionary<BlobAI, BlobData>();

		private static bool logBlob = Script.Bools["debugHygrodere"];

		private static bool triggerFlag = Script.Bools["debugTriggerFlags"];

		private static List<string> blobBlacklist = InitializeGamePatch.blobBlacklistFinal;

		private static LNetworkEvent BlobEatCorpseEvent(BlobAI instance)
		{
			string nWID = "NSSlimeEatEvent" + ((NetworkBehaviour)instance).NetworkObjectId;
			return Networking.NSEnemyNetworkEvent(nWID);
		}

		private static void Event_OnConfigSettingChanged(string entryKey, bool value)
		{
			if (entryKey == "debugHygrodere")
			{
				logBlob = value;
			}
			if (entryKey == "debugTriggerFlags")
			{
				triggerFlag = value;
			}
		}

		[HarmonyPatch("Start")]
		[HarmonyPrefix]
		private static void StartPatch(BlobAI __instance)
		{
			if (!slimeList.ContainsKey(__instance))
			{
				Script.Logger.Log((LogLevel)16, (object)("Creating data container for " + LibraryCalls.DebugStringHead((EnemyAI?)(object)__instance)));
				slimeList.Add(__instance, new BlobData());
			}
			if (Script.BoundingConfig.blobAICantOpenDoors.Value)
			{
				((EnemyAI)__instance).openDoorSpeedMultiplier = 0f;
			}
			BlobData blobData = slimeList[__instance];
			BlobEatCorpseEvent(__instance).OnClientReceived += EventReceived;
			Script.OnConfigSettingChanged = (Action<string, bool>)Delegate.Combine(Script.OnConfigSettingChanged, new Action<string, bool>(Event_OnConfigSettingChanged));
			void EventReceived()
			{
				blobData.playSound = true;
			}
		}

		[HarmonyPatch("DoAIInterval")]
		[HarmonyPrefix]
		private static bool DoAIIntervalPrefixPatch(BlobAI __instance)
		{
			//IL_0199: 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_00fe: Unknown result type (might be due to invalid IL or missing references)
			//IL_0116: 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_013c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0147: Unknown result type (might be due to invalid IL or missing references)
			//IL_015f: Unknown result type (might be due to invalid IL or missing references)
			//IL_016a: 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_006e: Unknown result type (might be due to invalid IL or missing references)
			//IL_007e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0089: 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_01eb: Unknown result type (might be due to invalid IL or missing references)
			//IL_0272: 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_0218: Unknown result type (might be due to invalid IL or missing references)
			//IL_0254: Unknown result type (might be due to invalid IL or missing references)
			//IL_023a: Unknown result type (might be due to invalid IL or missing references)
			if (((EnemyAI)__instance).isEnemyDead)
			{
				return true;
			}
			CheckDataIntegrityBlob(__instance);
			BlobData blobData = slimeList[__instance];
			if (Script.BoundingConfig.blobPathfind.Value)
			{
				GameObject val = null;
				if (RoundManagerPatch.deadEnemiesList.Count > 0)
				{
					foreach (GameObject deadEnemies in RoundManagerPatch.deadEnemiesList)
					{
						if ((Object)(object)val == (Object)null || Vector3.Distance(val.transform.position, ((Component)__instance).transform.position) > Vector3.Distance(deadEnemies.transform.position, ((Component)__instance).transform.position))
						{
							val = deadEnemies;
						}
					}
				}
				if (((Object)(object)((EnemyAI)__instance).GetClosestPlayer(false, false, false) != (Object)null && (!((EnemyAI)__instance).PlayerIsTargetable(((EnemyAI)__instance).GetClosestPlayer(false, false, false), false, false) || ((Object)(object)blobData.closestEnemy != (Object)null && Vector3.Distance(((Component)blobData.closestEnemy).transform.position, ((Component)__instance).transform.position) < Vector3.Distance(((Component)((EnemyAI)__instance).GetClosestPlayer(false, false, false)).transform.position, ((Component)__instance).transform.position)) || ((Object)(object)val != (Object)null && Vector3.Distance(val.transform.position, ((Component)__instance).transform.position) < Vector3.Distance(((Component)((EnemyAI)__instance).GetClosestPlayer(false, false, false)).transform.position, ((Component)__instance).transform.position)))) || (Object)(object)((EnemyAI)__instance).GetClosestPlayer(false, false, false) == (Object)null)
				{
					if (((EnemyAI)__instance).moveTowardsDestination)
					{
						((EnemyAI)__instance).agent.SetDestination(((EnemyAI)__instance).destination);
					}
					((EnemyAI)__instance).SyncPositionToClients();
					if (__instance.searchForPlayers.inProgress)
					{
						((EnemyAI)__instance).StopSearch(__instance.searchForPlayers, true);
					}
					if ((Object)(object)blobData.closestEnemy != (Object)null)
					{
						float num = Vector3.Distance(((Component)blobData.closestEnemy).transform.position, ((Component)__instance).transform.position);
						float num2 = 0f;
						if ((Object)(object)val != (Object)null)
						{
							num2 = Vector3.Distance(val.transform.position, ((Component)__instance).transform.position);
						}
						if ((Object)(object)val != (Object)null && num > num2)
						{
							((EnemyAI)__instance).SetDestinationToPosition(val.transform.position, true);
						}
						else
						{
							((EnemyAI)__instance).SetDestinationToPosition(((Component)blobData.closestEnemy).transform.position, true);
						}
					}
					else if ((Object)(object)val != (Object)null)
					{
						((EnemyAI)__instance).SetDestinationToPosition(val.transform.position, true);
					}
					return false;
				}
			}
			return true;
		}

		[HarmonyPatch("Update")]
		[HarmonyPrefix]
		private static void BlobUpdatePatch(BlobAI __instance)
		{
			if (((EnemyAI)__instance).isEnemyDead)
			{
				return;
			}
			CheckDataIntegrityBlob(__instance);
			BlobData blobData = slimeList[__instance];
			Type type = ((object)__instance).GetType();
			foreach (KeyValuePair<EnemyAI, float> item in new Dictionary<EnemyAI, float>(blobData.hitRegistry))
			{
				if (item.Value > 1.5f)
				{
					blobData.hitRegistry.Remove(item.Key);
				}
				else
				{
					blobData.hitRegistry[item.Key] += Time.deltaTime;
				}
			}
			if (RoundManagerPatch.RequestUpdate((EnemyAI)(object)__instance))
			{
				List<EnemyAI> importEnemyList = LibraryCalls.GetCompleteList((EnemyAI)(object)__instance, FilterThemselves: true, 1);
				LibraryCalls.FilterEnemyList(ref importEnemyList, blobBlacklist, (EnemyAI)(object)__instance);
				RoundManagerPatch.ScheduleGlobalListUpdate((EnemyAI)(object)__instance, ref importEnemyList);
			}
			if (((NetworkBehaviour)__instance).IsOwner)
			{
				List<EnemyAI> importEnemyList2 = NaturalSelectionLib.globalEnemyLists[type];
				LibraryCalls.GetInsideOrOutsideEnemyList(ref importEnemyList2, (EnemyAI)(object)__instance);
				blobData.closestEnemy = LibraryCalls.FindClosestEnemy(ref importEnemyList2, blobData.closestEnemy, (EnemyAI)(object)__instance, Script.BoundingConfig.blobPathfindToCorpses.Value);
			}
			if (blobData.playSound)
			{
				Script.Logger.Log((LogLevel)8, (object)("Playing sound. NetworkObjectID: " + ((NetworkBehaviour)__instance).NetworkObjectId));
				((EnemyAI)__instance).creatureVoice.PlayOneShot(__instance.killPlayerSFX);
				blobData.playSound = false;
			}
		}

		public static void CheckDataIntegrityBlob(BlobAI __instance)
		{
			if (!slimeList.ContainsKey(__instance))
			{
				Script.Logger.Log((LogLevel)1, (object)("Critical failule. Failed to get data for " + LibraryCalls.DebugStringHead((EnemyAI?)(object)__instance) + ". Attempting to fix..."));
				slimeList.Add(__instance, new BlobData());
			}
		}

		public static void OnCustomEnemyCollision(BlobAI __instance, EnemyAI mainscript2)
		{
			//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)
			CheckDataIntegrityBlob(__instance);
			BlobData blobData = slimeList[__instance];
			if (blobData.hitRegistry.ContainsKey(mainscript2) || blobBlacklist.Contains(mainscript2.enemyType.enemyName))
			{
				return;
			}
			if (mainscript2.isEnemyDead && !IsEnemyImmortal.EnemyIsImmortal(mainscript2) && Vector3.Distance(((Component)__instance).transform.position, ((Component)mainscript2).transform.position) <= 2.8f && Script.BoundingConfig.blobConsumesCorpses.Value)
			{
				if (((NetworkBehaviour)__instance).IsOwner && mainscript2.thisNetworkObject.IsSpawned)
				{
					BlobEatCorpseEvent(__instance).InvokeClients();
					Script.Logger.Log((LogLevel)8, (object)"Send event");
					mainscript2.thisNetworkObject.Despawn(true);
				}
			}
			else
			{
				if (mainscript2.isEnemyDead || mainscript2 is NutcrackerEnemyAI || mainscript2 is CaveDwellerAI)
				{
					return;
				}
				blobData.hitRegistry.Add(mainscript2, 0f);
				if (mainscript2 is FlowermanAI)
				{
					FlowermanAI val = (FlowermanAI)(object)((mainscript2 is FlowermanAI) ? mainscript2 : null);
					if ((Object)(object)val != (Object)null)
					{
						float angerMeter = val.angerMeter;
						bool isInAngerMode = val.isInAngerMode;
						((EnemyAI)val).HitEnemy(1, (PlayerControllerB)null, true, -1);
						if (mainscript2.enemyHP <= 0)
						{
							mainscript2.KillEnemyOnOwnerClient(false);
						}
						((EnemyAI)val).targetPlayer = null;
						((EnemyAI)val).movingTowardsTargetPlayer = false;
						val.isInAngerMode = false;
						val.angerMeter = angerMeter;
						val.isInAngerMode = isInAngerMode;
						return;
					}
				}
				if (mainscript2 is HoarderBugAI)
				{
					HoarderBugAI val2 = (HoarderBugAI)(object)((mainscript2 is HoarderBugAI) ? mainscript2 : null);
					if ((Object)(object)val2 != (Object)null)
					{
						HoarderBugPatch.CustomOnHit(1, (EnemyAI)(object)__instance, playHitSFX: false, val2);
						if (mainscript2.enemyHP <= 0)
						{
							mainscript2.KillEnemyOnOwnerClient(false);
						}
					}
				}
				else
				{
					mainscript2.HitEnemy(1, (PlayerControllerB)null, true, -1);
					if (mainscript2.enemyHP <= 0)
					{
						mainscript2.KillEnemyOnOwnerClient(false);
					}
				}
			}
		}

		public static void OnEnemyCorpseCollision(BlobAI __instance, GameObject corpse)
		{
			NetworkObject component = corpse.GetComponent<NetworkObject>();
			if (((NetworkBehaviour)__instance).IsOwner && component.IsSpawned)
			{
				BlobEatCorpseEvent(__instance).InvokeClients();
				Script.Logger.Log((LogLevel)8, (object)"Send event 2");
				component.Despawn(true);
			}
		}
	}
	internal class OnCollideWithUniversal
	{
		private class EnemyCollisionData
		{
			internal bool subscribed;
		}

		private static bool enableSpider = Script.BoundingConfig.enableSpider.Value;

		private static bool enableSlime = Script.BoundingConfig.enableSlime.Value;

		private static bool enableBees = Script.BoundingConfig.enableRedBees.Value;

		private static bool logUnspecified = Script.Bools["debugUnspecified"];

		private static bool triggerFlag = Script.Bools["debugTriggerFlags"];

		private static bool debugSpam = Script.Bools["spammyLogs"];

		private static void Event_OnConfigSettingChanged()
		{
			logUnspecified = Script.Bools["debugUnspecified"];
			debugSpam = Script.Bools["spammyLogs"];
			triggerFlag = Script.Bools["debugTriggerFlags"];
		}

		public static void Collide(string text, EnemyAI? mainscript, EnemyAI? mainscript2, GameObject? gameObject = null)
		{
			//IL_0098: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a3: Expected O, but got Unknown
			//IL_00ce: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d9: Expected O, but got Unknown
			//IL_00f2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fd: Expected O, but got Unknown
			//IL_0116: Unknown result type (might be due to invalid IL or missing references)
			//IL_0121: Expected O, but got Unknown
			if (logUnspecified && debugSpam && triggerFlag)
			{
				Script.Logger.Log((LogLevel)32, (object)(LibraryCalls.DebugStringHead(mainscript) + " hit collider of " + LibraryCalls.DebugStringHead(mainscript2) + " Tag: " + text));
			}
			if ((Object)(object)mainscript != (Object)null)
			{
				_ = text == "Player";
			}
			if ((Object)(object)mainscript != (Object)null && text == "Corpse" && mainscript is BlobAI && enableSlime && (Object)(object)gameObject != (Object)null)
			{
				BlobAIPatch.OnEnemyCorpseCollision((BlobAI)mainscript, gameObject);
			}
			if ((Object)(object)mainscript != (Object)null && (Object)(object)mainscript2 != (Object)null)
			{
				if (mainscript is SandSpiderAI && (Object)(object)mainscript2 != (Object)null && enableSpider)
				{
					SandSpiderAIPatch.OnCustomEnemyCollision((SandSpiderAI)mainscript, mainscript2);
				}
				if (mainscript is BlobAI && (Object)(object)mainscript2 != (Object)null && enableSlime)
				{
					BlobAIPatch.OnCustomEnemyCollision((BlobAI)mainscript, mainscript2);
				}
				if (mainscript is RedLocustBees && (Object)(object)mainscript2 != (Object)null && enableBees)
				{
					BeeAIPatch.OnCustomEnemyCollision((RedLocustBees)mainscript, mainscript2);
				}
			}
		}
	}
	[HarmonyPatch(typeof(EnemyAICollisionDetect))]
	public class AICollisionDetectPatch
	{
		[HarmonyPatch("OnTriggerStay")]
		[HarmonyPrefix]
		private static bool OnTriggerStayPrefix(Collider other, EnemyAICollisionDetect __instance)
		{
			if ((Object)(object)other == (Object)null)
			{
				Script.Logger.Log((LogLevel)2, (object)(LibraryCalls.DebugStringHead(__instance.mainScript) + " Collider is null! Using original function..."));
				return true;
			}
			EnemyAICollisionDetect component = ((Component)other).gameObject.GetComponent<EnemyAICollisionDetect>();
			if ((Object)(object)__instance != (Object)null)
			{
				EnemyAI val = null;
				DeadBodyTrackerScript component2 = ((Component)other).GetComponent<DeadBodyTrackerScript>();
				if ((Object)(object)component2 != (Object)null)
				{
					if (Script.Bools["spammyLogs"] && Script.Bools["debugTriggerFlags"])
					{
						Script.Logger.LogInfo((object)"Collided with corpse");
					}
					OnCollideWithUniversal.Collide("Corpse", __instance.mainScript, null, ((Component)component2).gameObject);
				}
				if (((Component)other).CompareTag("Player") && !__instance.mainScript.isEnemyDead)
				{
					OnCollideWithUniversal.Collide("Player", null, null);
					return true;
				}
				if ((Object)(object)component != (Object)null)
				{
					val = ((!((Object)(object)component?.mainScript == (Object)null)) ? ((Component)other).gameObject.GetComponentInParent<EnemyAI>() : component?.mainScript);
					if (((Component)other).CompareTag("Enemy") && (Object)(object)val != (Object)null && (Object)(object)val != (Object)(object)__instance.mainScript && !IsEnemyImmortal.EnemyIsImmortal(val) && !__instance.mainScript.isEnemyDead)
					{
						OnCollideWithUniversal.Collide("Enemy", __instance.mainScript, val);
						return true;
					}
				}
			}
			return true;
		}
	}
	public class IsEnemyImmortal
	{
		public static bool EnemyIsImmortal(EnemyAI instance)
		{
			if (instance is NutcrackerEnemyAI && instance.currentBehaviourStateIndex == 0)
			{
				return true;
			}
			if (instance is JesterAI)
			{
				return true;
			}
			if (instance is BlobAI)
			{
				return true;
			}
			if (instance is SpringManAI)
			{
				return true;
			}
			if (instance is SandWormAI)
			{
				return true;
			}
			if (instance is ButlerBeesEnemyAI)
			{
				return true;
			}
			return false;
		}
	}
	public enum CustomEnemySize
	{
		Undefined,
		Tiny,
		Small,
		Medium,
		Large,
		Giant
	}
	internal class EnemyData
	{
		internal float originalAgentRadius;

		internal Dictionary<Type, int> targetedByEnemies = new Dictionary<Type, int>();

		public CustomEnemySize customEnemySize = CustomEnemySize.Small;
	}
	[HarmonyPatch(typeof(EnemyAI))]
	internal class EnemyAIPatch
	{
		private static bool debugUnspecified = Script.Bools["debugUnspecified"];

		private static bool debugTriggerFlags = Script.Bools["debugTriggerFlags"];

		internal static Dictionary<EnemyAI, EnemyData> enemyData = new Dictionary<EnemyAI, EnemyData>();

		private static void Event_OnConfigSettingChanged(string entryKey, bool value)
		{
			if (entryKey == "debugUnspecified")
			{
				debugUnspecified = value;
			}
			if (entryKey == "debugTriggerFlags")
			{
				debugTriggerFlags = value;
			}
		}

		[HarmonyPatch("Start")]
		[HarmonyPostfix]
		private static void StartPostfix(EnemyAI __instance)
		{
			if (!EnemyAIPatch.enemyData.ContainsKey(__instance))
			{
				Script.Logger.Log((LogLevel)16, (object)("Creating data container for " + LibraryCalls.DebugStringHead(__instance)));
				EnemyAIPatch.enemyData.Add(__instance, new EnemyData());
			}
			EnemyData enemyData = EnemyAIPatch.enemyData[__instance];
			enemyData.originalAgentRadius = __instance.agent.radius;
			if (InitializeGamePatch.customSizeOverrideListDictionary.ContainsKey(__instance.enemyType.enemyName))
			{
				enemyData.customEnemySize = (CustomEnemySize)InitializeGamePatch.customSizeOverrideListDictionary[__instance.enemyType.enemyName];
			}
			Script.Logger.Log((LogLevel)32, (object)$"Final size: {enemyData.customEnemySize}");
			__instance.agent.radius = __instance.agent.radius * Script.BoundingConfig.agentRadiusModifier.Value;
			if (debugUnspecified && debugTriggerFlags)
			{
				Script.Logger.Log((LogLevel)8, (object)$"Modified agent radius. Original: {EnemyAIPatch.enemyData[__instance].originalAgentRadius}, Modified: {__instance.agent.radius}");
			}
			Script.OnConfigSettingChanged = (Action<string, bool>)Delegate.Combine(Script.OnConfigSettingChanged, new Action<string, bool>(Event_OnConfigSettingChanged));
		}

		public static int ReactToHit(int force = 0, EnemyAI? enemyAI = null, PlayerControllerB? player = null)
		{
			if (force > 0)
			{
				return 1;
			}
			if (force > 1)
			{
				return 2;
			}
			return 0;
		}

		[HarmonyPatch("HitEnemy")]
		[HarmonyPostfix]
		public static void HitEnemyPatch(EnemyAI __instance, int force, PlayerControllerB playerWhoHit, bool playHitSFX, int hitID)
		{
			string text = "unknown";
			if ((Object)(object)playerWhoHit != (Object)null)
			{
				text = $"{playerWhoHit.playerUsername}(SteamID: {playerWhoHit.playerSteamId}, playerClientID: {playerWhoHit.playerClientId})";
			}
			if (debugTriggerFlags)
			{
				Script.Logger.Log((LogLevel)16, (object)$"{LibraryCalls.DebugStringHead(__instance)} registered hit by {text} with force of {force}. playHitSFX:{playHitSFX}, hitID:{hitID}.");
			}
		}
	}
	public class ReversePatchAI
	{
		public static Action<EnemyAI> originalUpdate;

		static ReversePatchAI()
		{
			MethodInfo meth = AccessTools.Method(typeof(EnemyAI), "Update", (Type[])null, (Type[])null);
			DynamicMethod dynamicMethod = new DynamicMethod("Base.Update", null, new Type[1] { typeof(EnemyAI) }, typeof(EnemyAI));
			ILGenerator iLGenerator = dynamicMethod.GetILGenerator();
			iLGenerator.Emit(OpCodes.Ldarg_0);
			iLGenerator.Emit(OpCodes.Call, meth);
			iLGenerator.Emit(OpCodes.Ret);
			originalUpdate = (Action<EnemyAI>)dynamicMethod.CreateDelegate(typeof(Action<EnemyAI>));
		}
	}
	internal class GiantData
	{
		internal int extinguished;

		internal bool setFireOnKill;

		internal float CachedNetworkOwnerPostfixResult;
	}
	[HarmonyPatch(typeof(ForestGiantAI))]
	internal class ForestGiantPatch
	{
		private static Dictionary<ForestGiantAI, GiantData> giantDictionary = new Dictionary<ForestGiantAI, GiantData>();

		private static bool logGiant = Script.Bools["debugGiants"];

		private static bool debugSpam = Script.Bools["spammyLogs"];

		private static LNetworkEvent NetworkSetGiantOnFire(ForestGiantAI forestGiantAI)
		{
			string nWID = "NSSetGiantOnFire" + ((NetworkBehaviour)forestGiantAI).NetworkObjectId;
			return Networking.NSEnemyNetworkEvent(nWID);
		}

		internal static LNetworkEvent NetworkExtinguish(ForestGiantAI forestGiantAI)
		{
			string nWID = "NSExtinguish" + ((NetworkBehaviour)forestGiantAI).NetworkObjectId;
			return Networking.NSEnemyNetworkEvent(nWID);
		}

		private static LNetworkVariable<float> NetworkOwnerPostfixResult(ForestGiantAI forestGiantAI)
		{
			string nWID = "NSOwnerrealtimeSinceStartup" + ((NetworkBehaviour)forestGiantAI).NetworkObjectId;
			return Networking.NSEnemyNetworkVariable<float>(nWID);
		}

		private static void Event_OnConfigSettingChanged(string entryKey, bool value)
		{
			if (entryKey == "debugGiants")
			{
				logGiant = value;
			}
			if (entryKey == "spammyLogs")
			{
				debugSpam = value;
			}
		}

		[HarmonyPatch("Start")]
		[HarmonyPostfix]
		private static void startPostfix(ForestGiantAI __instance)
		{
			ForestGiantAI __instance2 = __instance;
			if (!giantDictionary.ContainsKey(__instance2))
			{
				Script.Logger.Log((LogLevel)16, (object)("Creating data container for " + LibraryCalls.DebugStringHead((EnemyAI?)(object)__instance2)));
				giantDictionary.Add(__instance2, new GiantData());
			}
			GiantData data = giantDictionary[__instance2];
			NetworkSetGiantOnFire(__instance2).OnServerReceived += UpdateSetGiantOnFireServer;
			NetworkExtinguish(__instance2).OnClientReceived += ExtuinguishGiant;
			NetworkOwnerPostfixResult(__instance2).OnValueChanged += OwnerPostfixResult;
			Script.OnConfigSettingChanged = (Action<string, bool>)Delegate.Combine(Script.OnConfigSettingChanged, new Action<string, bool>(Event_OnConfigSettingChanged));
			void ExtuinguishGiant()
			{
				((EnemyAI)__instance2).SwitchToBehaviourState(0);
				__instance2.burningParticlesContainer.SetActive(false);
				__instance2.giantBurningAudio.Stop();
				((EnemyAI)__instance2).creatureAnimator.SetBool("burning", false);
				data.extinguished = 1;
			}
			void OwnerPostfixResult(float oldValue, float newValue)
			{
				if (oldValue != newValue)
				{
					data.CachedNetworkOwnerPostfixResult = newValue;
				}
			}
			void UpdateSetGiantOnFireServer(ulong client)
			{
				if (((NetworkBehaviour)__instance2).IsOwner)
				{
					__instance2.timeAtStartOfBurning = Time.realtimeSinceStartup;
					((EnemyAI)__instance2).SwitchToBehaviourState(2);
					Script.Logger.Log((LogLevel)16, (object)"Received UpdateSetGiantOnFire event");
				}
			}
		}

		[HarmonyPatch("KillEnemy")]
		[HarmonyPostfix]
		private static void KillEnemyPatchPostfix(ForestGiantAI __instance)
		{
			CheckDataIntegrityGiant(__instance);
			GiantData giantData = giantDictionary[__instance];
			if (giantData.extinguished != 1 && ((EnemyAI)__instance).currentBehaviourStateIndex == 2)
			{
				__instance.burningParticlesContainer.SetActive(true);
			}
			if (logGiant)
			{
				Script.Logger.Log((LogLevel)16, (object)LibraryCalls.DebugStringHead((EnemyAI?)(object)__instance));
			}
		}

		[HarmonyPatch("Update")]
		[HarmonyPrefix]
		private static bool UpdatePrefix(ForestGiantAI __instance)
		{
			CheckDataIntegrityGiant(__instance);
			GiantData giantData = giantDictionary[__instance];
			if (((EnemyAI)__instance).currentBehaviourStateIndex == 2 && Time.realtimeSinceStartup - __instance.timeAtStartOfBurning > 9.5f && ((EnemyAI)__instance).enemyHP > 20 && giantData.extinguished == 0 && !((EnemyAI)__instance).isEnemyDead && ((NetworkBehaviour)__instance).IsOwner)
			{
				int num = Random.Range(0, 100);
				if (num <= Script.BoundingConfig.giantExtinguishChance.Value)
				{
					NetworkExtinguish(__instance).InvokeClients();
					Script.Logger.Log((LogLevel)16, (object)$"{LibraryCalls.DebugStringHead((EnemyAI?)(object)__instance)} successfully extinguished itself. Skipping Update. Rolled {num}");
				}
				else
				{
					Script.Logger.Log((LogLevel)16, (object)$"{LibraryCalls.DebugStringHead((EnemyAI?)(object)__instance)} failed to extinguish itself. rolled {num}");
					giantData.extinguished = 2;
				}
			}
			if (giantData.extinguished == 1)
			{
				((EnemyAI)__instance).enemyHP = ((EnemyAI)__instance).enemyHP - 20;
				giantData.extinguished = 2;
				return false;
			}
			return true;
		}

		[HarmonyPatch("Update")]
		[HarmonyPostfix]
		private static void UpdatePostfix(ForestGiantAI __instance)
		{
			CheckDataIntegrityGiant(__instance);
			GiantData giantData = giantDictionary[__instance];
			if (((NetworkBehaviour)__instance).IsOwner)
			{
				giantData.CachedNetworkOwnerPostfixResult = Time.realtimeSinceStartup - __instance.timeAtStartOfBurning;
			}
			if (((EnemyAI)__instance).isEnemyDead && ((EnemyAI)__instance).currentBehaviourStateIndex == 2 && giantData.CachedNetworkOwnerPostfixResult < 20f)
			{
				if (((NetworkBehaviour)__instance).IsOwner)
				{
					giantData.CachedNetworkOwnerPostfixResult = Time.realtimeSinceStartup - __ins