Decompiled source of Mouse Ping v0.2.1

SpellBrigadeMousePing.dll

Decompiled 7 hours ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Core.Logging.Interpolation;
using BepInEx.Logging;
using BepInEx.Unity.IL2CPP;
using HarmonyLib;
using Il2CppInterop.Common;
using Il2CppInterop.Runtime;
using Il2CppInterop.Runtime.InteropTypes;
using Il2CppInterop.Runtime.InteropTypes.Arrays;
using Il2CppInterop.Runtime.Runtime;
using Il2CppInterop.Runtime.Runtime.VersionSpecific.MethodInfo;
using SpellBrigadeMousePing.Core;
using SpellBrigadeMousePing.Game;
using Unity.Netcode;
using UnityEngine;
using UnityEngine.InputSystem;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETCoreApp,Version=v6.0", FrameworkDisplayName = ".NET 6.0")]
[assembly: AssemblyCompany("SpellBrigadeMousePing")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("0.2.1.0")]
[assembly: AssemblyInformationalVersion("0.2.1+e8e03ebb716439b22d25a68bf236583035b3d63e")]
[assembly: AssemblyProduct("SpellBrigadeMousePing")]
[assembly: AssemblyTitle("SpellBrigadeMousePing")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("0.2.1.0")]
[module: UnverifiableCode]
namespace SpellBrigadeMousePing
{
	internal static class ModConfig
	{
		public static ConfigEntry<bool> Enabled;

		public static ConfigEntry<bool> SnapToObjects;

		public static ConfigEntry<float> SnapRadius;

		public static ConfigEntry<bool> LogPings;

		public static void Init(ConfigFile cfg)
		{
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0069: Expected O, but got Unknown
			Enabled = cfg.Bind<bool>("General", "Enabled", true, "Quick pings (middle mouse / V) land at the mouse cursor instead of around your wizard. Read at every ping; if it is off when the game starts, the mod doesn't patch anything.");
			SnapToObjects = cfg.Bind<bool>("General", "SnapToObjects", true, "Ping the nearest pingable thing (potion, magnet, objective, revive zone...) near the cursor instead of the bare spot.");
			SnapRadius = cfg.Bind<float>("General", "SnapRadius", 2.5f, new ConfigDescription("How close to the cursor (game units) something must be to snap the ping to it.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.1f, 10f), Array.Empty<object>()));
			LogPings = cfg.Bind<bool>("Debug", "LogPings", false, "Write one line per ping (cursor state, chosen target, what was near the cursor) to BepInEx/SpellBrigadeMousePing.log.");
		}
	}
	internal static class ModLog
	{
		private static ManualLogSource? _log;

		private static StreamWriter? _file;

		private static readonly HashSet<string> Once = new HashSet<string>();

		private static readonly Dictionary<string, float> Throttle = new Dictionary<string, float>();

		public const string CleanExit = "clean exit";

		public static string FilePath => Path.Combine(Paths.BepInExRootPath, "SpellBrigadeMousePing.log");

		public static string PreviousFilePath => Path.Combine(Paths.BepInExRootPath, "SpellBrigadeMousePing.prev.log");

		public static string? PreviousCrashStep { get; private set; }

		public static void Init(ManualLogSource log)
		{
			//IL_0096: Unknown result type (might be due to invalid IL or missing references)
			//IL_009d: Expected O, but got Unknown
			//IL_017a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0181: Expected O, but got Unknown
			_log = log;
			bool flag = default(bool);
			try
			{
				if (File.Exists(FilePath))
				{
					File.Copy(FilePath, PreviousFilePath, overwrite: true);
					string text = null;
					string[] array = File.ReadAllLines(FilePath);
					foreach (string text2 in array)
					{
						int num = text2.IndexOf(" STEP  ", StringComparison.Ordinal);
						if (num >= 0)
						{
							string text3 = text2;
							int num2 = num + 7;
							text = text3.Substring(num2, text3.Length - num2).Trim();
						}
					}
					if (text != null && text != "clean exit")
					{
						PreviousCrashStep = text;
					}
				}
			}
			catch (Exception ex)
			{
				BepInExWarningLogInterpolatedStringHandler val = new BepInExWarningLogInterpolatedStringHandler(30, 2, ref flag);
				if (flag)
				{
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral("Could not read the previous ");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(FilePath);
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral(": ");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(ex.Message);
				}
				log.LogWarning(val);
			}
			try
			{
				_file = new StreamWriter(new FileStream(FilePath, FileMode.Create, FileAccess.Write, FileShare.ReadWrite))
				{
					AutoFlush = true
				};
				_file.WriteLine($"SpellBrigadeMousePing {"0.2.1"} log, started {DateTime.Now:yyyy-MM-dd HH:mm:ss}");
				if (PreviousCrashStep != null)
				{
					_file.WriteLine("Previous session did not exit cleanly; its last step was: " + PreviousCrashStep + " (log kept as SpellBrigadeMousePing.prev.log)");
				}
			}
			catch (Exception ex2)
			{
				BepInExWarningLogInterpolatedStringHandler val = new BepInExWarningLogInterpolatedStringHandler(17, 2, ref flag);
				if (flag)
				{
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral("Could not open ");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(FilePath);
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral(": ");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(ex2.Message);
				}
				log.LogWarning(val);
			}
		}

		public static void Info(string msg)
		{
			ManualLogSource? log = _log;
			if (log != null)
			{
				log.LogInfo((object)msg);
			}
			ToFile("INFO ", msg);
		}

		public static void Warn(string msg)
		{
			ManualLogSource? log = _log;
			if (log != null)
			{
				log.LogWarning((object)msg);
			}
			ToFile("WARN ", msg);
		}

		public static void Error(string msg)
		{
			ManualLogSource? log = _log;
			if (log != null)
			{
				log.LogError((object)msg);
			}
			ToFile("ERROR", msg);
		}

		public static void Debug(string msg)
		{
			ManualLogSource? log = _log;
			if (log != null)
			{
				log.LogDebug((object)msg);
			}
			ToFile("DEBUG", msg);
		}

		public static void Step(string msg)
		{
			ToFile("STEP ", msg);
		}

		public static void StepOnce(string key, string msg)
		{
			if (Once.Add("step:" + key))
			{
				Step(msg);
			}
		}

		public static void InfoOnce(string key, string msg)
		{
			if (Once.Add(key))
			{
				Info(msg);
			}
		}

		public static void WarnOnce(string key, string msg)
		{
			if (Once.Add(key))
			{
				Warn(msg);
			}
		}

		public static void ErrorThrottled(string key, Exception ex, float now, float seconds = 10f)
		{
			if (!Throttle.TryGetValue(key, out var value) || !(now - value < seconds))
			{
				Throttle[key] = now;
				Error($"[{key}] {ex.GetType().Name}: {ex.Message}\n{ex.StackTrace}");
			}
		}

		private static void ToFile(string level, string msg)
		{
			if (_file == null)
			{
				return;
			}
			try
			{
				lock (_file)
				{
					_file.WriteLine($"{DateTime.Now:HH:mm:ss.fff} {level} {msg}");
				}
			}
			catch
			{
			}
		}
	}
	[BepInPlugin("com.stefanws0.spellbrigademouseping", "SpellBrigadeMousePing", "0.2.1")]
	public class Plugin : BasePlugin
	{
		public const string Guid = "com.stefanws0.spellbrigademouseping";

		public const string Name = "SpellBrigadeMousePing";

		public const string Version = "0.2.1";

		internal static Harmony Harmony { get; private set; }

		public override void Load()
		{
			//IL_0025: Unknown result type (might be due to invalid IL or missing references)
			//IL_002f: Expected O, but got Unknown
			ModLog.Init(((BasePlugin)this).Log);
			ModLog.Step("Load: config");
			ModConfig.Init(((BasePlugin)this).Config);
			Harmony = new Harmony("com.stefanws0.spellbrigademouseping");
			ModLog.Step("Load: registering PingRunner");
			((BasePlugin)this).AddComponent<PingRunner>();
			if (ModConfig.Enabled.Value)
			{
				PingPatches.Install();
			}
			else
			{
				ModLog.Info("General.Enabled is off: no patches, pings stay as the game makes them.");
			}
			ModLog.Step("Load: done");
			ModLog.Info("SpellBrigadeMousePing 0.2.1 loaded.");
		}
	}
}
namespace SpellBrigadeMousePing.Game
{
	internal static class CursorProbe
	{
		private const float VisibleGraceSeconds = 0.25f;

		private static readonly CursorRecency Recency = new CursorRecency(0.25f);

		public static void Track(float now)
		{
			Recency.Observe(VisibleNow(), now);
		}

		public static bool Usable(float now)
		{
			return Recency.Usable(VisibleNow(), now);
		}

		public static bool VisibleNow()
		{
			try
			{
				return Cursor.visible;
			}
			catch
			{
				return false;
			}
		}

		public static string MouseActiveText()
		{
			try
			{
				Object obj = Object.FindAnyObjectByType(Il2CppType.Of<CursorService>());
				object obj2;
				if (obj == null)
				{
					obj2 = null;
				}
				else
				{
					CursorService obj3 = ((Il2CppObjectBase)obj).TryCast<CursorService>();
					obj2 = ((obj3 != null) ? obj3.inputActivityDetector : null);
				}
				IInputActivityDetector val = (IInputActivityDetector)obj2;
				return (val == null) ? "?" : val.IsMouseInputActive().ToString();
			}
			catch (Exception ex)
			{
				return "error " + ex.GetType().Name;
			}
		}

		public static Vector2? ScreenPosition()
		{
			//IL_000f: 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_0046: Unknown result type (might be due to invalid IL or missing references)
			//IL_0047: Unknown result type (might be due to invalid IL or missing references)
			//IL_004d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0053: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				Mouse current = Mouse.current;
				if (current != null)
				{
					return ((InputControl<Vector2>)(object)((Pointer)current).position).ReadValue();
				}
			}
			catch (Exception ex)
			{
				ModLog.WarnOnce("mouse-inputsystem", "Mouse.current.position failed (" + ex.Message + "); trying Input.mousePosition.");
			}
			try
			{
				Vector3 mousePosition = Input.mousePosition;
				return new Vector2(mousePosition.x, mousePosition.y);
			}
			catch (Exception ex2)
			{
				ModLog.WarnOnce("mouse-legacy", "Input.mousePosition failed too (" + ex2.Message + "): cursor pings can't work.");
				return null;
			}
		}

		public static Vector3? GroundUnderCursor(float groundY)
		{
			//IL_002c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0038: Unknown result type (might be due to invalid IL or missing references)
			//IL_0047: 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_0051: Unknown result type (might be due to invalid IL or missing references)
			//IL_0054: Unknown result type (might be due to invalid IL or missing references)
			//IL_0059: Unknown result type (might be due to invalid IL or missing references)
			//IL_005c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0061: Unknown result type (might be due to invalid IL or missing references)
			//IL_0063: Unknown result type (might be due to invalid IL or missing references)
			//IL_0069: Unknown result type (might be due to invalid IL or missing references)
			//IL_006f: Unknown result type (might be due to invalid IL or missing references)
			//IL_007a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0081: Unknown result type (might be due to invalid IL or missing references)
			//IL_0088: Unknown result type (might be due to invalid IL or missing references)
			//IL_00be: Unknown result type (might be due to invalid IL or missing references)
			Vector2? val = ScreenPosition();
			Camera main = Camera.main;
			if (!val.HasValue || (Object)(object)main == (Object)null)
			{
				return null;
			}
			Ray val2 = main.ScreenPointToRay(new Vector3(val.Value.x, val.Value.y, 0f));
			Vector3 origin = ((Ray)(ref val2)).origin;
			Vector3 direction = ((Ray)(ref val2)).direction;
			if (!GroundPoint.TryHit(new Vec3(origin.x, origin.y, origin.z), new Vec3(direction.x, direction.y, direction.z), groundY, out var hit))
			{
				return null;
			}
			return new Vector3(hit.X, hit.Y, hit.Z);
		}
	}
	internal sealed class NativeInfo
	{
		public string Label { get; }

		public IntPtr Code { get; set; }

		public uint Size { get; set; }

		public string? Refusal { get; set; }

		public NativeInfo(string label)
		{
			Label = label;
		}

		public override string ToString()
		{
			return Refusal ?? $"native 0x{Code.ToInt64():X}, {Size} bytes";
		}
	}
	internal static class NativeCode
	{
		private const uint MinBytes = 16u;

		private static readonly Dictionary<MethodBase, NativeInfo> Cache = new Dictionary<MethodBase, NativeInfo>();

		private static readonly Dictionary<IntPtr, List<string>> Owners = new Dictionary<IntPtr, List<string>>();

		[DllImport("kernel32.dll")]
		private static extern IntPtr RtlLookupFunctionEntry(ulong controlPc, out ulong imageBase, IntPtr historyTable);

		public static IntPtr Pointer(MethodBase method)
		{
			try
			{
				FieldInfo il2CppMethodInfoPointerFieldForGeneratedMethod = Il2CppInteropUtils.GetIl2CppMethodInfoPointerFieldForGeneratedMethod(method);
				if (il2CppMethodInfoPointerFieldForGeneratedMethod == null)
				{
					return IntPtr.Zero;
				}
				IntPtr intPtr = (IntPtr)il2CppMethodInfoPointerFieldForGeneratedMethod.GetValue(null);
				return (intPtr == IntPtr.Zero) ? IntPtr.Zero : Marshal.ReadIntPtr(intPtr);
			}
			catch
			{
				return IntPtr.Zero;
			}
		}

		public static NativeInfo Inspect(MethodBase method, string label)
		{
			if (Cache.TryGetValue(method, out NativeInfo value))
			{
				return value;
			}
			NativeInfo nativeInfo = new NativeInfo(label);
			Cache[method] = nativeInfo;
			bool isAbstract;
			try
			{
				nativeInfo.Code = MethodPointer(method, out isAbstract);
			}
			catch (Exception ex)
			{
				nativeInfo.Refusal = "native code not found: " + ex.GetType().Name + ": " + ex.Message;
				return nativeInfo;
			}
			if (nativeInfo.Code == IntPtr.Zero)
			{
				nativeInfo.Refusal = "no native code";
				return nativeInfo;
			}
			if (isAbstract)
			{
				nativeInfo.Refusal = $"abstract or interface method: 0x{nativeInfo.Code.ToInt64():X} is a stub shared by all abstract methods with this signature";
				return nativeInfo;
			}
			if (!Owners.TryGetValue(nativeInfo.Code, out List<string> value2))
			{
				value2 = (Owners[nativeInfo.Code] = new List<string>());
			}
			if (!value2.Contains(label))
			{
				value2.Add(label);
			}
			ulong num = (ulong)nativeInfo.Code.ToInt64();
			ulong imageBase;
			IntPtr intPtr = RtlLookupFunctionEntry(num, out imageBase, IntPtr.Zero);
			if (intPtr == IntPtr.Zero)
			{
				nativeInfo.Refusal = $"leaf function at 0x{num:X} [{FirstBytes(nativeInfo.Code)}]: empty or trivial, the compiler shares such code between methods";
				return nativeInfo;
			}
			ulong num2 = imageBase + (uint)Marshal.ReadInt32(intPtr);
			ulong num3 = imageBase + (uint)Marshal.ReadInt32(intPtr, 4);
			nativeInfo.Size = (uint)(num3 - num2);
			if (num2 != num)
			{
				nativeInfo.Refusal = $"0x{num:X} is not the start of a function (it starts at 0x{num2:X})";
			}
			else if (nativeInfo.Size < 16)
			{
				nativeInfo.Refusal = $"tiny function at 0x{num:X} ({nativeInfo.Size} bytes [{FirstBytes(nativeInfo.Code)}])";
			}
			return nativeInfo;
		}

		public static bool CanPatch(MethodBase method, string label, out string why)
		{
			NativeInfo nativeInfo = Inspect(method, label);
			if (nativeInfo.Refusal == null && Owners.TryGetValue(nativeInfo.Code, out List<string> value) && value.Count > 1)
			{
				why = $"native code 0x{nativeInfo.Code.ToInt64():X} is shared with {string.Join(", ", value.Where((string o) => o != label))}";
				return false;
			}
			why = nativeInfo.ToString();
			return nativeInfo.Refusal == null;
		}

		private unsafe static IntPtr MethodPointer(MethodBase method, out bool isAbstract)
		{
			isAbstract = false;
			IntPtr intPtr = (IntPtr)(Il2CppInteropUtils.GetIl2CppMethodInfoPointerFieldForGeneratedMethod(method) ?? throw new InvalidOperationException("not a generated interop method")).GetValue(null);
			if (intPtr == IntPtr.Zero)
			{
				return IntPtr.Zero;
			}
			INativeMethodInfoStruct val = UnityVersionHandler.Wrap((Il2CppMethodInfo*)(void*)intPtr);
			isAbstract = ((uint)val.Flags & 0x400u) != 0;
			return val.MethodPointer;
		}

		private static string FirstBytes(IntPtr code)
		{
			try
			{
				byte[] array = new byte[8];
				Marshal.Copy(code, array, 0, array.Length);
				return BitConverter.ToString(array).Replace('-', ' ');
			}
			catch
			{
				return "?";
			}
		}
	}
	internal static class PingPatches
	{
		private const float NoSearchRange = 0.001f;

		private const BindingFlags AnyInstance = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;

		private static Vector3? _pendingCursorPoint;

		private static float? _savedRange;

		private static SmartPingManager? _rangeOwner;

		private static int _pingCount;

		public static void Install()
		{
			MethodInfo method = typeof(SmartPingManager).GetMethod("SmartPing", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
			MethodInfo method2 = typeof(SmartPingManager).GetMethod("PingLocationRpc", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
			if (method == null || method2 == null)
			{
				ModLog.Error("SmartPingManager.SmartPing or PingLocationRpc not found: mouse pings are off.");
				return;
			}
			NativeCode.Inspect(method, "SmartPingManager.SmartPing");
			NativeCode.Inspect(method2, "SmartPingManager.PingLocationRpc");
			string why2;
			if (!NativeCode.CanPatch(method2, "SmartPingManager.PingLocationRpc", out string why))
			{
				ModLog.Error("Refusing to patch SmartPingManager.PingLocationRpc (" + why + "): mouse pings are off.");
			}
			else if (!NativeCode.CanPatch(method, "SmartPingManager.SmartPing", out why2))
			{
				ModLog.Error("Refusing to patch SmartPingManager.SmartPing (" + why2 + "): mouse pings are off.");
			}
			else if (Patch(method2, "SmartPingManager.PingLocationRpc [" + why + "]", "PingLocationPrefix", null))
			{
				Patch(method, "SmartPingManager.SmartPing [" + why2 + "]", "SmartPingPrefix", "SmartPingPostfix");
			}
		}

		public static void RestoreRangeIfLeftOver()
		{
			if (_savedRange.HasValue)
			{
				ModLog.WarnOnce("range-leftover", "SmartPing's range was still shrunk a frame later (its postfix didn't run); restored.");
				_pendingCursorPoint = null;
				RestoreRange();
			}
		}

		private static void SmartPingPrefix(SmartPingManager __instance)
		{
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				_pendingCursorPoint = null;
				if (!ModConfig.Enabled.Value)
				{
					return;
				}
				ModLog.StepOnce("smartping-prefix", "first SmartPing prefix");
				if (!CursorProbe.Usable(Time.unscaledTime))
				{
					LogPing("cursor hidden: the game's own ping");
					return;
				}
				NetworkObject localPlayer = __instance.GetLocalPlayer();
				if ((Object)(object)localPlayer == (Object)null)
				{
					LogPing("no local player: the game's own ping");
					return;
				}
				Vector3? pendingCursorPoint = CursorProbe.GroundUnderCursor(((Component)localPlayer).transform.position.y);
				if (!pendingCursorPoint.HasValue)
				{
					LogPing("no ground under the cursor: the game's own ping");
					return;
				}
				_pendingCursorPoint = pendingCursorPoint;
				_savedRange = __instance.range;
				_rangeOwner = __instance;
				__instance.range = 0.001f;
			}
			catch (Exception ex)
			{
				_pendingCursorPoint = null;
				RestoreRange();
				ModLog.ErrorThrottled("smartping-prefix", ex, Time.unscaledTime);
			}
		}

		private static void SmartPingPostfix()
		{
			try
			{
				RestoreRange();
				if (_pendingCursorPoint.HasValue)
				{
					LogPing("the game sent no location ping (cooldown, or it pinged something at the wizard)");
				}
				_pendingCursorPoint = null;
			}
			catch (Exception ex)
			{
				ModLog.ErrorThrottled("smartping-postfix", ex, Time.unscaledTime);
			}
		}

		private static bool PingLocationPrefix(SmartPingManager __instance, ulong __0, ref Vector3 __1)
		{
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			//IL_0018: Unknown result type (might be due to invalid IL or missing references)
			//IL_014c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0166: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00dc: Unknown result type (might be due to invalid IL or missing references)
			//IL_0122: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b4: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ce: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f6: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f7: Unknown result type (might be due to invalid IL or missing references)
			//IL_0059: Unknown result type (might be due to invalid IL or missing references)
			if (!_pendingCursorPoint.HasValue)
			{
				return true;
			}
			Vector3 value = _pendingCursorPoint.Value;
			_pendingCursorPoint = null;
			try
			{
				ModLog.StepOnce("pinglocation-prefix", "first PingLocationRpc redirect");
				if (ModConfig.SnapToObjects.Value)
				{
					List<string> seen = (ModConfig.LogPings.Value ? new List<string>() : null);
					NetworkObject val = null;
					try
					{
						val = PingTargets.Nearest(value, ModConfig.SnapRadius.Value, seen);
					}
					catch (Exception ex)
					{
						ModLog.ErrorThrottled("ping-targets", ex, Time.unscaledTime);
					}
					if ((Object)(object)val != (Object)null)
					{
						LogPing($"object '{((Object)val).name}' near the cursor {Fmt(value)} (wizard at {Fmt(__1)}); near cursor: {Join(seen)}");
						ModLog.StepOnce("pingrpc", "first PingRpc for an object near the cursor");
						__instance.PingRpc(__0, new NetworkObjectReference(val));
						return false;
					}
					LogPing($"spot {Fmt(value)} (wizard at {Fmt(__1)}); near cursor: {Join(seen)}");
				}
				else
				{
					LogPing($"spot {Fmt(value)} (wizard at {Fmt(__1)})");
				}
				__1 = value;
				return true;
			}
			catch (Exception ex2)
			{
				ModLog.ErrorThrottled("pinglocation-prefix", ex2, Time.unscaledTime);
				return true;
			}
		}

		private static void RestoreRange()
		{
			if (!_savedRange.HasValue)
			{
				return;
			}
			try
			{
				if ((Object)(object)_rangeOwner != (Object)null)
				{
					_rangeOwner.range = _savedRange.Value;
				}
			}
			finally
			{
				_savedRange = null;
				_rangeOwner = null;
			}
		}

		private static bool Patch(MethodInfo target, string label, string? prefix, string? postfix)
		{
			//IL_002b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0048: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				ModLog.Step("patch " + label);
				Plugin.Harmony.Patch((MethodBase)target, (prefix == null) ? ((HarmonyMethod)null) : new HarmonyMethod(typeof(PingPatches).GetMethod(prefix, BindingFlags.Static | BindingFlags.NonPublic)), (postfix == null) ? ((HarmonyMethod)null) : new HarmonyMethod(typeof(PingPatches).GetMethod(postfix, BindingFlags.Static | BindingFlags.NonPublic)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				ModLog.Step("patch ok: " + label);
				ModLog.Info("Patched " + label + ".");
				return true;
			}
			catch (Exception ex)
			{
				ModLog.Error($"Could not patch {label}: {ex.GetType().Name}: {ex.Message}");
				return false;
			}
		}

		private static void LogPing(string what)
		{
			if (ModConfig.LogPings.Value)
			{
				ModLog.Info($"Ping {++_pingCount}: {what} [cursor visible: {CursorProbe.VisibleNow()}, mouse active: {CursorProbe.MouseActiveText()}]");
			}
		}

		private static string Fmt(Vector3 v)
		{
			//IL_0017: 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_0053: Unknown result type (might be due to invalid IL or missing references)
			return $"({v.x:0.0}, {v.y:0.0}, {v.z:0.0})";
		}

		private static string Join(List<string>? seen)
		{
			if (seen != null && seen.Count != 0)
			{
				return string.Join(", ", seen);
			}
			return "nothing";
		}
	}
	public class PingRunner : MonoBehaviour
	{
		public PingRunner(IntPtr ptr)
			: base(ptr)
		{
		}

		public void Update()
		{
			try
			{
				CursorProbe.Track(Time.unscaledTime);
				PingPatches.RestoreRangeIfLeftOver();
			}
			catch (Exception ex)
			{
				ModLog.ErrorThrottled("runner", ex, Time.unscaledTime);
			}
		}

		public void OnApplicationQuit()
		{
			ModLog.Step("clean exit");
		}
	}
	internal static class PingTargets
	{
		private const int MaxLogged = 12;

		public static NetworkObject? Nearest(Vector3 center, float radius, List<string>? seen)
		{
			//IL_001e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0018: Unknown result type (might be due to invalid IL or missing references)
			//IL_016f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0175: Unknown result type (might be due to invalid IL or missing references)
			//IL_017b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0125: Unknown result type (might be due to invalid IL or missing references)
			//IL_0126: Unknown result type (might be due to invalid IL or missing references)
			//IL_012b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0136: Unknown result type (might be due to invalid IL or missing references)
			//IL_013d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0144: Unknown result type (might be due to invalid IL or missing references)
			ModLog.StepOnce("overlap", "first cursor OverlapSphere + game ping filters");
			__c val = (__c)(((object)__c.__9) ?? ((object)new __c()));
			Il2CppReferenceArray<Collider> val2 = Physics.OverlapSphere(center, radius, -1, (QueryTriggerInteraction)2);
			List<NetworkObject> list = new List<NetworkObject>();
			List<Vec3> list2 = new List<Vec3>();
			if (val2 != null)
			{
				foreach (Collider item in (Il2CppArrayBase<Collider>)(object)val2)
				{
					if ((Object)(object)item == (Object)null)
					{
						continue;
					}
					NetworkObject val3 = null;
					bool flag;
					try
					{
						flag = val._SmartPing_b__19_0(item) && val._SmartPing_b__19_1(item) && val._SmartPing_b__19_2(item);
						if (flag)
						{
							val3 = val._SmartPing_b__19_3(item);
							flag = (Object)(object)val3 != (Object)null && val._SmartPing_b__19_4(val3);
						}
					}
					catch (Exception ex)
					{
						ModLog.WarnOnce("filter-" + ex.GetType().Name, "A game ping filter threw on " + ((Object)item).name + ": " + ex.Message);
						flag = false;
					}
					if (seen != null && seen.Count < 12)
					{
						seen.Add(flag ? (((Object)item).name + " -> " + ((Object)val3).name) : ((Object)item).name);
					}
					if (flag)
					{
						Vector3 val4 = item.ClosestPointOnBounds(center);
						list.Add(val3);
						list2.Add(new Vec3(val4.x, val4.y, val4.z));
					}
				}
			}
			int num = NearestPick.Pick(new Vec3(center.x, center.y, center.z), list2, radius);
			if (num >= 0)
			{
				return list[num];
			}
			return null;
		}
	}
}
namespace SpellBrigadeMousePing.Core
{
	internal sealed class CursorRecency
	{
		private readonly float _graceSeconds;

		private float _lastVisible = float.NegativeInfinity;

		public CursorRecency(float graceSeconds)
		{
			_graceSeconds = graceSeconds;
		}

		public void Observe(bool visible, float now)
		{
			if (visible)
			{
				_lastVisible = now;
			}
		}

		public bool Usable(bool visibleNow, float now)
		{
			if (!visibleNow)
			{
				return now - _lastVisible <= _graceSeconds;
			}
			return true;
		}
	}
	internal struct Vec3
	{
		public float X;

		public float Y;

		public float Z;

		public Vec3(float x, float y, float z)
		{
			X = x;
			Y = y;
			Z = z;
		}

		public override string ToString()
		{
			return $"({X:0.0}, {Y:0.0}, {Z:0.0})";
		}
	}
	internal static class GroundPoint
	{
		public static bool TryHit(Vec3 origin, Vec3 direction, float groundY, out Vec3 hit)
		{
			hit = default(Vec3);
			if (Math.Abs(direction.Y) < 0.0001f)
			{
				return false;
			}
			float num = (groundY - origin.Y) / direction.Y;
			if (num <= 0f)
			{
				return false;
			}
			hit = new Vec3(origin.X + direction.X * num, groundY, origin.Z + direction.Z * num);
			return true;
		}
	}
	internal static class NearestPick
	{
		public static int Pick(Vec3 center, IReadOnlyList<Vec3> candidates, float radius)
		{
			int num = -1;
			float num2 = radius * radius;
			for (int i = 0; i < candidates.Count; i++)
			{
				float num3 = candidates[i].X - center.X;
				float num4 = candidates[i].Z - center.Z;
				float num5 = num3 * num3 + num4 * num4;
				if (!(num5 > num2) && (num < 0 || !(num5 >= num2)))
				{
					num = i;
					num2 = num5;
				}
			}
			return num;
		}
	}
}
namespace System.Runtime.CompilerServices
{
	[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 flag)
		{
			NullableFlags = new byte[1] { flag };
		}

		public NullableAttribute(byte[] flags)
		{
			NullableFlags = flags;
		}
	}
	[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 flag)
		{
			Flag = flag;
		}
	}
}