Decompiled source of CircletExtended v1.0.2

CircletExtended.dll

Decompiled a month ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using BepInEx;
using BepInEx.Configuration;
using HarmonyLib;
using JetBrains.Annotations;
using Microsoft.CodeAnalysis;
using ServerSync;
using TMPro;
using UnityEngine;

[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: Guid("01429425-f577-46f2-bba7-6faf98d54110")]
[assembly: ComVisible(false)]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCopyright("Copyright ©  2023")]
[assembly: AssemblyProduct("CircletExtended")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyTitle("CircletExtended")]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: CompilationRelaxations(8)]
[assembly: TargetFramework(".NETFramework,Version=v4.6.2", FrameworkDisplayName = ".NET Framework 4.6.2")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.0.0.0")]
[module: UnverifiableCode]
namespace CircletExtended
{
	[Serializable]
	public class HumanoidHelmetCirclet
	{
		public ItemData circlet;

		public HumanoidHelmetCirclet()
		{
			circlet = null;
		}
	}
	public static class HumanoidExtension
	{
		private static readonly ConditionalWeakTable<Humanoid, HumanoidHelmetCirclet> data = new ConditionalWeakTable<Humanoid, HumanoidHelmetCirclet>();

		public static HumanoidHelmetCirclet GetCirclet(this Humanoid humanoid)
		{
			return data.GetOrCreateValue(humanoid);
		}

		public static void AddData(this Humanoid humanoid, HumanoidHelmetCirclet value)
		{
			try
			{
				data.Add(humanoid, value);
			}
			catch
			{
			}
		}
	}
	[HarmonyPatch(typeof(Humanoid), "SetupVisEquipment")]
	public static class Humanoid_SetupVisEquipment_CircletOnTop
	{
		private static void Postfix(Humanoid __instance, VisEquipment visEq)
		{
			if (CircletExtended.modEnabled.Value && CircletExtended.enablePutOnTop.Value)
			{
				ItemData circlet = __instance.GetCirclet().circlet;
				string helmetItem = ((circlet != null) ? ((Object)circlet.m_dropPrefab).name : ((__instance.m_helmetItem != null) ? ((Object)__instance.m_helmetItem.m_dropPrefab).name : ""));
				visEq.SetHelmetItem(helmetItem);
			}
		}
	}
	[HarmonyPatch(typeof(Humanoid), "EquipItem")]
	public static class Humanoid_EquipItem_CircletOnTop
	{
		private static void Postfix(Humanoid __instance, ItemData item, ref bool __result, bool triggerEquipEffects)
		{
			//IL_0080: Unknown result type (might be due to invalid IL or missing references)
			//IL_0087: Invalid comparison between Unknown and I4
			if (!CircletExtended.modEnabled.Value || !CircletExtended.enablePutOnTop.Value)
			{
				return;
			}
			if (__instance.m_helmetItem != null && __instance.m_helmetItem.m_shared.m_name == "$item_helmet_dverger")
			{
				CircletExtended.LogInfo("Unequipping circlet on circlet equipment");
				__instance.UnequipItem(__instance.GetCirclet().circlet, triggerEquipEffects);
				return;
			}
			if ((int)item.m_shared.m_itemType == 55)
			{
				bool flag = __instance.GetCirclet().circlet != null;
				__instance.UnequipItem(__instance.GetCirclet().circlet, triggerEquipEffects);
				if (flag)
				{
					__instance.m_visEquipment.UpdateEquipmentVisuals();
				}
				__instance.GetCirclet().circlet = item;
			}
			if (__instance.IsItemEquiped(item))
			{
				item.m_equipped = true;
				__result = true;
			}
			__instance.SetupEquipment();
			if (triggerEquipEffects)
			{
				__instance.TriggerEquipEffect(item);
			}
		}
	}
	[HarmonyPatch(typeof(Humanoid), "UnequipItem")]
	public static class Humanoid_UnequipItem_CircletOnTop
	{
		private static void Postfix(Humanoid __instance, ItemData item, bool triggerEquipEffects)
		{
			if (CircletExtended.modEnabled.Value && CircletExtended.enablePutOnTop.Value && item != null)
			{
				if (__instance.GetCirclet().circlet == item || __instance.m_helmetItem == null)
				{
					__instance.GetCirclet().circlet = null;
				}
				__instance.SetupEquipment();
				if (triggerEquipEffects)
				{
					__instance.TriggerEquipEffect(item);
				}
			}
		}
	}
	[HarmonyPatch(typeof(Humanoid), "UnequipAllItems")]
	public class Humanoid_UnequipAllItems_CircletOnTop
	{
		public static void Postfix(Humanoid __instance)
		{
			if (CircletExtended.modEnabled.Value && CircletExtended.enablePutOnTop.Value)
			{
				__instance.UnequipItem(__instance.GetCirclet().circlet, false);
			}
		}
	}
	[HarmonyPatch(typeof(Humanoid), "IsItemEquiped")]
	public static class Humanoid_IsItemEquiped_CircletOnTop
	{
		private static void Postfix(Humanoid __instance, ItemData item, ref bool __result)
		{
			if (CircletExtended.modEnabled.Value && CircletExtended.enablePutOnTop.Value && item != null)
			{
				__result = __result || __instance.GetCirclet().circlet == item;
			}
		}
	}
	[HarmonyPatch(typeof(ItemData), "IsEquipable")]
	public static class ItemDropItemData_IsEquipable_CircletOnTop
	{
		private static void Postfix(ItemData __instance, ref bool __result)
		{
			//IL_0032: Unknown result type (might be due to invalid IL or missing references)
			//IL_0039: Invalid comparison between Unknown and I4
			if (CircletExtended.modEnabled.Value && CircletExtended.enablePutOnTop.Value)
			{
				__result = __result || (int)__instance.m_shared.m_itemType == 55;
			}
		}
	}
	[HarmonyPatch(typeof(ItemStand), "Awake")]
	public static class ItemStand_Awake_CircletOnTop
	{
		private static void Postfix(ItemStand __instance)
		{
			if (CircletExtended.modEnabled.Value && CircletExtended.enablePutOnTop.Value && CircletExtended.visualStateItemStand.Value)
			{
				__instance.m_supportedTypes.Add((ItemType)55);
			}
		}
	}
	[HarmonyPatch(typeof(ArmorStand), "Awake")]
	public static class ArmorStand_Awake_CircletOnTop
	{
		private static void Postfix(ArmorStand __instance)
		{
			if (CircletExtended.modEnabled.Value && CircletExtended.enablePutOnTop.Value && CircletExtended.visualStateArmorStand.Value)
			{
				CollectionExtensions.Do<ArmorStandSlot>(__instance.m_slots.Where((ArmorStandSlot x) => (int)x.m_slot == 6), (Action<ArmorStandSlot>)delegate(ArmorStandSlot x)
				{
					x.m_supportedTypes.Add((ItemType)55);
				});
			}
		}
	}
	[BepInPlugin("shudnal.CircletExtended", "Circlet Extended", "1.0.2")]
	[BepInIncompatibility("randyknapp.mods.dvergercolor")]
	[BepInIncompatibility("Azumatt.CircletDemister")]
	public class CircletExtended : BaseUnityPlugin
	{
		private const string pluginID = "shudnal.CircletExtended";

		private const string pluginName = "Circlet Extended";

		private const string pluginVersion = "1.0.2";

		private readonly Harmony harmony = new Harmony("shudnal.CircletExtended");

		internal static readonly ConfigSync configSync = new ConfigSync("shudnal.CircletExtended")
		{
			DisplayName = "Circlet Extended",
			CurrentVersion = "1.0.2",
			MinimumRequiredVersion = "1.0.2"
		};

		public static ConfigEntry<bool> modEnabled;

		private static ConfigEntry<bool> configLocked;

		private static ConfigEntry<bool> loggingEnabled;

		public static ConfigEntry<bool> getFeaturesByUpgrade;

		public static ConfigEntry<float> durabilityPerLevel;

		public static ConfigEntry<int> overloadChargesPerLevel;

		public static ConfigEntry<bool> enableOverload;

		public static ConfigEntry<bool> enableDemister;

		public static ConfigEntry<bool> enablePutOnTop;

		public static ConfigEntry<Color> circletColor;

		public static ConfigEntry<bool> disableOnSleep;

		public static ConfigEntry<bool> enableShadows;

		public static ConfigEntry<bool> enableOverloadDemister;

		public static ConfigEntry<float> overloadDemisterRange;

		public static ConfigEntry<float> overloadDemisterTime;

		public static ConfigEntry<bool> visualStateItemDrop;

		public static ConfigEntry<bool> visualStateItemStand;

		public static ConfigEntry<bool> visualStateArmorStand;

		public static ConfigEntry<KeyboardShortcut> widenShortcut;

		public static ConfigEntry<KeyboardShortcut> narrowShortcut;

		public static ConfigEntry<KeyboardShortcut> toggleShortcut;

		public static ConfigEntry<KeyboardShortcut> toggleDemisterShortcut;

		public static ConfigEntry<KeyboardShortcut> increaseIntensityShortcut;

		public static ConfigEntry<KeyboardShortcut> decreaseIntensityShortcut;

		public static ConfigEntry<KeyboardShortcut> toggleShadowsShortcut;

		public static ConfigEntry<KeyboardShortcut> toggleSpotShortcut;

		public static ConfigEntry<KeyboardShortcut> overloadShortcut;

		public static ConfigEntry<int> maxSteps;

		public static ConfigEntry<float> minAngle;

		public static ConfigEntry<float> maxAngle;

		public static ConfigEntry<float> minIntensity;

		public static ConfigEntry<float> maxIntensity;

		public static ConfigEntry<float> minRange;

		public static ConfigEntry<float> maxRange;

		public static ConfigEntry<float> pointIntensity;

		public static ConfigEntry<float> pointRange;

		public static ConfigEntry<int> maxSteps2;

		public static ConfigEntry<float> minAngle2;

		public static ConfigEntry<float> maxAngle2;

		public static ConfigEntry<float> minIntensity2;

		public static ConfigEntry<float> maxIntensity2;

		public static ConfigEntry<float> minRange2;

		public static ConfigEntry<float> maxRange2;

		public static ConfigEntry<float> pointIntensity2;

		public static ConfigEntry<float> pointRange2;

		public static ConfigEntry<int> maxSteps3;

		public static ConfigEntry<float> minAngle3;

		public static ConfigEntry<float> maxAngle3;

		public static ConfigEntry<float> minIntensity3;

		public static ConfigEntry<float> maxIntensity3;

		public static ConfigEntry<float> minRange3;

		public static ConfigEntry<float> maxRange3;

		public static ConfigEntry<float> pointIntensity3;

		public static ConfigEntry<float> pointRange3;

		public static ConfigEntry<int> maxSteps4;

		public static ConfigEntry<float> minAngle4;

		public static ConfigEntry<float> maxAngle4;

		public static ConfigEntry<float> minIntensity4;

		public static ConfigEntry<float> maxIntensity4;

		public static ConfigEntry<float> minRange4;

		public static ConfigEntry<float> maxRange4;

		public static ConfigEntry<float> pointIntensity4;

		public static ConfigEntry<float> pointRange4;

		internal static CircletExtended instance;

		public const string itemNameHelmetDverger = "HelmetDverger";

		public const string itemDropNameHelmetDverger = "$item_helmet_dverger";

		public static int itemHashHelmetDverger = 703889544;

		public static GameObject overloadEffect;

		public static int demisterEffectHash = 0;

		public static GameObject demisterForceField;

		public const string forceFieldDemisterName = "Particle System Force Field";

		public const int maxQuality = 4;

		public static List<int> hotkeys = new List<int>();

		public static Dictionary<int, Requirement[]> recipeRequirements = new Dictionary<int, Requirement[]>();

		public const ItemType itemTypeCirclet = 55;

		public static string customDataKey;

		private void Awake()
		{
			harmony.PatchAll();
			instance = this;
			ConfigInit();
			configSync.AddLockingConfigEntry<bool>(configLocked);
			Game.isModded = true;
			customDataKey = "shudnal.CircletExtended.DvergerLightState";
		}

		private void OnDestroy()
		{
			((BaseUnityPlugin)this).Config.Save();
			instance = null;
			Harmony obj = harmony;
			if (obj != null)
			{
				obj.UnpatchSelf();
			}
		}

		public static void LogInfo(object data)
		{
			if (loggingEnabled.Value)
			{
				((BaseUnityPlugin)instance).Logger.LogInfo(data);
			}
		}

		public void ConfigInit()
		{
			//IL_0090: Unknown result type (might be due to invalid IL or missing references)
			//IL_024f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0279: Unknown result type (might be due to invalid IL or missing references)
			//IL_02a0: Unknown result type (might be due to invalid IL or missing references)
			//IL_02ca: Unknown result type (might be due to invalid IL or missing references)
			//IL_02f4: Unknown result type (might be due to invalid IL or missing references)
			//IL_0327: Unknown result type (might be due to invalid IL or missing references)
			//IL_035a: Unknown result type (might be due to invalid IL or missing references)
			//IL_038d: Unknown result type (might be due to invalid IL or missing references)
			//IL_03c0: Unknown result type (might be due to invalid IL or missing references)
			config("General", "NexusID", 2617, "Nexus mod ID for updates", synchronizedSetting: false);
			modEnabled = config("General", "Enabled", defaultValue: true, "Enable the mod.");
			configLocked = config("General", "Lock Configuration", defaultValue: true, "Configuration is locked and can be changed by server admins only.");
			loggingEnabled = config("General", "Logging enabled", defaultValue: false, "Enable logging. [Not Synced with Server]", synchronizedSetting: false);
			circletColor = config<Color>("Circlet", "Light color", new Color(1f, 0.9f, 0.8f, 1f), "Circlet beam light color. Changing this ingame will change current circlet color [Not Synced with Server]", synchronizedSetting: false);
			disableOnSleep = config("Circlet", "Disable when sleeping", defaultValue: true, "Turn off the light when sleeping. [Not Synced with Server]", synchronizedSetting: false);
			enableShadows = config("Circlet", "Enables shadows toggle", defaultValue: true, "Enables option to toggle circlet's light to emit shadows. Disable if it impacts your performance. [Not Synced with Server]", synchronizedSetting: false);
			getFeaturesByUpgrade = config("Circlet - Features", "Get features by circlet upgrade", defaultValue: true, "Get circlet features by upgrading it. If False all features are available by default.\nIf True the order of upgrades are \"Default\" -> \"Put on top\" -> \"Overload\" -> \"Demister\"");
			durabilityPerLevel = config("Circlet - Features", "Durability per level", 500f, "Durability added per level");
			overloadChargesPerLevel = config("Circlet - Features", "Overload charges", 50, "How many overload charges is available. It is the fraction of durability being damaged on Overload use. x2 if upgrades are disabled or quality is maximum.");
			enableOverload = config("Circlet - Features", "Enable overload", defaultValue: true, "Enables overload. Press hotkey to blind opponents with a bright flash at the cost of some circlet durability");
			enableDemister = config("Circlet - Features", "Enable demister", defaultValue: true, "Enables demister. Press hotkey to spawn a little wisp to push away the mists");
			enablePutOnTop = config("Circlet - Features", "Enable put on top", defaultValue: true, "Enables equipping circlet on top of other helmet. Equip circlet without using a helmet slot.");
			enableOverloadDemister = config("Circlet - Overload demister", "Enable temporary demister on overload", defaultValue: true, "Push away mist on overload activation");
			overloadDemisterRange = config("Circlet - Overload demister", "Range", 40f, "Maximum range");
			overloadDemisterTime = config("Circlet - Overload demister", "Time", 8f, "Time to gradually decrease effect radius");
			visualStateItemDrop = config("Circlet - Visual state", "Enable itemdrop state", defaultValue: true, "Circlet dropped on the ground will preserve light state");
			visualStateItemStand = config("Circlet - Visual state", "Enable item stand state", defaultValue: true, "Circlet put on the item stand will preserve light state");
			visualStateArmorStand = config("Circlet - Visual state", "Enable armor stand state", defaultValue: true, "Circlet put on the armor stand will preserve light state");
			widenShortcut = config<KeyboardShortcut>("Hotkeys", "Beam widen", new KeyboardShortcut((KeyCode)275, Array.Empty<KeyCode>()), "Widen beam shortcut. [Not Synced with Server]", synchronizedSetting: false);
			narrowShortcut = config<KeyboardShortcut>("Hotkeys", "Beam narrow", new KeyboardShortcut((KeyCode)276, Array.Empty<KeyCode>()), "Narrow beam shortcut. [Not Synced with Server]", synchronizedSetting: false);
			overloadShortcut = config<KeyboardShortcut>("Hotkeys", "Overload", new KeyboardShortcut((KeyCode)116, Array.Empty<KeyCode>()), "Overload shortcut. Blind opponents with a bright flash at the cost of some circlet durability. [Not Synced with Server]", synchronizedSetting: false);
			toggleShortcut = config<KeyboardShortcut>("Hotkeys", "Toggle light", new KeyboardShortcut((KeyCode)273, Array.Empty<KeyCode>()), "Toggle main light shortcut. Enable/disable frontlight. [Not Synced with Server]", synchronizedSetting: false);
			toggleDemisterShortcut = config<KeyboardShortcut>("Hotkeys", "Toggle demister", new KeyboardShortcut((KeyCode)274, Array.Empty<KeyCode>()), "Toggle demister shortcut. Spawn/despawn demister wisplight. [Not Synced with Server]", synchronizedSetting: false);
			increaseIntensityShortcut = config<KeyboardShortcut>("Hotkeys - Extra", "Intensity increase", new KeyboardShortcut((KeyCode)273, (KeyCode[])(object)new KeyCode[1] { (KeyCode)304 }), "Increase intensity shortcut. Light becomes brighter and have more range. Intensity is capped at 150% [Not Synced with Server]", synchronizedSetting: false);
			decreaseIntensityShortcut = config<KeyboardShortcut>("Hotkeys - Extra", "Intensity decrease", new KeyboardShortcut((KeyCode)274, (KeyCode[])(object)new KeyCode[1] { (KeyCode)304 }), "Decrease intensity shortcut. Light becomes darker and have less range. Intensity is capped at 50% [Not Synced with Server]", synchronizedSetting: false);
			toggleShadowsShortcut = config<KeyboardShortcut>("Hotkeys - Extra", "Toggle shadows", new KeyboardShortcut((KeyCode)276, (KeyCode[])(object)new KeyCode[1] { (KeyCode)304 }), "Toggle shadows shortcut. Enables/disables the current light source to emit soft shadows. [Not Synced with Server]", synchronizedSetting: false);
			toggleSpotShortcut = config<KeyboardShortcut>("Hotkeys - Extra", "Toggle radiance", new KeyboardShortcut((KeyCode)275, (KeyCode[])(object)new KeyCode[1] { (KeyCode)304 }), "Toggle spotlight shortcut. Enables/disables the radiance when circlet is equipped. [Not Synced with Server]", synchronizedSetting: false);
			maxSteps = config("Light - Default", "Max Steps", 3, "Define how many steps of focus the Dverger light beam has. Must be at least 2.");
			minAngle = config("Light - Default", "Min Angle", 30f, "The angle of the beam at the narrowest setting.");
			maxAngle = config("Light - Default", "Max Angle", 110f, "The angle of the beam at the widest setting.");
			minIntensity = config("Light - Default", "Min Intensity", 1.4f, "The intensity of the beam at the widest setting.");
			maxIntensity = config("Light - Default", "Max Intensity", 2.2f, "The intensity of the beam at the narrowest setting");
			minRange = config("Light - Default", "Min Range", 45f, "The range of the beam at the narrowest setting.");
			maxRange = config("Light - Default", "Max Range", 15f, "The range of the beam at the widest setting");
			pointIntensity = config("Light - Default", "Point Intensity", 1.1f, "The intensity of the Dverger light pool on the point light setting.");
			pointRange = config("Light - Default", "Point Range", 10f, "The range of the Dverger light pool on the point light setting.");
			maxSteps2 = config("Light - Quality 2", "Max Steps", 3, "Define how many steps of focus the Dverger light beam has. Must be at least 2.");
			minAngle2 = config("Light - Quality 2", "Min Angle", 30f, "The angle of the beam at the narrowest setting.");
			maxAngle2 = config("Light - Quality 2", "Max Angle", 110f, "The angle of the beam at the widest setting.");
			minIntensity2 = config("Light - Quality 2", "Min Intensity", 1.4f, "The intensity of the beam at the widest setting.");
			maxIntensity2 = config("Light - Quality 2", "Max Intensity", 2.2f, "The intensity of the beam at the narrowest setting");
			minRange2 = config("Light - Quality 2", "Min Range", 45f, "The range of the beam at the narrowest setting.");
			maxRange2 = config("Light - Quality 2", "Max Range", 15f, "The range of the beam at the widest setting");
			pointIntensity2 = config("Light - Quality 2", "Point Intensity", 1.1f, "The intensity of the Dverger light pool on the point light setting.");
			pointRange2 = config("Light - Quality 2", "Point Range", 10f, "The range of the Dverger light pool on the point light setting.");
			maxSteps3 = config("Light - Quality 3", "Max Steps", 3, "Define how many steps of focus the Dverger light beam has. Must be at least 2.");
			minAngle3 = config("Light - Quality 3", "Min Angle", 30f, "The angle of the beam at the narrowest setting.");
			maxAngle3 = config("Light - Quality 3", "Max Angle", 110f, "The angle of the beam at the widest setting.");
			minIntensity3 = config("Light - Quality 3", "Min Intensity", 1.4f, "The intensity of the beam at the widest setting.");
			maxIntensity3 = config("Light - Quality 3", "Max Intensity", 2.2f, "The intensity of the beam at the narrowest setting");
			minRange3 = config("Light - Quality 3", "Min Range", 45f, "The range of the beam at the narrowest setting.");
			maxRange3 = config("Light - Quality 3", "Max Range", 15f, "The range of the beam at the widest setting");
			pointIntensity3 = config("Light - Quality 3", "Point Intensity", 1.1f, "The intensity of the Dverger light pool on the point light setting.");
			pointRange3 = config("Light - Quality 3", "Point Range", 10f, "The range of the Dverger light pool on the point light setting.");
			maxSteps4 = config("Light - Quality 4", "Max Steps", 3, "Define how many steps of focus the Dverger light beam has. Must be at least 2.");
			minAngle4 = config("Light - Quality 4", "Min Angle", 30f, "The angle of the beam at the narrowest setting.");
			maxAngle4 = config("Light - Quality 4", "Max Angle", 110f, "The angle of the beam at the widest setting.");
			minIntensity4 = config("Light - Quality 4", "Min Intensity", 1.4f, "The intensity of the beam at the widest setting.");
			maxIntensity4 = config("Light - Quality 4", "Max Intensity", 2.2f, "The intensity of the beam at the narrowest setting");
			minRange4 = config("Light - Quality 4", "Min Range", 45f, "The range of the beam at the narrowest setting.");
			maxRange4 = config("Light - Quality 4", "Max Range", 15f, "The range of the beam at the widest setting");
			pointIntensity4 = config("Light - Quality 4", "Point Intensity", 1.1f, "The intensity of the Dverger light pool on the point light setting.");
			pointRange4 = config("Light - Quality 4", "Point Range", 10f, "The range of the Dverger light pool on the point light setting.");
			itemHashHelmetDverger = StringExtensionMethods.GetStableHashCode("HelmetDverger");
			demisterEffectHash = StringExtensionMethods.GetStableHashCode("Demister");
			Dictionary<int, int> dictionary = new Dictionary<int, int>();
			AddShortcut(dictionary, widenShortcut);
			AddShortcut(dictionary, narrowShortcut);
			AddShortcut(dictionary, toggleShortcut);
			AddShortcut(dictionary, toggleSpotShortcut);
			AddShortcut(dictionary, increaseIntensityShortcut);
			AddShortcut(dictionary, decreaseIntensityShortcut);
			AddShortcut(dictionary, toggleShadowsShortcut);
			AddShortcut(dictionary, overloadShortcut);
			AddShortcut(dictionary, toggleDemisterShortcut);
			hotkeys = (from x in dictionary
				orderby x.Value descending
				select x.Key).ToList();
		}

		private void AddShortcut(Dictionary<int, int> shortcuts, ConfigEntry<KeyboardShortcut> shortcut)
		{
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			int hashCode = ((object)((ConfigEntryBase)shortcut).Definition).GetHashCode();
			KeyboardShortcut value = shortcut.Value;
			shortcuts.Add(hashCode, ((KeyboardShortcut)(ref value)).Modifiers.Count());
		}

		private ConfigEntry<T> config<T>(string group, string name, T defaultValue, ConfigDescription description, bool synchronizedSetting = true)
		{
			ConfigEntry<T> val = ((BaseUnityPlugin)this).Config.Bind<T>(group, name, defaultValue, description);
			SyncedConfigEntry<T> syncedConfigEntry = configSync.AddConfigEntry<T>(val);
			syncedConfigEntry.SynchronizedConfig = synchronizedSetting;
			return val;
		}

		private ConfigEntry<T> config<T>(string group, string name, T defaultValue, string description, bool synchronizedSetting = true)
		{
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0018: Expected O, but got Unknown
			return config(group, name, defaultValue, new ConfigDescription(description, (AcceptableValueBase)null, Array.Empty<object>()), synchronizedSetting);
		}

		public static void PatchCircletItemData(ItemData item)
		{
			//IL_00be: Unknown result type (might be due to invalid IL or missing references)
			if (modEnabled.Value && item != null)
			{
				if (getFeaturesByUpgrade.Value)
				{
					item.m_shared.m_maxQuality = 4;
					item.m_shared.m_durabilityPerLevel = durabilityPerLevel.Value;
					item.m_shared.m_useDurability = item.GetDurabilityPercentage() != 1f || item.m_quality >= 3;
				}
				if (enablePutOnTop.Value && ((getFeaturesByUpgrade.Value && item.m_quality >= 2) || !getFeaturesByUpgrade.Value))
				{
					item.m_shared.m_itemType = (ItemType)55;
				}
			}
		}

		public static int GetMaxSteps(int quality)
		{
			return ((!getFeaturesByUpgrade.Value) ? 1 : Mathf.Clamp(quality, 1, 4)) switch
			{
				1 => maxSteps.Value, 
				2 => maxSteps2.Value, 
				3 => maxSteps3.Value, 
				4 => maxSteps4.Value, 
				_ => maxSteps.Value, 
			};
		}

		public static float GetMinAngle(int quality)
		{
			return ((!getFeaturesByUpgrade.Value) ? 1 : Mathf.Clamp(quality, 1, 4)) switch
			{
				1 => minAngle.Value, 
				2 => minAngle2.Value, 
				3 => minAngle3.Value, 
				4 => minAngle4.Value, 
				_ => minAngle.Value, 
			};
		}

		public static float GetMaxAngle(int quality)
		{
			return ((!getFeaturesByUpgrade.Value) ? 1 : Mathf.Clamp(quality, 1, 4)) switch
			{
				1 => maxAngle.Value, 
				2 => maxAngle2.Value, 
				3 => maxAngle3.Value, 
				4 => maxAngle4.Value, 
				_ => maxAngle.Value, 
			};
		}

		public static float GetMinIntensity(int quality)
		{
			return ((!getFeaturesByUpgrade.Value) ? 1 : Mathf.Clamp(quality, 1, 4)) switch
			{
				1 => minIntensity.Value, 
				2 => minIntensity2.Value, 
				3 => minIntensity3.Value, 
				4 => minIntensity4.Value, 
				_ => minIntensity.Value, 
			};
		}

		public static float GetMaxIntensity(int quality)
		{
			return ((!getFeaturesByUpgrade.Value) ? 1 : Mathf.Clamp(quality, 1, 4)) switch
			{
				1 => maxIntensity.Value, 
				2 => maxIntensity2.Value, 
				3 => maxIntensity3.Value, 
				4 => maxIntensity4.Value, 
				_ => maxIntensity.Value, 
			};
		}

		public static float GetMinRange(int quality)
		{
			return ((!getFeaturesByUpgrade.Value) ? 1 : Mathf.Clamp(quality, 1, 4)) switch
			{
				1 => minRange.Value, 
				2 => minRange2.Value, 
				3 => minRange3.Value, 
				4 => minRange4.Value, 
				_ => minRange.Value, 
			};
		}

		public static float GetMaxRange(int quality)
		{
			return ((!getFeaturesByUpgrade.Value) ? 1 : Mathf.Clamp(quality, 1, 4)) switch
			{
				1 => maxRange.Value, 
				2 => maxRange2.Value, 
				3 => maxRange3.Value, 
				4 => maxRange4.Value, 
				_ => maxRange.Value, 
			};
		}

		public static float GetPointIntensity(int quality)
		{
			return ((!getFeaturesByUpgrade.Value) ? 1 : Mathf.Clamp(quality, 1, 4)) switch
			{
				1 => pointIntensity.Value, 
				2 => pointIntensity2.Value, 
				3 => pointIntensity3.Value, 
				4 => pointIntensity4.Value, 
				_ => pointIntensity.Value, 
			};
		}

		public static float GetPointRange(int quality)
		{
			return ((!getFeaturesByUpgrade.Value) ? 1 : Mathf.Clamp(quality, 1, 4)) switch
			{
				1 => pointRange.Value, 
				2 => pointRange2.Value, 
				3 => pointRange3.Value, 
				4 => pointRange4.Value, 
				_ => pointRange.Value, 
			};
		}
	}
	[HarmonyPatch(typeof(ObjectDB), "Awake")]
	public static class ObjectDB_Awake_CircletStats
	{
		[HarmonyPriority(0)]
		private static void Postfix(ObjectDB __instance, ref List<Recipe> ___m_recipes)
		{
			//IL_011e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0123: Unknown result type (might be due to invalid IL or missing references)
			//IL_012a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0132: Expected O, but got Unknown
			//IL_017f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0184: Unknown result type (might be due to invalid IL or missing references)
			//IL_019e: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ab: Expected O, but got Unknown
			//IL_01ae: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b3: Unknown result type (might be due to invalid IL or missing references)
			//IL_01cd: Unknown result type (might be due to invalid IL or missing references)
			//IL_01da: 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_01fc: Unknown result type (might be due to invalid IL or missing references)
			//IL_0209: Expected O, but got Unknown
			//IL_020c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0211: Unknown result type (might be due to invalid IL or missing references)
			//IL_022b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0237: Expected O, but got Unknown
			//IL_023f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0244: Unknown result type (might be due to invalid IL or missing references)
			//IL_025e: Unknown result type (might be due to invalid IL or missing references)
			//IL_026a: Expected O, but got Unknown
			//IL_026d: 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_028c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0298: Expected O, but got Unknown
			//IL_029b: Unknown result type (might be due to invalid IL or missing references)
			//IL_02a0: Unknown result type (might be due to invalid IL or missing references)
			//IL_02ba: Unknown result type (might be due to invalid IL or missing references)
			//IL_02c6: Expected O, but got Unknown
			//IL_02ce: Unknown result type (might be due to invalid IL or missing references)
			//IL_02d3: Unknown result type (might be due to invalid IL or missing references)
			//IL_02ed: Unknown result type (might be due to invalid IL or missing references)
			//IL_02f9: Expected O, but got Unknown
			//IL_02fc: Unknown result type (might be due to invalid IL or missing references)
			//IL_0301: Unknown result type (might be due to invalid IL or missing references)
			//IL_031b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0327: Expected O, but got Unknown
			//IL_032c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0331: Unknown result type (might be due to invalid IL or missing references)
			//IL_034b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0357: Expected O, but got Unknown
			if (!CircletExtended.modEnabled.Value || !CircletExtended.getFeaturesByUpgrade.Value)
			{
				return;
			}
			GameObject itemPrefab = __instance.GetItemPrefab(CircletExtended.itemHashHelmetDverger);
			if ((Object)(object)itemPrefab == (Object)null)
			{
				return;
			}
			if (___m_recipes.RemoveAll((Recipe x) => ((Object)x).name == "HelmetDverger") > 0)
			{
				CircletExtended.LogInfo("Removed recipe HelmetDverger");
			}
			CraftingStation val = ((IEnumerable<Recipe>)__instance.m_recipes).FirstOrDefault((Func<Recipe, bool>)((Recipe rec) => rec.m_craftingStation?.m_name == "$piece_forge"))?.m_craftingStation;
			ItemDrop component = itemPrefab.GetComponent<ItemDrop>();
			CircletExtended.PatchCircletItemData(component.m_itemData);
			Recipe val2 = ScriptableObject.CreateInstance<Recipe>();
			((Object)val2).name = "HelmetDverger";
			val2.m_amount = 1;
			val2.m_minStationLevel = 3;
			val2.m_item = component;
			val2.m_enabled = true;
			if ((Object)(object)val != (Object)null)
			{
				val2.m_craftingStation = val;
			}
			val2.m_resources = (Requirement[])(object)new Requirement[1]
			{
				new Requirement
				{
					m_amount = 1,
					m_resItem = component
				}
			};
			___m_recipes.Add(val2);
			CircletExtended.recipeRequirements.Clear();
			for (int i = 0; i <= 5; i++)
			{
				List<Requirement> list = new List<Requirement>();
				switch (i)
				{
				case 2:
					list.Add(new Requirement
					{
						m_resItem = ObjectDB.instance.GetItemPrefab("Resin").GetComponent<ItemDrop>(),
						m_amount = 20
					});
					list.Add(new Requirement
					{
						m_resItem = ObjectDB.instance.GetItemPrefab("LeatherScraps").GetComponent<ItemDrop>(),
						m_amount = 10
					});
					list.Add(new Requirement
					{
						m_resItem = ObjectDB.instance.GetItemPrefab("IronNails").GetComponent<ItemDrop>(),
						m_amount = 10
					});
					list.Add(new Requirement
					{
						m_resItem = ObjectDB.instance.GetItemPrefab("Chain").GetComponent<ItemDrop>(),
						m_amount = 1
					});
					break;
				case 3:
					list.Add(new Requirement
					{
						m_resItem = ObjectDB.instance.GetItemPrefab("Thunderstone").GetComponent<ItemDrop>(),
						m_amount = 5
					});
					list.Add(new Requirement
					{
						m_resItem = ObjectDB.instance.GetItemPrefab("Silver").GetComponent<ItemDrop>(),
						m_amount = 1
					});
					list.Add(new Requirement
					{
						m_resItem = ObjectDB.instance.GetItemPrefab("JuteRed").GetComponent<ItemDrop>(),
						m_amount = 2
					});
					break;
				case 4:
					list.Add(new Requirement
					{
						m_resItem = ObjectDB.instance.GetItemPrefab("Demister").GetComponent<ItemDrop>(),
						m_amount = 1
					});
					list.Add(new Requirement
					{
						m_resItem = ObjectDB.instance.GetItemPrefab("BlackCore").GetComponent<ItemDrop>(),
						m_amount = 1
					});
					break;
				default:
					list.Add(new Requirement
					{
						m_resItem = ObjectDB.instance.GetItemPrefab("HelmetDverger").GetComponent<ItemDrop>(),
						m_amount = 1
					});
					break;
				}
				CircletExtended.recipeRequirements.Add(i, list.ToArray());
			}
			GameObject itemPrefab2 = __instance.GetItemPrefab("Demister");
			object demisterForceField;
			if (itemPrefab2 == null)
			{
				demisterForceField = null;
			}
			else
			{
				Transform obj = itemPrefab2.transform.Find("Particle System Force Field");
				demisterForceField = ((obj != null) ? ((Component)obj).gameObject : null);
			}
			CircletExtended.demisterForceField = (GameObject)demisterForceField;
		}
	}
	[HarmonyPatch(typeof(Player), "AddKnownItem")]
	public static class Player_AddKnownItem_CircletStats
	{
		private static void Postfix(ref ItemData item)
		{
			if (CircletExtended.modEnabled.Value && CircletExtended.getFeaturesByUpgrade.Value && !(item.m_shared.m_name != "$item_helmet_dverger"))
			{
				CircletExtended.PatchCircletItemData(item);
			}
		}
	}
	[HarmonyPatch(typeof(Player), "OnSpawned")]
	public class Player_OnSpawned_CircletStats
	{
		public static void Postfix(Player __instance)
		{
			if (!CircletExtended.modEnabled.Value || !CircletExtended.getFeaturesByUpgrade.Value || (Object)(object)__instance != (Object)(object)Player.m_localPlayer)
			{
				return;
			}
			List<ItemData> list = new List<ItemData>();
			((Humanoid)__instance).GetInventory().GetAllItems("$item_helmet_dverger", list);
			foreach (ItemData item in list)
			{
				CircletExtended.PatchCircletItemData(item);
			}
		}
	}
	[HarmonyPatch(typeof(Inventory), "Load")]
	public class Inventory_Load_CircletStats
	{
		public static void Postfix(Inventory __instance)
		{
			if (!CircletExtended.modEnabled.Value)
			{
				return;
			}
			List<ItemData> list = new List<ItemData>();
			__instance.GetAllItems("$item_helmet_dverger", list);
			foreach (ItemData item in list)
			{
				CircletExtended.PatchCircletItemData(item);
			}
		}
	}
	[HarmonyPatch(typeof(ItemDrop), "Start")]
	public static class ItemDrop_Start_CircletStats
	{
		private static void Postfix(ref ItemDrop __instance)
		{
			if (CircletExtended.modEnabled.Value && CircletExtended.getFeaturesByUpgrade.Value && !(__instance.GetPrefabName(((Object)__instance).name) != "HelmetDverger"))
			{
				CircletExtended.PatchCircletItemData(__instance.m_itemData);
			}
		}
	}
	[HarmonyPatch(typeof(Requirement), "GetAmount")]
	public class PieceRequirement_GetAmount_CircletUpgrade
	{
		public static void Postfix(Requirement __instance, int qualityLevel, ref int __result)
		{
			if (CircletExtended.modEnabled.Value && CircletExtended.getFeaturesByUpgrade.Value && __instance.m_resItem.GetPrefabName(((Object)__instance.m_resItem).name) == "HelmetDverger")
			{
				__result = ((qualityLevel <= 1) ? 1 : 0);
			}
		}
	}
	[HarmonyPatch(typeof(InventoryGui), "DoCrafting")]
	public class InventoryGui_DoCrafting_CircletUpgrade
	{
		private static bool PatchMethod(ItemData ___m_craftUpgradeItem, Recipe ___m_craftRecipe)
		{
			if (!CircletExtended.modEnabled.Value)
			{
				return false;
			}
			if (!CircletExtended.getFeaturesByUpgrade.Value)
			{
				return false;
			}
			if ((Object)(object)___m_craftRecipe == (Object)null || ___m_craftUpgradeItem == null)
			{
				return false;
			}
			if (___m_craftUpgradeItem.m_shared.m_name != "$item_helmet_dverger")
			{
				return false;
			}
			return true;
		}

		[HarmonyPriority(800)]
		public static void Prefix(Player player, ref Recipe ___m_craftRecipe, ref KeyValuePair<bool, Requirement[]> __state, ItemData ___m_craftUpgradeItem)
		{
			if (PatchMethod(___m_craftUpgradeItem, ___m_craftRecipe))
			{
				int key = ___m_craftUpgradeItem.m_quality + 1;
				__state = new KeyValuePair<bool, Requirement[]>(player.m_noPlacementCost, ___m_craftRecipe.m_resources.ToArray());
				___m_craftRecipe.m_resources = CircletExtended.recipeRequirements[key].ToArray();
				player.m_noPlacementCost = true;
			}
		}

		[HarmonyPriority(0)]
		public static void Postfix(Player player, ref Recipe ___m_craftRecipe, KeyValuePair<bool, Requirement[]> __state, ItemData ___m_craftUpgradeItem)
		{
			if (PatchMethod(___m_craftUpgradeItem, ___m_craftRecipe))
			{
				player.m_noPlacementCost = __state.Key;
				if (!player.m_noPlacementCost)
				{
					player.ConsumeResources(___m_craftRecipe.m_resources, 1, -1);
				}
				___m_craftRecipe.m_resources = __state.Value.ToArray();
				CircletExtended.PatchCircletItemData(___m_craftUpgradeItem);
			}
		}
	}
	[HarmonyPatch(typeof(InventoryGui), "SetupRequirementList")]
	public class InventoryGui_SetupRequirementList_CircletUpgrade
	{
		private static bool PatchMethod(KeyValuePair<Recipe, ItemData> ___m_selectedRecipe)
		{
			if (!CircletExtended.modEnabled.Value)
			{
				return false;
			}
			if (!CircletExtended.getFeaturesByUpgrade.Value)
			{
				return false;
			}
			if (___m_selectedRecipe.Key.m_item.GetPrefabName(((Object)___m_selectedRecipe.Key.m_item).name) != "HelmetDverger")
			{
				return false;
			}
			return true;
		}

		[HarmonyPriority(800)]
		public static void Prefix(ref int quality, ref KeyValuePair<Recipe, ItemData> ___m_selectedRecipe, ref KeyValuePair<int, Requirement[]> __state, Recipe ___m_craftRecipe)
		{
			if (PatchMethod(___m_selectedRecipe))
			{
				__state = new KeyValuePair<int, Requirement[]>(quality, ___m_selectedRecipe.Key.m_resources.ToArray());
				___m_selectedRecipe.Key.m_resources = CircletExtended.recipeRequirements[quality].ToArray();
				quality = 1;
			}
		}

		[HarmonyPriority(0)]
		public static void Postfix(ref int quality, ref KeyValuePair<Recipe, ItemData> ___m_selectedRecipe, KeyValuePair<int, Requirement[]> __state, Recipe ___m_craftRecipe)
		{
			if (PatchMethod(___m_selectedRecipe))
			{
				___m_selectedRecipe.Key.m_resources = __state.Value.ToArray();
				quality = __state.Key;
			}
		}
	}
	[HarmonyPatch(typeof(Player), "HaveRequirementItems")]
	public class Player_HaveRequirementItems_CircletUpgrade
	{
		private static bool PatchMethod(bool discover, Recipe piece)
		{
			if (!CircletExtended.modEnabled.Value)
			{
				return false;
			}
			if (!CircletExtended.getFeaturesByUpgrade.Value)
			{
				return false;
			}
			if (discover)
			{
				return false;
			}
			if (piece.m_item.GetPrefabName(((Object)piece.m_item).name) != "HelmetDverger")
			{
				return false;
			}
			return true;
		}

		[HarmonyPriority(800)]
		public static void Prefix(ref Recipe piece, bool discover, ref int qualityLevel, ref KeyValuePair<int, Requirement[]> __state)
		{
			if (PatchMethod(discover, piece))
			{
				__state = new KeyValuePair<int, Requirement[]>(qualityLevel, piece.m_resources.ToArray());
				piece.m_resources = CircletExtended.recipeRequirements[qualityLevel].ToArray();
				qualityLevel = 1;
			}
		}

		[HarmonyPriority(0)]
		public static void Postfix(ref Recipe piece, bool discover, ref int qualityLevel, KeyValuePair<int, Requirement[]> __state)
		{
			if (PatchMethod(discover, piece))
			{
				piece.m_resources = __state.Value.ToArray();
				qualityLevel = __state.Key;
			}
		}
	}
	[RequireComponent(typeof(Light))]
	public class DvergerLightController : MonoBehaviour
	{
		private class LightState
		{
			public bool on = true;

			public int level = 2;

			public int intensity = 100;

			public Color color = new Color(0.25f, 0.38f, 0.37f);

			public bool shadows = true;

			public bool spot = false;

			public float overload = 1f;

			public bool demister = false;
		}

		private ZNetView m_nview;

		private Light m_frontLight;

		private Light m_spotLight;

		private Player m_playerAttached;

		private ItemData m_item;

		private int m_zdoIndex;

		private LightState m_state = new LightState();

		private bool m_forceOff = false;

		private int m_quality = 1;

		private ParticleSystemForceField m_overloadDemister;

		private int m_maxLevel = 3;

		private float m_minAngle = 30f;

		private float m_maxAngle = 110f;

		private float m_minIntensity = 1.4f;

		private float m_maxIntensity = 2.2f;

		private float m_minRange = 45f;

		private float m_maxRange = 15f;

		private float m_pointIntensity = 1.1f;

		private float m_pointRange = 10f;

		private int m_overloadCharges = 50;

		private const int intensityIncrement = 10;

		private const int intensityFactorMax = 150;

		private const int intensityFactorMin = 50;

		private const float overloadIntensityInterval = 2f;

		private const float overloadIntensityMin = 0.5f;

		private const float overloadIntensityMax = 4f;

		private static int s_rayMaskSolids;

		private static int s_rayMaskCharacters;

		private void Awake()
		{
			m_nview = ((Component)this).GetComponentInParent<ZNetView>();
		}

		private void Start()
		{
			GetSpotLight();
		}

		private void Update()
		{
			if (!CircletExtended.modEnabled.Value)
			{
				return;
			}
			Player localPlayer = Player.m_localPlayer;
			if ((Object)(object)localPlayer != (Object)null && (Object)(object)localPlayer == (Object)(object)m_playerAttached && ((Character)localPlayer).TakeInput())
			{
				m_forceOff = CircletExtended.disableOnSleep.Value && ((Character)localPlayer).InBed();
				if (!m_forceOff && StateChanged(localPlayer))
				{
					SaveState();
				}
			}
			UpdateLights();
		}

		private void OnDestroy()
		{
			if (CircletExtended.modEnabled.Value)
			{
				Player localPlayer = Player.m_localPlayer;
				if ((Object)(object)localPlayer != (Object)null && (Object)(object)localPlayer == (Object)(object)m_playerAttached && m_state.demister && (Object)(object)((Character)localPlayer).GetSEMan().GetStatusEffect(CircletExtended.demisterEffectHash) != (Object)null && (((Humanoid)localPlayer).m_utilityItem == null || ((Humanoid)localPlayer).m_utilityItem.m_shared.m_name != "$item_demister"))
				{
					((Character)localPlayer).GetSEMan().RemoveStatusEffect(CircletExtended.demisterEffectHash, false);
				}
			}
		}

		private bool QualityLevelAvailable(int quality)
		{
			return !CircletExtended.getFeaturesByUpgrade.Value || m_quality >= quality;
		}

		private bool StateChanged(Player player)
		{
			foreach (int hotkey in CircletExtended.hotkeys)
			{
				if (IsShortcutDown(hotkey, CircletExtended.toggleShortcut))
				{
					m_state.on = !m_state.on;
					CircletExtended.LogInfo("Toggle " + (m_state.on ? "on" : "off"));
					return true;
				}
				if (QualityLevelAvailable(2) && IsShortcutDown(hotkey, CircletExtended.toggleSpotShortcut))
				{
					m_state.spot = !m_state.spot;
					CircletExtended.LogInfo("Toggle spot " + (m_state.spot ? "on" : "off"));
					return true;
				}
				if (CircletExtended.enableDemister.Value && QualityLevelAvailable(4) && IsShortcutDown(hotkey, CircletExtended.toggleDemisterShortcut))
				{
					m_state.demister = !m_state.demister;
					CircletExtended.LogInfo("Toggle demister " + (m_state.demister ? "on" : "off"));
				}
				if (!m_state.on)
				{
					continue;
				}
				if (m_state.level > 0 && IsShortcutDown(hotkey, CircletExtended.widenShortcut))
				{
					m_state.level--;
					CircletExtended.LogInfo($"Widen {m_state.level}");
					return true;
				}
				if (m_state.level < m_maxLevel && IsShortcutDown(hotkey, CircletExtended.narrowShortcut))
				{
					m_state.level++;
					CircletExtended.LogInfo($"Narrow {m_state.level}");
					return true;
				}
				if (m_state.intensity < 150 && IsShortcutDown(hotkey, CircletExtended.increaseIntensityShortcut))
				{
					m_state.intensity = Mathf.Clamp(m_state.intensity + 10, 50, 150);
					CircletExtended.LogInfo($"Increase intensity {m_state.intensity}%");
					return true;
				}
				if (m_state.intensity > 50 && IsShortcutDown(hotkey, CircletExtended.decreaseIntensityShortcut))
				{
					m_state.intensity = Mathf.Clamp(m_state.intensity - 10, 50, 150);
					CircletExtended.LogInfo($"Decrease intensity {m_state.intensity}%");
					return true;
				}
				if (IsShortcutDown(hotkey, CircletExtended.toggleShadowsShortcut))
				{
					m_state.shadows = !m_state.shadows;
					CircletExtended.LogInfo("Toggle shadows " + (m_state.shadows ? "on" : "off"));
					return true;
				}
				if (CircletExtended.enableOverload.Value && QualityLevelAvailable(3) && IsShortcutDown(hotkey, CircletExtended.overloadShortcut))
				{
					CircletExtended.LogInfo("Overload");
					if (m_state.overload != 1f)
					{
						MessageHud.instance.ShowMessage((MessageType)2, "$item_helmet_dverger: $hud_powernotready", 0, (Sprite)null);
					}
					else
					{
						ApplyOverloadEffect(player);
					}
				}
			}
			return false;
		}

		private void ApplyOverloadEffect(Player player)
		{
			//IL_02bf: Unknown result type (might be due to invalid IL or missing references)
			//IL_02cf: Unknown result type (might be due to invalid IL or missing references)
			//IL_0306: Unknown result type (might be due to invalid IL or missing references)
			//IL_030b: Unknown result type (might be due to invalid IL or missing references)
			//IL_03a2: Unknown result type (might be due to invalid IL or missing references)
			//IL_03b3: Unknown result type (might be due to invalid IL or missing references)
			//IL_03e9: Unknown result type (might be due to invalid IL or missing references)
			//IL_03ee: 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_0401: Expected O, but got Unknown
			//IL_048e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0485: Unknown result type (might be due to invalid IL or missing references)
			//IL_0493: Unknown result type (might be due to invalid IL or missing references)
			//IL_0495: Unknown result type (might be due to invalid IL or missing references)
			//IL_04a2: Unknown result type (might be due to invalid IL or missing references)
			//IL_04a7: Unknown result type (might be due to invalid IL or missing references)
			//IL_04ac: Unknown result type (might be due to invalid IL or missing references)
			//IL_04b9: Unknown result type (might be due to invalid IL or missing references)
			//IL_04c0: Unknown result type (might be due to invalid IL or missing references)
			//IL_04f3: Unknown result type (might be due to invalid IL or missing references)
			//IL_04f8: Unknown result type (might be due to invalid IL or missing references)
			//IL_0559: Unknown result type (might be due to invalid IL or missing references)
			//IL_0528: Unknown result type (might be due to invalid IL or missing references)
			//IL_052d: Unknown result type (might be due to invalid IL or missing references)
			if (m_item == null)
			{
				return;
			}
			if ((Object)(object)CircletExtended.overloadEffect == (Object)null)
			{
				Incinerator val = Resources.FindObjectsOfTypeAll<Incinerator>().FirstOrDefault();
				CircletExtended.overloadEffect = Object.Instantiate<GameObject>(val.m_lightingAOEs);
				((Object)CircletExtended.overloadEffect).name = "circletExtendedOverload";
				for (int num = CircletExtended.overloadEffect.transform.childCount - 1; num > 0; num--)
				{
					Transform child = CircletExtended.overloadEffect.transform.GetChild(num);
					switch (((Object)child).name)
					{
					case "AOE_AREA":
					case "Lighting":
					case "lightning":
					case "poff_ring":
					case "shockwave":
					case "AOE_ROD":
					case "Lighting_rod":
					case "Sparcs":
					case "sfx_shockwave (1)":
					case "vfx_RockHit (1)":
						child.parent = null;
						Object.Destroy((Object)(object)((Component)child).gameObject);
						break;
					case "glow":
						((Component)child).gameObject.SetActive(true);
						break;
					}
				}
			}
			if (s_rayMaskSolids == 0)
			{
				s_rayMaskSolids = LayerMask.GetMask(new string[7] { "Default", "static_solid", "Default_small", "piece", "piece_nonsolid", "terrain", "vehicle" });
				s_rayMaskCharacters = LayerMask.GetMask(new string[4] { "character", "character_net", "character_ghost", "character_noenv" });
			}
			Object.Instantiate<GameObject>(CircletExtended.overloadEffect, ((Component)player).transform.position, ((Component)m_frontLight).transform.rotation);
			if (((Character)player).InWater())
			{
				((Character)player).AddLightningDamage(5f);
				((Character)player).AddStaggerDamage(((Character)player).GetStaggerTreshold() + 1f, -((Component)player).transform.forward);
			}
			((MonoBehaviour)this).StartCoroutine(OverloadIntensity());
			if (CircletExtended.enableOverloadDemister.Value && (Object)(object)m_overloadDemister != (Object)null && CircletExtended.overloadDemisterTime.Value != 0f)
			{
				((MonoBehaviour)this).StartCoroutine(OverloadDemister());
			}
			float num2 = (float)Math.Tan((double)(m_frontLight.spotAngle / 2f) * (Math.PI / 180.0)) * m_frontLight.range;
			RaycastHit[] array = Physics.SphereCastAll(((Component)m_frontLight).transform.position, num2, ((Component)m_frontLight).transform.forward, m_frontLight.range, s_rayMaskCharacters);
			if (array.Length != 0)
			{
				for (int i = 0; i < array.Length; i++)
				{
					RaycastHit val2 = array[i];
					GameObject val3 = (Object.op_Implicit((Object)((RaycastHit)(ref val2)).collider) ? Projectile.FindHitObject(((RaycastHit)(ref val2)).collider) : null);
					bool flag = false;
					IDestructible val4 = (Object.op_Implicit((Object)(object)val3) ? val3.GetComponent<IDestructible>() : null);
					if (val4 != null)
					{
						flag = val4 is Character;
						if (!IsValidTarget(val4))
						{
							continue;
						}
					}
					if (flag)
					{
						Character val5 = (Character)(object)((val4 is Character) ? val4 : null);
						Vector3 val6 = (((Object)(object)val5.m_head != (Object)null) ? val5.GetHeadPoint() : val5.GetTopPoint());
						Vector3 val7 = val6 - ((Component)m_frontLight).transform.position;
						bool flag2 = Vector3.Angle(((Component)m_frontLight).transform.forward, ((Vector3)(ref val7)).normalized) <= (m_frontLight.spotAngle + 5f) / 2f;
						float num3 = Utils.DistanceXZ(((Component)m_frontLight).transform.position, val6);
						if (num3 <= 5f || (flag2 && num3 <= m_frontLight.range && !Physics.Linecast(((Component)m_frontLight).transform.position, val6, s_rayMaskSolids)))
						{
							val5.AddStaggerDamage(val5.GetStaggerTreshold() + 1f, ((Vector3)(ref val7)).normalized);
						}
					}
				}
			}
			m_item.m_shared.m_useDurability = true;
			float num4 = m_item.GetMaxDurability() / (float)m_overloadCharges;
			m_item.m_durability = Mathf.Max(0f, m_item.m_durability - num4);
		}

		public IEnumerator OverloadIntensity()
		{
			m_state.overload = 4f;
			float increment = 1.75f * Time.fixedDeltaTime;
			while (m_state.overload > 0.5f)
			{
				m_state.overload -= increment;
				yield return (object)new WaitForFixedUpdate();
			}
			yield return (object)new WaitForSeconds(1f);
			while (m_state.overload <= 1.05f)
			{
				m_state.overload += increment;
				yield return (object)new WaitForFixedUpdate();
			}
			yield return (object)new WaitForSeconds(1f);
			while (m_state.overload >= 1f)
			{
				m_state.overload -= increment;
				yield return (object)new WaitForFixedUpdate();
			}
			m_state.overload = 1f;
		}

		public IEnumerator OverloadDemister()
		{
			((Component)m_overloadDemister).gameObject.SetActive(true);
			for (int i = 0; (float)i < CircletExtended.overloadDemisterTime.Value; i++)
			{
				m_overloadDemister.endRange = 10f + (CircletExtended.overloadDemisterRange.Value - 10f) * (1f - (float)i / CircletExtended.overloadDemisterTime.Value);
				yield return (object)new WaitForSeconds(1f);
			}
			((Component)m_overloadDemister).gameObject.SetActive(false);
		}

		public bool IsValidTarget(IDestructible destr)
		{
			Character val = (Character)(object)((destr is Character) ? destr : null);
			if (Object.op_Implicit((Object)(object)val))
			{
				if ((Object)(object)val == (Object)(object)m_playerAttached)
				{
					return false;
				}
				if ((Object)(object)m_playerAttached != (Object)null)
				{
					bool flag = BaseAI.IsEnemy((Character)(object)m_playerAttached, val) || (Object.op_Implicit((Object)(object)val.GetBaseAI()) && val.GetBaseAI().IsAggravatable() && ((Character)m_playerAttached).IsPlayer());
					if (!((Character)m_playerAttached).IsPlayer() && !flag)
					{
						return false;
					}
					if (((Character)m_playerAttached).IsPlayer() && !((Character)m_playerAttached).IsPVPEnabled() && !flag)
					{
						return false;
					}
				}
				if (val.IsDodgeInvincible())
				{
					return false;
				}
			}
			return true;
		}

		private bool IsShortcutDown(int hotkey, ConfigEntry<KeyboardShortcut> shortcut)
		{
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			//IL_0020: Unknown result type (might be due to invalid IL or missing references)
			//IL_0025: Unknown result type (might be due to invalid IL or missing references)
			//IL_0028: Unknown result type (might be due to invalid IL or missing references)
			//IL_0035: Unknown result type (might be due to invalid IL or missing references)
			//IL_003a: Unknown result type (might be due to invalid IL or missing references)
			int result;
			if (hotkey == ((object)((ConfigEntryBase)shortcut).Definition).GetHashCode())
			{
				KeyboardShortcut value = shortcut.Value;
				if (!((KeyboardShortcut)(ref value)).IsDown())
				{
					value = shortcut.Value;
					if (Input.GetKeyDown(((KeyboardShortcut)(ref value)).MainKey))
					{
						value = shortcut.Value;
						result = ((!((KeyboardShortcut)(ref value)).Modifiers.Any()) ? 1 : 0);
					}
					else
					{
						result = 0;
					}
				}
				else
				{
					result = 1;
				}
			}
			else
			{
				result = 0;
			}
			return (byte)result != 0;
		}

		private void ShowMessage()
		{
			if ((Object)(object)MessageHud.instance != (Object)null && (Object)(object)m_playerAttached != (Object)null && (Object)(object)Player.m_localPlayer == (Object)(object)m_playerAttached)
			{
				MessageHud.instance.m_msgQeue.Clear();
				MessageHud.instance.m_msgQueueTimer = 1f;
				if (!m_forceOff && m_state.on)
				{
					MessageHud.instance.ShowMessage((MessageType)1, $"$item_helmet_dverger: $msg_level {m_state.level} ({m_state.intensity}%)", 0, (Sprite)null);
				}
				else
				{
					MessageHud.instance.ShowMessage((MessageType)1, "$item_helmet_dverger: $hud_off", 0, (Sprite)null);
				}
			}
		}

		public void Initialize(Light light, Player player, ItemData item, int zdoIndex = 0)
		{
			m_frontLight = light;
			m_playerAttached = player;
			m_item = item;
			m_zdoIndex = zdoIndex;
			if (CircletExtended.enableOverloadDemister.Value && Object.op_Implicit((Object)(object)player) && Object.op_Implicit((Object)(object)CircletExtended.demisterForceField) && !Object.op_Implicit((Object)(object)m_overloadDemister))
			{
				GameObject val = Object.Instantiate<GameObject>(CircletExtended.demisterForceField, ((Component)this).transform);
				((Object)val).name = "Particle System Force Field";
				val.SetActive(false);
				m_overloadDemister = val.GetComponent<ParticleSystemForceField>();
				m_overloadDemister.endRange = CircletExtended.overloadDemisterRange.Value;
			}
			LoadState();
			UpdateLights();
		}

		private void LoadState()
		{
			if (IsStateLoaded())
			{
				SetQuality();
			}
		}

		private bool IsStateLoaded()
		{
			//IL_0086: Unknown result type (might be due to invalid IL or missing references)
			//IL_008d: Expected O, but got Unknown
			string text = "";
			if (m_item != null)
			{
				text = GeneralExtensions.GetValueSafe<string, string>(m_item.m_customData, CircletExtended.customDataKey);
				m_quality = m_item.m_quality;
				CircletExtended.LogInfo("Loading state from item: " + text);
			}
			if (string.IsNullOrWhiteSpace(text) && (Object)(object)m_nview != (Object)null && m_nview.IsValid())
			{
				ZDO zDO = m_nview.GetZDO();
				ItemData val = new ItemData();
				ItemDrop.LoadFromZDO(val, zDO);
				text = GeneralExtensions.GetValueSafe<string, string>(val.m_customData, CircletExtended.customDataKey);
				m_quality = val.m_quality;
				CircletExtended.LogInfo("Loading state from zdo: " + text);
				if (string.IsNullOrWhiteSpace(text))
				{
					ItemDrop.LoadFromZDO(m_zdoIndex, val, zDO);
					text = GeneralExtensions.GetValueSafe<string, string>(val.m_customData, CircletExtended.customDataKey);
					m_quality = val.m_quality;
					CircletExtended.LogInfo($"Loading state from zdo index {m_zdoIndex}: {text}");
				}
			}
			if (!string.IsNullOrWhiteSpace(text))
			{
				try
				{
					m_state = JsonUtility.FromJson<LightState>(text);
				}
				catch (Exception arg)
				{
					CircletExtended.LogInfo($"State parsing error:\n{arg}");
					return false;
				}
			}
			m_state.overload = 1f;
			return true;
		}

		private void SaveState()
		{
			//IL_0040: Unknown result type (might be due to invalid IL or missing references)
			//IL_0045: Unknown result type (might be due to invalid IL or missing references)
			if (!((Object)(object)m_nview == (Object)null) && m_nview.IsValid() && m_item != null)
			{
				m_state.color = CircletExtended.circletColor.Value;
				m_item.m_customData[CircletExtended.customDataKey] = JsonUtility.ToJson((object)m_state);
				ShowMessage();
			}
		}

		private void SetQuality()
		{
			m_maxLevel = Mathf.Clamp(CircletExtended.GetMaxSteps(m_quality), 1, 50);
			m_minAngle = Mathf.Clamp(CircletExtended.GetMinAngle(m_quality), 1f, 360f);
			m_maxAngle = Mathf.Clamp(CircletExtended.GetMaxAngle(m_quality), 1f, 360f);
			m_minIntensity = Mathf.Clamp(CircletExtended.GetMaxIntensity(m_quality), 0f, 10f);
			m_maxIntensity = Mathf.Clamp(CircletExtended.GetMinIntensity(m_quality), 0f, 10f);
			m_minRange = Mathf.Clamp(CircletExtended.GetMinRange(m_quality), 0f, 1000f);
			m_maxRange = Mathf.Clamp(CircletExtended.GetMaxRange(m_quality), 0f, 1000f);
			m_pointIntensity = Mathf.Clamp(CircletExtended.GetPointIntensity(m_quality), 0f, 10f);
			m_pointRange = Mathf.Clamp(CircletExtended.GetPointRange(m_quality), 0f, 1000f);
			m_overloadCharges = CircletExtended.overloadChargesPerLevel.Value * ((!QualityLevelAvailable(4)) ? 1 : 2);
		}

		private void UpdateLights()
		{
			//IL_00e2: Unknown result type (might be due to invalid IL or missing references)
			if (m_state.level == m_maxLevel)
			{
				m_frontLight.type = (LightType)2;
				m_frontLight.intensity = m_pointIntensity;
				m_frontLight.range = m_pointRange;
			}
			else
			{
				float num = (float)m_state.level / (float)Math.Max(m_maxLevel - 1, 1);
				m_frontLight.type = (LightType)0;
				m_frontLight.spotAngle = Mathf.Lerp(m_minAngle, m_maxAngle, num);
				m_frontLight.intensity = Mathf.Lerp(m_minIntensity, m_maxIntensity, num);
				m_frontLight.range = Mathf.Lerp(m_minRange, m_maxRange, num);
			}
			m_frontLight.color = m_state.color;
			float num2 = (float)m_state.intensity / 100f;
			Light frontLight = m_frontLight;
			frontLight.range *= num2;
			Light frontLight2 = m_frontLight;
			frontLight2.intensity *= num2;
			Light frontLight3 = m_frontLight;
			frontLight3.intensity *= m_state.overload;
			float num3 = 1f + (float)m_quality * 0.05f;
			Light frontLight4 = m_frontLight;
			frontLight4.range *= num3;
			Light frontLight5 = m_frontLight;
			frontLight5.intensity *= num3;
			((Behaviour)m_frontLight).enabled = !m_forceOff && m_state.on;
			m_frontLight.shadows = (LightShadows)((CircletExtended.enableShadows.Value && m_state.shadows && m_state.level != m_maxLevel) ? 2 : 0);
			m_frontLight.shadowStrength = 1f - (float)m_state.level * 0.1f;
			if ((Object)(object)m_spotLight != (Object)null)
			{
				((Behaviour)m_spotLight).enabled = !m_forceOff && m_state.spot;
				m_spotLight.intensity = m_state.overload;
			}
			if ((Object)(object)m_playerAttached != (Object)null && (Object)(object)m_nview != (Object)null && m_nview.IsValid())
			{
				SEMan sEMan = ((Character)m_playerAttached).GetSEMan();
				if (m_state.demister && (Object)(object)sEMan.GetStatusEffect(CircletExtended.demisterEffectHash) == (Object)null)
				{
					sEMan.AddStatusEffect(CircletExtended.demisterEffectHash, false, 0, 0f);
				}
				else if (!m_state.demister && (Object)(object)sEMan.GetStatusEffect(CircletExtended.demisterEffectHash) != (Object)null)
				{
					sEMan.RemoveStatusEffect(CircletExtended.demisterEffectHash, false);
				}
			}
		}

		private void GetSpotLight()
		{
			if ((Object)(object)m_spotLight != (Object)null)
			{
				return;
			}
			Light[] componentsInParent = ((Component)m_frontLight).GetComponentsInParent<Light>();
			foreach (Light val in componentsInParent)
			{
				if ((Object)(object)val != (Object)(object)m_frontLight)
				{
					m_spotLight = val;
				}
			}
			if ((Object)(object)m_spotLight != (Object)null)
			{
				UpdateLights();
			}
		}
	}
	[HarmonyPatch(typeof(VisEquipment), "AttachItem")]
	public static class VisEquipment_AttachItem_HumanoidAttachment
	{
		private static void Postfix(VisEquipment __instance, GameObject __result, int itemHash)
		{
			if (!CircletExtended.modEnabled.Value || itemHash != CircletExtended.itemHashHelmetDverger || (Object)(object)__result == (Object)null)
			{
				return;
			}
			DvergerLightController component = __result.GetComponent<DvergerLightController>();
			if ((Object)(object)component != (Object)null)
			{
				Object.Destroy((Object)(object)component);
			}
			Light[] componentsInChildren = __result.GetComponentsInChildren<Light>();
			if (componentsInChildren.Length == 0)
			{
				return;
			}
			ItemData val = null;
			Player val2 = null;
			if (__instance.m_isPlayer)
			{
				val2 = ((Component)__instance).GetComponentInParent<Player>();
				if ((Object)(object)val2 == (Object)null)
				{
					return;
				}
				val = ((Humanoid)(object)val2).GetCirclet().circlet ?? ((Humanoid)val2).m_helmetItem;
				if (val == null || ((Object)val.m_dropPrefab).name != "HelmetDverger")
				{
					return;
				}
				CircletExtended.PatchCircletItemData(val);
			}
			CircletExtended.instance.ConfigInit();
			__instance.UpdateVisuals();
			__result.AddComponent<DvergerLightController>().Initialize(componentsInChildren[0], val2, val);
		}
	}
	[HarmonyPatch(typeof(ItemDrop), "Start")]
	public static class ItemDrop_Start_ItemDropAttachment
	{
		private static void Postfix(ItemDrop __instance)
		{
			if (CircletExtended.modEnabled.Value && CircletExtended.visualStateItemDrop.Value && !(__instance.GetPrefabName(((Object)__instance).name) != "HelmetDverger"))
			{
				DvergerLightController componentInChildren = ((Component)__instance).GetComponentInChildren<DvergerLightController>();
				if ((Object)(object)componentInChildren != (Object)null)
				{
					Object.Destroy((Object)(object)componentInChildren);
				}
				Light[] componentsInChildren = ((Component)__instance).GetComponentsInChildren<Light>();
				if (componentsInChildren.Length != 0)
				{
					((Component)((Component)componentsInChildren[0]).gameObject.transform.parent).gameObject.AddComponent<DvergerLightController>().Initialize(componentsInChildren[0], null, __instance.m_itemData);
				}
			}
		}
	}
	[HarmonyPatch(typeof(ItemStand), "SetVisualItem")]
	public static class ItemStand_SetVisualItem_ItemStandAttachment
	{
		private static void Prefix(ItemStand __instance, GameObject ___m_visualItem, string ___m_visualName, int ___m_visualVariant, string itemName, int variant, ref bool __state)
		{
			if (CircletExtended.modEnabled.Value && CircletExtended.visualStateItemStand.Value && !(__instance.GetAttachedItem() != "HelmetDverger") && !((Object)(object)___m_visualItem != (Object)null) && (!(___m_visualName == itemName) || ___m_visualVariant != variant))
			{
				__state = true;
			}
		}

		private static void Postfix(GameObject ___m_visualItem, bool __state)
		{
			if (CircletExtended.modEnabled.Value && __state)
			{
				DvergerLightController componentInChildren = ___m_visualItem.GetComponentInChildren<DvergerLightController>();
				if ((Object)(object)componentInChildren != (Object)null)
				{
					Object.Destroy((Object)(object)componentInChildren);
				}
				Light[] componentsInChildren = ___m_visualItem.GetComponentsInChildren<Light>();
				if (componentsInChildren.Length != 0)
				{
					___m_visualItem.AddComponent<DvergerLightController>().Initialize(componentsInChildren[0], null, null);
				}
			}
		}
	}
	[HarmonyPatch(typeof(ArmorStand), "SetVisualItem")]
	public static class ArmorStand_SetVisualItem_ArmorStandAttachment
	{
		private static void Prefix(int index, List<ArmorStandSlot> ___m_slots, string itemName, int variant, ref bool __state)
		{
			//IL_0041: Unknown result type (might be due to invalid IL or missing references)
			//IL_0047: Invalid comparison between Unknown and I4
			if (CircletExtended.modEnabled.Value && CircletExtended.visualStateArmorStand.Value && !(itemName != "HelmetDverger"))
			{
				ArmorStandSlot val = ___m_slots[index];
				if ((int)val.m_slot == 6 && (!(val.m_visualName == itemName) || val.m_visualVariant != variant))
				{
					__state = true;
				}
			}
		}

		private static void Postfix(int index, VisEquipment ___m_visEquipment, List<ArmorStandSlot> ___m_slots, bool __state)
		{
			if (!CircletExtended.modEnabled.Value || !__state)
			{
				return;
			}
			___m_visEquipment.UpdateVisuals();
			ArmorStandSlot val = ___m_slots[index];
			if (val.m_visualName != "HelmetDverger")
			{
				return;
			}
			GameObject helmetItemInstance = ___m_visEquipment.m_helmetItemInstance;
			if (!((Object)(object)helmetItemInstance == (Object)null))
			{
				DvergerLightController componentInChildren = helmetItemInstance.GetComponentInChildren<DvergerLightController>();
				if ((Object)(object)componentInChildren != (Object)null)
				{
					Object.Destroy((Object)(object)componentInChildren);
				}
				Light[] componentsInChildren = helmetItemInstance.GetComponentsInChildren<Light>();
				if (componentsInChildren.Length != 0)
				{
					helmetItemInstance.AddComponent<DvergerLightController>().Initialize(componentsInChildren[0], null, null, index);
				}
			}
		}
	}
}
namespace Microsoft.CodeAnalysis
{
	[Microsoft.CodeAnalysis.Embedded]
	[CompilerGenerated]
	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;
		}
	}
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace ServerSync
{
	[PublicAPI]
	internal abstract class OwnConfigEntryBase
	{
		public object? LocalBaseValue;

		public bool SynchronizedConfig = true;

		public abstract ConfigEntryBase BaseConfig { get; }
	}
	[PublicAPI]
	internal class SyncedConfigEntry<T> : OwnConfigEntryBase
	{
		public readonly ConfigEntry<T> SourceConfig;

		public override ConfigEntryBase BaseConfig => (ConfigEntryBase)(object)SourceConfig;

		public T Value
		{
			get
			{
				return SourceConfig.Value;
			}
			set
			{
				SourceConfig.Value = value;
			}
		}

		public SyncedConfigEntry(ConfigEntry<T> sourceConfig)
		{
			SourceConfig = sourceConfig;
		}

		public void AssignLocalValue(T value)
		{
			if (LocalBaseValue == null)
			{
				Value = value;
			}
			else
			{
				LocalBaseValue = value;
			}
		}
	}
	internal abstract class CustomSyncedValueBase
	{
		public object? LocalBaseValue;

		public readonly string Identifier;

		public readonly Type Type;

		private object? boxedValue;

		protected bool localIsOwner;

		public readonly int Priority;

		public object? BoxedValue
		{
			get
			{
				return boxedValue;
			}
			set
			{
				boxedValue = value;
				this.ValueChanged?.Invoke();
			}
		}

		public event Action? ValueChanged;

		protected CustomSyncedValueBase(ConfigSync configSync, string identifier, Type type, int priority)
		{
			Priority = priority;
			Identifier = identifier;
			Type = type;
			configSync.AddCustomValue(this);
			localIsOwner = configSync.IsSourceOfTruth;
			configSync.SourceOfTruthChanged += delegate(bool truth)
			{
				localIsOwner = truth;
			};
		}
	}
	[PublicAPI]
	internal sealed class CustomSyncedValue<T> : CustomSyncedValueBase
	{
		public T Value
		{
			get
			{
				return (T)base.BoxedValue;
			}
			set
			{
				base.BoxedValue = value;
			}
		}

		public CustomSyncedValue(ConfigSync configSync, string identifier, T value = default(T), int priority = 0)
			: base(configSync, identifier, typeof(T), priority)
		{
			Value = value;
		}

		public void AssignLocalValue(T value)
		{
			if (localIsOwner)
			{
				Value = value;
			}
			else
			{
				LocalBaseValue = value;
			}
		}
	}
	internal class ConfigurationManagerAttributes
	{
		[UsedImplicitly]
		public bool? ReadOnly = false;
	}
	[PublicAPI]
	internal class ConfigSync
	{
		[HarmonyPatch(typeof(ZRpc), "HandlePackage")]
		private static class SnatchCurrentlyHandlingRPC
		{
			public static ZRpc? currentRpc;

			[HarmonyPrefix]
			private static void Prefix(ZRpc __instance)
			{
				currentRpc = __instance;
			}
		}

		[HarmonyPatch(typeof(ZNet), "Awake")]
		internal static class RegisterRPCPatch
		{
			[HarmonyPostfix]
			private static void Postfix(ZNet __instance)
			{
				isServer = __instance.IsServer();
				foreach (ConfigSync configSync2 in configSyncs)
				{
					ZRoutedRpc.instance.Register<ZPackage>(configSync2.Name + " ConfigSync", (Action<long, ZPackage>)configSync2.RPC_FromOtherClientConfigSync);
					if (isServer)
					{
						configSync2.InitialSyncDone = true;
						Debug.Log((object)("Registered '" + configSync2.Name + " ConfigSync' RPC - waiting for incoming connections"));
					}
				}
				if (isServer)
				{
					((MonoBehaviour)__instance).StartCoroutine(WatchAdminListChanges());
				}
				static void SendAdmin(List<ZNetPeer> peers, bool isAdmin)
				{
					ZPackage package = ConfigsToPackage(null, null, new PackageEntry[1]
					{
						new PackageEntry
						{
							section = "Internal",
							key = "lockexempt",
							type = typeof(bool),
							value = isAdmin
						}
					});
					ConfigSync configSync = configSyncs.First();
					if (configSync != null)
					{
						((MonoBehaviour)ZNet.instance).StartCoroutine(configSync.sendZPackage(peers, package));
					}
				}
				static IEnumerator WatchAdminListChanges()
				{
					SyncedList adminList = (SyncedList)AccessTools.DeclaredField(typeof(ZNet), "m_adminList").GetValue(ZNet.instance);
					List<string> CurrentList = new List<string>(adminList.GetList());
					while (true)
					{
						yield return (object)new WaitForSeconds(30f);
						if (!adminList.GetList().SequenceEqual(CurrentList))
						{
							CurrentList = new List<string>(adminList.GetList());
							List<ZNetPeer> adminPeer = (from p in ZNet.instance.GetPeers()
								where adminList.Contains(p.m_rpc.GetSocket().GetHostName())
								select p).ToList();
							List<ZNetPeer> nonAdminPeer = ZNet.instance.GetPeers().Except(adminPeer).ToList();
							SendAdmin(nonAdminPeer, isAdmin: false);
							SendAdmin(adminPeer, isAdmin: true);
						}
					}
				}
			}
		}

		[HarmonyPatch(typeof(ZNet), "OnNewConnection")]
		private static class RegisterClientRPCPatch
		{
			[HarmonyPostfix]
			private static void Postfix(ZNet __instance, ZNetPeer peer)
			{
				if (__instance.IsServer())
				{
					return;
				}
				foreach (ConfigSync configSync in configSyncs)
				{
					peer.m_rpc.Register<ZPackage>(configSync.Name + " ConfigSync", (Action<ZRpc, ZPackage>)configSync.RPC_FromServerConfigSync);
				}
			}
		}

		private class ParsedConfigs
		{
			public readonly Dictionary<OwnConfigEntryBase, object?> configValues = new Dictionary<OwnConfigEntryBase, object>();

			public readonly Dictionary<CustomSyncedValueBase, object?> customValues = new Dictionary<CustomSyncedValueBase, object>();
		}

		[HarmonyPatch(typeof(ZNet), "Shutdown")]
		private class ResetConfigsOnShutdown
		{
			[HarmonyPostfix]
			private static void Postfix()
			{
				ProcessingServerUpdate = true;
				foreach (ConfigSync configSync in configSyncs)
				{
					configSync.resetConfigsFromServer();
					configSync.IsSourceOfTruth = true;
					configSync.InitialSyncDone = false;
				}
				ProcessingServerUpdate = false;
			}
		}

		[HarmonyPatch(typeof(ZNet), "RPC_PeerInfo")]
		private class SendConfigsAfterLogin
		{
			private class BufferingSocket : ISocket
			{
				public volatile bool finished = false;

				public volatile int versionMatchQueued = -1;

				public readonly List<ZPackage> Package = new List<ZPackage>();

				public readonly ISocket Original;

				public BufferingSocket(ISocket original)
				{
					Original = original;
				}

				public bool IsConnected()
				{
					return Original.IsConnected();
				}

				public ZPackage Recv()
				{
					return Original.Recv();
				}

				public int GetSendQueueSize()
				{
					return Original.GetSendQueueSize();
				}

				public int GetCurrentSendRate()
				{
					return Original.GetCurrentSendRate();
				}

				public bool IsHost()
				{
					return Original.IsHost();
				}

				public void Dispose()
				{
					Original.Dispose();
				}

				public bool GotNewData()
				{
					return Original.GotNewData();
				}

				public void Close()
				{
					Original.Close();
				}

				public string GetEndPointString()
				{
					return Original.GetEndPointString();
				}

				public void GetAndResetStats(out int totalSent, out int totalRecv)
				{
					Original.GetAndResetStats(ref totalSent, ref totalRecv);
				}

				public void GetConnectionQuality(out float localQuality, out float remoteQuality, out int ping, out float outByteSec, out float inByteSec)
				{
					Original.GetConnectionQuality(ref localQuality, ref remoteQuality, ref ping, ref outByteSec, ref inByteSec);
				}

				public ISocket Accept()
				{
					return Original.Accept();
				}

				public int GetHostPort()
				{
					return Original.GetHostPort();
				}

				public bool Flush()
				{
					return Original.Flush();
				}

				public string GetHostName()
				{
					return Original.GetHostName();
				}

				public void VersionMatch()
				{
					if (finished)
					{
						Original.VersionMatch();
					}
					else
					{
						versionMatchQueued = Package.Count;
					}
				}

				public void Send(ZPackage pkg)
				{
					//IL_0057: Unknown result type (might be due to invalid IL or missing references)
					//IL_005d: Expected O, but got Unknown
					int pos = pkg.GetPos();
					pkg.SetPos(0);
					int num = pkg.ReadInt();
					if ((num == StringExtensionMethods.GetStableHashCode("PeerInfo") || num == StringExtensionMethods.GetStableHashCode("RoutedRPC") || num == StringExtensionMethods.GetStableHashCode("ZDOData")) && !finished)
					{
						ZPackage val = new ZPackage(pkg.GetArray());
						val.SetPos(pos);
						Package.Add(val);
					}
					else
					{
						pkg.SetPos(pos);
						Original.Send(pkg);
					}
				}
			}

			[HarmonyPrefix]
			[HarmonyPriority(800)]
			private static void Prefix(ref Dictionary<Assembly, BufferingSocket>? __state, ZNet __instance, ZRpc rpc)
			{
				//IL_0078: Unknown result type (might be due to invalid IL or missing references)
				//IL_007e: Invalid comparison between Unknown and I4
				if (__instance.IsServer())
				{
					BufferingSocket value = new BufferingSocket(rpc.GetSocket());
					AccessTools.DeclaredField(typeof(ZRpc), "m_socket").SetValue(rpc, value);
					object? obj = AccessTools.DeclaredMethod(typeof(ZNet), "GetPeer", new Type[1] { typeof(ZRpc) }, (Type[])null).Invoke(__instance, new object[1] { rpc });
					ZNetPeer val = (ZNetPeer)((obj is ZNetPeer) ? obj : null);
					if (val != null && (int)ZNet.m_onlineBackend > 0)
					{
						AccessTools.DeclaredField(typeof(ZNetPeer), "m_socket").SetValue(val, value);
					}
					if (__state == null)
					{
						__state = new Dictionary<Assembly, BufferingSocket>();
					}
					__state[Assembly.GetExecutingAssembly()] = value;
				}
			}

			[HarmonyPostfix]
			private static void Postfix(Dictionary<Assembly, BufferingSocket> __state, ZNet __instance, ZRpc rpc)
			{
				ZRpc rpc2 = rpc;
				ZNet __instance2 = __instance;
				Dictionary<Assembly, BufferingSocket> __state2 = __state;
				ZNetPeer peer;
				if (__instance2.IsServer())
				{
					object obj = AccessTools.DeclaredMethod(typeof(ZNet), "GetPeer", new Type[1] { typeof(ZRpc) }, (Type[])null).Invoke(__instance2, new object[1] { rpc2 });
					peer = (ZNetPeer)((obj is ZNetPeer) ? obj : null);
					if (peer == null)
					{
						SendBufferedData();
					}
					else
					{
						((MonoBehaviour)__instance2).StartCoroutine(sendAsync());
					}
				}
				void SendBufferedData()
				{
					if (rpc2.GetSocket() is BufferingSocket bufferingSocket)
					{
						AccessTools.DeclaredField(typeof(ZRpc), "m_socket").SetValue(rpc2, bufferingSocket.Original);
						object? obj2 = AccessTools.DeclaredMethod(typeof(ZNet), "GetPeer", new Type[1] { typeof(ZRpc) }, (Type[])null).Invoke(__instance2, new object[1] { rpc2 });
						ZNetPeer val = (ZNetPeer)((obj2 is ZNetPeer) ? obj2 : null);
						if (val != null)
						{
							AccessTools.DeclaredField(typeof(ZNetPeer), "m_socket").SetValue(val, bufferingSocket.Original);
						}
					}
					BufferingSocket bufferingSocket2 = __state2[Assembly.GetExecutingAssembly()];
					bufferingSocket2.finished = true;
					for (int i = 0; i < bufferingSocket2.Package.Count; i++)
					{
						if (i == bufferingSocket2.versionMatchQueued)
						{
							bufferingSocket2.Original.VersionMatch();
						}
						bufferingSocket2.Original.Send(bufferingSocket2.Package[i]);
					}
					if (bufferingSocket2.Package.Count == bufferingSocket2.versionMatchQueued)
					{
						bufferingSocket2.Original.VersionMatch();
					}
				}
				IEnumerator sendAsync()
				{
					foreach (ConfigSync configSync in configSyncs)
					{
						List<PackageEntry> entries = new List<PackageEntry>();
						if (configSync.CurrentVersion != null)
						{
							entries.Add(new PackageEntry
							{
								section = "Internal",
								key = "serverversion",
								type = typeof(string),
								value = configSync.CurrentVersion
							});
						}
						MethodInfo listContainsId = AccessTools.DeclaredMethod(typeof(ZNet), "ListContainsId", (Type[])null, (Type[])null);
						SyncedList adminList = (SyncedList)AccessTools.DeclaredField(typeof(ZNet), "m_adminList").GetValue(ZNet.instance);
						entries.Add(new PackageEntry
						{
							section = "Internal",
							key = "lockexempt",
							type = typeof(bool),
							value = (((object)listContainsId == null) ? ((object)adminList.Contains(rpc2.GetSocket().GetHostName())) : listContainsId.Invoke(ZNet.instance, new object[2]
							{
								adminList,
								rpc2.GetSocket().GetHostName()
							}))
						});
						ZPackage package = ConfigsToPackage(configSync.allConfigs.Select((OwnConfigEntryBase c) => c.BaseConfig), configSync.allCustomValues, entries, partial: false);
						yield return ((MonoBehaviour)__instance2).StartCoroutine(configSync.sendZPackage(new List<ZNetPeer> { peer }, package));
					}
					SendBufferedData();
				}
			}
		}

		private class PackageEntry
		{
			public string section = null;

			public string key = null;

			public Type type = null;

			public object? value;
		}

		[HarmonyPatch(typeof(ConfigEntryBase), "GetSerializedValue")]
		private static class PreventSavingServerInfo
		{
			[HarmonyPrefix]
			private static bool Prefix(ConfigEntryBase __instance, ref string __result)
			{
				OwnConfigEntryBase ownConfigEntryBase = configData(__instance);
				if (ownConfigEntryBase == null || isWritableConfig(ownConfigEntryBase))
				{
					return true;
				}
				__result = TomlTypeConverter.ConvertToString(ownConfigEntryBase.LocalBaseValue, __instance.SettingType);
				return false;
			}
		}

		[HarmonyPatch(typeof(ConfigEntryBase), "SetSerializedValue")]
		private static class PreventConfigRereadChangingValues
		{
			[HarmonyPrefix]
			private static bool Prefix(ConfigEntryBase __instance, string value)
			{
				OwnConfigEntryBase ownConfigEntryBase = configData(__instance);
				if (ownConfigEntryBase == null || ownConfigEntryBase.LocalBaseValue == null)
				{
					return true;
				}
				try
				{
					ownConfigEntryBase.LocalBaseValue = TomlTypeConverter.ConvertToValue(value, __instance.SettingType);
				}
				catch (Exception ex)
				{
					Debug.LogWarning((object)$"Config value of setting \"{__instance.Definition}\" could not be parsed and will be ignored. Reason: {ex.Message}; Value: {value}");
				}
				return false;
			}
		}

		private class InvalidDeserializationTypeException : Exception
		{
			public string expected = null;

			public string received = null;

			public string field = "";
		}

		public static bool ProcessingServerUpdate;

		public readonly string Name;

		public string? DisplayName;

		public string? CurrentVersion;

		public string? MinimumRequiredVersion;

		public bool ModRequired = false;

		private bool? forceConfigLocking;

		private bool isSourceOfTruth = true;

		private static readonly HashSet<ConfigSync> configSyncs;

		private readonly HashSet<OwnConfigEntryBase> allConfigs = new HashSet<OwnConfigEntryBase>();

		private HashSet<CustomSyncedValueBase> allCustomValues = new HashSet<CustomSyncedValueBase>();

		private static bool isServer;

		private static bool lockExempt;

		private OwnConfigEntryBase? lockedConfig = null;

		private const byte PARTIAL_CONFIGS = 1;

		private const byte FRAGMENTED_CONFIG = 2;

		private const byte COMPRESSED_CONFIG = 4;

		private readonly Dictionary<string, SortedDictionary<int, byte[]>> configValueCache = new Dictionary<string, SortedDictionary<int, byte[]>>();

		private readonly List<KeyValuePair<long, string>> cacheExpirations = new List<KeyValuePair<long, string>>();

		private static long packageCounter;

		public bool IsLocked
		{
			get
			{
				bool? flag = forceConfigLocking;
				bool num;
				if (!flag.HasValue)
				{
					if (lockedConfig == null)
					{
						goto IL_0052;
					}
					num = ((IConvertible)lockedConfig.BaseConfig.BoxedValue).ToInt32(CultureInfo.InvariantCulture) != 0;
				}
				else
				{
					num = flag.GetValueOrDefault();
				}
				if (!num)
				{
					goto IL_0052;
				}
				int result = ((!lockExempt) ? 1 : 0);
				goto IL_0053;
				IL_0053:
				return (byte)result != 0;
				IL_0052:
				result = 0;
				goto IL_0053;
			}
			set
			{
				forceConfigLocking = value;
			}
		}

		public bool IsAdmin => lockExempt || isSourceOfTruth;

		public bool IsSourceOfTruth
		{
			get
			{
				return isSourceOfTruth;
			}
			private set
			{
				if (value != isSourceOfTruth)
				{
					isSourceOfTruth = value;
					this.SourceOfTruthChanged?.Invoke(value);
				}
			}
		}

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


		public event Action<bool>? SourceOfTruthChanged;

		private event Action? lockedConfigChanged;

		static ConfigSync()
		{
			ProcessingServerUpdate = false;
			configSyncs = new HashSet<ConfigSync>();
			lockExempt = false;
			packageCounter = 0L;
			RuntimeHelpers.RunClassConstructor(typeof(VersionCheck).TypeHandle);
		}

		public ConfigSync(string name)
		{
			Name = name;
			configSyncs.Add(this);
			new VersionCheck(this);
		}

		public SyncedConfigEntry<T> AddConfigEntry<T>(ConfigEntry<T> configEntry)
		{
			ConfigEntry<T> configEntry2 = configEntry;
			OwnConfigEntryBase ownConfigEntryBase = configData((ConfigEntryBase)(object)configEntry2);
			SyncedConfigEntry<T> syncedEntry = ownConfigEntryBase as SyncedConfigEntry<T>;
			if (syncedEntry == null)
			{
				syncedEntry = new SyncedConfigEntry<T>(configEntry2);
				AccessTools.DeclaredField(typeof(ConfigDescription), "<Tags>k__BackingField").SetValue(((ConfigEntryBase)configEntry2).Description, new object[1]
				{
					new ConfigurationManagerAttributes()
				}.Concat(((ConfigEntryBase)configEntry2).Description.Tags ?? Array.Empty<object>()).Concat(new SyncedConfigEntry<T>[1] { syncedEntry }).ToArray());
				configEntry2.SettingChanged += delegate
				{
					if (!ProcessingServerUpdate && syncedEntry.SynchronizedConfig)
					{
						Broadcast(ZRoutedRpc.Everybody, (ConfigEntryBase)configEntry2);
					}
				};
				allConfigs.Add(syncedEntry);
			}
			return syncedEntry;
		}

		public SyncedConfigEntry<T> AddLockingConfigEntry<T>(ConfigEntry<T> lockingConfig) where T : IConvertible
		{
			if (lockedConfig != null)
			{
				throw new Exception("Cannot initialize locking ConfigEntry twice");
			}
			lockedConfig = AddConfigEntry<T>(lockingConfig);
			lockingConfig.SettingChanged += delegate
			{
				this.lockedConfigChanged?.Invoke();
			};
			return (SyncedConfigEntry<T>)lockedConfig;
		}

		internal void AddCustomValue(CustomSyncedValueBase customValue)
		{
			CustomSyncedValueBase customValue2 = customValue;
			if (allCustomValues.Select((CustomSyncedValueBase v) => v.Identifier).Concat(new string[1] { "serverversion" }).Contains(customValue2.Identifier))
			{
				throw new Exception("Cannot have multiple settings with the same name or with a reserved name (serverversion)");
			}
			allCustomValues.Add(customValue2);
			allCustomValues = new HashSet<CustomSyncedValueBase>(allCustomValues.OrderByDescending((CustomSyncedValueBase v) => v.Priority));
			customValue2.ValueChanged += delegate
			{
				if (!ProcessingServerUpdate)
				{
					Broadcast(ZRoutedRpc.Everybody, customValue2);
				}
			};
		}

		private void RPC_FromServerConfigSync(ZRpc rpc, ZPackage package)
		{
			lockedConfigChanged += serverLockedSettingChanged;
			IsSourceOfTruth = false;
			if (HandleConfigSyncRPC(0L, package, clientUpdate: false))
			{
				InitialSyncDone = true;
			}
		}

		private void RPC_FromOtherClientConfigSync(long sender, ZPackage package)
		{
			HandleConfigSyncRPC(sender, package, clientUpdate: true);
		}

		private bool HandleConfigSyncRPC(long sender, ZPackage package, bool clientUpdate)
		{
			//IL_0074: Unknown result type (might be due to invalid IL or missing references)
			//IL_007b: Expected O, but got Unknown
			//IL_024e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0255: Expected O, but got Unknown
			//IL_01e8: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ef: Expected O, but got Unknown
			try
			{
				if (isServer && IsLocked)
				{
					ZRpc? currentRpc = SnatchCurrentlyHandlingRPC.currentRpc;
					object obj;
					if (currentRpc == null)
					{
						obj = null;
					}
					else
					{
						ISocket socket = currentRpc.GetSocket();
						obj = ((socket != null) ? socket.GetHostName() : null);
					}
					string text = (string)obj;
					if (text != null)
					{
						MethodInfo methodInfo = AccessTools.DeclaredMethod(typeof(ZNet), "ListContainsId", (Type[])null, (Type[])null);
						SyncedList val = (SyncedList)AccessTools.DeclaredField(typeof(ZNet), "m_adminList").GetValue(ZNet.instance);
						if (!(((object)methodInfo == null) ? val.Contains(text) : ((bool)methodInfo.Invoke(ZNet.instance, new object[2] { val, text }))))
						{
							return false;
						}
					}
				}
				cacheExpirations.RemoveAll(delegate(KeyValuePair<long, string> kv)
				{
					if (kv.Key < DateTimeOffset.Now.Ticks)
					{
						configValueCache.Remove(kv.Value);
						return true;
					}
					return false;
				});
				byte b = package.ReadByte();
				if ((b & 2u) != 0)
				{
					long num = package.ReadLong();
					string text2 = sender.ToString() + num;
					if (!configValueCache.TryGetValue(text2, out SortedDictionary<int, byte[]> value))
					{
						value = new SortedDictionary<int, byte[]>();
						configValueCache[text2] = value;
						cacheExpirations.Add(new KeyValuePair<long, string>(DateTimeOffset.Now.AddSeconds(60.0).Ticks, text2));
					}
					int key = package.ReadInt();
					int num2 = package.ReadInt();
					value.Add(key, package.ReadByteArray());
					if (value.Count < num2)
					{
						return false;
					}
					configValueCache.Remove(text2);
					package = new ZPackage(value.Values.SelectMany((byte[] a) => a).ToArray());
					b = package.ReadByte();
				}
				ProcessingServerUpdate = true;
				if ((b & 4u) != 0)
				{
					byte[] buffer = package.ReadByteArray();
					MemoryStream stream = new MemoryStream(buffer);
					MemoryStream memoryStream = new MemoryStream();
					using (DeflateStream deflateStream = new DeflateStream(stream, CompressionMode.Decompress))
					{
						deflateStream.CopyTo(memoryStream);
					}
					package = new ZPackage(memoryStream.ToArray());
					b = package.ReadByte();
				}
				if ((b & 1) == 0)
				{
					resetConfigsFromServer();
				}
				ParsedConfigs parsedConfigs = ReadConfigsFromPackage(package);
				foreach (KeyValuePair<OwnConfigEntryBase, object> configValue in parsedConfigs.configValues)
				{
					if (!isServer && configValue.Key.LocalBaseValue == null)
					{
						configValue.Key.LocalBaseValue = configValue.Key.BaseConfig.BoxedValue;
					}
					configValue.Key.BaseConfig.BoxedValue = configValue.Value;
				}
				foreach (KeyValuePair<CustomSyncedValueBase, object> customValue in parsedConfigs.customValues)
				{
					if (!isServer)
					{
						CustomSyncedValueBase key2 = customValue.Key;
						if (key2.LocalBaseValue == null)
						{
							key2.LocalBaseValue = customValue.Key.BoxedValue;
						}
					}
					customValue.Key.BoxedValue = customValue.Value;
				}
				Debug.Log((object)string.Format("Received {0} configs and {1} custom values from {2} for mod {3}", parsedConfigs.configValues.Count, parsedConfigs.customValues.Count, (isServer || clientUpdate) ? $"client {sender}" : "the server", DisplayName ?? Name));
				if (!isServer)
				{
					serverLockedSettingChanged();
				}
				return true;
			}
			finally
			{
				ProcessingServerUpdate = false;
			}
		}

		private ParsedConfigs ReadConfigsFromPackage(ZPackage package)
		{
			ParsedConfigs parsedConfigs = new ParsedConfigs();
			Dictionary<string, OwnConfigEntryBase> dictionary = allConfigs.Where((OwnConfigEntryBase c) => c.SynchronizedConfig).ToDictionary((OwnConfigEntryBase c) => c.BaseConfig.Definition.Section + "_" + c.BaseConfig.Definition.Key, (OwnConfigEntryBase c) => c);
			Dictionary<string, CustomSyncedValueBase> dictionary2 = allCustomValues.ToDictionary((CustomSyncedValueBase c) => c.Identifier, (CustomSyncedValueBase c) => c);
			int num = package.ReadInt();
			for (int i = 0; i < num; i++)
			{
				string text = package.ReadString();
				string text2 = package.ReadString();
				string text3 = package.ReadString();
				Type type = Type.GetType(text3);
				if (text3 == "" || type != null)
				{
					object obj;
					try
					{
						obj = ((text3 == "") ? null : ReadValueWithTypeFromZPackage(package, type));
					}
					catch (InvalidDeserializationTypeException ex)
					{
						Debug.LogWarning((object)("Got unexpected struct internal type " + ex.received + " for field " + ex.field + " struct " + text3 + " for " + text2 + " in section " + text + " for mod " + (DisplayName ?? Name) + ", expecting " + ex.expected));
						continue;
					}
					OwnConfigEntryBase value2;
					if (text == "Internal")
					{
						CustomSyncedValueBase value;
						if (text2 == "serverversion")
						{
							if (obj?.ToString() != CurrentVersion)
							{
								Debug.LogWarning((object)("Received server version is not equal: server version = " + (obj?.ToString() ?? "null") + "; local version = " + (CurrentVersion ?? "unknown")));
							}
						}
						else if (text2 == "lockexempt")
						{
							if (obj is bool flag)
							{
								lockExempt = flag;
							}
						}
						else if (dictionary2.TryGetValue(text2, out value))
						{
							if ((text3 == "" && (!value.Type.IsValueType || Nullable.GetUnderlyingType(value.Type) != null)) || GetZPackageTypeString(value.Type) == text3)
							{
								parsedConfigs.customValues[value] = obj;
								continue;
							}
							Debug.LogWarning((object)("Got unexpected type " + text3 + " for internal value " + text2 + " for mod " + (DisplayName ?? Name) + ", expecting " + value.Type.AssemblyQualifiedName));
						}
					}
					else if (dictionary.TryGetValue(text + "_" + text2, out value2))
					{
						Type type2 = configType(value2.BaseConfig);
						if ((text3 == "" && (!type2.IsValueType || Nullable.GetUnderlyingType(type2) != null)) || GetZPackageTypeString(type2) == text3)
						{
							parsedConfigs.configValues[value2] = obj;
							continue;
						}
						Debug.LogWarning((object)("Got unexpected type " + text3 + " for " + text2 + " in section " + text + " for mod " + (DisplayName ?? Name) + ", expecting " + type2.AssemblyQualifiedName));
					}
					else
					{
						Debug.LogWarning((object)("Received unknown config entry " + text2 + " in section " + text + " for mod " + (DisplayName ?? Name) + ". This may happen if client and server versions of the mod do not match."));
					}
					continue;
				}
				Debug.LogWarning((object)("Got invalid type " + text3 + ", abort reading of received configs"));
				return new ParsedConfigs();
			}
			return parsedConfigs;
		}

		private static bool isWritableConfig(OwnConfigEntryBase config)
		{
			OwnConfigEntryBase config2 = config;
			ConfigSync configSync = configSyncs.FirstOrDefault((ConfigSync cs) => cs.allConfigs.Contains(config2));
			if (configSync == null)
			{
				return true;
			}
			return configSync.IsSourceOfTruth || !config2.SynchronizedConfig || config2.LocalBaseValue == null || (!configSync.IsLocked && (config2 != configSync.lockedConfig || lockExempt));
		}

		private void serverLockedSettingChanged()
		{
			foreach (OwnConfigEntryBase allConfig in allConfigs)
			{
				configAttribute<ConfigurationManagerAttributes>(allConfig.BaseConfig).ReadOnly = !isWritableConfig(allConfig);
			}
		}

		private void resetConfigsFromServer()
		{
			foreach (OwnConfigEntryBase item in allConfigs.Where((OwnConfigEntryBase config) => config.LocalBaseValue != null))
			{
				item.BaseConfig.BoxedValue = item.LocalBaseValue;
				item.LocalBaseValue = null;
			}
			foreach (CustomSyncedValueBase item2 in allCustomValues.Where((CustomSyncedValueBase config) => config.LocalBaseValue != null))
			{
				item2.BoxedValue = item2.LocalBaseValue;
				item2.LocalBaseValue = null;
			}
			lockedConfigChanged -= serverLockedSettingChanged;
			serverLockedSettingChanged();
		}

		private IEnumerator<bool> distributeConfigToPeers(ZNetPeer peer, ZPackage package)
		{
			ZNetPeer peer2 = peer;
			ZRoutedRpc rpc = ZRoutedRpc.instance;
			if (rpc == null)
			{
				yield break;
			}
			byte[] data = package.GetArray();
			if (data != null && data.LongLength > 250000)
			{
				int fragments = (int)(1 + (data.LongLength - 1) / 250000);
				long packageIdentifier = ++packageCounter;
				int fragment = 0;
				while (fragment < fragments)
				{
					foreach (bool item in waitForQueue())
					{
						yield return item;
					}
					if (peer2.m_socket.IsConnected())
					{
						ZPackage fragmentedPackage = new ZPackage();
						fragmentedPackage.Write((byte)2);
						fragmentedPackage.Write(packageIdentifier);
						fragmentedPackage.Write(fragment);
						fragmentedPackage.Write(fragments);
						fragmentedPackage.Write(data.Skip(250000 * fragment).Take(250000).ToArray());
						SendPackage(fragmentedPackage);
						if (fragment != fragments - 1)
						{
							yield return true;
						}
						int num = fragment + 1;
						fragment = num;
						continue;
					}
					break;
				}
				yield break;
			}
			foreach (bool item2 in waitForQueue())
			{
				yield return item2;
			}
			SendPackage(package);
			void SendPackage(ZPackage pkg)
			{
				string text = Name + " ConfigSync";
				if (isServer)
				{
					peer2.m_rpc.Invoke(text, new object[1] { pkg });
				}
				else
				{
					rpc.InvokeRoutedRPC(peer2.m_server ? 0 : peer2.m_uid, text, new object[1] { pkg });
				}
			}
			IEnumerable<bool> waitForQueue()
			{
				float timeout = Time.time + 30f;
				while (peer2.m_socket.GetSendQueueSize() > 20000)
				{
					if (Time.time > timeout)
					{
						Debug.Log((object)$"Disconnecting {peer2.m_uid} after 30 seconds config sending timeout");
						peer2.m_rpc.Invoke("Error", new object[1] { (object)(ConnectionStatus)5 });
						ZNet.instance.Disconnect(peer2);
						break;
					}
					yield return false;
				}
			}
		}

		private IEnumerator sendZPackage(long target, ZPackage package)
		{
			if (!Object.op_Implicit((Object)(object)ZNet.instance))
			{
				return Enumerable.Empty<object>().GetEnumerator();
			}
			List<ZNetPeer> list = (List<ZNetPeer>)AccessTools.DeclaredField(typeof(ZRoutedRpc), "m_peers").GetValue(ZRoutedRpc.instance);
			if (target != ZRoutedRpc.Everybody)
			{
				list = list.Where((ZNetPeer p) => p.m_uid == target).ToList();
			}
			return sendZPackage(list, package);
		}

		private IEnumerator sendZPackage(List<ZNetPeer> peers, ZPackage package)
		{
			ZPackage package2 = package;
			if (!Object.op_Implicit((Object)(object)ZNet.instance))
			{
				yield break;
			}
			byte[] rawData = package2.GetArray();
			if (rawData != null && rawData.LongLength > 10000)
			{
				ZPackage compressedPackage = new ZPackage();
				compressedPackage.Write((byte)4);
				MemoryStream output = new MemoryStream();
				using (DeflateStream deflateStream = new DeflateStream(output, CompressionLevel.Optimal))
				{
					deflateStream.Write(rawData, 0, rawData.Length);
				}
				compressedPackage.Write(output.ToArray());
				package2 = compressedPackage;
			}
			List<IEnumerator<bool>> writers = (from peer in peers
				where peer.IsReady()
				select peer into p
				select distributeConfigToPeers(p, package2)).ToList();
			writers.RemoveAll((IEnumerator<bool> writer) => !writer.MoveNext());
			while (writers.Count > 0)
			{
				yield return null;
				writers.RemoveAll((IEnumerator<bool> writer) => !writer.MoveNext());
			}
		}

		private void Broadcast(long target, params ConfigEntryBase[] configs)
		{
			if (!IsLocked || isServer)
			{
				ZPackage package = ConfigsToPackage(configs);
				ZNet instance = ZNet.instance;
				if (instance != null)
				{
					((MonoBehaviour)instance).StartCoroutine(sendZPackage(target, package));
				}
			}
		}

		private void Broadcast(long target, params CustomSyncedValueBase[] customValues)
		{
			if (!IsLocked || isServer)
			{
				ZPackage package = ConfigsToPackage(null, customValues);
				ZNet instance = ZNet.instance;
				if (instance != null)
				{
					((MonoBehaviour)instance).StartCoroutine(sendZPackage(target, package));
				}
			}
		}

		private static OwnConfigEntryBase? configData(ConfigEntryBase config)
		{
			return config.Description.Tags?.OfType<OwnConfigEntryBase>().SingleOrDefault();
		}

		public static SyncedConfigEntry<T>? ConfigData<T>(ConfigEntry<T> config)
		{
			return ((ConfigEntryBase)config).Description.Tags?.