Decompiled source of Wisplight Control v1.0.1

plugins/WisplightControl.dll

Decompiled an hour ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using BepInEx;
using BepInEx.Configuration;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.Events;
using UnityEngine.UI;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: AssemblyVersion("0.0.0.0")]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace OctoberJemini.WisplightControl
{
	public static class EyeIconPixels
	{
		public const int Size = 64;

		public static byte[] Render(bool hidden)
		{
			byte[] array = new byte[16384];
			for (int i = 0; i < 64; i++)
			{
				for (int j = 0; j < 64; j++)
				{
					double num = ((double)j + 0.5 - 32.0) / 32.0;
					double num2 = ((double)i + 0.5 - 32.0) / 32.0;
					int num3 = (i * 64 + j) * 4;
					if (!(num * num + num2 * num2 > 0.8835999999999999))
					{
						array[num3] = 18;
						array[num3 + 1] = 20;
						array[num3 + 2] = 23;
						array[num3 + 3] = 235;
						bool flag = num * num + num2 * num2 > 0.7569;
						double num4 = Math.Abs(num);
						double num5 = 0.38 * Math.Sin(Math.PI * (num + 0.72) / 1.44);
						bool num6 = num4 < 0.72 && Math.Abs(Math.Abs(num2) - num5) < 0.055;
						bool flag2 = num * num + num2 * num2 < 0.0256;
						if (flag)
						{
							array[num3] = 82;
							array[num3 + 1] = 74;
							array[num3 + 2] = 53;
						}
						if (num6 || flag2)
						{
							array[num3] = (byte)(hidden ? 166u : 255u);
							array[num3 + 1] = (byte)(hidden ? 170u : 222u);
							array[num3 + 2] = (byte)(hidden ? 177u : 138u);
						}
						if (hidden && num4 < 0.67 && Math.Abs(num2 + num * 0.85) < 0.085)
						{
							array[num3] = byte.MaxValue;
							array[num3 + 1] = 179;
							array[num3 + 2] = 68;
						}
					}
				}
			}
			return array;
		}
	}
	[BepInPlugin("OctoberJemini.WisplightControl", "Wisplight Control", "1.0.0")]
	[BepInIncompatibility("com.Azura.wisptoggle")]
	[BepInIncompatibility("mtsukn.upgradeablewisplight")]
	public sealed class Plugin : BaseUnityPlugin
	{
		[HarmonyPatch(typeof(ObjectDB), "Awake")]
		private static class DbAwakePatch
		{
			private static void Postfix(ObjectDB __instance)
			{
				if (Object.op_Implicit((Object)(object)Instance))
				{
					Instance.Configure(__instance);
				}
			}
		}

		[HarmonyPatch(typeof(ObjectDB), "CopyOtherDB")]
		private static class DbCopyPatch
		{
			private static void Postfix(ObjectDB __instance)
			{
				if (Object.op_Implicit((Object)(object)Instance))
				{
					Instance.Configure(__instance);
				}
			}
		}

		[HarmonyPatch(typeof(SE_Demister), "UpdateStatusEffect")]
		private static class WispEffectPatch
		{
			private static void Postfix(SE_Demister __instance)
			{
				Character character = ((StatusEffect)__instance).m_character;
				Player val = (Player)(object)((character is Player) ? character : null);
				if (!Object.op_Implicit((Object)(object)val) || (Object)(object)val != (Object)(object)Player.m_localPlayer)
				{
					return;
				}
				GameObject val2 = Ball.Invoke(__instance);
				if (Object.op_Implicit((Object)(object)val2))
				{
					WispController wispController = val2.GetComponent<WispController>();
					if (!Object.op_Implicit((Object)(object)wispController))
					{
						wispController = val2.AddComponent<WispController>();
					}
					wispController.Owner = val;
				}
			}
		}

		[HarmonyPatch(typeof(Demister), "Awake")]
		private static class BallPatch
		{
			private static void Postfix(Demister __instance)
			{
				ZNetView componentInParent = ((Component)__instance).GetComponentInParent<ZNetView>();
				if (Object.op_Implicit((Object)(object)componentInParent) && (!(((Object)((Component)componentInParent).gameObject).name != "demister_ball") || !(((Object)((Component)componentInParent).gameObject).name != "demister_ball(Clone)")) && !Object.op_Implicit((Object)(object)((Component)componentInParent).GetComponent<WispController>()))
				{
					((Component)componentInParent).gameObject.AddComponent<WispController>();
				}
			}
		}

		[HarmonyPatch(typeof(ItemData), "GetTooltip", new Type[]
		{
			typeof(ItemData),
			typeof(int),
			typeof(bool),
			typeof(float),
			typeof(int),
			typeof(bool)
		})]
		private static class TooltipPatch
		{
			private static void Postfix(ItemData __0, int __1, ref string __result)
			{
				//IL_0055: Unknown result type (might be due to invalid IL or missing references)
				//IL_005a: Unknown result type (might be due to invalid IL or missing references)
				if (IsWisp(__0))
				{
					__result = __result + "\n\n<color=orange>Wisplight Control</color>\nMist radius: " + WispRules.Radius(__1, BaseRadius.Value, RadiusStep.Value).ToString("0.#") + "m\n" + ((object)ToggleKey.Value/*cast due to .constrained prefix*/).ToString() + " or equipped slot's eye button: Hide/show wisp\nMist clearing stays on. Character glow only while wisp is hidden.";
				}
			}
		}

		public const string Id = "OctoberJemini.WisplightControl";

		internal const string ModeKey = "OctoberJemini.WisplightControl.VisualMode";

		internal static Plugin Instance;

		internal static ConfigEntry<KeyboardShortcut> ToggleKey;

		internal static ConfigEntry<float> BaseRadius;

		internal static ConfigEntry<float> RadiusStep;

		internal static ConfigEntry<float> LightRange;

		internal static ConfigEntry<float> LightIntensity;

		private Harmony harmony;

		private ObjectDB configuredDb;

		private float nextCheck;

		private readonly Dictionary<SharedData, int> originalQualities = new Dictionary<SharedData, int>();

		private readonly Dictionary<Requirement, int> originalCosts = new Dictionary<Requirement, int>();

		private readonly Dictionary<Requirement, int> originalCraftCosts = new Dictionary<Requirement, int>();

		private static readonly FieldRef<SE_Demister, GameObject> Ball = AccessTools.FieldRefAccess<SE_Demister, GameObject>("m_ballInstance");

		private static readonly Func<Player, bool> CanTakeInput = AccessTools.MethodDelegate<Func<Player, bool>>(AccessTools.Method(typeof(Player), "TakeInput", (Type[])null, (Type[])null), (object)null, true);

		private void Awake()
		{
			//IL_0020: Unknown result type (might be due to invalid IL or missing references)
			//IL_0062: Unknown result type (might be due to invalid IL or missing references)
			//IL_006c: Expected O, but got Unknown
			//IL_009f: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a9: Expected O, but got Unknown
			//IL_00dc: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e6: Expected O, but got Unknown
			//IL_0119: Unknown result type (might be due to invalid IL or missing references)
			//IL_0123: Expected O, but got Unknown
			//IL_012e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0138: Expected O, but got Unknown
			Instance = this;
			ToggleKey = ((BaseUnityPlugin)this).Config.Bind<KeyboardShortcut>("Controls", "Toggle key", new KeyboardShortcut((KeyCode)290, Array.Empty<KeyCode>()), "Hide/show the wisp. Mist clearing stays active either way. Character glow replaces the wisp's light only while hidden. Unequip to turn everything off.");
			BaseRadius = ((BaseUnityPlugin)this).Config.Bind<float>("Mist clearing", "Level 1 radius", 15f, new ConfigDescription("Clearing radius in metres at quality 1. Installed vanilla value is 15m.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(1f, 40f), Array.Empty<object>()));
			RadiusStep = ((BaseUnityPlugin)this).Config.Bind<float>("Mist clearing", "Radius per upgrade", 5f, new ConfigDescription("Additional metres per quality level, up to quality 4.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 20f), Array.Empty<object>()));
			LightRange = ((BaseUnityPlugin)this).Config.Bind<float>("Lighting", "Character light radius", 10f, new ConfigDescription("Radius of the steady white character glow, only while the wisp is hidden. Visible wisps retain their normal movement and light.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(1f, 25f), Array.Empty<object>()));
			LightIntensity = ((BaseUnityPlugin)this).Config.Bind<float>("Lighting", "Character light brightness", 1.8f, new ConfigDescription("Steady character-glow intensity. No visible orb or flame. 0 disables its illumination.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 3f), Array.Empty<object>()));
			harmony = new Harmony("OctoberJemini.WisplightControl");
			harmony.PatchAll(typeof(Plugin).Assembly);
			((BaseUnityPlugin)this).Logger.LogInfo((object)"Wisplight Control loaded: four quality levels, steady character light; F9 hides/shows wisp visuals; mist clearing stays on.");
		}

		private void Update()
		{
			//IL_00b3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b8: Unknown result type (might be due to invalid IL or missing references)
			if (Time.unscaledTime >= nextCheck)
			{
				nextCheck = Time.unscaledTime + 1f;
				if (Object.op_Implicit((Object)(object)ObjectDB.instance) && (Object)(object)configuredDb != (Object)(object)ObjectDB.instance)
				{
					Configure(ObjectDB.instance);
				}
				Player localPlayer = Player.m_localPlayer;
				if (Object.op_Implicit((Object)(object)localPlayer))
				{
					foreach (ItemData allItem in ((Humanoid)localPlayer).GetInventory().GetAllItems())
					{
						if (IsWisp(allItem))
						{
							AllowUpgrades(allItem.m_shared);
						}
					}
				}
			}
			Player localPlayer2 = Player.m_localPlayer;
			if (Object.op_Implicit((Object)(object)localPlayer2))
			{
				KeyboardShortcut value = ToggleKey.Value;
				if (((KeyboardShortcut)(ref value)).IsDown() && CanTakeInput(localPlayer2) && !InventoryGui.IsVisible() && !TextInput.IsVisible() && !Menu.IsVisible())
				{
					ToggleVisibility(localPlayer2);
				}
			}
		}

		internal static bool ToggleVisibility(Player player)
		{
			if (!Object.op_Implicit((Object)(object)player) || (Object)(object)player != (Object)(object)Player.m_localPlayer || ((Character)player).IsDead() || ((Character)player).IsTeleporting())
			{
				return false;
			}
			if (Equipped(player) == null)
			{
				((Character)player).Message((MessageType)2, "Equip a Wisplight to switch modes.", 0, (Sprite)null, false);
				return false;
			}
			player.m_customData.TryGetValue("OctoberJemini.WisplightControl.VisualMode", out var value);
			string text = WispRules.Toggle(value);
			player.m_customData["OctoberJemini.WisplightControl.VisualMode"] = text;
			((Character)player).Message((MessageType)2, WispRules.IsWispHidden(text) ? "Wisp hidden (mist clearing stays ON)" : "Wisp visible (mist clearing stays ON)", 0, (Sprite)null, false);
			WispController[] array = WispController.Live.ToArray();
			foreach (WispController wispController in array)
			{
				if ((Object)(object)wispController.Owner == (Object)(object)player)
				{
					wispController.Refresh();
				}
			}
			return true;
		}

		internal static bool IsWisp(ItemData item)
		{
			if (item != null)
			{
				if (!Object.op_Implicit((Object)(object)item.m_dropPrefab) || !(((Object)item.m_dropPrefab).name == "Demister"))
				{
					return item.m_shared.m_name == "$item_demister";
				}
				return true;
			}
			return false;
		}

		internal static ItemData Equipped(Player player)
		{
			return (from i in ((Humanoid)player).GetInventory().GetAllItems()
				where i.m_equipped && IsWisp(i)
				orderby i.m_quality descending
				select i).FirstOrDefault();
		}

		private void AllowUpgrades(SharedData shared)
		{
			if (!originalQualities.ContainsKey(shared))
			{
				originalQualities.Add(shared, shared.m_maxQuality);
			}
			shared.m_maxQuality = 4;
		}

		internal void Configure(ObjectDB db)
		{
			GameObject itemPrefab = db.GetItemPrefab("Demister");
			if (!Object.op_Implicit((Object)(object)itemPrefab))
			{
				return;
			}
			ItemDrop component = itemPrefab.GetComponent<ItemDrop>();
			if (!Object.op_Implicit((Object)(object)component))
			{
				return;
			}
			Recipe val = ((IEnumerable<Recipe>)db.m_recipes).FirstOrDefault((Func<Recipe, bool>)((Recipe r) => Object.op_Implicit((Object)(object)r) && Object.op_Implicit((Object)(object)r.m_item) && IsWisp(r.m_item.m_itemData)));
			if (!Object.op_Implicit((Object)(object)val) || !TieredUpgradeCosts.Configure(db, val))
			{
				return;
			}
			AllowUpgrades(component.m_itemData.m_shared);
			Requirement[] resources = val.m_resources;
			foreach (Requirement val2 in resources)
			{
				if (!Object.op_Implicit((Object)(object)val2.m_resItem))
				{
					continue;
				}
				string name = ((Object)((Component)val2.m_resItem).gameObject).name;
				if (!(name != "Wisp") || !(name != "Silver"))
				{
					if (!originalCosts.ContainsKey(val2))
					{
						originalCosts.Add(val2, val2.m_amountPerLevel);
					}
					if (!originalCraftCosts.ContainsKey(val2))
					{
						originalCraftCosts.Add(val2, val2.m_amount);
					}
					val2.m_amount = 1;
					val2.m_amountPerLevel = ((!(name == "Wisp")) ? 4 : 0);
				}
			}
			configuredDb = db;
			((BaseUnityPlugin)this).Logger.LogInfo((object)"Wisplight upgrades enabled: 20 Wisps per upgrade; Refined Eitr, Gjall and Seeker Soldier trophy progression. Initial craft remains 1 Wisp + 1 Silver.");
		}

		private void OnDestroy()
		{
			TieredUpgradeCosts.Restore();
			WispEyeGrid[] array = WispEyeGrid.Live.ToArray();
			foreach (WispEyeGrid wispEyeGrid in array)
			{
				if (Object.op_Implicit((Object)(object)wispEyeGrid))
				{
					Object.DestroyImmediate((Object)(object)wispEyeGrid);
				}
			}
			WispEyeButton.ReleaseSprites();
			WispController[] array2 = WispController.Live.ToArray();
			foreach (WispController wispController in array2)
			{
				if (Object.op_Implicit((Object)(object)wispController))
				{
					Object.DestroyImmediate((Object)(object)wispController);
				}
			}
			foreach (KeyValuePair<SharedData, int> originalQuality in originalQualities)
			{
				originalQuality.Key.m_maxQuality = originalQuality.Value;
			}
			foreach (KeyValuePair<Requirement, int> originalCost in originalCosts)
			{
				originalCost.Key.m_amountPerLevel = originalCost.Value;
			}
			foreach (KeyValuePair<Requirement, int> originalCraftCost in originalCraftCosts)
			{
				originalCraftCost.Key.m_amount = originalCraftCost.Value;
			}
			Harmony obj = harmony;
			if (obj != null)
			{
				obj.UnpatchSelf();
			}
			Instance = null;
		}
	}
	internal static class TieredUpgradeCosts
	{
		[HarmonyPatch(typeof(Requirement), "GetAmount")]
		private static class AmountPatch
		{
			private static void Postfix(Requirement __instance, int __0, ref int __result)
			{
				if (Owned.TryGetValue(__instance, out var value))
				{
					__result = WispRules.MaterialCost(value, __0);
				}
			}
		}

		private static readonly Dictionary<Recipe, Requirement[]> Originals = new Dictionary<Recipe, Requirement[]>();

		private static readonly Dictionary<Requirement, string> Owned = new Dictionary<Requirement, string>();

		internal static bool Configure(ObjectDB db, Recipe recipe)
		{
			//IL_012b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0130: Unknown result type (might be due to invalid IL or missing references)
			//IL_0138: Unknown result type (might be due to invalid IL or missing references)
			//IL_013f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0146: Unknown result type (might be due to invalid IL or missing references)
			//IL_014f: Expected O, but got Unknown
			if (Originals.ContainsKey(recipe))
			{
				return true;
			}
			List<ItemDrop> list = new List<ItemDrop>();
			string[] array = new string[3] { "Eitr", "TrophyGjall", "TrophySeekerBrute" };
			foreach (string text in array)
			{
				GameObject itemPrefab = db.GetItemPrefab(text);
				ItemDrop val = (Object.op_Implicit((Object)(object)itemPrefab) ? itemPrefab.GetComponent<ItemDrop>() : null);
				if (!Object.op_Implicit((Object)(object)val))
				{
					return false;
				}
				list.Add(val);
			}
			List<Requirement> list2 = new List<Requirement>(recipe.m_resources);
			Originals.Add(recipe, recipe.m_resources);
			foreach (Requirement item in list2)
			{
				if (Object.op_Implicit((Object)(object)item.m_resItem) && (((Object)item.m_resItem).name == "Wisp" || ((Object)item.m_resItem).name == "Silver"))
				{
					Owned[item] = ((Object)item.m_resItem).name;
				}
			}
			foreach (ItemDrop item2 in list)
			{
				Requirement val2 = new Requirement
				{
					m_resItem = item2,
					m_amount = 0,
					m_amountPerLevel = 0,
					m_recover = false
				};
				list2.Add(val2);
				Owned.Add(val2, ((Object)item2).name);
			}
			recipe.m_resources = list2.ToArray();
			return true;
		}

		internal static void Restore()
		{
			foreach (KeyValuePair<Recipe, Requirement[]> original in Originals)
			{
				if (Object.op_Implicit((Object)(object)original.Key))
				{
					original.Key.m_resources = original.Value;
				}
			}
			Originals.Clear();
			Owned.Clear();
		}
	}
	public sealed class WispController : MonoBehaviour
	{
		internal static readonly HashSet<WispController> Live = new HashSet<WispController>();

		private const string VersionKey = "oct_wisp_control";

		private const string ModeKey = "oct_wisp_hidden";

		private const string RadiusKey = "oct_wisp_radius";

		private const string WearerKey = "oct_wisp_wearer";

		internal Player Owner;

		private ZNetView view;

		private Light characterLight;

		private float nextCheck;

		private bool applied;

		private bool lastHidden;

		private float lastRadius;

		private float lastLightRange;

		private float lastLightIntensity;

		private Demister[] demisters;

		private bool[] demisterEnabled;

		private ParticleSystemForceField[] fields;

		private bool[] fieldEnabled;

		private float[] fieldRanges;

		private Light[] lights;

		private bool[] lightEnabled;

		private LightFlicker[] flickers;

		private bool[] flickerEnabled;

		private LightLod[] lightLods;

		private bool[] lightLodEnabled;

		private AudioSource[] audioSources;

		private bool[] audioMute;

		private Renderer[] renderers;

		private bool[] rendererEnabled;

		private void Awake()
		{
			view = ((Component)this).GetComponent<ZNetView>();
			demisters = ((Component)this).GetComponentsInChildren<Demister>(true);
			demisterEnabled = demisters.Select((Demister d) => ((Behaviour)d).enabled).ToArray();
			fields = ((Component)this).GetComponentsInChildren<ParticleSystemForceField>(true);
			fieldEnabled = fields.Select((ParticleSystemForceField f) => ((Behaviour)f).enabled).ToArray();
			fieldRanges = fields.Select((ParticleSystemForceField f) => f.endRange).ToArray();
			lights = ((Component)this).GetComponentsInChildren<Light>(true);
			lightEnabled = lights.Select((Light l) => ((Behaviour)l).enabled).ToArray();
			flickers = ((Component)this).GetComponentsInChildren<LightFlicker>(true);
			flickerEnabled = flickers.Select((LightFlicker f) => ((Behaviour)f).enabled).ToArray();
			lightLods = ((Component)this).GetComponentsInChildren<LightLod>(true);
			lightLodEnabled = lightLods.Select((LightLod l) => ((Behaviour)l).enabled).ToArray();
			audioSources = ((Component)this).GetComponentsInChildren<AudioSource>(true);
			audioMute = audioSources.Select((AudioSource a) => a.mute).ToArray();
			renderers = ((Component)this).GetComponentsInChildren<Renderer>(true);
			rendererEnabled = renderers.Select((Renderer r) => r.enabled).ToArray();
			Live.Add(this);
		}

		internal void Refresh()
		{
			nextCheck = 0f;
		}

		private void LateUpdate()
		{
			//IL_002b: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ab: Unknown result type (might be due to invalid IL or missing references)
			//IL_0173: Unknown result type (might be due to invalid IL or missing references)
			//IL_017e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0196: Unknown result type (might be due to invalid IL or missing references)
			if (Object.op_Implicit((Object)(object)characterLight) && Object.op_Implicit((Object)(object)Owner))
			{
				((Component)characterLight).transform.position = ((Character)Owner).GetCenterPoint();
			}
			if (Time.unscaledTime < nextCheck || !Object.op_Implicit((Object)(object)Plugin.Instance))
			{
				return;
			}
			nextCheck = Time.unscaledTime + 0.2f;
			if (!Object.op_Implicit((Object)(object)view) || !view.IsValid())
			{
				return;
			}
			ZDO zDO = view.GetZDO();
			if (!Object.op_Implicit((Object)(object)Owner) && Object.op_Implicit((Object)(object)ZNetScene.instance))
			{
				GameObject val = ZNetScene.instance.FindInstance(zDO.GetZDOID("oct_wisp_wearer"));
				if (Object.op_Implicit((Object)(object)val))
				{
					Owner = val.GetComponent<Player>();
				}
			}
			if (Object.op_Implicit((Object)(object)Owner) && (Object)(object)Owner == (Object)(object)Player.m_localPlayer && view.IsOwner())
			{
				ItemData val2 = Plugin.Equipped(Owner);
				if (val2 != null)
				{
					Owner.m_customData.TryGetValue("OctoberJemini.WisplightControl.VisualMode", out var value);
					bool flag = WispRules.IsWispHidden(value);
					float num = WispRules.Radius(val2.m_quality, Plugin.BaseRadius.Value, Plugin.RadiusStep.Value);
					if (zDO.GetInt("oct_wisp_control", 0) != 1)
					{
						zDO.Set("oct_wisp_control", 1);
					}
					if (zDO.GetZDOID("oct_wisp_wearer") != ((Character)Owner).GetZDOID())
					{
						zDO.Set("oct_wisp_wearer", ((Character)Owner).GetZDOID());
					}
					if (zDO.GetBool("oct_wisp_hidden", true) != flag)
					{
						zDO.Set("oct_wisp_hidden", flag);
					}
					if (Math.Abs(zDO.GetFloat("oct_wisp_radius", 0f) - num) > 0.01f)
					{
						zDO.Set("oct_wisp_radius", num);
					}
				}
			}
			if (zDO.GetInt("oct_wisp_control", 0) == 1)
			{
				bool flag2 = zDO.GetBool("oct_wisp_hidden", true);
				float num2 = Mathf.Clamp(zDO.GetFloat("oct_wisp_radius", 15f), 1f, 100f);
				if (!applied || flag2 != lastHidden || num2 != lastRadius || Plugin.LightRange.Value != lastLightRange || Plugin.LightIntensity.Value != lastLightIntensity)
				{
					applied = true;
					lastHidden = flag2;
					lastRadius = num2;
					lastLightRange = Plugin.LightRange.Value;
					lastLightIntensity = Plugin.LightIntensity.Value;
					Apply(flag2, num2);
				}
			}
		}

		private void Apply(bool hideWisp, float radius)
		{
			//IL_01ed: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f4: Expected O, but got Unknown
			//IL_02ba: Unknown result type (might be due to invalid IL or missing references)
			//IL_02ad: Unknown result type (might be due to invalid IL or missing references)
			//IL_0240: Unknown result type (might be due to invalid IL or missing references)
			if (Object.op_Implicit((Object)(object)characterLight))
			{
				((Behaviour)characterLight).enabled = false;
			}
			for (int i = 0; i < lightLods.Length; i++)
			{
				if (Object.op_Implicit((Object)(object)lightLods[i]))
				{
					((Behaviour)lightLods[i]).enabled = !hideWisp && lightLodEnabled[i];
				}
			}
			for (int j = 0; j < flickers.Length; j++)
			{
				if (Object.op_Implicit((Object)(object)flickers[j]))
				{
					((Behaviour)flickers[j]).enabled = !hideWisp && flickerEnabled[j];
				}
			}
			for (int k = 0; k < demisters.Length; k++)
			{
				if (Object.op_Implicit((Object)(object)demisters[k]))
				{
					((Behaviour)demisters[k]).enabled = demisterEnabled[k];
				}
			}
			for (int l = 0; l < fields.Length; l++)
			{
				if (Object.op_Implicit((Object)(object)fields[l]))
				{
					fields[l].endRange = radius;
					((Behaviour)fields[l]).enabled = fieldEnabled[l];
				}
			}
			for (int m = 0; m < lights.Length; m++)
			{
				if (Object.op_Implicit((Object)(object)lights[m]))
				{
					((Behaviour)lights[m]).enabled = !hideWisp && lightEnabled[m];
				}
			}
			for (int n = 0; n < audioSources.Length; n++)
			{
				if (Object.op_Implicit((Object)(object)audioSources[n]))
				{
					audioSources[n].mute = hideWisp || audioMute[n];
				}
			}
			for (int num = 0; num < renderers.Length; num++)
			{
				if (Object.op_Implicit((Object)(object)renderers[num]))
				{
					renderers[num].enabled = !hideWisp && rendererEnabled[num];
				}
			}
			if (!Object.op_Implicit((Object)(object)characterLight))
			{
				GameObject val = new GameObject("OCT_WisplightCharacterGlow");
				val.transform.SetParent(Object.op_Implicit((Object)(object)Owner) ? ((Component)Owner).transform : ((Component)this).transform, false);
				characterLight = val.AddComponent<Light>();
				characterLight.type = (LightType)2;
				characterLight.color = Color.white;
				characterLight.shadows = (LightShadows)0;
			}
			characterLight.range = lastLightRange;
			characterLight.intensity = lastLightIntensity;
			((Behaviour)characterLight).enabled = WispRules.CharacterGlow(hideWisp, lastLightIntensity);
			((Component)characterLight).transform.position = (Object.op_Implicit((Object)(object)Owner) ? ((Character)Owner).GetCenterPoint() : ((Component)this).transform.position);
		}

		private void OnDestroy()
		{
			Live.Remove(this);
			if (Object.op_Implicit((Object)(object)characterLight))
			{
				Object.Destroy((Object)(object)((Component)characterLight).gameObject);
			}
			if (!applied)
			{
				return;
			}
			for (int i = 0; i < demisters.Length; i++)
			{
				if (Object.op_Implicit((Object)(object)demisters[i]))
				{
					((Behaviour)demisters[i]).enabled = demisterEnabled[i];
				}
			}
			for (int j = 0; j < fields.Length; j++)
			{
				if (Object.op_Implicit((Object)(object)fields[j]))
				{
					((Behaviour)fields[j]).enabled = fieldEnabled[j];
					fields[j].endRange = fieldRanges[j];
				}
			}
			for (int k = 0; k < lights.Length; k++)
			{
				if (Object.op_Implicit((Object)(object)lights[k]))
				{
					((Behaviour)lights[k]).enabled = lightEnabled[k];
				}
			}
			for (int l = 0; l < flickers.Length; l++)
			{
				if (Object.op_Implicit((Object)(object)flickers[l]))
				{
					((Behaviour)flickers[l]).enabled = flickerEnabled[l];
				}
			}
			for (int m = 0; m < lightLods.Length; m++)
			{
				if (Object.op_Implicit((Object)(object)lightLods[m]))
				{
					((Behaviour)lightLods[m]).enabled = lightLodEnabled[m];
				}
			}
			for (int n = 0; n < audioSources.Length; n++)
			{
				if (Object.op_Implicit((Object)(object)audioSources[n]))
				{
					audioSources[n].mute = audioMute[n];
				}
			}
			for (int num = 0; num < renderers.Length; num++)
			{
				if (Object.op_Implicit((Object)(object)renderers[num]))
				{
					renderers[num].enabled = rendererEnabled[num];
				}
			}
		}
	}
	public sealed class WispEyeButton : MonoBehaviour, IBeginDragHandler, IEventSystemHandler, IDragHandler, IEndDragHandler
	{
		private static Sprite openEye;

		private static Sprite closedEye;

		private static Texture2D openTexture;

		private static Texture2D closedTexture;

		private Player player;

		private ItemData item;

		private Image icon;

		private Button button;

		private UITooltip tooltip;

		private bool painted;

		private bool lastHidden;

		private void Awake()
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_000b: Unknown result type (might be due to invalid IL or missing references)
			//IL_001d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			//IL_0024: 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_0026: Unknown result type (might be due to invalid IL or missing references)
			//IL_002c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0037: Unknown result type (might be due to invalid IL or missing references)
			//IL_0041: Unknown result type (might be due to invalid IL or missing references)
			//IL_004c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0060: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f7: Unknown result type (might be due to invalid IL or missing references)
			//IL_010f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0119: Expected O, but got Unknown
			RectTransform val = (RectTransform)((Component)this).transform;
			Vector2 val2 = default(Vector2);
			((Vector2)(ref val2))..ctor(1f, 1f);
			val.anchorMax = val2;
			Vector2 anchorMin = val2;
			val.anchorMin = anchorMin;
			val.pivot = new Vector2(1f, 1f);
			val.anchoredPosition = new Vector2(-2f, -2f);
			val.sizeDelta = new Vector2(22f, 22f);
			if (!Object.op_Implicit((Object)(object)openEye))
			{
				openEye = MakeSprite(hidden: false, out openTexture);
			}
			if (!Object.op_Implicit((Object)(object)closedEye))
			{
				closedEye = MakeSprite(hidden: true, out closedTexture);
			}
			icon = ((Component)this).gameObject.AddComponent<Image>();
			((Graphic)icon).raycastTarget = true;
			button = ((Component)this).gameObject.AddComponent<Button>();
			((Selectable)button).targetGraphic = (Graphic)(object)icon;
			Button obj = button;
			Navigation navigation = default(Navigation);
			((Navigation)(ref navigation)).mode = (Mode)0;
			((Selectable)obj).navigation = navigation;
			((UnityEvent)button.onClick).AddListener(new UnityAction(Toggle));
			tooltip = ((Component)this).gameObject.AddComponent<UITooltip>();
		}

		internal void Bind(Player wearer, ItemData equippedItem, UITooltip originalTooltip)
		{
			player = wearer;
			item = equippedItem;
			if (Object.op_Implicit((Object)(object)originalTooltip))
			{
				tooltip.m_tooltipPrefab = originalTooltip.m_tooltipPrefab;
			}
			((Behaviour)tooltip).enabled = Object.op_Implicit((Object)(object)originalTooltip) && Object.op_Implicit((Object)(object)originalTooltip.m_tooltipPrefab);
			((Selectable)button).interactable = Object.op_Implicit((Object)(object)player) && (Object)(object)player == (Object)(object)Player.m_localPlayer && item != null && item.m_equipped;
			Paint();
		}

		private void Paint()
		{
			if (Object.op_Implicit((Object)(object)player))
			{
				player.m_customData.TryGetValue("OctoberJemini.WisplightControl.VisualMode", out var value);
				bool flag = WispRules.IsWispHidden(value);
				if (!painted || flag != lastHidden)
				{
					painted = true;
					lastHidden = flag;
					icon.sprite = (flag ? closedEye : openEye);
					tooltip.m_topic = (flag ? "Show wisp" : "Hide wisp");
					tooltip.m_text = "Click to " + (flag ? "show" : "hide") + " the wisp.\nMist clearing stays ON.\nCharacter glow: " + (flag ? "ON" : "OFF");
				}
			}
		}

		private void Toggle()
		{
			if (Object.op_Implicit((Object)(object)player) && item != null && item.m_equipped && ((Humanoid)player).GetInventory().GetAllItems().Contains(item) && Plugin.ToggleVisibility(player))
			{
				Paint();
			}
		}

		public void OnBeginDrag(PointerEventData data)
		{
			((AbstractEventData)data).Use();
		}

		public void OnDrag(PointerEventData data)
		{
			((AbstractEventData)data).Use();
		}

		public void OnEndDrag(PointerEventData data)
		{
			((AbstractEventData)data).Use();
		}

		private static Sprite MakeSprite(bool hidden, out Texture2D texture)
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_000d: Expected O, but got Unknown
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_006e: Unknown result type (might be due to invalid IL or missing references)
			texture = new Texture2D(64, 64, (TextureFormat)4, false);
			((Object)texture).name = (hidden ? "OCT_WispEyeClosed" : "OCT_WispEyeOpen");
			((Texture)texture).filterMode = (FilterMode)1;
			((Texture)texture).wrapMode = (TextureWrapMode)1;
			texture.LoadRawTextureData(EyeIconPixels.Render(hidden));
			texture.Apply(false, true);
			return Sprite.Create(texture, new Rect(0f, 0f, 64f, 64f), new Vector2(0.5f, 0.5f), 64f);
		}

		internal static void ReleaseSprites()
		{
			if (Object.op_Implicit((Object)(object)openEye))
			{
				Object.Destroy((Object)(object)openEye);
			}
			if (Object.op_Implicit((Object)(object)closedEye))
			{
				Object.Destroy((Object)(object)closedEye);
			}
			if (Object.op_Implicit((Object)(object)openTexture))
			{
				Object.Destroy((Object)(object)openTexture);
			}
			if (Object.op_Implicit((Object)(object)closedTexture))
			{
				Object.Destroy((Object)(object)closedTexture);
			}
		}
	}
	public sealed class WispEyeGrid : MonoBehaviour
	{
		[HarmonyPatch(typeof(InventoryGrid), "UpdateGui")]
		private static class GridPatch
		{
			private static void Postfix(InventoryGrid __instance, Inventory ___m_inventory, List<InventoryElement> ___m_elements)
			{
				if (Object.op_Implicit((Object)(object)Plugin.Instance) && ___m_inventory != null && ___m_elements != null)
				{
					WispEyeGrid wispEyeGrid = ((Component)__instance).GetComponent<WispEyeGrid>();
					if (!Object.op_Implicit((Object)(object)wispEyeGrid))
					{
						wispEyeGrid = ((Component)__instance).gameObject.AddComponent<WispEyeGrid>();
					}
					wispEyeGrid.Sync(___m_inventory, ___m_elements);
				}
			}
		}

		internal static readonly HashSet<WispEyeGrid> Live = new HashSet<WispEyeGrid>();

		private WispEyeButton eye;

		private void Awake()
		{
			Live.Add(this);
		}

		internal void Sync(Inventory inventory, List<InventoryElement> elements)
		{
			//IL_012b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0132: Expected O, but got Unknown
			//IL_0091: Unknown result type (might be due to invalid IL or missing references)
			//IL_00aa: Unknown result type (might be due to invalid IL or missing references)
			Player localPlayer = Player.m_localPlayer;
			ItemData val = null;
			if (Object.op_Implicit((Object)(object)localPlayer) && inventory != null)
			{
				foreach (ItemData allItem in inventory.GetAllItems())
				{
					if (allItem.m_equipped && Plugin.IsWisp(allItem) && ((Humanoid)localPlayer).GetInventory().GetAllItems().Contains(allItem))
					{
						val = allItem;
						break;
					}
				}
			}
			InventoryElement val2 = null;
			if (val != null)
			{
				foreach (InventoryElement element in elements)
				{
					if (Object.op_Implicit((Object)(object)element) && element.Position.x == val.m_gridPos.x && element.Position.y == val.m_gridPos.y)
					{
						val2 = element;
						break;
					}
				}
			}
			if (!Object.op_Implicit((Object)(object)val2))
			{
				if (Object.op_Implicit((Object)(object)eye))
				{
					((Component)eye).gameObject.SetActive(false);
				}
				return;
			}
			if (!Object.op_Implicit((Object)(object)eye))
			{
				GameObject val3 = new GameObject("OCT_WisplightEye", new Type[1] { typeof(RectTransform) });
				val3.layer = ((Component)val2).gameObject.layer;
				val3.transform.SetParent(((Component)val2).transform, false);
				eye = val3.AddComponent<WispEyeButton>();
			}
			if ((Object)(object)((Component)eye).transform.parent != (Object)(object)((Component)val2).transform)
			{
				((Component)eye).transform.SetParent(((Component)val2).transform, false);
			}
			((Component)eye).gameObject.SetActive(true);
			((Component)eye).transform.SetAsLastSibling();
			eye.Bind(localPlayer, val, val2.m_tooltip);
		}

		private void OnDestroy()
		{
			Live.Remove(this);
			if (Object.op_Implicit((Object)(object)eye))
			{
				Object.Destroy((Object)(object)((Component)eye).gameObject);
			}
		}
	}
	public static class WispRules
	{
		public const int MaxQuality = 4;

		public const int CraftAmount = 1;

		public const int WispsPerUpgrade = 20;

		public const int SilverPerLevel = 4;

		public static int MaterialCost(string prefab, int targetQuality)
		{
			int num = Quality(targetQuality);
			switch (prefab)
			{
			case "Wisp":
				if (num != 1)
				{
					return 20;
				}
				return 1;
			case "Silver":
				if (num != 1)
				{
					return UpgradeCost(num, 4);
				}
				return 1;
			case "Eitr":
				return num switch
				{
					3 => 25, 
					2 => 10, 
					_ => 0, 
				};
			case "TrophyGjall":
				return (num == 3) ? 1 : 0;
			case "TrophySeekerBrute":
				return (num == 4) ? 1 : 0;
			default:
				return 0;
			}
		}

		public static bool CharacterGlow(bool wispHidden, float brightness)
		{
			if (wispHidden)
			{
				return brightness > 0f;
			}
			return false;
		}

		public static int Quality(int quality)
		{
			return Math.Max(1, Math.Min(4, quality));
		}

		public static float Radius(int quality, float firstRadius, float step)
		{
			return Math.Max(1f, firstRadius) + (float)(Quality(quality) - 1) * Math.Max(0f, step);
		}

		public static int UpgradeCost(int targetQuality, int perLevel)
		{
			int num = Quality(targetQuality);
			if (num > 1)
			{
				return ((num == 4) ? 4 : (num - 1)) * Math.Max(0, perLevel);
			}
			return 0;
		}

		public static bool IsWispHidden(string saved)
		{
			return saved != "visible";
		}

		public static string Toggle(string saved)
		{
			if (!IsWispHidden(saved))
			{
				return "hidden";
			}
			return "visible";
		}
	}
}