Decompiled source of ZenRaids v0.7.2

plugins/ZenRaids.dll

Decompiled 2 weeks ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Security.Permissions;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Configuration;
using HarmonyLib;
using Jotunn.Utils;
using Microsoft.CodeAnalysis;
using UnityEngine;
using UnityEngine.SceneManagement;
using Zen;
using Zen.Lib;
using Zen.Lib.Config;
using ZenRaids.Compatibility;
using ZenRaids.SpawnProtect;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: AssemblyTitle("ZenRaids")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("ZenRaids")]
[assembly: AssemblyCopyright("Copyright \ufffd  2021")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
[assembly: Guid("e3243d22-4307-4008-ba36-9f326008cde5")]
[assembly: AssemblyFileVersion("0.0.1.0")]
[assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("0.0.1.0")]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

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

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

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

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace ZenRaids
{
	[BepInPlugin("ZenDragon.ZenRaids", "ZenRaids", "0.7.2")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[NetworkCompatibility(/*Could not decode attribute arguments.*/)]
	internal class Plugin : ZenMod<Plugin>
	{
		public const string PluginName = "ZenRaids";

		public const string PluginVersion = "0.7.2";

		public const string PluginGUID = "ZenDragon.ZenRaids";

		protected override void Setup()
		{
			((ZenMod)this).RunOnServer = true;
			base.PrefabsRegistered += LitArea.SetPrefabObjects;
			RaidRules.SetupConsole();
		}

		protected override void TitleScene(bool isFirstBoot)
		{
		}

		protected override void WorldStart()
		{
			RaidRules.Init();
			Farming.Check();
		}

		protected override void Shutdown()
		{
		}

		protected override void HotRestore()
		{
			LitArea.SetPrefabObjects();
		}
	}
	[HarmonyPatch]
	internal static class RaidRules
	{
		private static class Configs
		{
			public static readonly ConfigEntry<StringList> NeverActivatedRaids;

			public static readonly ConfigEntry<StringList> NeverDeactivatedRaids;

			public static readonly ConfigEntry<bool> IgnoreConditionKnownItems;

			public static readonly ConfigEntry<Biome> NoRaidBiomes;

			public static readonly ConfigEntry<StringList> NoRaidBiomesExceptions;

			public static readonly ConfigEntry<int> MinPlayerCount;

			public static readonly ConfigEntry<bool> AppendGlobalKeysToPlayerKeys;

			public static readonly ConfigEntry<StringList> AllowedBiomes;

			public static readonly ConfigEntry<StringList> GlobalKeysActivate;

			public static readonly ConfigEntry<StringList> GlobalKeysDeactivate;

			public static readonly ConfigEntry<StringList> PlayerKeysActivateAll;

			public static readonly ConfigEntry<StringList> PlayerKeysActivateAny;

			public static readonly ConfigEntry<StringList> PlayerKeysDeactivate;

			public static readonly ConfigEntry<StringList> PlayerKnownItemsActivate;

			public static readonly ConfigEntry<StringList> PlayerKnownItemsDeactivate;

			static Configs()
			{
				//IL_0049: Unknown result type (might be due to invalid IL or missing references)
				//IL_004e: Unknown result type (might be due to invalid IL or missing references)
				//IL_0059: Expected O, but got Unknown
				//IL_0063: Expected O, but got Unknown
				//IL_0187: Unknown result type (might be due to invalid IL or missing references)
				//IL_018c: Unknown result type (might be due to invalid IL or missing references)
				//IL_0197: Expected O, but got Unknown
				//IL_0197: Unknown result type (might be due to invalid IL or missing references)
				//IL_01a2: Expected O, but got Unknown
				//IL_01a2: Unknown result type (might be due to invalid IL or missing references)
				//IL_01ad: Expected O, but got Unknown
				//IL_01ad: Unknown result type (might be due to invalid IL or missing references)
				//IL_01b8: Expected O, but got Unknown
				//IL_01b8: Unknown result type (might be due to invalid IL or missing references)
				//IL_01c3: Expected O, but got Unknown
				//IL_01cd: Expected O, but got Unknown
				//IL_01dd: Unknown result type (might be due to invalid IL or missing references)
				//IL_01e2: Unknown result type (might be due to invalid IL or missing references)
				//IL_01ed: Expected O, but got Unknown
				//IL_01ed: Unknown result type (might be due to invalid IL or missing references)
				//IL_01f8: Expected O, but got Unknown
				//IL_0202: Expected O, but got Unknown
				MinPlayerCount = Config.Define<int>(true, "Raids General", "Min Player Count", 1, Config.AcceptRange<int>(1, 10), "Minimum number of players required to be online to trigger a raid.");
				NoRaidBiomes = Config.Define<Biome>(true, "Raids General", "No Raid Biomes", (Biome)1, "No Raids allowed in these biomes");
				StringList val = new StringList();
				((List<string>)val).Add("army_eikthyr");
				NoRaidBiomesExceptions = Config.Define<StringList>(true, "Raids General", "No Raid Biomes Exeption Raids", val, "These raids are allowed even in NoRaidBiomes. Comma separated list of raid names.");
				IgnoreConditionKnownItems = Config.Define<bool>(true, "Raids General", "Ignore Condition - Known Items", true, "For per player events: Ignore item knowledge as a raid condition. (Vanilla: false)\r\nIn vanilla, knowledge of specific items flags you for raids based on that knowledge. \r\nIf this option is true then it doesn't matter what items you know, per player raids will only be based on player keys.\r\nThis prevents accidentally getting flagged by just picking up the wrong item.\r\n[restart required for changes to take effect]");
				NeverActivatedRaids = Config.Define<StringList>(true, "Raids General", "Never Activated Raids", StringList.Empty, "Comma separated list of raid names.\r\nThese raids have their activate condition removed so they are never in rotation to be triggered.\r\n[restart required for changes to take effect]");
				NeverDeactivatedRaids = Config.Define<StringList>(true, "Raids General", "Never Deactivated Raids", StringList.Empty, "Comma separated list of raid names.\r\nOnce activated, these raids have their disable condition removed so they are always in rotation to be triggered.\r\n[restart required for changes to take effect]");
				AppendGlobalKeysToPlayerKeys = Config.Define<bool>(true, "Raid Keys", "Append Global Keys To Player Keys", true, "Append any global keys to the player keys list for triggering a raid.\r\nThis can be useful when using modded content that did not consider raid to be per player progression.\r\n[restart required for changes to take effect]");
				AllowedBiomes = Config.Define<StringList>(true, "Raid Keys", "Allowed Biomes", StringList.Empty, "Comma separated list of raidname and biomes it is allowed to spawn in.\r\nSyntax: raidname:biome1|biome2|biome3, raidname:NONE, raidname:ALL, etc...\r\nSpecify NONE to disable all biomes for a given raid.\r\nSpecifiy ALL to allow all biomes for a given raid.\r\nPossible biomes: " + GeneralExtensions.Join<string>((IEnumerable<string>)Enum.GetNames(typeof(Biome)), (Func<string, string>)null, ", ") + "\r\nIf raid name is not defined then vanilla values are used for that raid instead.\r\nConsole command: Zen_RaidRules to view current raid conditions.\r\n[restart required for changes to take effect]");
				GlobalKeysActivate = Config.Define<StringList>(true, "Raid Keys", "Global Keys - Activate", StringList.Empty, "Set global keys to activate raids.\r\nComma separated list of raid name and keys separated by vertical bar.\r\nSyntax: raidname:key1|key2|key3, raidname:key1|key2, raidname:NONE, etc...\r\nSpecify NONE to clear all global keys for a given raid.\r\nIf raid name is not defined then vanilla values are used for that raid instead.\r\nConsole command: Zen_RaidRules to view current raid conditions.\r\n[restart required for changes to take effect]");
				GlobalKeysDeactivate = Config.Define<StringList>(true, "Raid Keys", "Global Keys - Deactivate", StringList.Empty, "Set global keys to deactivate raids.\r\nComma separated list of raid name and keys separated by vertical bar.\r\nSyntax: raidname:key1|key2|key3, raidname:key1|key2, raidname:NONE, etc...\r\nSpecify NONE to clear all global keys for a given raid.\r\nIf raid name is not defined then vanilla values are used for that raid instead.\r\nConsole command: Zen_RaidRules to view current raid conditions.\r\n[restart required for changes to take effect]");
				PlayerKeysActivateAll = Config.Define<StringList>(true, "Raid Keys", "Player Keys All - Activate", StringList.Empty, "PlayerEvents: player key to enable a raid, ALL keys must be set.\r\nComma separated list of raid name and keys separated by vertical bar.\r\nSyntax: raidname:key1|key2|key3, raidname:key1|key2, raidname:NONE, etc...\r\nSpecify NONE to clear the player keys for a given raid.\r\nIf raid name is not defined then vanilla values are used for that raid instead.\r\nConsole command: Zen_RaidRules to view current raid conditions.\r\n[restart required for changes to take effect]");
				StringList val2 = new StringList();
				((List<string>)val2).Add("army_charred:GP_Queen");
				((List<string>)val2).Add("army_charredspawners:GP_Queen");
				((List<string>)val2).Add("army_goblin:GP_Moder");
				((List<string>)val2).Add("army_moder:GP_Bonemass");
				((List<string>)val2).Add("army_gjall:GP_Yagluth");
				PlayerKeysActivateAny = Config.Define<StringList>(true, "Raid Keys", "Player Keys Any - Activate", val2, "PlayerEvents: player key to activate a raid, ANY key must be set.\r\nComma separated list of raid name and keys separated by vertical bar.\r\nSyntax: raidname:key1|key2|key3, raidname:key1|key2, raidname:NONE, etc...\r\nSpecify NONE to clear the player keys for a given raid.\r\nIf raid name is not defined then vanilla values are used for that raid instead.\r\nConsole command: Zen_RaidRules to view current raid conditions.\r\n[restart required for changes to take effect]");
				StringList val3 = new StringList();
				((List<string>)val3).Add("army_charred:GP_Fader");
				((List<string>)val3).Add("army_charredspawners:GP_Fader");
				PlayerKeysDeactivate = Config.Define<StringList>(true, "Raid Keys", "Player Keys - Deactivate", val3, "PlayerEvents: player key to disable a raid, ALL conditions must be true.\r\nComma separated list of raid name and keys separated by vertical bar.\r\nSyntax: raidname:key1|key2|key3, raidname:key1|key2, raidname:NONE, etc...\r\nSpecify NONE to clear all player keys for a given raid.\r\nIf raid name is not defined then vanilla values are used for that raid instead.\r\nConsole command: Zen_RaidRules to view current raid conditions.\r\n[restart required for changes to take effect]");
				PlayerKnownItemsActivate = Config.Define<StringList>(true, "Raid Keys", "Player Known Items - Activate", StringList.Empty, "PlayerEvents: known items that will trigger the raid.\r\nComma separated list of raid name and item prefab names separated by vertical bar.\r\nSyntax: raidname:prefab1|prefab2|prefab3, raidname:prefab1|prefab2, raidname:NONE, etc...\r\nSpecify NONE to clear all required known items for a given raid.\r\nIf raid name is not defined then vanilla values are used for that raid instead.\r\nConsole command: Zen_RaidRules to view current raid conditions.\r\n[restart required for changes to take effect]");
				PlayerKnownItemsDeactivate = Config.Define<StringList>(true, "Raid Keys", "Player Known Items - Deactivate", StringList.Empty, "PlayerEvents: known items that will disable the raid.\r\nComma separated list of raid name and item prefab names separated by vertical bar.\r\nSyntax: raidname:prefab1|prefab2|prefab3, raidname:prefab1|prefab2, raidname:NONE, etc...\r\nSpecify NONE to clear all required not-known items for a given raid.\r\nIf raid name is not defined then vanilla values are used for that raid instead.\r\nConsole command: Zen_RaidRules to view current raid conditions.\r\n[restart required for changes to take effect]");
			}
		}

		public const string ConsoleCmd = "RaidRules";

		private static void CmdRaidRules(string[] args)
		{
			if (!Object.op_Implicit((Object)(object)RandEventSystem.instance))
			{
				Console.instance.Print("RandEventSystem not initialized");
				return;
			}
			string text = ((args.Length > 1) ? args[1] : null);
			foreach (RandomEvent @event in RandEventSystem.instance.m_events)
			{
				if (text == null)
				{
					if (@event.m_name.StartsWith("boss_"))
					{
						continue;
					}
				}
				else if (text.ToLower() != "all" && @event.m_name != text)
				{
					continue;
				}
				string text2 = "=======================================================\r\nRaid: " + @event.m_name + "\r\n- Global Keys Activate: " + GeneralExtensions.Join<string>((IEnumerable<string>)@event.m_requiredGlobalKeys, (Func<string, string>)null, ", ") + "\r\n- Global Keys Deactivate: " + GeneralExtensions.Join<string>((IEnumerable<string>)@event.m_notRequiredGlobalKeys, (Func<string, string>)null, ", ") + "\r\n- Player Keys All Activate: " + GeneralExtensions.Join<string>((IEnumerable<string>)@event.m_altRequiredPlayerKeysAll, (Func<string, string>)null, ", ") + "\r\n- Player Keys Any Activate: " + GeneralExtensions.Join<string>((IEnumerable<string>)@event.m_altRequiredPlayerKeysAny, (Func<string, string>)null, ", ") + "\r\n- Player Keys Deactivate: " + GeneralExtensions.Join<string>((IEnumerable<string>)@event.m_altNotRequiredPlayerKeys, (Func<string, string>)null, ", ") + "\r\n- Known Items Activate: " + GeneralExtensions.Join<ItemDrop>((IEnumerable<ItemDrop>)@event.m_altRequiredKnownItems, (Func<ItemDrop, string>)((ItemDrop i) => ItemDataExt.GetPrefabName(i)), ", ") + "\r\n- Known Items Deactivate: " + GeneralExtensions.Join<ItemDrop>((IEnumerable<ItemDrop>)@event.m_altRequiredNotKnownItems, (Func<ItemDrop, string>)((ItemDrop i) => ItemDataExt.GetPrefabName(i)), ", ");
				Console.instance.Print(text2);
				if (Logging<Plugin>.IsEnabled)
				{
					Logging<Plugin>.Message((object)text2, 0);
				}
			}
		}

		internal static void SetupConsole()
		{
			ZenMod<Plugin>.Terminal.CreateCommand("RaidRules", "Print the current raid conditions for all or a single raid.", true, (Action<string[]>)CmdRaidRules);
		}

		internal static void Init()
		{
			foreach (RandomEvent raid in RandEventSystem.instance.m_events)
			{
				Logging<Plugin>.Info((object)("Set configs for raid " + raid.m_name), 0);
				SetConfigKeys(raid);
				SetAllowedBiomes(raid);
				if (Configs.AppendGlobalKeysToPlayerKeys.Value)
				{
					IEnumerable<string> collection = raid.m_requiredGlobalKeys.Where((string key) => !raid.m_altRequiredPlayerKeysAll.Contains(key));
					raid.m_altRequiredPlayerKeysAll.AddRange(collection);
					IEnumerable<string> collection2 = raid.m_notRequiredGlobalKeys.Where((string key) => !raid.m_altNotRequiredPlayerKeys.Contains(key));
					raid.m_altNotRequiredPlayerKeys.AddRange(collection2);
				}
				if (Configs.IgnoreConditionKnownItems.Value)
				{
					raid.m_altRequiredKnownItems.Clear();
					raid.m_altRequiredNotKnownItems.Clear();
				}
				if (Configs.NeverActivatedRaids.Value.Contains(raid.m_name, true))
				{
					SuppressRaid(raid);
				}
				if (Configs.NeverDeactivatedRaids.Value.Contains(raid.m_name, true))
				{
					KeepRaidForever(raid);
				}
			}
		}

		private static void SetAllowedBiomes(RandomEvent raid)
		{
			//IL_0099: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c2: Unknown result type (might be due to invalid IL or missing references)
			//IL_0129: Unknown result type (might be due to invalid IL or missing references)
			//IL_012e: Unknown result type (might be due to invalid IL or missing references)
			RandomEvent raid2 = raid;
			foreach (KeyValuePair<string, string> item in from kvp in Configs.AllowedBiomes.Value.ToDictionary(':')
				where kvp.Key == raid2.m_name
				select kvp)
			{
				Logging<Plugin>.Info((object)(raid2.m_name + " allowed biomes: " + item.Value), 0);
				if (item.Value.ToUpper() == "ALL")
				{
					raid2.m_biome = (Biome)895;
					continue;
				}
				if (item.Value.ToUpper() == "NONE")
				{
					raid2.m_biome = (Biome)0;
					continue;
				}
				raid2.m_biome = ((IEnumerable<string>)item.Value.Split(new char[1] { '|' })).Select((Func<string, Biome>)((string biome) => (Biome)Enum.Parse(typeof(Biome), biome.Trim()))).Aggregate((Biome a, Biome b) => (Biome)(a | b));
			}
		}

		private static void SetConfigKeys(RandomEvent raid)
		{
			RandomEvent raid2 = raid;
			SetKeys<string>(Configs.GlobalKeysActivate, raid2.m_requiredGlobalKeys);
			SetKeys<string>(Configs.GlobalKeysDeactivate, raid2.m_notRequiredGlobalKeys);
			SetKeys<string>(Configs.PlayerKeysActivateAll, raid2.m_altRequiredPlayerKeysAll);
			SetKeys<string>(Configs.PlayerKeysActivateAny, raid2.m_altRequiredPlayerKeysAny);
			SetKeys<string>(Configs.PlayerKeysDeactivate, raid2.m_altNotRequiredPlayerKeys);
			SetKeys<ItemDrop>(Configs.PlayerKnownItemsActivate, raid2.m_altRequiredKnownItems);
			SetKeys<ItemDrop>(Configs.PlayerKnownItemsDeactivate, raid2.m_altRequiredNotKnownItems);
			void SetKeys<T>(ConfigEntry<StringList> config, List<T> list) where T : notnull
			{
				foreach (KeyValuePair<string, string> item in from kvp in config.Value.ToDictionary(':')
					where kvp.Key == raid2.m_name
					select kvp)
				{
					Logging<Plugin>.Info((object)(((ConfigEntryBase)config).Definition.Key + " " + item.Key + " = " + item.Value), 0);
					list.Clear();
					if (!(item.Value.ToUpper() == "NONE"))
					{
						if (list is List<string> list2)
						{
							list2.AddRange(item.Value.Split(new char[1] { '|' }));
						}
						else if (list is List<ItemDrop> list3)
						{
							IEnumerable<ItemDrop> source = item.Value.Split(new char[1] { '|' }).Select(delegate(string prefabName)
							{
								GameObject itemPrefab = ObjectDB.instance.GetItemPrefab(prefabName);
								return (itemPrefab == null) ? null : itemPrefab.GetComponent<ItemDrop>();
							});
							list3.AddRange(source.Where((ItemDrop item) => (Object)(object)item != (Object)null));
						}
					}
				}
			}
		}

		private static void KeepRaidForever(RandomEvent raid)
		{
			raid.m_notRequiredGlobalKeys.Clear();
			raid.m_altNotRequiredPlayerKeys.Clear();
			raid.m_altRequiredNotKnownItems.Clear();
		}

		private static void SuppressRaid(RandomEvent raid)
		{
			raid.m_requiredGlobalKeys.Clear();
			raid.m_altRequiredPlayerKeysAll.Clear();
			raid.m_altRequiredPlayerKeysAny.Clear();
			raid.m_altRequiredKnownItems.Clear();
		}

		[HarmonyPrefix]
		[HarmonyPatch(typeof(RandEventSystem), "StartRandomEvent")]
		private static void RandEventSystem_StartRandomEvent(ref bool __runOriginal)
		{
			int nrOfPlayers = ZNet.instance.GetNrOfPlayers();
			int value = Configs.MinPlayerCount.Value;
			__runOriginal = nrOfPlayers >= value;
			if (!__runOriginal)
			{
				Logging<Plugin>.Message((object)$"Not enough players online for raid. Min player count: {value}, currently online: {nrOfPlayers}", 0);
			}
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(RandEventSystem), "InValidBiome")]
		private static void RandEventSystem_InValidBiome(RandEventSystem __instance, RandomEvent ev, Vector3 point, ref bool __result)
		{
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_000b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_001b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0067: Unknown result type (might be due to invalid IL or missing references)
			Biome biome = WorldGenerator.instance.GetBiome(point);
			if (((Enum)Configs.NoRaidBiomes.Value).HasFlag((Enum)(object)biome))
			{
				if (Configs.NoRaidBiomesExceptions.Value.Contains(ev.m_name, true))
				{
					Logging<Plugin>.Message((object)("Exception, raid " + ev.m_name + " allowed in Value"), 0);
					return;
				}
				Logging<Plugin>.Message((object)string.Format("{0} {1} suppressed raid: {2}", "NoRaidBiomes", biome, ev.m_name), 0);
				__result = false;
			}
		}
	}
}
namespace ZenRaids.SpawnProtect
{
	internal static class Configs
	{
		public static readonly ConfigEntry<bool> FireMustBeLit;

		public static readonly ConfigEntry<bool> InteractViewPerimeter;

		public static readonly ConfigEntry<float> LightRangePercent;

		public static readonly ConfigEntry<int> PlayerBaseRaidThreshold;

		public static readonly ConfigEntry<StringList> OverrideMaxFuel;

		public const int VanillaBaseCount = 3;

		internal static readonly Dictionary<string, float> OverrideRange;

		static Configs()
		{
			//IL_012f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0134: Unknown result type (might be due to invalid IL or missing references)
			//IL_013f: Expected O, but got Unknown
			//IL_0162: Expected O, but got Unknown
			OverrideRange = new Dictionary<string, float>
			{
				{ "piece_walltorch", 12f },
				{ "piece_brazierfloor01", 15f },
				{ "piece_brazierfloor02", 15f },
				{ "piece_brazierceiling01", 15f },
				{ "piece_groundtorch_green", 15f },
				{ "piece_groundtorch_blue", 15f }
			};
			FireMustBeLit = Config.Define<bool>(true, "Spawn Protection", "Fire Must Be Lit", true, "Workbenches and other objects will no longer protect against monster spawns. (Vanilla: false)\r\nInstead sources of fire (Fireplaces/Torches) must be lit for spawn protection. \r\nIf this is off then vanilla behavior applies.\r\nNOTE: See the detailed explanation in the readme or on thunderstore.\r\n[logout required for changes to take effect]");
			InteractViewPerimeter = Config.Define<bool>(true, "Spawn Protection", "Interact Show Perimeter", true, "Players can interact with fire sources to see the perimeter of the light's protection.\r\n[logout required for changes to take effect]");
			LightRangePercent = Config.Define<float>(true, "Spawn Protection", "Light Range Percent", 1f, Config.AcceptRange<float>(0f, 3f), "When \"" + ((ConfigEntryBase)FireMustBeLit).Definition.Key + "\" is enabled this adjusts the light radius size to use for spawn protection.\r\nNote: Setting this to 0 will disable all spawn protection.\r\n[logout requried for changes to take effect]");
			PlayerBaseRaidThreshold = Config.Define<int>(true, "Spawn Protection", "Raid Threshold", 3, Config.AcceptRange<int>(1, 100), $"Number of base pieces the player needs to be near to trigger raids. (Vanilla = {3})\r\nWhen {((ConfigEntryBase)FireMustBeLit).Definition.Key} is enabled it removes spawn protection from vanilla pieces.\r\nTherefor it reduces the number of pieces in proximity to the player that can trigger raids. \r\nHigher numbers would reduce the odds of triggering a raid because you are less likely to be near so many.\r\nHowever, Keep in mind that a lit light source counts as both spawn protection and towards your raid threshold.\r\nTherefor you have two options.\r\n1. Put lights everywhere to keep the monsters from spawning in your base.\r\n2. Have a dimly lit castle and reduce the chance of raids but increase the chance of random spawns inside your base.\r\nCandles are a good example of a dimly lit castle.");
			StringList val = new StringList();
			((List<string>)val).Add("piece_walltorch:4");
			OverrideMaxFuel = Config.Define<StringList>(true, "Spawn Protection", "Fuel Override", val, "When \"" + ((ConfigEntryBase)FireMustBeLit).Definition.Key + "\" is enabled overrides the prefab max fuel for the specified light sources.\r\nComma separated list of prefab names and max fuel values.\r\nNOTE: The Sconce is reduced from vanilla (6) because: \r\nit burns at half the rate of a wood torch, it protects more area than a wood torch, \r\nit costs less bronze than a brazier, it produces no smoke, and it's immune to rain.\r\n[logout requried for changes to take effect]");
		}
	}
	internal static class Extensions
	{
		internal static bool TryGetTorch(this Player? player, out ItemData torch)
		{
			torch = null;
			if (!Object.op_Implicit((Object)(object)player))
			{
				return false;
			}
			ItemData val = ((IEnumerable<ItemData>)((Humanoid)player).GetInventory().GetAllItems()).FirstOrDefault((Func<ItemData, bool>)((ItemData item) => ItemDataExt.IsItemType(item, (ItemType)15)));
			if (val == null)
			{
				return false;
			}
			torch = val;
			return true;
		}

		internal static bool IsTorchHeld(this Player? player)
		{
			if (!Object.op_Implicit((Object)(object)player))
			{
				return false;
			}
			ItemData rightItem = ((Humanoid)player).RightItem;
			if (rightItem == null || !ItemDataExt.IsItemType(rightItem, (ItemType)15))
			{
				ItemData leftItem = ((Humanoid)player).LeftItem;
				if (leftItem == null)
				{
					return false;
				}
				return ItemDataExt.IsItemType(leftItem, (ItemType)15);
			}
			return true;
		}

		internal static bool TryEquipTorch(this Player? player)
		{
			if (!Object.op_Implicit((Object)(object)player))
			{
				return false;
			}
			Logging<Plugin>.Info((object)"Trying to equip torch", 0);
			if (player.TryGetTorch(out ItemData torch))
			{
				Logging<Plugin>.Info((object)("Torch found in inventory " + ItemDataExt.GetPrefabName(torch)), 0);
				if (!torch.m_equipped)
				{
					((Humanoid)player).ToggleEquipped(torch);
				}
				return true;
			}
			Logging<Plugin>.Info((object)"Torch not found in inventory", 0);
			return false;
		}

		public static bool IsPlacementGhost(this Fireplace fireplace)
		{
			return Player.IsPlacementGhost(((Component)fireplace).gameObject);
		}

		public static bool IsLit(this Fireplace fireplace)
		{
			GameObject enabledObject = fireplace.GetEnabledObject();
			bool flag = Object.op_Implicit((Object)(object)enabledObject) && enabledObject.activeInHierarchy;
			bool flag2 = GameObjectExt.GetPrefabName(((Component)fireplace).gameObject) == "bonfire";
			if (fireplace.IsBurning())
			{
				return flag || flag2;
			}
			return false;
		}

		public static GameObject? GetEnabledObject(this Fireplace fireplace)
		{
			if (Object.op_Implicit((Object)(object)fireplace.m_enabledObjectHigh))
			{
				return fireplace.m_enabledObjectHigh;
			}
			if (Object.op_Implicit((Object)(object)fireplace.m_enabledObject))
			{
				return fireplace.m_enabledObject;
			}
			return null;
		}
	}
	[HarmonyPatch]
	public class LitArea : MonoBehaviour
	{
		private static GameObject _prefabAreaMarker;

		private static GameObject _prefabPulse;

		private Fireplace _fireplace;

		private GameObject _litArea;

		private GameObject _litPulse;

		private float _lastActivated;

		private const float Delay = 0.5f;

		private const string LitAreaName = "LitAreaMarker";

		public bool IsVisible
		{
			get
			{
				return _litArea.activeSelf;
			}
			set
			{
				_litArea.SetActive(value || Time.time < _lastActivated + 0.5f);
				_litPulse.SetActive(_litArea.activeSelf);
				if (value)
				{
					_lastActivated = Time.time;
				}
			}
		}

		internal static Action? SetPrefabObjects()
		{
			_prefabAreaMarker = ((Component)ZNetScene.instance.GetPrefab("piece_workbench").transform.Find("AreaMarker")).gameObject;
			_prefabPulse = ((Component)ZNetScene.instance.GetPrefab("guard_stone").transform.Find("WayEffect/pulse (2)")).gameObject;
			return null;
		}

		private void Awake()
		{
			//IL_0060: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f9: Unknown result type (might be due to invalid IL or missing references)
			_fireplace = ((Component)this).GetComponent<Fireplace>();
			_litArea = Object.Instantiate<GameObject>(_prefabAreaMarker, ((Component)this).transform, false);
			((Object)_litArea).name = "LitAreaMarker";
			_litArea.SetActive(false);
			((Component)_litArea.GetComponentInChildren<ParticleSystem>()).gameObject.SetActive(false);
			_litArea.transform.localPosition = Vector3.zero;
			_litPulse = Object.Instantiate<GameObject>(_prefabPulse, ((Component)this).transform, false);
			((Object)_litPulse).name = "LitAreaMarker_Pulse";
			_litPulse.SetActive(false);
			_litPulse.transform.localPosition = Vector3.zero;
			GameObject obj = Object.Instantiate<GameObject>(((Component)_prefabPulse.transform.parent.Find("sfx")).gameObject, _litPulse.transform, false);
			((Object)obj).name = "LitAreaMarker_SFX";
			obj.SetActive(true);
			obj.transform.localPosition = Vector3.zero;
			AudioSource component = obj.GetComponent<AudioSource>();
			component.minDistance = 0f;
			component.maxDistance = 30f;
			component.pitch = 1.7f;
		}

		public void Init(float lightRange)
		{
			//IL_0034: Unknown result type (might be due to invalid IL or missing references)
			//IL_0039: Unknown result type (might be due to invalid IL or missing references)
			//IL_0065: Unknown result type (might be due to invalid IL or missing references)
			//IL_006a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0076: Unknown result type (might be due to invalid IL or missing references)
			//IL_0084: Unknown result type (might be due to invalid IL or missing references)
			lightRange *= Configs.LightRangePercent.Value;
			Logging<Plugin>.Info((object)$"Light Radius: {lightRange:F2} - {GameObjectExt.GetPrefabName(((Component)_fireplace).gameObject)} {MathExt.XZY(((Component)_fireplace).transform.position)}", 0);
			_litArea.GetComponent<CircleProjector>().m_radius = lightRange;
			Vector3 lossyScale = ((Component)this).transform.lossyScale;
			_litPulse.transform.localScale = Vector3.one * (lightRange / ((Vector3)(ref lossyScale)).magnitude);
			if (_fireplace.IsPlacementGhost())
			{
				return;
			}
			Collider collider = _fireplace.m_playerBaseObject.GetComponent<EffectArea>().m_collider;
			SphereCollider val = (SphereCollider)(object)((collider is SphereCollider) ? collider : null);
			if (val == null)
			{
				CapsuleCollider val2 = (CapsuleCollider)(object)((collider is CapsuleCollider) ? collider : null);
				if (val2 != null)
				{
					val2.radius = lightRange;
				}
				else
				{
					Logging<Plugin>.Error((object)(((Object)_fireplace).name + " PlayerBase object has no sphere or capsule collider"), (ushort)0);
				}
			}
			else
			{
				val.radius = lightRange;
			}
		}

		private void LateUpdate()
		{
			if (!Configs.FireMustBeLit.Value)
			{
				return;
			}
			if (_fireplace.IsPlacementGhost())
			{
				_litArea.SetActive(true);
				_litPulse.SetActive(false);
				return;
			}
			_fireplace.m_playerBaseObject.SetActive(_fireplace.IsLit());
			if (IsVisible && !Player.m_localPlayer.IsTorchHeld())
			{
				IsVisible = false;
			}
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(CircleProjector), "Start")]
		private static void CircleProjector_Start(CircleProjector __instance)
		{
			CircleProjector __instance2 = __instance;
			if (!(((Object)__instance2).name != "LitAreaMarker"))
			{
				CollectionExtensions.Do<GameObject>((IEnumerable<GameObject>)__instance2.m_segments, (Action<GameObject>)delegate(GameObject segment)
				{
					//IL_0021: Unknown result type (might be due to invalid IL or missing references)
					//IL_003b: Unknown result type (might be due to invalid IL or missing references)
					segment.transform.localScale = new Vector3(0.05f, 0.25f, __instance2.m_radius / 20f);
					((Renderer)segment.GetComponent<MeshRenderer>()).material.color = UIColor.op_Implicit(UIColor.Orange);
				});
			}
		}
	}
	[HarmonyPatch]
	public static class Patches
	{
		[HarmonyPostfix]
		[HarmonyPatch(typeof(EffectArea), "Awake")]
		private static void PlayerBaseEffectArea_Awake(EffectArea __instance)
		{
			//IL_0020: Unknown result type (might be due to invalid IL or missing references)
			EffectArea __instance2 = __instance;
			if (!Configs.FireMustBeLit.Value || !((Enum)__instance2.m_type).HasFlag((Enum)(object)(Type)4))
			{
				return;
			}
			Piece piece = ((Component)__instance2).GetComponentInParent<Piece>();
			Timing.EndOfFrame((MonoBehaviour)(object)__instance2, (Action)delegate
			{
				if (Object.op_Implicit((Object)(object)piece) && piece.IsPlacedByPlayer())
				{
					((Component)__instance2).gameObject.SetActive(false);
				}
			});
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(EffectArea), "GetBaseValue")]
		private static void EffectArea_GetBaseValue(ref int __result)
		{
			__result -= 3 - Configs.PlayerBaseRaidThreshold.Value;
			Logging<Plugin>.Debug((object)$"Nearby PlayerBase: {__result} (Config raid threshold: {Configs.PlayerBaseRaidThreshold.Value})", 0);
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(Fireplace), "Awake")]
		[HarmonyPriority(0)]
		private static void Fireplace_Awake(Fireplace __instance)
		{
			if (Configs.FireMustBeLit.Value)
			{
				SetupMaxFuel(__instance);
			}
			FixPlayerBaseObject(__instance);
		}

		private static void SetupMaxFuel(Fireplace fireplace)
		{
			string prefabName = fireplace.m_nview.GetPrefabName();
			if (Configs.OverrideMaxFuel.Value.ToDictionary(':').TryGetValue(prefabName, out var value))
			{
				if (float.TryParse(value, out var result))
				{
					fireplace.m_maxFuel = result;
				}
				else
				{
					Logging<Plugin>.Warning((object)("Unable to parse fuel value: " + prefabName + ":" + value), 0);
				}
			}
		}

		private static void FixPlayerBaseObject(Fireplace fireplace)
		{
			//IL_0014: Unknown result type (might be due to invalid IL or missing references)
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			if (Object.op_Implicit((Object)(object)fireplace.m_playerBaseObject))
			{
				Scene scene = fireplace.m_playerBaseObject.scene;
				if (!((Scene)(ref scene)).isLoaded)
				{
					Logging<Plugin>.Info((object)(((Object)fireplace).name + " playerBaseObject is pointing to prefab, nulling to fix"), 0);
					fireplace.m_playerBaseObject = null;
				}
			}
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(Fireplace), "Start")]
		private static void Fireplace_Start(Fireplace __instance)
		{
			//IL_003f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0044: Unknown result type (might be due to invalid IL or missing references)
			if (Configs.FireMustBeLit.Value && (__instance.IsValidInteract(requireLit: false) || __instance.IsPlacementGhost()))
			{
				float lightRange = GetLightRange(__instance);
				if (lightRange < 0f)
				{
					Logging<Plugin>.Info((object)$"{((Object)__instance).name} {MathExt.XZY(((Component)__instance).transform.position)} light range not found, skipping", 0);
				}
				else
				{
					((Component)__instance).gameObject.AddComponent<LitArea>().Init(lightRange);
				}
			}
		}

		private static float GetLightRange(Fireplace fireplace)
		{
			GameObject enabledObject = fireplace.GetEnabledObject();
			if ((Object)(object)enabledObject == (Object)null)
			{
				return -1f;
			}
			LightLod componentInChildren = enabledObject.GetComponentInChildren<LightLod>();
			if (!Object.op_Implicit((Object)(object)componentInChildren))
			{
				return -1f;
			}
			string key = (Object.op_Implicit((Object)(object)fireplace.m_nview) ? fireplace.m_nview.GetPrefabName() : Utils.GetPrefabName(((Object)fireplace).name));
			if (Configs.OverrideRange.TryGetValue(key, out var value))
			{
				return value;
			}
			if (Object.op_Implicit((Object)(object)componentInChildren.m_light))
			{
				if (!componentInChildren.m_lightLod)
				{
					return componentInChildren.m_light.range;
				}
				return componentInChildren.m_baseRange;
			}
			Logging<Plugin>.Debug((object)"LightLod never initialized. Getting the Light component range directly", 0);
			return ((Component)componentInChildren).GetComponent<Light>().range;
		}

		[HarmonyPrefix]
		[HarmonyPatch(typeof(Fireplace), "Interact")]
		private static void Fireplace_Interact(Fireplace __instance, bool alt, bool hold, ref bool __runOriginal, ref bool __result)
		{
			if (!Configs.FireMustBeLit.Value || ZInput.GetKey((KeyCode)304, true) || ZInput.GetKey((KeyCode)303, true))
			{
				return;
			}
			if (alt && hold)
			{
				__runOriginal = false;
			}
			else if (!(!alt || hold) && __instance.IsValidInteract(requireLit: true))
			{
				__runOriginal = false;
				LitArea litArea = default(LitArea);
				if (!Player.m_localPlayer.IsTorchHeld() && !Player.m_localPlayer.TryEquipTorch())
				{
					((Character)Player.m_localPlayer).Message((MessageType)2, "You need a torch to check the perimeter.", 0, (Sprite)null);
				}
				else if (((Component)__instance).TryGetComponent<LitArea>(ref litArea))
				{
					litArea.IsVisible = !litArea.IsVisible;
				}
			}
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(Fireplace), "GetHoverText")]
		[HarmonyPriority(200)]
		private static void Fireplace_GetHoverText(Fireplace __instance, ref string __result)
		{
			LitArea litArea = default(LitArea);
			if (Configs.FireMustBeLit.Value && __instance.IsValidInteract(requireLit: true) && ((Component)__instance).TryGetComponent<LitArea>(ref litArea))
			{
				string text = (litArea.IsVisible ? "Hide" : "Show") + " perimeter";
				__result = StringExt.Localize(UI.InsertInteractAlt(__result, text));
			}
		}

		private static bool IsValidInteract(this Fireplace fireplace, bool requireLit)
		{
			if (!Configs.InteractViewPerimeter.Value)
			{
				return false;
			}
			if (!Object.op_Implicit((Object)(object)fireplace.m_piece) || !fireplace.m_piece.IsPlacedByPlayer() || !Object.op_Implicit((Object)(object)fireplace.m_playerBaseObject))
			{
				return false;
			}
			if (requireLit && !fireplace.IsLit())
			{
				return false;
			}
			return true;
		}
	}
}
namespace ZenRaids.Compatibility
{
	internal static class Farming
	{
		private const string FarmingGUID = "org.bepinex.plugins.farming";

		private static bool IsLoaded()
		{
			return Chainloader.PluginInfos.ContainsKey("org.bepinex.plugins.farming");
		}

		public static void Check()
		{
			if (Configs.FireMustBeLit.Value && IsLoaded())
			{
				Logging<Plugin>.Warning((object)"Farming mod installed, light perimeter rings may not display correctly when placing light sources.", 0);
			}
		}
	}
}