Decompiled source of TotemPins v3.0.0

TotemPins.dll

Decompiled 3 weeks ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Text;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
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("TotemPins")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("3.0.0.0")]
[assembly: AssemblyInformationalVersion("3.0.0")]
[assembly: AssemblyProduct("TotemPins")]
[assembly: AssemblyTitle("TotemPins")]
[assembly: AssemblyVersion("3.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 TotemPins
{
	[BepInPlugin("valheimtotems.totempins", "TotemPins", "3.0.0")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	public class TotemPinsPlugin : BaseUnityPlugin
	{
		public enum PinStyle
		{
			Discoverable,
			Unlocked
		}

		public enum Override
		{
			PlayerChoice,
			On,
			Off
		}

		private sealed class ServerState
		{
			public bool SmallPins = true;

			public bool HideDuplicatePins = true;

			public bool ShareUnlocks = true;

			public Override ShowMapPins;

			public Override ShowDiscoverableMapPins;

			public Override AdminBypass;

			public Dictionary<int, int> SharedUnlocks = new Dictionary<int, int>();
		}

		private sealed class TotemInfo
		{
			public Vector3 Position;

			public bool Unlocked;

			public bool Built;

			public bool AlwaysLock;

			public int Bin;

			public int Id;
		}

		public const string Guid = "valheimtotems.totempins";

		public const string Version = "3.0.0";

		public const string TravelTotemsGuid = "com.orianaventure.mod.TravelTotems";

		public const string DiscoverableIconName = "TotemPins_Totem";

		public const string UnlockedIconName = "TotemPins_TotemUnlocked";

		private const string RpcReport = "TotemPins_Unlocked";

		private const string RpcState = "TotemPins_State";

		private const string VisitedKeyPrefix = "TotemPins_Visited_";

		private const float TotemMatchDistance = 20f;

		private const float TickInterval = 2f;

		internal static ManualLogSource Log;

		internal static ConfigEntry<bool> Enabled;

		internal static ConfigEntry<string> LocationPrefix;

		internal static ConfigEntry<bool> UseTravelTotemsIcon;

		internal static ConfigEntry<string> IconName;

		internal static ConfigEntry<PinStyle> Style;

		internal static ConfigEntry<bool> SmallPins;

		internal static ConfigEntry<bool> HideDuplicatePins;

		internal static ConfigEntry<bool> ShareUnlocks;

		internal static ConfigEntry<bool> ShareBuiltTotems;

		internal static ConfigEntry<Override> ShowMapPins;

		internal static ConfigEntry<Override> ShowDiscoverableMapPins;

		internal static ConfigEntry<Override> AdminBypass;

		internal static ConfigEntry<bool> LogIconNames;

		private static ServerState _state;

		private static FieldInfo _fLocations;

		private static FieldInfo _fPrefabName;

		private static FieldInfo _fPrefab;

		private static FieldInfo _fIconPlaced;

		private static PropertyInfo _pRefName;

		private static int _lastLocationCount = -1;

		private static object _lastList;

		private static object _registeredList;

		private static object _discoverableSprite;

		private static object _unlockedSprite;

		private static bool _warnedNoSprite;

		private static FieldInfo _fLocationPins;

		private static FieldInfo _fPinIcon;

		private static FieldInfo _fPinDoubleSize;

		private static MethodInfo _mDestroyPinMarker;

		private static List<Vector3> _pinPositions = new List<Vector3>();

		private static string _pinSignature = "";

		private static bool _syncReady;

		private static PropertyInfo _pRpcInstance;

		private static PropertyInfo _pZNetInstance;

		private static PropertyInfo _pZoneSystemInstance;

		private static MethodInfo _mRegister;

		private static MethodInfo _mInvokeToServer;

		private static MethodInfo _mInvokeToPeer;

		private static MethodInfo _mIsServer;

		private static MethodInfo _mSendLocationIcons;

		private static MethodInfo _mGetLocationIcons;

		private static MethodInfo _mGetSessionId;

		private static MethodInfo _mZdoGetInt;

		private static MethodInfo _mZdoSetInt;

		private static MethodInfo _mZdoSetOwner;

		private static MethodInfo _mZdoGetPosition;

		private static MethodInfo _mZdoGetPrefab;

		private static MethodInfo _mGetTravelTotems;

		private static MethodInfo _mGetTotemType;

		private static MethodInfo _mAddKnownTotem;

		private static MethodInfo _mRefreshMapPins;

		private static FieldInfo _fLocalPlayer;

		private static FieldInfo _fKnownTotemIds;

		private static FieldInfo _fTrackerZdo;

		private static readonly HashSet<int> PiecePrefabHashes = new HashSet<int>();

		private const int TotemTypeAlwaysLock = 3;

		private static object _registeredRpc;

		private static string _lastReport;

		private static string _lastServerSignature;

		private static volatile bool _configFileChanged;

		private static float _lastReloadTime = -10f;

		private static bool _settingsDirty;

		private float _tickTimer;

		private FileSystemWatcher _watcher;

		private void Awake()
		{
			Log = ((BaseUnityPlugin)this).Logger;
			Enabled = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "Enabled", true, "Turns TotemPins on or off.");
			LocationPrefix = ((BaseUnityPlugin)this).Config.Bind<string>("General", "LocationPrefix", "VV_TravelTotemLocation", "Server: locations whose prefab name starts with this get a map pin.");
			UseTravelTotemsIcon = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "UseTravelTotemsIcon", true, "Server: use a Travel Totems map icon. Requires TotemPins on the server AND every player. Set false to use the vanilla IconName below instead (server-only install works, but the other features need TotemPins on players too).");
			IconName = ((BaseUnityPlugin)this).Config.Bind<string>("General", "IconName", "StartTemple", "Server: vanilla location icon used only when UseTravelTotemsIcon is false (e.g. StartTemple). With StartTemple, Travel Totems' AllowSelectDefaultSpawn treats pins as spawn points.");
			Style = ((BaseUnityPlugin)this).Config.Bind<PinStyle>("Pins", "PinStyle", PinStyle.Discoverable, "Icon for totems nobody has unlocked. Discoverable = Travel Totems' grey 'not yet unlocked' icon, Unlocked = the normal totem icon. Server setting: players get the server's value.");
			SmallPins = ((BaseUnityPlugin)this).Config.Bind<bool>("Pins", "SmallPins", true, "Draw TotemPins pins at normal pin size instead of the large trader-icon size. Server setting: players get the server's value.");
			HideDuplicatePins = ((BaseUnityPlugin)this).Config.Bind<bool>("Pins", "HideDuplicatePins", true, "Hide Travel Totems' own grey pin where a TotemPins pin already marks the same totem. Server setting: players get the server's value.");
			ShareUnlocks = ((BaseUnityPlugin)this).Config.Bind<bool>("Unlocks", "ShareUnlocks", true, "When one player unlocks a world totem, unlock it for every player. Unlocks are added to each character, as if they had walked there. Server setting: players get the server's value.");
			ShareBuiltTotems = ((BaseUnityPlugin)this).Config.Bind<bool>("Unlocks", "ShareBuiltTotems", false, "Also share unlocks of totems players have built. When false, built totems stay per player.");
			ShowMapPins = ((BaseUnityPlugin)this).Config.Bind<Override>("Travel Totems", "ShowMapPins", Override.On, "Overrides Travel Totems' ShowMapPins for every player. On = always show totem pins on the map, Off = only while using a totem, PlayerChoice = each player's own Travel Totems setting. Server setting: players get the server's value.");
			ShowDiscoverableMapPins = ((BaseUnityPlugin)this).Config.Bind<Override>("Travel Totems", "ShowDiscoverableMapPins", Override.On, "Overrides Travel Totems' ShowDiscoverableMapPins for every player: grey pins for totems a player knows about but hasn't unlocked. PlayerChoice = each player's own Travel Totems setting. Server setting: players get the server's value.");
			AdminBypass = ((BaseUnityPlugin)this).Config.Bind<Override>("Travel Totems", "AdminBypass", Override.PlayerChoice, "Overrides Travel Totems' AdminBypass for admins. Off = admins must unlock totems like everyone else, On = admins can use and change every totem, PlayerChoice = each admin's own Travel Totems setting. Server setting: players get the server's value.");
			LogIconNames = ((BaseUnityPlugin)this).Config.Bind<bool>("Debug", "LogIconNames", false, "Log every map location icon name the game knows.");
			((BaseUnityPlugin)this).Config.SettingChanged += delegate
			{
				_settingsDirty = true;
			};
			WatchConfigFile();
			ApplyPatches();
		}

		private void OnDestroy()
		{
			_watcher?.Dispose();
		}

		private void WatchConfigFile()
		{
			try
			{
				_watcher = new FileSystemWatcher(Path.GetDirectoryName(((BaseUnityPlugin)this).Config.ConfigFilePath), Path.GetFileName(((BaseUnityPlugin)this).Config.ConfigFilePath));
				_watcher.Changed += delegate
				{
					_configFileChanged = true;
				};
				_watcher.Created += delegate
				{
					_configFileChanged = true;
				};
				_watcher.Renamed += delegate
				{
					_configFileChanged = true;
				};
				_watcher.EnableRaisingEvents = true;
			}
			catch (Exception ex)
			{
				Log.LogWarning((object)("Could not watch the config file; changes need a restart: " + ex.Message));
			}
		}

		private static void ApplyPatches()
		{
			//IL_002d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0033: Expected O, but got Unknown
			if (!ResolveLocationFields())
			{
				return;
			}
			_syncReady = ResolveSyncMembers();
			if (!_syncReady)
			{
				Log.LogWarning((object)"Could not hook Travel Totems; unlock sharing and setting overrides are off.");
			}
			Harmony val = new Harmony("valheimtotems.totempins");
			int num = 0;
			MethodInfo[] methods = AccessTools.TypeByName("ZoneSystem").GetMethods(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
			foreach (MethodInfo methodInfo in methods)
			{
				if (methodInfo.Name == "PlaceLocations")
				{
					val.Patch((MethodBase)methodInfo, Hm("EnsureFlagsPrefix"), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
					num++;
				}
				else if (methodInfo.Name == "GetLocationIcons")
				{
					val.Patch((MethodBase)methodInfo, Hm("EnsureFlagsPrefix"), Hm("FilterIconsPostfix"), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
					num++;
				}
			}
			Type type = AccessTools.TypeByName("Minimap");
			MethodInfo methodInfo2 = AccessTools.Method(type, "Start", (Type[])null, (Type[])null);
			MethodInfo methodInfo3 = AccessTools.Method(type, "UpdateLocationPins", (Type[])null, (Type[])null);
			if (methodInfo2 != null)
			{
				val.Patch((MethodBase)methodInfo2, (HarmonyMethod)null, Hm("RegisterIconsPatch"), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			}
			if (methodInfo3 != null)
			{
				val.Patch((MethodBase)methodInfo3, Hm("RegisterIconsPatch"), Hm("StylePinsPostfix"), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			}
			if (_syncReady)
			{
				Type type2 = AccessTools.TypeByName("VentureValheim.TravelTotems.TravelTotemsPlugin");
				Type type3 = AccessTools.TypeByName("VentureValheim.TravelTotems.TravelTotemMap");
				PatchIfFound(val, AccessTools.Method(type2, "GetShowMapPins", (Type[])null, (Type[])null), Hm("ShowMapPinsPrefix"));
				PatchIfFound(val, AccessTools.Method(type2, "GetShowDiscoverableMapPins", (Type[])null, (Type[])null), Hm("ShowDiscoverablePrefix"));
				PatchIfFound(val, AccessTools.Method(type2, "AdminAccess", (Type[])null, (Type[])null), Hm("AdminAccessPrefix"));
				PatchIfFound(val, AccessTools.Method(type3, "AddMapPin", (Type[])null, (Type[])null), Hm("AddMapPinPrefix"));
			}
			Log.LogInfo((object)string.Format("TotemPins {0} loaded ({1} location methods patched, Travel Totems hooks {2}).", "3.0.0", num, _syncReady ? "on" : "off"));
			static HarmonyMethod Hm(string name)
			{
				//IL_0012: Unknown result type (might be due to invalid IL or missing references)
				//IL_0018: Expected O, but got Unknown
				return new HarmonyMethod(AccessTools.Method(typeof(TotemPinsPlugin), name, (Type[])null, (Type[])null));
			}
		}

		private static void PatchIfFound(Harmony harmony, MethodInfo target, HarmonyMethod prefix)
		{
			if (target == null)
			{
				Log.LogWarning((object)"Travel Totems method not found; one setting override won't work.");
			}
			else
			{
				harmony.Patch((MethodBase)target, prefix, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			}
		}

		private static bool ResolveLocationFields()
		{
			Type type = AccessTools.TypeByName("ZoneSystem");
			Type type2 = AccessTools.TypeByName("ZoneLocation") ?? AccessTools.TypeByName("ZoneSystem+ZoneLocation");
			if (type == null || type2 == null)
			{
				Log.LogError((object)"Could not find ZoneSystem/ZoneLocation - game version not supported.");
				return false;
			}
			_fLocations = AccessTools.Field(type, "m_locations");
			_fPrefabName = AccessTools.Field(type2, "m_prefabName");
			_fPrefab = AccessTools.Field(type2, "m_prefab");
			_fIconPlaced = AccessTools.Field(type2, "m_iconPlaced");
			if (_fPrefab != null)
			{
				_pRefName = AccessTools.Property(_fPrefab.FieldType, "Name");
			}
			if (_fLocations == null || _fIconPlaced == null || (_fPrefab == null && _fPrefabName == null))
			{
				Log.LogError((object)"Expected ZoneSystem/ZoneLocation fields are missing - game version not supported.");
				return false;
			}
			return true;
		}

		private static bool ResolveSyncMembers()
		{
			Type type = AccessTools.TypeByName("ZRoutedRpc");
			Type type2 = AccessTools.TypeByName("ZNet");
			Type type3 = AccessTools.TypeByName("ZoneSystem");
			Type type4 = AccessTools.TypeByName("ZDO");
			Type type5 = AccessTools.TypeByName("ZDOMan");
			Type type6 = AccessTools.TypeByName("Player");
			Type type7 = AccessTools.TypeByName("Minimap");
			Type type8 = AccessTools.TypeByName("VentureValheim.TravelTotems.TravelTotems");
			Type type9 = AccessTools.TypeByName("VentureValheim.TravelTotems.TravelTotemPlayer");
			Type type10 = AccessTools.TypeByName("VentureValheim.TravelTotems.TravelTotemPortal");
			Type type11 = AccessTools.TypeByName("VentureValheim.TravelTotems.TravelTotemMap");
			Type type12 = AccessTools.TypeByName("VentureValheim.TravelTotems.AssetManager");
			if (type == null || type2 == null || type3 == null || type4 == null || type5 == null || type6 == null || type7 == null || type8 == null || type9 == null || type10 == null || type11 == null || type12 == null)
			{
				return false;
			}
			_pRpcInstance = AccessTools.Property(type, "instance");
			_pZNetInstance = AccessTools.Property(type2, "instance");
			_pZoneSystemInstance = AccessTools.Property(type3, "instance");
			MethodInfo[] methods = type.GetMethods(BindingFlags.Instance | BindingFlags.Public);
			foreach (MethodInfo methodInfo in methods)
			{
				ParameterInfo[] parameters = methodInfo.GetParameters();
				if (methodInfo.Name == "Register" && methodInfo.IsGenericMethodDefinition && methodInfo.GetGenericArguments().Length == 1 && parameters.Length == 2)
				{
					_mRegister = methodInfo.MakeGenericMethod(typeof(string));
				}
				else if (methodInfo.Name == "InvokeRoutedRPC" && parameters.Length == 2 && parameters[0].ParameterType == typeof(string))
				{
					_mInvokeToServer = methodInfo;
				}
				else if (methodInfo.Name == "InvokeRoutedRPC" && parameters.Length == 3 && parameters[0].ParameterType == typeof(long) && parameters[1].ParameterType == typeof(string))
				{
					_mInvokeToPeer = methodInfo;
				}
			}
			_mIsServer = AccessTools.Method(type2, "IsServer", Type.EmptyTypes, (Type[])null);
			_mSendLocationIcons = AccessTools.Method(type3, "SendLocationIcons", new Type[1] { typeof(long) }, (Type[])null);
			_mGetLocationIcons = AccessTools.Method(type3, "GetLocationIcons", (Type[])null, (Type[])null);
			_mGetSessionId = AccessTools.Method(type5, "GetSessionID", Type.EmptyTypes, (Type[])null);
			_mZdoGetInt = AccessTools.Method(type4, "GetInt", new Type[2]
			{
				typeof(string),
				typeof(int)
			}, (Type[])null);
			_mZdoSetInt = AccessTools.Method(type4, "Set", new Type[2]
			{
				typeof(string),
				typeof(int)
			}, (Type[])null);
			_mZdoSetOwner = AccessTools.Method(type4, "SetOwner", new Type[1] { typeof(long) }, (Type[])null);
			_mZdoGetPosition = AccessTools.Method(type4, "GetPosition", Type.EmptyTypes, (Type[])null);
			_mZdoGetPrefab = AccessTools.Method(type4, "GetPrefab", Type.EmptyTypes, (Type[])null);
			_mGetTravelTotems = AccessTools.Method(type8, "GetTravelTotems", Type.EmptyTypes, (Type[])null);
			_mGetTotemType = AccessTools.Method(type10, "GetTotemType", new Type[1] { type4 }, (Type[])null);
			_mAddKnownTotem = AccessTools.Method(type9, "AddKnownTotem", new Type[2]
			{
				typeof(int),
				typeof(int)
			}, (Type[])null);
			_mRefreshMapPins = AccessTools.Method(type11, "RefreshMapPins", Type.EmptyTypes, (Type[])null);
			_mDestroyPinMarker = AccessTools.Method(type7, "DestroyPinMarker", (Type[])null, (Type[])null);
			_fTrackerZdo = AccessTools.Field(type8, "TravelTotemTrackerZDO");
			_fKnownTotemIds = AccessTools.Field(type9, "KnownTravelTotemIDs");
			_fLocalPlayer = AccessTools.Field(type6, "m_localPlayer");
			string[] array = new string[3] { "TravelTotemPieceHash", "TravelTotemPieceMistlandsHash", "TravelTotemPieceAshlandsHash" };
			foreach (string text in array)
			{
				if (AccessTools.Field(type12, text)?.GetValue(null) is int item)
				{
					PiecePrefabHashes.Add(item);
				}
			}
			if (_pRpcInstance != null && _pZNetInstance != null && _pZoneSystemInstance != null && _mRegister != null && _mInvokeToServer != null && _mInvokeToPeer != null && _mIsServer != null && _mSendLocationIcons != null && _mGetLocationIcons != null && _mGetSessionId != null && _mZdoGetInt != null && _mZdoSetInt != null && _mZdoSetOwner != null && _mZdoGetPosition != null && _mZdoGetPrefab != null && _mGetTravelTotems != null && _mGetTotemType != null && _mAddKnownTotem != null && _mRefreshMapPins != null && _mDestroyPinMarker != null && _fTrackerZdo != null && _fKnownTotemIds != null && _fLocalPlayer != null)
			{
				return PiecePrefabHashes.Count == 3;
			}
			return false;
		}

		private void Update()
		{
			if (_configFileChanged)
			{
				_configFileChanged = false;
				if (Time.realtimeSinceStartup - _lastReloadTime > 1f)
				{
					_lastReloadTime = Time.realtimeSinceStartup;
					try
					{
						((BaseUnityPlugin)this).Config.Reload();
					}
					catch (Exception ex)
					{
						Log.LogWarning((object)("Could not reload config: " + ex.Message));
					}
				}
			}
			if (!_syncReady)
			{
				return;
			}
			_tickTimer -= Time.deltaTime;
			if (_tickTimer > 0f && !_settingsDirty)
			{
				return;
			}
			_tickTimer = 2f;
			bool settingsDirty = _settingsDirty;
			_settingsDirty = false;
			try
			{
				object value = _pRpcInstance.GetValue(null, null);
				if (value == null)
				{
					if (_registeredRpc != null)
					{
						ResetSession();
					}
					return;
				}
				if (value != _registeredRpc)
				{
					ResetSession();
					Register(value, "TotemPins_Unlocked", "RPC_Report");
					Register(value, "TotemPins_State", "RPC_State");
					_registeredRpc = value;
				}
				if (IsServer())
				{
					ServerTick(value, settingsDirty);
				}
				if (Enabled.Value && _fLocalPlayer.GetValue(null) != null)
				{
					PlayerTick(value);
				}
			}
			catch (Exception ex2)
			{
				_syncReady = false;
				Log.LogWarning((object)("TotemPins sync failed and is now off: " + ex2.Message));
			}
		}

		private static void Register(object rpc, string name, string handler)
		{
			Delegate obj = Delegate.CreateDelegate(typeof(Action<, >).MakeGenericType(typeof(long), typeof(string)), AccessTools.Method(typeof(TotemPinsPlugin), handler, (Type[])null, (Type[])null));
			_mRegister.Invoke(rpc, new object[2] { name, obj });
		}

		private static void ResetSession()
		{
			bool num = _state != null;
			_registeredRpc = null;
			_lastReport = null;
			_lastServerSignature = null;
			_state = null;
			_pinSignature = "";
			_pinPositions = new List<Vector3>();
			if (num)
			{
				RefreshTravelTotemsPins();
			}
		}

		private static void PlayerTick(object rpc)
		{
			if (!(_fKnownTotemIds.GetValue(null) is IList<int> list))
			{
				return;
			}
			if (_state != null && _state.ShareUnlocks)
			{
				foreach (KeyValuePair<int, int> sharedUnlock in _state.SharedUnlocks)
				{
					int num = ((sharedUnlock.Key < list.Count) ? list[sharedUnlock.Key] : 0);
					int num2 = sharedUnlock.Value & ~num;
					if (num2 != 0)
					{
						_mAddKnownTotem.Invoke(null, new object[2] { sharedUnlock.Key, num2 });
					}
				}
			}
			List<string> list2 = new List<string>();
			for (int i = 0; i < list.Count; i++)
			{
				if (list[i] != 0)
				{
					list2.Add(i + ":" + list[i]);
				}
			}
			string text = string.Join(";", list2.ToArray());
			if (!(text == _lastReport))
			{
				_mInvokeToServer.Invoke(rpc, new object[2]
				{
					"TotemPins_Unlocked",
					new object[1] { text }
				});
				_lastReport = text;
			}
		}

		private static void ServerTick(object rpc, bool settingsChanged)
		{
			if (settingsChanged)
			{
				_lastList = null;
			}
			if (!Enabled.Value)
			{
				return;
			}
			int unlockedWorldTotems;
			string text = BuildState(out unlockedWorldTotems);
			string text2 = unlockedWorldTotems + "|" + text;
			if (!settingsChanged && text2 == _lastServerSignature)
			{
				return;
			}
			bool num = _lastServerSignature == null;
			_lastServerSignature = text2;
			if (!num)
			{
				object value = _pZoneSystemInstance.GetValue(null, null);
				if (value != null)
				{
					_mSendLocationIcons.Invoke(value, new object[1] { 0L });
				}
				_mInvokeToPeer.Invoke(rpc, new object[3]
				{
					0L,
					"TotemPins_State",
					new object[1] { text }
				});
			}
		}

		private static void RPC_Report(long sender, string report)
		{
			try
			{
				if (!Enabled.Value || !IsServer())
				{
					return;
				}
				object value = _fTrackerZdo.GetValue(null);
				int i;
				if (value != null && !string.IsNullOrEmpty(report))
				{
					bool flag = false;
					string[] array = report.Split(';');
					for (i = 0; i < array.Length; i++)
					{
						string[] array2 = array[i].Split(':');
						if (array2.Length != 2 || !int.TryParse(array2[0], out var result) || !int.TryParse(array2[1], out var result2) || result < 0)
						{
							continue;
						}
						string text = "TotemPins_Visited_" + result;
						int num = (int)_mZdoGetInt.Invoke(value, new object[2] { text, 0 });
						if ((num | result2) != num)
						{
							if (!flag)
							{
								_mZdoSetOwner.Invoke(value, new object[1] { _mGetSessionId.Invoke(null, null) });
								flag = true;
							}
							_mZdoSetInt.Invoke(value, new object[2]
							{
								text,
								num | result2
							});
						}
					}
				}
				object value2 = _pRpcInstance.GetValue(null, null);
				if (value2 != null)
				{
					_mInvokeToPeer.Invoke(value2, new object[3]
					{
						sender,
						"TotemPins_State",
						new object[1] { BuildState(out i) }
					});
				}
			}
			catch (Exception ex)
			{
				Log.LogWarning((object)("Could not record totem unlocks: " + ex.Message));
			}
		}

		private static void RPC_State(long sender, string message)
		{
			try
			{
				if (!Enabled.Value || message == null)
				{
					return;
				}
				ServerState serverState = new ServerState();
				string[] array = message.Split('|');
				foreach (string text in array)
				{
					int num = text.IndexOf('=');
					if (num <= 0)
					{
						continue;
					}
					string text2 = text.Substring(0, num);
					string text3 = text.Substring(num + 1);
					switch (text2)
					{
					case "small":
						serverState.SmallPins = text3 == "1";
						break;
					case "dedupe":
						serverState.HideDuplicatePins = text3 == "1";
						break;
					case "share":
						serverState.ShareUnlocks = text3 == "1";
						break;
					case "mappins":
						serverState.ShowMapPins = ParseOverride(text3);
						break;
					case "discover":
						serverState.ShowDiscoverableMapPins = ParseOverride(text3);
						break;
					case "bypass":
						serverState.AdminBypass = ParseOverride(text3);
						break;
					case "unlocks":
					{
						string[] array2 = text3.Split(',');
						for (int j = 0; j < array2.Length; j++)
						{
							string[] array3 = array2[j].Split(':');
							if (array3.Length == 2 && int.TryParse(array3[0], out var result) && int.TryParse(array3[1], out var result2) && result >= 0)
							{
								serverState.SharedUnlocks[result] = result2;
							}
						}
						break;
					}
					}
				}
				ServerState state = _state;
				_state = serverState;
				if (state == null || state.ShowMapPins != serverState.ShowMapPins || state.ShowDiscoverableMapPins != serverState.ShowDiscoverableMapPins || state.AdminBypass != serverState.AdminBypass || state.HideDuplicatePins != serverState.HideDuplicatePins)
				{
					RefreshTravelTotemsPins();
				}
			}
			catch (Exception ex)
			{
				Log.LogWarning((object)("Could not read TotemPins settings from the server: " + ex.Message));
			}
		}

		private static Override ParseOverride(string value)
		{
			if (!Enum.TryParse<Override>(value, out var result))
			{
				return Override.PlayerChoice;
			}
			return result;
		}

		private static bool IsServer()
		{
			object obj = _pZNetInstance?.GetValue(null, null);
			if (obj != null)
			{
				return (bool)_mIsServer.Invoke(obj, null);
			}
			return false;
		}

		private static List<TotemInfo> GetTotems()
		{
			//IL_0114: Unknown result type (might be due to invalid IL or missing references)
			//IL_0119: Unknown result type (might be due to invalid IL or missing references)
			List<TotemInfo> list = new List<TotemInfo>();
			object value = _fTrackerZdo.GetValue(null);
			if (value == null || !(_mGetTravelTotems.Invoke(null, null) is IList list2))
			{
				return list;
			}
			Dictionary<int, int> dictionary = new Dictionary<int, int>();
			foreach (object item in list2)
			{
				if (item == null)
				{
					continue;
				}
				int num = (int)_mZdoGetInt.Invoke(item, new object[2] { "VV_TotemIDBin", -1 });
				int num2 = (int)_mZdoGetInt.Invoke(item, new object[2] { "VV_TotemID", -1 });
				if (num >= 0 && num2 > 0)
				{
					if (!dictionary.TryGetValue(num, out var value2))
					{
						value2 = (dictionary[num] = (int)_mZdoGetInt.Invoke(value, new object[2]
						{
							"TotemPins_Visited_" + num,
							0
						}));
					}
					list.Add(new TotemInfo
					{
						Position = (Vector3)_mZdoGetPosition.Invoke(item, null),
						Unlocked = ((value2 & num2) != 0),
						Built = PiecePrefabHashes.Contains((int)_mZdoGetPrefab.Invoke(item, null)),
						AlwaysLock = (Convert.ToInt32(_mGetTotemType.Invoke(null, new object[1] { item })) == 3),
						Bin = num,
						Id = num2
					});
				}
			}
			return list;
		}

		private static string BuildState(out int unlockedWorldTotems)
		{
			unlockedWorldTotems = 0;
			SortedDictionary<int, int> sortedDictionary = new SortedDictionary<int, int>();
			foreach (TotemInfo totem in GetTotems())
			{
				if (totem.Unlocked)
				{
					if (!totem.Built)
					{
						unlockedWorldTotems++;
					}
					if (ShareUnlocks.Value && !totem.AlwaysLock && (!totem.Built || ShareBuiltTotems.Value))
					{
						sortedDictionary.TryGetValue(totem.Bin, out var value);
						sortedDictionary[totem.Bin] = value | totem.Id;
					}
				}
			}
			List<string> list = new List<string>();
			foreach (KeyValuePair<int, int> item in sortedDictionary)
			{
				list.Add(item.Key + ":" + item.Value);
			}
			return "small=" + (SmallPins.Value ? "1" : "0") + "|dedupe=" + (HideDuplicatePins.Value ? "1" : "0") + "|share=" + (ShareUnlocks.Value ? "1" : "0") + "|mappins=" + ShowMapPins.Value.ToString() + "|discover=" + ShowDiscoverableMapPins.Value.ToString() + "|bypass=" + AdminBypass.Value.ToString() + "|unlocks=" + string.Join(",", list.ToArray());
		}

		private static string GetLocationName(object zoneLocation)
		{
			if (_fPrefab != null && _pRefName != null)
			{
				try
				{
					object value = _fPrefab.GetValue(zoneLocation);
					if (value != null && _pRefName.GetValue(value, null) is string { Length: >0 } text)
					{
						return text;
					}
				}
				catch (Exception)
				{
				}
			}
			return _fPrefabName?.GetValue(zoneLocation) as string;
		}

		private static void EnsureFlagsPrefix(object __instance)
		{
			if (!Enabled.Value || __instance == null)
			{
				return;
			}
			try
			{
				if (!(_fLocations.GetValue(__instance) is IList list) || (list == _lastList && list.Count == _lastLocationCount))
				{
					return;
				}
				_lastList = list;
				_lastLocationCount = list.Count;
				string value = LocationPrefix.Value;
				int num = 0;
				foreach (object item in list)
				{
					if (item == null)
					{
						continue;
					}
					string locationName = GetLocationName(item);
					if (locationName != null && locationName.StartsWith(value, StringComparison.Ordinal))
					{
						if (!(bool)_fIconPlaced.GetValue(item))
						{
							_fIconPlaced.SetValue(item, true);
						}
						num++;
					}
				}
				Log.LogInfo((object)$"Flagged {num} location type(s) matching '{value}' for map icons.");
			}
			catch (Exception ex)
			{
				Log.LogWarning((object)("EnsureFlags failed: " + ex.Message));
			}
		}

		private static void FilterIconsPostfix(object __0)
		{
			//IL_00e8: Unknown result type (might be due to invalid IL or missing references)
			//IL_011f: Unknown result type (might be due to invalid IL or missing references)
			if (!Enabled.Value || !(__0 is IDictionary { Count: not 0 } dictionary))
			{
				return;
			}
			try
			{
				string value = LocationPrefix.Value;
				List<object> list = new List<object>();
				foreach (DictionaryEntry item in dictionary)
				{
					if (item.Value is string text && text.StartsWith(value, StringComparison.Ordinal))
					{
						list.Add(item.Key);
					}
				}
				if (list.Count == 0)
				{
					return;
				}
				if (_syncReady && IsServer())
				{
					List<Vector3> list2 = new List<Vector3>();
					foreach (TotemInfo totem in GetTotems())
					{
						if (totem.Unlocked && !totem.Built)
						{
							list2.Add(totem.Position);
						}
					}
					int num = list.Count - 1;
					while (num >= 0 && list2.Count > 0)
					{
						if (IsNear((Vector3)list[num], list2))
						{
							dictionary.Remove(list[num]);
							list.RemoveAt(num);
						}
						num--;
					}
				}
				string value2 = ((!UseTravelTotemsIcon.Value) ? IconName.Value : ((Style.Value == PinStyle.Unlocked) ? "TotemPins_TotemUnlocked" : "TotemPins_Totem"));
				foreach (object item2 in list)
				{
					dictionary[item2] = value2;
				}
			}
			catch (Exception ex)
			{
				Log.LogWarning((object)("Filtering location icons failed: " + ex.Message));
			}
		}

		private static bool IsNear(Vector3 pos, List<Vector3> others)
		{
			//IL_000b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_0016: 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)
			foreach (Vector3 other in others)
			{
				float num = other.x - pos.x;
				float num2 = other.z - pos.z;
				if (num * num + num2 * num2 <= 400f)
				{
					return true;
				}
			}
			return false;
		}

		private static void RegisterIconsPatch(object __instance)
		{
			if (__instance == null || !Enabled.Value)
			{
				return;
			}
			try
			{
				object obj = AccessTools.Field(__instance.GetType(), "m_locationIcons")?.GetValue(__instance);
				IList list = obj as IList;
				if (list == null || list == _registeredList)
				{
					return;
				}
				Type entryType = (list.GetType().IsGenericType ? list.GetType().GetGenericArguments()[0] : null);
				FieldInfo fName = ((entryType == null) ? null : AccessTools.Field(entryType, "m_name"));
				FieldInfo fIcon = ((entryType == null) ? null : AccessTools.Field(entryType, "m_icon"));
				if (fName == null || fIcon == null)
				{
					_registeredList = list;
					Log.LogWarning((object)"Minimap icon list has an unexpected format.");
					return;
				}
				HashSet<string> names = new HashSet<string>();
				foreach (object item2 in list)
				{
					if (item2 != null && fName.GetValue(item2) is string item)
					{
						names.Add(item);
					}
				}
				if (LogIconNames.Value)
				{
					Log.LogInfo((object)("Map location icons: " + string.Join(", ", new List<string>(names).ToArray())));
				}
				Type type = AccessTools.TypeByName("VentureValheim.TravelTotems.AssetManager");
				object obj2 = ((type == null) ? null : AccessTools.Property(type, "TotemDiscoverableMapSprite")?.GetValue(null, null));
				object obj3 = ((type == null) ? null : AccessTools.Property(type, "TotemMapSprite")?.GetValue(null, null));
				if (obj2 == null || obj3 == null)
				{
					if (!_warnedNoSprite)
					{
						_warnedNoSprite = true;
						Log.LogWarning((object)"Travel Totems map sprites not available yet; will retry.");
					}
				}
				else
				{
					Add("TotemPins_Totem", obj2);
					Add("TotemPins_TotemUnlocked", obj3);
					_discoverableSprite = obj2;
					_unlockedSprite = obj3;
					_registeredList = list;
					Log.LogInfo((object)"Registered Travel Totems map icons.");
				}
				void Add(string name, object sprite)
				{
					if (!names.Contains(name))
					{
						object obj4 = Activator.CreateInstance(entryType);
						fName.SetValue(obj4, name);
						fIcon.SetValue(obj4, sprite);
						list.Add(obj4);
					}
				}
			}
			catch (Exception ex)
			{
				_registeredList = null;
				Log.LogWarning((object)("Could not register totem map icons: " + ex.Message));
			}
		}

		private static void StylePinsPostfix(object __instance)
		{
			//IL_00f4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fc: Unknown result type (might be due to invalid IL or missing references)
			//IL_026c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0271: Unknown result type (might be due to invalid IL or missing references)
			//IL_0275: Unknown result type (might be due to invalid IL or missing references)
			//IL_0289: Unknown result type (might be due to invalid IL or missing references)
			//IL_0140: Unknown result type (might be due to invalid IL or missing references)
			if (!Enabled.Value || _discoverableSprite == null || __instance == null)
			{
				return;
			}
			try
			{
				if ((object)_fLocationPins == null)
				{
					_fLocationPins = AccessTools.Field(__instance.GetType(), "m_locationPins");
				}
				object obj = _pZoneSystemInstance?.GetValue(null, null);
				if (!(_fLocationPins?.GetValue(__instance) is IDictionary dictionary) || obj == null || _mGetLocationIcons == null)
				{
					return;
				}
				Dictionary<Vector3, string> dictionary2 = new Dictionary<Vector3, string>();
				_mGetLocationIcons.Invoke(obj, new object[1] { dictionary2 });
				bool flag = _state?.SmallPins ?? SmallPins.Value;
				List<Vector3> list = new List<Vector3>();
				foreach (DictionaryEntry item in dictionary)
				{
					if (item.Value == null || !(item.Key is Vector3 val) || !dictionary2.TryGetValue(val, out var value))
					{
						continue;
					}
					object obj2 = ((value == "TotemPins_Totem") ? _discoverableSprite : ((value == "TotemPins_TotemUnlocked") ? _unlockedSprite : null));
					if (obj2 == null)
					{
						continue;
					}
					list.Add(val);
					object value2 = item.Value;
					if (_fPinIcon == null)
					{
						_fPinIcon = AccessTools.Field(value2.GetType(), "m_icon");
						_fPinDoubleSize = AccessTools.Field(value2.GetType(), "m_doubleSize");
						if (_fPinIcon == null || _fPinDoubleSize == null)
						{
							return;
						}
					}
					if (_fPinIcon.GetValue(value2) != obj2 || (bool)_fPinDoubleSize.GetValue(value2) != !flag)
					{
						_fPinIcon.SetValue(value2, obj2);
						_fPinDoubleSize.SetValue(value2, !flag);
						_mDestroyPinMarker?.Invoke(__instance, new object[1] { value2 });
					}
				}
				list.Sort((Vector3 a, Vector3 b) => (a.x == b.x) ? a.z.CompareTo(b.z) : a.x.CompareTo(b.x));
				StringBuilder stringBuilder = new StringBuilder();
				foreach (Vector3 item2 in list)
				{
					stringBuilder.Append((int)item2.x).Append(',').Append((int)item2.z)
						.Append(';');
				}
				_pinPositions = list;
				if (stringBuilder.ToString() != _pinSignature)
				{
					_pinSignature = stringBuilder.ToString();
					if (_state?.HideDuplicatePins ?? HideDuplicatePins.Value)
					{
						RefreshTravelTotemsPins();
					}
				}
			}
			catch (Exception ex)
			{
				Log.LogWarning((object)("Could not update totem pins: " + ex.Message));
			}
		}

		private static void RefreshTravelTotemsPins()
		{
			try
			{
				_mRefreshMapPins?.Invoke(null, null);
			}
			catch (Exception ex)
			{
				Log.LogWarning((object)("Could not refresh Travel Totems pins: " + ex.Message));
			}
		}

		private static bool ApplyOverride(Override value, ref bool result)
		{
			if (!Enabled.Value || value == Override.PlayerChoice)
			{
				return true;
			}
			result = value == Override.On;
			return false;
		}

		private static bool ShowMapPinsPrefix(ref bool __result)
		{
			return ApplyOverride(_state?.ShowMapPins ?? Override.PlayerChoice, ref __result);
		}

		private static bool ShowDiscoverablePrefix(ref bool __result)
		{
			return ApplyOverride(_state?.ShowDiscoverableMapPins ?? Override.PlayerChoice, ref __result);
		}

		private static bool AdminAccessPrefix(ref bool __result)
		{
			Override obj = _state?.AdminBypass ?? Override.PlayerChoice;
			if (!Enabled.Value || obj == Override.PlayerChoice)
			{
				return true;
			}
			__result = obj == Override.On && IsAdmin();
			return false;
		}

		private static bool IsAdmin()
		{
			try
			{
				Type type = AccessTools.TypeByName("Jotunn.Managers.SynchronizationManager");
				object obj = ((type == null) ? null : AccessTools.Property(type, "Instance")?.GetValue(null, null));
				bool flag = default(bool);
				int num;
				if (obj != null)
				{
					object obj2 = AccessTools.Property(type, "PlayerIsAdmin")?.GetValue(obj, null);
					if (obj2 is bool)
					{
						flag = (bool)obj2;
						num = 1;
					}
					else
					{
						num = 0;
					}
				}
				else
				{
					num = 0;
				}
				return (byte)((uint)num & (flag ? 1u : 0u)) != 0;
			}
			catch (Exception)
			{
				return false;
			}
		}

		private static bool AddMapPinPrefix(object __0, bool __1)
		{
			//IL_0049: Unknown result type (might be due to invalid IL or missing references)
			if (__1 || __0 == null || !Enabled.Value || !(_state?.HideDuplicatePins ?? HideDuplicatePins.Value) || _pinPositions.Count == 0)
			{
				return true;
			}
			try
			{
				return !IsNear((Vector3)_mZdoGetPosition.Invoke(__0, null), _pinPositions);
			}
			catch (Exception)
			{
				return true;
			}
		}
	}
}