Decompiled source of Portal Map Markers v1.0.0

plugins/PortalMapMarkers.dll

Decompiled a day ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using BepInEx;
using BepInEx.Bootstrap;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("BenjSammy")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0")]
[assembly: AssemblyProduct("PortalMapMarkers")]
[assembly: AssemblyTitle("PortalMapMarkers")]
[assembly: AssemblyVersion("1.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 BenjSammy.PortalMapMarkers
{
	[BepInPlugin("benjsammy.portalmapmarkers", "Portal Map Markers by BenjSammy", "1.0.0")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	public sealed class PortalMapMarkers : BaseUnityPlugin
	{
		private const string PluginId = "benjsammy.portalmapmarkers";

		private const string RequestRpc = "BenjSammy.PortalMapMarkers.Request.v1";

		private const string SnapshotRpc = "BenjSammy.PortalMapMarkers.Snapshot.v1";

		private const int MaxPacketBytes = 2097152;

		private const float RefreshSeconds = 8f;

		private const float MinimapIconScale = 0.6f;

		private static PortalMapMarkers active;

		private readonly Dictionary<Vector3, PinData> pins = new Dictionary<Vector3, PinData>();

		private FieldRef<Minimap, MapMode> mapMode;

		private FieldRef<Minimap, float> smallPinSize;

		private FieldRef<PinData, RectTransform> pinElement;

		private Harmony harmony;

		private ZRoutedRpc router;

		private Minimap map;

		private MapMode previousMode;

		private Sprite icon;

		private Texture2D texture;

		private MethodInfo worldPortals;

		private MethodInfo getServerPeerId;

		private MethodInfo findPeer;

		private MethodInfo isPeerReady;

		private MethodInfo addPin;

		private object[] pinArguments;

		private float clientRefreshAt;

		private float serverRefreshAt;

		private bool serverSnapshotReceived;

		private ZPackage serverSnapshot;

		private readonly HashSet<long> servedPeers = new HashSet<long>();

		private bool targetPortalInstalled;

		private FieldInfo targetPortalVisible;

		private FieldInfo targetPortalTeleporting;

		private FieldInfo targetPortalPins;

		private FieldInfo targetPortalPinType;

		private MethodInfo targetPortalAddPins;

		private Minimap initializedTargetMap;

		private void Awake()
		{
			FieldInfo fieldInfo = AccessTools.DeclaredField(typeof(Minimap), "m_mode");
			if (fieldInfo?.FieldType == typeof(MapMode))
			{
				mapMode = AccessTools.FieldRefAccess<Minimap, MapMode>(fieldInfo);
			}
			ConfigureMinimapSize();
			if (Chainloader.PluginInfos.TryGetValue("org.bepinex.plugins.targetportal", out var value) && (Object)(object)value.Instance != (Object)null)
			{
				targetPortalInstalled = true;
				Type type = ((object)value.Instance).GetType().Assembly.GetType("TargetPortal.Map");
				if (type != null)
				{
					targetPortalVisible = AccessTools.DeclaredField(type, "shouldPortalsBeVisible");
					targetPortalTeleporting = AccessTools.DeclaredField(type, "Teleporting");
					targetPortalAddPins = AccessTools.DeclaredMethod(type, "AddPortalPins", Type.EmptyTypes, (Type[])null);
					targetPortalPins = AccessTools.DeclaredField(type, "activePins");
					Type nestedType = type.GetNestedType("AddMinimapPortalIcon", BindingFlags.Public | BindingFlags.NonPublic);
					if (nestedType != null)
					{
						targetPortalPinType = AccessTools.DeclaredField(nestedType, "pinType");
					}
				}
				if (targetPortalVisible?.FieldType != typeof(bool) || targetPortalTeleporting?.FieldType != typeof(bool) || targetPortalAddPins == null)
				{
					((BaseUnityPlugin)this).Logger.LogWarning((object)"Automatic TargetPortal display is unavailable. Use TargetPortal's map shortcut.");
				}
				return;
			}
			worldPortals = AccessTools.GetDeclaredMethods(typeof(ZDOMan)).FirstOrDefault((MethodInfo method) => (method.Name == "GetPortalList" || method.Name == "GetPortals") && method.GetParameters().Length == 0 && (typeof(IEnumerable<ZDO>).IsAssignableFrom(method.ReturnType) || typeof(IDictionary).IsAssignableFrom(method.ReturnType)));
			if (worldPortals == null)
			{
				((BaseUnityPlugin)this).Logger.LogWarning((object)"The full world portal list is unavailable on this Valheim build.");
			}
			getServerPeerId = AccessTools.DeclaredMethod(typeof(ZRoutedRpc), "GetServerPeerID", Type.EmptyTypes, (Type[])null);
			findPeer = AccessTools.DeclaredMethod(typeof(ZNet), "GetPeer", new Type[1] { typeof(long) }, (Type[])null);
			isPeerReady = AccessTools.DeclaredMethod(typeof(ZNetPeer), "IsReady", Type.EmptyTypes, (Type[])null);
			if (getServerPeerId == null || findPeer == null || isPeerReady == null)
			{
				((BaseUnityPlugin)this).Logger.LogWarning((object)"Some multiplayer portal sync methods are unavailable on this Valheim build.");
			}
			Type[] pinTypes = new Type[5]
			{
				typeof(Vector3),
				typeof(PinType),
				typeof(string),
				typeof(bool),
				typeof(bool)
			};
			addPin = AccessTools.GetDeclaredMethods(typeof(Minimap)).FirstOrDefault((MethodInfo method) => method.Name == "AddPin" && method.ReturnType == typeof(PinData) && (from parameter in method.GetParameters().Take(pinTypes.Length)
				select parameter.ParameterType).SequenceEqual(pinTypes) && method.GetParameters().Skip(pinTypes.Length).All((ParameterInfo parameter) => parameter.IsOptional));
			if (addPin == null)
			{
				((BaseUnityPlugin)this).Logger.LogWarning((object)"The map pin API is unavailable on this Valheim build.");
				return;
			}
			pinArguments = (from parameter in addPin.GetParameters()
				select (!parameter.IsOptional) ? null : parameter.DefaultValue).ToArray();
			pinArguments[1] = (object)(PinType)6;
			pinArguments[3] = false;
			pinArguments[4] = false;
		}

		private void ConfigureMinimapSize()
		{
			//IL_00bf: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c9: Expected O, but got Unknown
			//IL_00e1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ee: Expected O, but got Unknown
			FieldInfo fieldInfo = AccessTools.DeclaredField(typeof(Minimap), "m_pinSizeSmall");
			FieldInfo fieldInfo2 = AccessTools.DeclaredField(typeof(PinData), "m_uiElement");
			MethodInfo methodInfo = AccessTools.DeclaredMethod(typeof(Minimap), "UpdatePins", Type.EmptyTypes, (Type[])null);
			if (mapMode == null || fieldInfo?.FieldType != typeof(float) || fieldInfo2?.FieldType != typeof(RectTransform) || methodInfo == null)
			{
				((BaseUnityPlugin)this).Logger.LogWarning((object)"Custom portal sizing is unavailable on this Valheim build.");
				return;
			}
			smallPinSize = AccessTools.FieldRefAccess<Minimap, float>(fieldInfo);
			pinElement = AccessTools.FieldRefAccess<PinData, RectTransform>(fieldInfo2);
			harmony = new Harmony("benjsammy.portalmapmarkers");
			harmony.Patch((MethodBase)methodInfo, (HarmonyMethod)null, new HarmonyMethod(typeof(PortalMapMarkers), "ResizeMinimapPins", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			active = this;
		}

		private MapMode CurrentMode(Minimap current)
		{
			if (!((Object)(object)current == (Object)null))
			{
				if (mapMode == null)
				{
					if (Minimap.IsOpen())
					{
						return (MapMode)2;
					}
					return (MapMode)0;
				}
				return mapMode.Invoke(current);
			}
			return (MapMode)0;
		}

		private static void ResizeMinimapPins(Minimap __instance)
		{
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_0017: Invalid comparison between Unknown and I4
			//IL_00d2: Unknown result type (might be due to invalid IL or missing references)
			//IL_0074: Unknown result type (might be due to invalid IL or missing references)
			//IL_007b: Expected O, but got Unknown
			//IL_007e: Unknown result type (might be due to invalid IL or missing references)
			PortalMapMarkers portalMapMarkers = active;
			if ((Object)(object)portalMapMarkers == (Object)null || (int)portalMapMarkers.CurrentMode(__instance) != 1)
			{
				return;
			}
			float num = portalMapMarkers.smallPinSize.Invoke(__instance) * 0.6f;
			Vector2 dimensions = default(Vector2);
			((Vector2)(ref dimensions))..ctor(num, num);
			if (portalMapMarkers.targetPortalInstalled)
			{
				if (!(portalMapMarkers.targetPortalPins?.GetValue(null) is IDictionary dictionary))
				{
					return;
				}
				{
					foreach (PinData key in dictionary.Keys)
					{
						PinData pin = key;
						portalMapMarkers.ResizePin(pin, dimensions);
					}
					return;
				}
			}
			if (!((Object)(object)portalMapMarkers.map == (Object)(object)__instance))
			{
				return;
			}
			foreach (PinData value in portalMapMarkers.pins.Values)
			{
				portalMapMarkers.ResizePin(value, dimensions);
			}
		}

		private void ResizePin(PinData pin, Vector2 dimensions)
		{
			//IL_0018: Unknown result type (might be due to invalid IL or missing references)
			RectTransform val = pinElement.Invoke(pin);
			if ((Object)(object)val != (Object)null)
			{
				val.sizeDelta = dimensions;
			}
		}

		private void Update()
		{
			//IL_00b2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b7: 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_00d3: Unknown result type (might be due to invalid IL or missing references)
			//IL_0124: Unknown result type (might be due to invalid IL or missing references)
			//IL_0129: Unknown result type (might be due to invalid IL or missing references)
			//IL_012d: Unknown result type (might be due to invalid IL or missing references)
			//IL_012e: Unknown result type (might be due to invalid IL or missing references)
			if (targetPortalInstalled)
			{
				ShowTargetPortalPins();
				return;
			}
			if (router != ZRoutedRpc.instance)
			{
				ClearPins();
				map = null;
				router = ZRoutedRpc.instance;
				clientRefreshAt = 0f;
				serverRefreshAt = 0f;
				serverSnapshot = null;
				servedPeers.Clear();
				serverSnapshotReceived = false;
				ZRoutedRpc obj = router;
				if (obj != null)
				{
					obj.Register<int>("BenjSammy.PortalMapMarkers.Request.v1", (Action<long, int>)ReceiveRequest);
				}
				ZRoutedRpc obj2 = router;
				if (obj2 != null)
				{
					obj2.Register<ZPackage>("BenjSammy.PortalMapMarkers.Snapshot.v1", (Action<long, ZPackage>)ReceiveSnapshot);
				}
			}
			Minimap instance = Minimap.instance;
			MapMode val = CurrentMode(instance);
			if (addPin == null || (Object)(object)Player.m_localPlayer == (Object)null || (int)val == 0)
			{
				ClearPins();
				clientRefreshAt = 0f;
				previousMode = (MapMode)0;
				serverSnapshotReceived = false;
				return;
			}
			if ((Object)(object)map != (Object)(object)instance)
			{
				ClearPins();
				map = instance;
				clientRefreshAt = 0f;
				serverSnapshotReceived = false;
			}
			if (previousMode != val)
			{
				previousMode = val;
				clientRefreshAt = 0f;
			}
			if (router == null || (Object)(object)ZNet.instance == (Object)null || Time.unscaledTime < clientRefreshAt)
			{
				return;
			}
			clientRefreshAt = Time.unscaledTime + 8f;
			if (ZNet.instance.IsServer())
			{
				UpdatePins(ReadWorldPortals() ?? ReadLoadedPortals());
				return;
			}
			if (!serverSnapshotReceived)
			{
				UpdatePins(ReadLoadedPortals());
			}
			long num = ServerPeerId();
			if (num != 0L)
			{
				router.InvokeRoutedRPC(num, "BenjSammy.PortalMapMarkers.Request.v1", new object[1] { 1 });
			}
		}

		private void ShowTargetPortalPins()
		{
			//IL_0083: Unknown result type (might be due to invalid IL or missing references)
			Minimap instance = Minimap.instance;
			if (targetPortalVisible?.FieldType != typeof(bool) || targetPortalTeleporting?.FieldType != typeof(bool) || targetPortalAddPins == null || (Object)(object)instance == (Object)null || (Object)(object)initializedTargetMap == (Object)(object)instance || (Object)(object)Player.m_localPlayer == (Object)null || (int)CurrentMode(instance) == 0 || (bool)targetPortalTeleporting.GetValue(null) || (targetPortalPinType != null && (!(targetPortalPinType.GetValue(null) is int num) || num <= 0)))
			{
				return;
			}
			initializedTargetMap = instance;
			if ((bool)targetPortalVisible.GetValue(null))
			{
				return;
			}
			try
			{
				targetPortalAddPins.Invoke(null, null);
				targetPortalVisible.SetValue(null, true);
			}
			catch (TargetInvocationException ex)
			{
				((BaseUnityPlugin)this).Logger.LogWarning((object)("Could not enable TargetPortal's map pins: " + ex.GetBaseException().Message));
			}
		}

		private void ReceiveRequest(long sender, int version)
		{
			if (version != 1 || router != ZRoutedRpc.instance || (Object)(object)ZNet.instance == (Object)null || !ZNet.instance.IsServer())
			{
				return;
			}
			object? obj = findPeer?.Invoke(ZNet.instance, new object[1] { sender });
			ZNetPeer val = (ZNetPeer)((obj is ZNetPeer) ? obj : null);
			if (val != null && object.Equals(isPeerReady?.Invoke(val, null), true))
			{
				if (Time.unscaledTime >= serverRefreshAt)
				{
					serverRefreshAt = Time.unscaledTime + 4f;
					servedPeers.Clear();
					Dictionary<Vector3, string> dictionary = ReadWorldPortals();
					serverSnapshot = ((dictionary == null) ? null : WriteSnapshot(dictionary));
				}
				if (serverSnapshot != null && servedPeers.Add(sender))
				{
					router.InvokeRoutedRPC(sender, "BenjSammy.PortalMapMarkers.Snapshot.v1", new object[1] { serverSnapshot });
				}
			}
		}

		private void ReceiveSnapshot(long sender, ZPackage package)
		{
			//IL_0061: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b0: Unknown result type (might be due to invalid IL or missing references)
			if (router == null || router != ZRoutedRpc.instance || (Object)(object)ZNet.instance == (Object)null || ZNet.instance.IsServer() || sender == 0L || sender != ServerPeerId() || (Object)(object)map == (Object)null || (Object)(object)map != (Object)(object)Minimap.instance || (int)CurrentMode(map) == 0 || package == null || package.Size() > 2097152)
			{
				return;
			}
			Dictionary<Vector3, string> dictionary;
			try
			{
				int num = package.ReadInt();
				if (num < 0 || num > (package.Size() - 4) / 13)
				{
					return;
				}
				dictionary = new Dictionary<Vector3, string>(num);
				for (int i = 0; i < num; i++)
				{
					Vector3 position = package.ReadVector3();
					string tag = package.ReadString();
					AddPortal(dictionary, position, tag);
				}
				if (package.GetPos() != package.Size())
				{
					return;
				}
			}
			catch (IOException)
			{
				return;
			}
			catch (FormatException)
			{
				return;
			}
			serverSnapshotReceived = true;
			UpdatePins(dictionary);
		}

		private long ServerPeerId()
		{
			object obj = getServerPeerId?.Invoke(router, null);
			if (obj is long)
			{
				return (long)obj;
			}
			return 0L;
		}

		private Dictionary<Vector3, string> ReadWorldPortals()
		{
			//IL_004d: Unknown result type (might be due to invalid IL or missing references)
			ZDOMan instance = ZDOMan.instance;
			if (worldPortals == null || instance == null)
			{
				return null;
			}
			Dictionary<Vector3, string> result = new Dictionary<Vector3, string>();
			foreach (ZDO item in EnumeratePortals(worldPortals.Invoke(instance, null)))
			{
				if (item != null && item.IsValid())
				{
					AddPortal(result, item.GetPosition(), item.GetString("tag", ""));
				}
			}
			return result;
		}

		private static IEnumerable<ZDO> EnumeratePortals(object data)
		{
			if (data is IEnumerable<ZDO> result)
			{
				return result;
			}
			if (data is IDictionary dictionary)
			{
				return dictionary.Values.OfType<IEnumerable<ZDO>>().SelectMany((IEnumerable<ZDO> portals) => portals);
			}
			return Enumerable.Empty<ZDO>();
		}

		private static Dictionary<Vector3, string> ReadLoadedPortals()
		{
			//IL_001b: Unknown result type (might be due to invalid IL or missing references)
			Dictionary<Vector3, string> result = new Dictionary<Vector3, string>();
			TeleportWorld[] array = Object.FindObjectsOfType<TeleportWorld>();
			foreach (TeleportWorld val in array)
			{
				AddPortal(result, ((Component)val).transform.position, val.GetText());
			}
			return result;
		}

		private static void AddPortal(Dictionary<Vector3, string> result, Vector3 position, string tag)
		{
			//IL_001d: Unknown result type (might be due to invalid IL or missing references)
			if (!float.IsNaN(((Vector3)(ref position)).sqrMagnitude) && !float.IsInfinity(((Vector3)(ref position)).sqrMagnitude))
			{
				result[position] = CleanTag(tag);
			}
		}

		private static string CleanTag(string tag)
		{
			if (string.IsNullOrEmpty(tag))
			{
				return "";
			}
			return tag.Replace('<', '‹').Replace('>', '›').Replace('\r', ' ')
				.Replace('\n', ' ')
				.Trim();
		}

		private static ZPackage WriteSnapshot(Dictionary<Vector3, string> portals)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: Expected O, but got Unknown
			//IL_0026: Unknown result type (might be due to invalid IL or missing references)
			ZPackage val = new ZPackage();
			val.Write(portals.Count);
			foreach (KeyValuePair<Vector3, string> portal in portals)
			{
				val.Write(portal.Key);
				val.Write(portal.Value);
			}
			if (val.Size() > 2097152)
			{
				return null;
			}
			return val;
		}

		private void UpdatePins(Dictionary<Vector3, string> portals)
		{
			//IL_0063: Unknown result type (might be due to invalid IL or missing references)
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			//IL_0076: Unknown result type (might be due to invalid IL or missing references)
			//IL_0088: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ba: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cf: Unknown result type (might be due to invalid IL or missing references)
			//IL_0100: Unknown result type (might be due to invalid IL or missing references)
			//IL_0107: Expected O, but got Unknown
			//IL_011c: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)icon == (Object)null)
			{
				LoadIcon();
			}
			Vector3[] array = pins.Keys.Where((Vector3 position) => !portals.ContainsKey(position) || pins[position].m_name != portals[position] || pins[position].m_shouldDelete).ToArray();
			foreach (Vector3 key in array)
			{
				map.RemovePin(pins[key]);
				pins.Remove(key);
			}
			foreach (KeyValuePair<Vector3, string> portal in portals)
			{
				if (!pins.ContainsKey(portal.Key))
				{
					pinArguments[0] = portal.Key;
					pinArguments[2] = portal.Value;
					PinData val = (PinData)addPin.Invoke(map, pinArguments);
					val.m_icon = icon;
					pins.Add(portal.Key, val);
				}
			}
		}

		private void LoadIcon()
		{
			//IL_002c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0036: Expected O, but got Unknown
			//IL_008a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0099: Unknown result type (might be due to invalid IL or missing references)
			using Stream stream = typeof(PortalMapMarkers).Assembly.GetManifestResourceStream("PortalMapMarkers.PortalPin.png");
			using MemoryStream memoryStream = new MemoryStream();
			stream.CopyTo(memoryStream);
			texture = new Texture2D(2, 2, (TextureFormat)4, false);
			ImageConversion.LoadImage(texture, memoryStream.ToArray(), true);
			((Texture)texture).filterMode = (FilterMode)1;
			((Texture)texture).wrapMode = (TextureWrapMode)1;
			icon = Sprite.Create(texture, new Rect(0f, 0f, (float)((Texture)texture).width, (float)((Texture)texture).height), new Vector2(0.5f, 0.5f));
		}

		private void ClearPins()
		{
			if (pins.Count == 0)
			{
				return;
			}
			if ((Object)(object)map != (Object)null)
			{
				foreach (PinData value in pins.Values)
				{
					map.RemovePin(value);
				}
			}
			pins.Clear();
		}

		private void OnDestroy()
		{
			Harmony obj = harmony;
			if (obj != null)
			{
				obj.UnpatchSelf();
			}
			if ((Object)(object)active == (Object)(object)this)
			{
				active = null;
			}
			ClearPins();
			if ((Object)(object)icon != (Object)null)
			{
				Object.Destroy((Object)(object)icon);
			}
			if ((Object)(object)texture != (Object)null)
			{
				Object.Destroy((Object)(object)texture);
			}
		}
	}
}