Decompiled source of Persistent Pings v1.0.1

PersistentPings.dll

Decompiled an hour ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Configuration;
using BepInEx.Core.Logging.Interpolation;
using BepInEx.Logging;
using BepInEx.Unity.IL2CPP;
using HarmonyLib;
using Il2CppInterop.Runtime;
using Il2CppInterop.Runtime.Injection;
using Il2CppInterop.Runtime.InteropTypes;
using Il2CppSystem;
using MelonLoader;
using MelonLoader.Preferences;
using Microsoft.CodeAnalysis;
using PersistentPings;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.SceneManagement;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: MelonInfo(typeof(PersistentPingsMod), "Persistent Pings", "1.0.1", "Persistent Pings", null)]
[assembly: MelonGame("BoltBlasterGames", "TheSpellBrigade")]
[assembly: TargetFramework(".NETCoreApp,Version=v6.0", FrameworkDisplayName = ".NET 6.0")]
[assembly: AssemblyCompany("PersistentPings")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.1.0")]
[assembly: AssemblyInformationalVersion("1.0.1")]
[assembly: AssemblyProduct("PersistentPings")]
[assembly: AssemblyTitle("PersistentPings")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.0.1.0")]
[module: UnverifiableCode]
[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 PersistentPings
{
	public class PersistentPingsMod : MelonMod
	{
		private sealed class Tracked
		{
			public PingPerformer Performer;

			public Transform Target;

			public GameObject Visual;

			public IScreenPointerManager Pointers;

			public ulong PingedBy;

			public float PingedAt;
		}

		private const float Forever = 1000000f;

		private const float CheckInterval = 0.25f;

		private const float VisualGracePeriod = 1.5f;

		internal static MelonLogger.Instance Log;

		private static MelonPreferences_Category _category;

		internal static MelonPreferences_Entry<bool> Enabled;

		internal static MelonPreferences_Entry<bool> RepingClears;

		internal static MelonPreferences_Entry<bool> PersistLocations;

		internal static MelonPreferences_Entry<bool> PersistPlayers;

		private static readonly Dictionary<IntPtr, Tracked> Active = new Dictionary<IntPtr, Tracked>();

		private static readonly List<IntPtr> ToRemove = new List<IntPtr>();

		private float _nextCheck;

		public override void OnInitializeMelon()
		{
			//IL_012a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0138: Expected O, but got Unknown
			Log = base.LoggerInstance;
			_category = MelonPreferences.CreateCategory("PersistentPings", "Persistent Pings");
			Enabled = _category.CreateEntry("Enabled", default_value: true, "Enabled", "Keep pings visible for as long as the pinged thing still exists");
			RepingClears = _category.CreateEntry("RepingClears", default_value: false, "Ping Again to Clear", "Pinging something you already pinged removes your ping");
			PersistLocations = _category.CreateEntry("PersistLocations", default_value: false, "Persist Ground Pings", "Also keep plain location pings (pinging empty ground) forever");
			PersistPlayers = _category.CreateEntry("PersistPlayers", default_value: false, "Persist Player Pings", "Also keep pings on living players / ghosts forever (revive zones always persist)");
			_category.SaveToFile(printmsg: false);
			Enabled.OnEntryValueChanged.Subscribe(delegate(bool _, bool now)
			{
				if (!now)
				{
					ReleaseAll();
				}
			});
			try
			{
				MethodInfo methodInfo = AccessTools.Method(typeof(PingPerformer), "PerformPing", (Type[])null, (Type[])null);
				if (methodInfo == null)
				{
					throw new MissingMethodException("PingPerformer.PerformPing not found");
				}
				base.HarmonyInstance.Patch((MethodBase)methodInfo, new HarmonyMethod(typeof(PersistentPingsMod), "PerformPingPrefix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				Log.Msg("ready — pings now last until the pinged object is gone");
			}
			catch (Exception ex)
			{
				Log.Error("failed to hook PingPerformer.PerformPing, mod disabled. " + ex.GetType().Name + ": " + ex.Message);
			}
		}

		private static bool PerformPingPrefix(PingPerformer __instance, ulong performerId, ref float pingVisibilityDuration)
		{
			try
			{
				if (!Enabled.Value || (Object)(object)__instance == (Object)null)
				{
					return true;
				}
				if (!PersistLocations.Value && (Object)(object)((Component)__instance).GetComponentInParent<PingLocation>() != (Object)null)
				{
					return true;
				}
				if (!PersistPlayers.Value && IsLivingPlayer(__instance))
				{
					return true;
				}
				IntPtr pointer = ((Il2CppObjectBase)__instance).Pointer;
				if (RepingClears.Value && Active.TryGetValue(pointer, out var value) && value.PingedBy == performerId && IsShowing(value))
				{
					Active.Remove(pointer);
					Hide(value);
					return false;
				}
				pingVisibilityDuration = 1000000f;
				Active[pointer] = new Tracked
				{
					Performer = __instance,
					Target = (((Object)(object)__instance.pingableTransform != (Object)null) ? __instance.pingableTransform : ((Component)__instance).transform),
					Visual = __instance.pingVisual,
					Pointers = __instance.screenPointerManager,
					PingedBy = performerId,
					PingedAt = Time.time
				};
			}
			catch (Exception value2)
			{
				Log.Error($"ping: {value2}");
			}
			return true;
		}

		public override void OnUpdate()
		{
			if (Active.Count == 0 || Time.unscaledTime < _nextCheck)
			{
				return;
			}
			_nextCheck = Time.unscaledTime + 0.25f;
			try
			{
				foreach (KeyValuePair<IntPtr, Tracked> item2 in Active)
				{
					item2.Deconstruct(out var key, out var value);
					IntPtr item = key;
					Tracked tracked = value;
					PingPerformer performer = tracked.Performer;
					if ((Object)(object)performer == (Object)null)
					{
						StopPointer(tracked);
						ToRemove.Add(item);
					}
					else if (!((Component)performer).gameObject.activeInHierarchy || ((Object)(object)tracked.Target != (Object)null && !((Component)tracked.Target).gameObject.activeInHierarchy))
					{
						Hide(tracked);
						ToRemove.Add(item);
					}
					else if (performer.IsDeactivated || (Time.time - tracked.PingedAt > 1.5f && !IsShowing(tracked)))
					{
						ToRemove.Add(item);
					}
				}
			}
			catch (Exception ex)
			{
				Log.Error("watchdog: " + ex.Message);
				ToRemove.AddRange(Active.Keys);
			}
			foreach (IntPtr item3 in ToRemove)
			{
				Active.Remove(item3);
			}
			ToRemove.Clear();
		}

		public override void OnSceneWasUnloaded(int buildIndex, string sceneName)
		{
			Active.Clear();
		}

		private static bool IsLivingPlayer(PingPerformer p)
		{
			if (!((Object)(object)((Component)p).GetComponentInParent<GameplayPlayer>() != (Object)null))
			{
				return (Object)(object)((Component)p).GetComponentInParent<PlayerGhost>() != (Object)null;
			}
			return true;
		}

		private static bool IsShowing(Tracked t)
		{
			if (!((Object)(object)t.Visual == (Object)null))
			{
				return t.Visual.activeSelf;
			}
			return true;
		}

		private static void Hide(Tracked t)
		{
			PingPerformer performer = t.Performer;
			try
			{
				if ((Object)(object)performer != (Object)null && ((Behaviour)performer).isActiveAndEnabled)
				{
					performer.CancelHidePingCoroutine();
					performer.hideCoroutine = ((MonoBehaviour)performer).StartCoroutine(performer.HideCoroutine(0f));
					return;
				}
			}
			catch (Exception ex)
			{
				Log.Warning("hide: " + ex.Message);
			}
			try
			{
				if ((Object)(object)t.Visual != (Object)null)
				{
					t.Visual.SetActive(false);
				}
			}
			catch
			{
			}
			StopPointer(t);
		}

		private static void StopPointer(Tracked t)
		{
			try
			{
				IScreenPointerManager pointers = t.Pointers;
				ScreenPointerManager val = ((pointers != null) ? ((Il2CppObjectBase)pointers).TryCast<ScreenPointerManager>() : null);
				if ((Object)(object)val != (Object)null && t.Target != null)
				{
					val.StopHighlight(t.Target);
				}
			}
			catch
			{
			}
		}

		private static void ReleaseAll()
		{
			foreach (Tracked value in Active.Values)
			{
				Hide(value);
			}
			Active.Clear();
		}
	}
}
namespace PersistentPings.BepInExPlugin
{
	[BepInPlugin("SpellBrigade.PersistentPings", "Persistent Pings", "1.0.1")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	public class Plugin : BasePlugin
	{
		public const string Guid = "SpellBrigade.PersistentPings";

		public override void Load()
		{
			MelonCompat.Start<PersistentPingsMod, Runner>((BasePlugin)(object)this, "SpellBrigade.PersistentPings");
		}
	}
	public class Runner : MonoBehaviour
	{
		public Runner(IntPtr ptr)
			: base(ptr)
		{
		}

		private void Update()
		{
			MelonCompat.Update();
		}
	}
}
namespace MelonLoader
{
	[AttributeUsage(AttributeTargets.Assembly)]
	public sealed class MelonInfoAttribute : Attribute
	{
		public MelonInfoAttribute(Type type, string name, string version, string author, string downloadLink = null)
		{
		}
	}
	[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)]
	public sealed class MelonGameAttribute : Attribute
	{
		public MelonGameAttribute(string developer = null, string name = null)
		{
		}
	}
	[AttributeUsage(AttributeTargets.Assembly)]
	public sealed class MelonOptionalDependenciesAttribute : Attribute
	{
		public MelonOptionalDependenciesAttribute(params string[] names)
		{
		}
	}
	public abstract class MelonBase
	{
		public MelonLogger.Instance LoggerInstance { get; internal set; }

		public Harmony HarmonyInstance { get; internal set; }

		public static object FindMelon(string name, string author)
		{
			try
			{
				foreach (PluginInfo value in ((BaseChainloader<BasePlugin>)(object)IL2CPPChainloader.Instance).Plugins.Values)
				{
					if (((value != null) ? value.Metadata : null) != null && string.Equals(value.Metadata.Name, name, StringComparison.OrdinalIgnoreCase) && value.Instance != null)
					{
						return value;
					}
				}
			}
			catch
			{
			}
			return null;
		}
	}
	public abstract class MelonMod : MelonBase
	{
		public virtual void OnInitializeMelon()
		{
		}

		public virtual void OnLateInitializeMelon()
		{
		}

		public virtual void OnUpdate()
		{
		}

		public virtual void OnLateUpdate()
		{
		}

		public virtual void OnFixedUpdate()
		{
		}

		public virtual void OnGUI()
		{
		}

		public virtual void OnApplicationQuit()
		{
		}

		public virtual void OnSceneWasLoaded(int buildIndex, string sceneName)
		{
		}

		public virtual void OnSceneWasInitialized(int buildIndex, string sceneName)
		{
		}

		public virtual void OnSceneWasUnloaded(int buildIndex, string sceneName)
		{
		}
	}
	public static class MelonLogger
	{
		public sealed class Instance
		{
			private readonly ManualLogSource _log;

			public Instance(ManualLogSource log)
			{
				_log = log;
			}

			public void Msg(string text)
			{
				_log.LogInfo((object)text);
			}

			public void Msg(object value)
			{
				_log.LogInfo(value);
			}

			public void Msg(string format, params object[] args)
			{
				_log.LogInfo((object)string.Format(format, args));
			}

			public void Warning(string text)
			{
				_log.LogWarning((object)text);
			}

			public void Warning(object value)
			{
				_log.LogWarning(value);
			}

			public void Error(string text)
			{
				_log.LogError((object)text);
			}

			public void Error(object value)
			{
				_log.LogError(value);
			}

			public void Error(string text, Exception e)
			{
				//IL_000a: Unknown result type (might be due to invalid IL or missing references)
				//IL_0010: Expected O, but got Unknown
				ManualLogSource log = _log;
				bool flag = default(bool);
				BepInExErrorLogInterpolatedStringHandler val = new BepInExErrorLogInterpolatedStringHandler(1, 2, ref flag);
				if (flag)
				{
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(text);
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral("\n");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<Exception>(e);
				}
				log.LogError(val);
			}
		}
	}
	public static class MelonCompat
	{
		internal static ConfigFile Config;

		private static MelonMod _mod;

		private static bool _lateInit;

		public static void Start<TMod, TRunner>(BasePlugin plugin, string harmonyId) where TMod : MelonMod, new() where TRunner : MonoBehaviour
		{
			//IL_002d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0037: Expected O, but got Unknown
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0073: Expected O, but got Unknown
			Config = plugin.Config;
			_mod = new TMod
			{
				LoggerInstance = new MelonLogger.Instance(plugin.Log),
				HarmonyInstance = new Harmony(harmonyId)
			};
			try
			{
				_mod.HarmonyInstance.PatchAll(typeof(TMod).Assembly);
			}
			catch (Exception ex)
			{
				ManualLogSource log = plugin.Log;
				bool flag = default(bool);
				BepInExErrorLogInterpolatedStringHandler val = new BepInExErrorLogInterpolatedStringHandler(17, 1, ref flag);
				if (flag)
				{
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral("Harmony patches: ");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<Exception>(ex);
				}
				log.LogError(val);
			}
			_mod.OnInitializeMelon();
			HookScenes();
			ClassInjector.RegisterTypeInIl2Cpp<TRunner>();
			plugin.AddComponent<TRunner>();
		}

		private static void HookScenes()
		{
			SceneManager.sceneLoaded += DelegateSupport.ConvertDelegate<UnityAction<Scene, LoadSceneMode>>((Delegate)new Action<Scene, LoadSceneMode>(OnSceneLoaded));
			SceneManager.sceneUnloaded += DelegateSupport.ConvertDelegate<UnityAction<Scene>>((Delegate)new Action<Scene>(OnSceneUnloaded));
		}

		private static void OnSceneLoaded(Scene scene, LoadSceneMode mode)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			Guard(delegate
			{
				_mod.OnSceneWasLoaded(((Scene)(ref scene)).buildIndex, ((Scene)(ref scene)).name);
			});
			Guard(delegate
			{
				_mod.OnSceneWasInitialized(((Scene)(ref scene)).buildIndex, ((Scene)(ref scene)).name);
			});
		}

		private static void OnSceneUnloaded(Scene scene)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			Guard(delegate
			{
				_mod.OnSceneWasUnloaded(((Scene)(ref scene)).buildIndex, ((Scene)(ref scene)).name);
			});
		}

		public static void Update()
		{
			if (_mod != null)
			{
				if (!_lateInit)
				{
					_lateInit = true;
					Guard(_mod.OnLateInitializeMelon);
				}
				_mod.OnUpdate();
			}
		}

		public static void LateUpdate()
		{
			_mod?.OnLateUpdate();
		}

		public static void FixedUpdate()
		{
			_mod?.OnFixedUpdate();
		}

		public static void OnGUI()
		{
			_mod?.OnGUI();
		}

		public static void Quit()
		{
			_mod?.OnApplicationQuit();
		}

		private static void Guard(Action a)
		{
			try
			{
				a();
			}
			catch (Exception ex)
			{
				_mod.LoggerInstance.Error(ex.ToString());
			}
		}
	}
	public static class MelonPreferences
	{
		private static readonly Dictionary<string, MelonPreferences_Category> Categories = new Dictionary<string, MelonPreferences_Category>();

		public static MelonPreferences_Category CreateCategory(string identifier, string displayName = null, bool is_hidden = false, bool is_inlined = false)
		{
			if (!Categories.TryGetValue(identifier, out var value))
			{
				value = (Categories[identifier] = new MelonPreferences_Category(identifier, displayName ?? identifier)
				{
					IsHidden = is_hidden
				});
			}
			return value;
		}

		public static MelonPreferences_Category GetCategory(string identifier)
		{
			if (!Categories.TryGetValue(identifier, out var value))
			{
				return null;
			}
			return value;
		}

		public static void Save()
		{
			ConfigFile config = MelonCompat.Config;
			if (config != null)
			{
				config.Save();
			}
		}
	}
	public sealed class MelonPreferences_Category
	{
		public readonly List<MelonPreferences_Entry> Entries = new List<MelonPreferences_Entry>();

		public string Identifier { get; }

		public string DisplayName { get; }

		public bool IsHidden { get; internal set; }

		internal MelonPreferences_Category(string identifier, string displayName)
		{
			Identifier = identifier;
			DisplayName = displayName;
		}

		public MelonPreferences_Entry<T> CreateEntry<T>(string identifier, T default_value, string display_name = null, string description = null, bool is_hidden = false, bool dont_save_default = false, ValueValidator validator = null, string oldIdentifier = null)
		{
			//IL_008c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0096: Expected O, but got Unknown
			ConfigurationManagerAttributes configurationManagerAttributes = new ConfigurationManagerAttributes
			{
				DispName = (display_name ?? identifier),
				Browsable = (!is_hidden && !IsHidden),
				Order = -Entries.Count,
				Category = DisplayName
			};
			AcceptableValueBase val = validator?.ToAcceptable(typeof(T));
			ConfigEntry<T> cfg = MelonCompat.Config.Bind<T>(Identifier, identifier, default_value, new ConfigDescription(description ?? "", val, new object[1] { configurationManagerAttributes }));
			MelonPreferences_Entry<T> melonPreferences_Entry = new MelonPreferences_Entry<T>(this, cfg, identifier, display_name ?? identifier, description, is_hidden);
			Entries.Add(melonPreferences_Entry);
			return melonPreferences_Entry;
		}

		public MelonPreferences_Entry GetEntry(string identifier)
		{
			return Entries.Find((MelonPreferences_Entry e) => e.Identifier == identifier);
		}

		public MelonPreferences_Entry<T> GetEntry<T>(string identifier)
		{
			return GetEntry(identifier) as MelonPreferences_Entry<T>;
		}

		public bool HasEntry(string identifier)
		{
			return GetEntry(identifier) != null;
		}

		public void SaveToFile(bool printmsg = true)
		{
			ConfigFile config = MelonCompat.Config;
			if (config != null)
			{
				config.Save();
			}
		}

		public void LoadFromFile(bool printmsg = true)
		{
			ConfigFile config = MelonCompat.Config;
			if (config != null)
			{
				config.Reload();
			}
		}
	}
	public abstract class MelonPreferences_Entry
	{
		public readonly MelonEvent<object, object> OnEntryValueChangedUntyped = new MelonEvent<object, object>();

		public MelonPreferences_Category Category { get; protected set; }

		public string Identifier { get; protected set; }

		public string DisplayName { get; protected set; }

		public string Description { get; protected set; }

		public bool IsHidden { get; protected set; }

		public abstract ConfigEntryBase Raw { get; }

		public abstract object BoxedValue { get; set; }

		public abstract void ResetToDefault();
	}
	public sealed class MelonPreferences_Entry<T> : MelonPreferences_Entry
	{
		private readonly ConfigEntry<T> _cfg;

		private T _last;

		public readonly MelonEvent<T, T> OnEntryValueChanged = new MelonEvent<T, T>();

		public readonly MelonEvent<T, T> OnValueChanged;

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

		public T DefaultValue => (T)((ConfigEntryBase)_cfg).DefaultValue;

		public override ConfigEntryBase Raw => (ConfigEntryBase)(object)_cfg;

		public override object BoxedValue
		{
			get
			{
				return ((ConfigEntryBase)_cfg).BoxedValue;
			}
			set
			{
				((ConfigEntryBase)_cfg).BoxedValue = value;
			}
		}

		internal MelonPreferences_Entry(MelonPreferences_Category category, ConfigEntry<T> cfg, string identifier, string displayName, string description, bool hidden)
		{
			base.Category = category;
			_cfg = cfg;
			base.Identifier = identifier;
			base.DisplayName = displayName;
			base.Description = description;
			base.IsHidden = hidden;
			OnValueChanged = OnEntryValueChanged;
			_last = cfg.Value;
			cfg.SettingChanged += OnSettingChanged;
		}

		private void OnSettingChanged(object sender, EventArgs e)
		{
			T last = _last;
			_last = _cfg.Value;
			if (!EqualityComparer<T>.Default.Equals(last, _last))
			{
				OnEntryValueChanged.Invoke(last, _last);
				OnEntryValueChangedUntyped.Invoke(last, _last);
			}
		}

		public override void ResetToDefault()
		{
			_cfg.Value = DefaultValue;
		}
	}
	public sealed class MelonEvent<T1, T2>
	{
		private readonly List<Action<T1, T2>> _handlers = new List<Action<T1, T2>>();

		public void Subscribe(Action<T1, T2> handler, int priority = 0, bool unsubscribeOnFirstInvocation = false)
		{
			_handlers.Add(handler);
		}

		public void Unsubscribe(Action<T1, T2> handler)
		{
			_handlers.Remove(handler);
		}

		internal void Invoke(T1 a, T2 b)
		{
			Action<T1, T2>[] array = _handlers.ToArray();
			foreach (Action<T1, T2> action in array)
			{
				try
				{
					action(a, b);
				}
				catch (Exception ex)
				{
					Debug.LogError(Object.op_Implicit(ex.ToString()));
				}
			}
		}
	}
	public sealed class ConfigurationManagerAttributes
	{
		public string DispName;

		public bool? Browsable;

		public int? Order;

		public string Category;
	}
}
namespace MelonLoader.Preferences
{
	public abstract class ValueValidator
	{
		public abstract AcceptableValueBase ToAcceptable(Type type);
	}
	public sealed class ValueRange<T> : ValueValidator where T : IComparable
	{
		public T MinValue { get; }

		public T MaxValue { get; }

		public ValueRange(T min, T max)
		{
			MinValue = min;
			MaxValue = max;
		}

		public override AcceptableValueBase ToAcceptable(Type type)
		{
			if (!(type == typeof(T)))
			{
				return null;
			}
			return (AcceptableValueBase)(object)new AcceptableValueRange<T>(MinValue, MaxValue);
		}
	}
}
namespace Il2CppTMPro
{
	internal static class NamespaceStandIn
	{
	}
}
namespace Il2Cpp
{
	internal static class NamespaceStandIn
	{
	}
}