Decompiled source of AutoMapPins v2.3.18

plugins/AutoMapPins.dll

Decompiled 5 days ago
using System;
using System.CodeDom.Compiler;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using AutoMapPins.Common;
using AutoMapPins.Data;
using AutoMapPins.Discovery;
using AutoMapPins.Icons;
using AutoMapPins.Model;
using AutoMapPins.Patches;
using AutoMapPins.Properties;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using JetBrains.Annotations;
using Microsoft.CodeAnalysis;
using ServerSync;
using Splatform;
using TMPro;
using UnityEngine;
using UnityEngine.UI;
using YamlDotNet.Core;
using YamlDotNet.Core.Events;
using YamlDotNet.Core.Tokens;
using YamlDotNet.Helpers;
using YamlDotNet.Serialization;
using YamlDotNet.Serialization.BufferedDeserialization;
using YamlDotNet.Serialization.BufferedDeserialization.TypeDiscriminators;
using YamlDotNet.Serialization.Callbacks;
using YamlDotNet.Serialization.Converters;
using YamlDotNet.Serialization.EventEmitters;
using YamlDotNet.Serialization.NamingConventions;
using YamlDotNet.Serialization.NodeDeserializers;
using YamlDotNet.Serialization.NodeTypeResolvers;
using YamlDotNet.Serialization.ObjectFactories;
using YamlDotNet.Serialization.ObjectGraphTraversalStrategies;
using YamlDotNet.Serialization.ObjectGraphVisitors;
using YamlDotNet.Serialization.Schemas;
using YamlDotNet.Serialization.TypeInspectors;
using YamlDotNet.Serialization.TypeResolvers;
using YamlDotNet.Serialization.Utilities;
using YamlDotNet.Serialization.ValueDeserializers;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: AssemblyTitle("AutoMapPins")]
[assembly: AssemblyDescription("Github Template for a Valheim mod project")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("AutoMapPins")]
[assembly: AssemblyCopyright("Copyright © 2023")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
[assembly: Guid("F5D7B6C6-C13D-4B48-B472-E7854E5141E0")]
[assembly: AssemblyFileVersion("2.3.18")]
[assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = "")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("2.3.18.0")]
[module: UnverifiableCode]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[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 P_0)
		{
			NullableFlags = new byte[1] { P_0 };
		}

		public NullableAttribute(byte[] P_0)
		{
			NullableFlags = P_0;
		}
	}
	[CompilerGenerated]
	[Embedded]
	[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 P_0)
		{
			Flag = P_0;
		}
	}
}
namespace AutoMapPins
{
	[BepInPlugin("FixItFelix.AutoMapPins", "AutoMapPins", "2.3.18")]
	public class AutoMapPinsPlugin : BaseUnityPlugin
	{
		internal const string ModName = "AutoMapPins";

		internal const string ModVersion = "2.3.18";

		private const string ModAuthor = "FixItFelix";

		private const string ModGuid = "FixItFelix.AutoMapPins";

		private const string ConfigFileName = "FixItFelix.AutoMapPins.cfg";

		private static AutoMapPinsPlugin _instance = null;

		private readonly Harmony _harmony = new Harmony("FixItFelix.AutoMapPins");

		private FileSystemWatcher? _configFileWatcher;

		private GeneratedPinService? _generatedPins;

		private GeneratedPinNetworkService? _generatedPinNetwork;

		public static readonly ManualLogSource Log = Logger.CreateLogSource("FixItFelix.AutoMapPins");

		internal static YamlFileStorage FileIO = null;

		internal static IconConfigStorage IconIO = null;

		private static readonly ConfigSync ConfigSync = new ConfigSync("FixItFelix.AutoMapPins")
		{
			DisplayName = "AutoMapPins",
			CurrentVersion = "2.3.18"
		};

		private static ConfigEntry<bool> _configLocked = null;

		private static CustomSyncedValue<Dictionary<string, string>> _categoryPinsConfigFilesContent = null;

		private static Dictionary<string, string>? _lastLocalYamlContent;

		private static readonly IconReloadThrottle IconReload = new IconReloadThrottle();

		internal static ConfigEntry<float> GroupingRadius = null;

		internal static ConfigEntry<float> MaxDetectionHeight = null;

		internal static ConfigEntry<bool> PrefabDiscoveryEnabled = null;

		internal static ConfigEntry<bool> SilentDiscoveryEnabled = null;

		internal static ConfigEntry<MapDiscoveryRadiusSource> DiscoveryRadiusSource = null;

		internal static ConfigEntry<float> FallbackDiscoveryRadius = null;

		internal static ConfigEntry<float> DiscoveryRadiusMultiplier = null;

		internal static ConfigEntry<bool> TemporaryPinsWithinDiscoveryRadiusOnly = null;

		internal static ConfigEntry<bool> DiscoverGeneratedZonePins = null;

		internal static ConfigEntry<string> SkillRadiusPluginGuid = null;

		internal static ConfigEntry<string> SkillRadiusTypeName = null;

		internal static ConfigEntry<string> SkillRadiusMemberName = null;

		internal static bool OwnsDistantPin(MapPin pin)
		{
			AutoMapPinsPlugin instance = _instance;
			if (instance == null)
			{
				return false;
			}
			return instance._generatedPins?.Owns(pin) == true;
		}

		private void Awake()
		{
			_instance = this;
			_configLocked = CreateConfig("1 - General", "Lock Configuration", value: true, "If 'true' and playing on a server, config can only be changed on server-side configuration, clients cannot override");
			ConfigSync.AddLockingConfigEntry<bool>(_configLocked);
			PrefabDiscoveryEnabled = CreateConfig("1 - General", "Enable the prefab discovery", value: false, "This option will either enable (true) or disable (false, default) the discovery of new prefabs that have not yet been configured. For smoother gameplay you can simply disable it, the mod will then not print to console that there are new objects that have not been configured, yet. If you want to create new configurations for not configured prefabs, you will need to enable this flag.");
			SilentDiscoveryEnabled = CreateConfig("1 - General", "Prefab discovery silent mode", value: true, "This option will either enable (true, default) or disable (false) the log messages on discovery of new prefabs that have not yet been configured. For smoother gameplay you can simply enable it, the mod will then not print to console that there are new objects that have not been configured, yet. For finding out if there are prefabs missing that were not configured, you will need to disable this flag.");
			MaxDetectionHeight = CreateConfig("1 - General", "Maximum height to map objects", 4000f, "This option will set the height over sea level until where game objects will get the auto map pins logic applied. The usual default is '4000', since over 4000 meters over ground the dungeons are placed in the game scene. BEWARE: if you set this to a lower height, your map has chances to get pins added that point to a location inside a dungeon that is just above the height on ground, you should better not change this.");
			GroupingRadius = CreateConfig("2 - Grouping", "Fallback General Grouping Radius", 15f, "Grouping radius can be set per configured pin, but if it was set to 0 or no config for a pin was provided, this value will be used instead. Radius that will be applied when trying to group pins together that have grouping enabled. Default 15.0");
			DiscoveryRadiusSource = CreateConfig("3 - Map Discovery Radius", "Radius Source", MapDiscoveryRadiusSource.AutoDetectSkillMod, "ConfigOnly keeps the historical explored-map behavior unless Fallback Radius is above 0. AutoDetectSkillMod can read Advize CartographySkill, Searica ExplorersVision, Smoothbrain Exploration, Smoothbrain Sailing, blacks7ar Explorer, or a configured soft dependency. SpecificIntegration only uses the configured soft dependency.");
			FallbackDiscoveryRadius = CreateConfig("3 - Map Discovery Radius", "Fallback Radius", 0f, "Additional local-player XZ radius where pins may become visible before Minimap.IsExplored returns true. Default 0 preserves legacy behavior.");
			DiscoveryRadiusMultiplier = CreateConfig("3 - Map Discovery Radius", "Radius Multiplier", 1f, "Multiplier applied to the effective discovery radius from config or a skill integration.");
			TemporaryPinsWithinDiscoveryRadiusOnly = CreateConfig("3 - Map Discovery Radius", "Temporary Pins Within Discovery Radius Only", value: false, "If 'true', temporary (non-permanent) pins are only shown while their object is inside the current discovery radius: leave the radius and the pin disappears, come back and it reappears. Explored map area no longer keeps temporary pins visible. Permanent pins are not affected.");
			TemporaryPinsWithinDiscoveryRadiusOnly.SettingChanged += OnTemporaryVisibilitySettingChanged;
			DiscoverGeneratedZonePins = CreateConfig("3 - Map Discovery Radius", "Scan Previously Generated Zones (Local World Only)", value: false, "Experimental, OFF by default: scan existing server ZDOs up to 1100m for configured objects. Never generates new world zones. May affect performance and cannot find non-networked objects. Dedicated-server transport is not yet verified in a real multiplayer session: install the same version on server and clients, enable on server, and test only in a backed-up world. The historical setting name is retained for compatibility with 2.3.6.");
			SkillRadiusPluginGuid = CreateConfig("3 - Map Discovery Radius", "Skill Radius Plugin GUID", "", "Optional BepInEx plugin GUID for a soft skill-mod integration. Leave empty to use fallback radius only.");
			SkillRadiusTypeName = CreateConfig("3 - Map Discovery Radius", "Skill Radius Type Name", "", "Optional fully-qualified type name that exposes the skill-mod discovery radius.");
			SkillRadiusMemberName = CreateConfig("3 - Map Discovery Radius", "Skill Radius Member Name", "", "Optional field, property, or method name returning a numeric radius. Methods may take no args or Player.");
			_categoryPinsConfigFilesContent = new CustomSyncedValue<Dictionary<string, string>>(ConfigSync, "CategoryPinsConfigFilesContent", new Dictionary<string, string>());
			_categoryPinsConfigFilesContent.ValueChanged += ReloadRegistry;
			IconIO = new IconConfigStorage("FixItFelix.AutoMapPins");
			ReadIconFileContent(null, null);
			FileIO = new YamlFileStorage("FixItFelix.AutoMapPins");
			ReadYamlFileContent(null, null);
			SetupFileWatcher("FixItFelix.AutoMapPins.cfg");
			Assembly executingAssembly = Assembly.GetExecutingAssembly();
			_harmony.PatchAll(executingAssembly);
			_generatedPins = new GeneratedPinService((MonoBehaviour)(object)this);
			_generatedPinNetwork = new GeneratedPinNetworkService((MonoBehaviour)(object)this);
			LogUsageMode();
			DiscoveryRadiusService.LogActiveProvider();
		}

		internal static void ReadYamlFileContent(object? _, FileSystemEventArgs? change)
		{
			if (_categoryPinsConfigFilesContent != null && FileIO != null)
			{
				Dictionary<string, string> dictionary = FileIO.ReadConfigFiles();
				if (change == null || !SameFileContents(_lastLocalYamlContent, dictionary))
				{
					Log.LogInfo((object)"loading pin configs from yaml files");
					_categoryPinsConfigFilesContent.Value = dictionary;
					_lastLocalYamlContent = new Dictionary<string, string>(dictionary);
				}
			}
		}

		private static bool SameFileContents(Dictionary<string, string>? previous, Dictionary<string, string> current)
		{
			if (previous == null || previous.Count != current.Count)
			{
				return false;
			}
			foreach (KeyValuePair<string, string> item in current)
			{
				if (!previous.TryGetValue(item.Key, out string value) || !string.Equals(value, item.Value, StringComparison.Ordinal))
				{
					return false;
				}
			}
			return true;
		}

		internal static void ReadIconFileContent(object? _, FileSystemEventArgs? change)
		{
			if (IconIO == null)
			{
				return;
			}
			if (change != null)
			{
				IconReload.ScheduleChange(Time.realtimeSinceStartup);
				return;
			}
			Log.LogInfo((object)"loading icon configs from yaml files");
			Config.IconConfigFile iconConfig = IconIO.ReadIconConfigFiles();
			if (IconIO.HasPendingMissingFiles)
			{
				IconReload.RetryAfterFailure(Time.realtimeSinceStartup);
				return;
			}
			if (Assets.LoadCustomIconConfig(iconConfig))
			{
				IconReload.Clear();
			}
			else
			{
				IconReload.RetryAfterFailure(Time.realtimeSinceStartup);
			}
			MinimapPatch.UpdatePins();
			MinimapPatch.RefreshIconVisuals();
		}

		private static void ReloadRegistry()
		{
			Registry.InitializeRegistry(FileIO.DeserializeAndMergeFileData(_categoryPinsConfigFilesContent.Value));
		}

		private void SetupFileWatcher(string fileName)
		{
			_configFileWatcher = new FileSystemWatcher(Paths.ConfigPath, fileName)
			{
				IncludeSubdirectories = true,
				SynchronizingObject = ThreadingHelper.SynchronizingObject,
				EnableRaisingEvents = true
			};
			_configFileWatcher.Changed += ReloadConfig;
			_configFileWatcher.Created += ReloadConfig;
			_configFileWatcher.Renamed += ReloadConfig;
		}

		private void ReloadConfig(object? _, FileSystemEventArgs? __)
		{
			Log.LogWarning((object)"config file 'FixItFelix.AutoMapPins.cfg' change registered");
			((BaseUnityPlugin)this).Config.Reload();
			PinComponent.RefreshVisiblePinsAfterConfigChange();
			LogUsageMode();
			DiscoveryRadiusService.LogActiveProvider();
		}

		private static void OnTemporaryVisibilitySettingChanged(object sender, EventArgs args)
		{
			PinComponent.RefreshVisiblePinsAfterConfigChange();
		}

		private static void LogUsageMode()
		{
			if (PrefabDiscoveryEnabled.Value)
			{
				Log.LogWarning((object)"loaded mod with game object discovery enabled, deactivate to increase performance");
			}
			if (!SilentDiscoveryEnabled.Value)
			{
				Log.LogWarning((object)"silent discovery mode was deactivated, this will print log each time an object without config will be approached");
			}
		}

		private void Update()
		{
			if (IconReload.TryConsume(Time.realtimeSinceStartup))
			{
				ReadIconFileContent(null, null);
			}
			_generatedPins?.Tick();
			_generatedPinNetwork?.Tick(_generatedPins);
		}

		public void OnDestroy()
		{
			_generatedPinNetwork?.Reset();
			_generatedPins?.Reset();
			if (TemporaryPinsWithinDiscoveryRadiusOnly != null)
			{
				TemporaryPinsWithinDiscoveryRadiusOnly.SettingChanged -= OnTemporaryVisibilitySettingChanged;
			}
			if (_categoryPinsConfigFilesContent != null)
			{
				_categoryPinsConfigFilesContent.ValueChanged -= ReloadRegistry;
			}
			if (_configFileWatcher != null)
			{
				_configFileWatcher.Changed -= ReloadConfig;
				_configFileWatcher.Created -= ReloadConfig;
				_configFileWatcher.Renamed -= ReloadConfig;
				_configFileWatcher.Dispose();
				_configFileWatcher = null;
			}
			PickerIconOverrides.Reset();
			IconIO?.Dispose();
			FileIO?.Dispose();
			_lastLocalYamlContent = null;
			IconReload.Clear();
			_harmony.UnpatchSelf();
		}

		private static ConfigEntry<T> CreateConfig<T>(string group, string parameterName, T value, ConfigDescription description, bool synchronizedSetting = true)
		{
			ConfigEntry<T> val = ((BaseUnityPlugin)_instance).Config.Bind<T>(group, parameterName, value, description);
			ConfigSync.AddConfigEntry<T>(val).SynchronizedConfig = synchronizedSetting;
			return val;
		}

		private static ConfigEntry<T> CreateConfig<T>(string group, string parameterName, T value, string description, bool synchronizedSetting = true)
		{
			//IL_000a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0016: Expected O, but got Unknown
			return CreateConfig(group, parameterName, value, new ConfigDescription(description, (AcceptableValueBase)null, Array.Empty<object>()), synchronizedSetting);
		}
	}
}
namespace AutoMapPins.Patches
{
	internal static class CommonPatchLogic
	{
		internal static void Patch(GameObject gameObject)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			PinComponent pinComponent = default(PinComponent);
			if (gameObject.transform.position.y < AutoMapPinsPlugin.MaxDetectionHeight.Value && !gameObject.TryGetComponent<PinComponent>(ref pinComponent))
			{
				gameObject.AddComponent<PinComponent>();
			}
		}
	}
	[HarmonyPatch(typeof(Destructible), "Start")]
	internal class DestructiblePatch
	{
		[UsedImplicitly]
		private static void Postfix(ref Destructible __instance)
		{
			Pickable val = default(Pickable);
			if (!((Component)__instance).TryGetComponent<Pickable>(ref val))
			{
				CommonPatchLogic.Patch(((Component)__instance).gameObject);
			}
		}
	}
	[HarmonyPatch(typeof(TreeBase), "Awake")]
	internal class TreeBasePatch
	{
		[UsedImplicitly]
		private static void Postfix(ref TreeBase __instance)
		{
			CommonPatchLogic.Patch(((Component)__instance).gameObject);
		}
	}
	[HarmonyPatch(typeof(Beehive), "Awake")]
	internal class BeehivePatch
	{
		[UsedImplicitly]
		private static void Postfix(ref Beehive __instance)
		{
			Piece val = default(Piece);
			if (!((Component)__instance).TryGetComponent<Piece>(ref val))
			{
				CommonPatchLogic.Patch(((Component)__instance).gameObject);
			}
		}
	}
	[HarmonyPatch(typeof(SpawnOnDamaged), "Start")]
	internal class SpawnOnDamagedPatch
	{
		[UsedImplicitly]
		private static void Postfix(ref SpawnOnDamaged __instance)
		{
			CommonPatchLogic.Patch(((Component)__instance).gameObject);
		}
	}
	[HarmonyPatch(typeof(ResourceRoot), "Awake")]
	internal class ResourceRootPatch
	{
		[UsedImplicitly]
		private static void Postfix(ref ResourceRoot __instance)
		{
			CommonPatchLogic.Patch(((Component)__instance).gameObject);
		}
	}
	[HarmonyPatch(typeof(MineRock), "Start")]
	internal class MineRockPatch
	{
		[UsedImplicitly]
		private static void Postfix(ref MineRock __instance)
		{
			CommonPatchLogic.Patch(((Component)__instance).gameObject);
		}
	}
	[HarmonyPatch(typeof(MineRock5), "Awake")]
	internal class MineRock5Patch
	{
		[UsedImplicitly]
		private static void Postfix(ref MineRock5 __instance)
		{
			CommonPatchLogic.Patch(((Component)__instance).gameObject);
		}
	}
	[HarmonyPatch(typeof(Location), "Awake")]
	internal class LocationPatch
	{
		[UsedImplicitly]
		private static void Postfix(ref Location __instance)
		{
			CommonPatchLogic.Patch(((Component)__instance).gameObject);
		}
	}
	[HarmonyPatch(typeof(Leviathan), "Awake")]
	internal class LeviathanPatch
	{
		[UsedImplicitly]
		private static void Postfix(ref Leviathan __instance)
		{
			CommonPatchLogic.Patch(((Component)__instance).gameObject);
		}
	}
	[HarmonyPatch(typeof(TeleportWorld), "Awake")]
	internal class TeleportWorldPatch
	{
		[UsedImplicitly]
		private static void Postfix(ref TeleportWorld __instance)
		{
			CommonPatchLogic.Patch(((Component)__instance).gameObject);
		}
	}
	[HarmonyPatch(typeof(PickableItem), "Awake")]
	internal class PickableItemPatch
	{
		[UsedImplicitly]
		private static void Postfix(ref PickableItem __instance)
		{
			CommonPatchLogic.Patch(((Component)__instance).gameObject);
		}
	}
	[HarmonyPatch(typeof(Container), "Awake")]
	internal class ContainerPatch
	{
		[UsedImplicitly]
		private static void Postfix(ref Container __instance)
		{
			CommonPatchLogic.Patch(((Component)__instance).gameObject);
		}
	}
	[HarmonyPatch(typeof(Console), "Awake")]
	internal class ConsolePatches : HasLogger
	{
		private const string WriteMissingConfigsOption = "write_missing_configs_file";

		private const string PrintEffectiveConfig = "print_effective_config";

		private const string DebugLogPins = "debug_log_pins";

		private const string ClearPins = "clear_pins";

		private const string ScanNearby = "scan_nearby";

		private const string Scan = "scan";

		private const string DebugRadius = "debug_radius";

		private const string ClearAmpMessage = "removed {0} AutoMapPins pins from map; your own, death, boss and location pins were kept";

		private const string PrintEffectiveConfigRequiredNameMessage = "for printing the effective config of an object, please provide the object name as argument to the command";

		[UsedImplicitly]
		private static void Postfix(Console __instance)
		{
			//IL_001e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0030: Unknown result type (might be due to invalid IL or missing references)
			//IL_003d: Expected O, but got Unknown
			//IL_003d: Expected O, but got Unknown
			//IL_0038: Unknown result type (might be due to invalid IL or missing references)
			new ConsoleCommand("amp", "auto map pins commands", (ConsoleEvent)delegate(ConsoleEventArgs consoleEventArgs)
			{
				if (consoleEventArgs.Length > 1)
				{
					AutoMapPinsPlugin.Log.LogInfo((object)("called amp with args: '" + string.Join(", ", consoleEventArgs.Args.ToList()) + "'"));
					switch (consoleEventArgs.Args[1])
					{
					case "debug_log_pins":
						if (Object.op_Implicit((Object)(object)Minimap.instance))
						{
							HasLogger.Log.LogInfo((object)("vanilla map registered pins:\n" + MinimapPatch.PrintMapPins()));
						}
						break;
					case "clear_pins":
						if (Object.op_Implicit((Object)(object)Minimap.instance))
						{
							int num = MinimapPatch.ClearAmpPins();
							string text2 = $"removed {num} AutoMapPins pins from map; your own, death, boss and location pins were kept";
							__instance.Print(text2);
							HasLogger.Log.LogWarning((object)text2);
						}
						break;
					case "print_effective_config":
						if (consoleEventArgs.Args.Length < 3)
						{
							__instance.Print("for printing the effective config of an object, please provide the object name as argument to the command");
						}
						else
						{
							string text = consoleEventArgs.Args[2];
							if (!string.IsNullOrEmpty(text) && Registry.ConfiguredPins.TryGetValue(text, out Config.Pin value))
							{
								__instance.Print(text + ":");
								__instance.Print("  " + value.ToString().Replace("\n", "\n  "));
							}
							else
							{
								__instance.Print("no config found for object name '" + text + "'");
							}
						}
						break;
					case "write_missing_configs_file":
						WriteMissingConfigs();
						break;
					case "scan_nearby":
					{
						if (!LoadedObjectScanOptions.TryParseLegacy(consoleEventArgs.Args, out var radius2, out var all2))
						{
							__instance.Print($"usage: amp scan_nearby [radius 1..{1000f:F0}] [all]");
						}
						else
						{
							ScanNearbyObjects(__instance, radius2, all2);
						}
						break;
					}
					case "scan":
					{
						if (!LoadedObjectScanOptions.TryParse(consoleEventArgs.Args, out var radius, out var all))
						{
							__instance.Print("usage: amp scan [radius 1..100] [all]");
						}
						else
						{
							ScanLoadedObjectIds(__instance, radius, all);
						}
						break;
					}
					case "debug_radius":
					{
						string debugBreakdown = DiscoveryRadiusService.GetDebugBreakdown();
						HasLogger.Log.LogInfo((object)("discovery radius debug:\n" + debugBreakdown));
						__instance.Print(debugBreakdown);
						break;
					}
					default:
						PrintUsage(__instance);
						break;
					}
				}
				else
				{
					PrintUsage(__instance);
				}
			}, false, false, false, false, false, false, new ConsoleOptionsFetcher(OptionFetcher), false, false, false);
		}

		private static void PrintUsage(Console __instance)
		{
			__instance.Print("Auto Map Pins (amp) console commands - use 'amp' followed by one of the following options");
			__instance.Print(" debug_log_pins --> print all active pins to log");
			__instance.Print(" clear_pins --> remove all pins created by AutoMapPins (including its saved permanent pins); your own, death, boss and location pins stay. Pins of nearby objects reappear when rediscovered");
			__instance.Print(" print_effective_config <object name> --> replace '<object name>' with the object to print the effective config for, this can be used to debug config issues and config inheritance");
			__instance.Print(" write_missing_configs_file --> will write all objects without config to a yaml file");
			__instance.Print(" scan_nearby [radius] [all] --> list all pinnable objects near the player (default 30m) with their real object names, component types and config status; use this to find the correct object names for yaml configs; add 'all' to also list every GameObject nearby with all of its components, including objects without a known pinnable component");
			__instance.Print(" scan [radius] [all] --> summarize loaded object IDs, counts and nearest distance within 1..100m (default 30m). 'all' includes child objects; only loaded objects are visible");
			__instance.Print(" debug_radius --> print the current map discovery radius breakdown (provider, base radius, skill factors, ship attachment) to console and log");
		}

		private static void ScanLoadedObjectIds(Console console, float radius, bool all)
		{
			//IL_0022: Unknown result type (might be due to invalid IL or missing references)
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			//IL_002f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0064: Unknown result type (might be due to invalid IL or missing references)
			if (!Object.op_Implicit((Object)(object)Player.m_localPlayer))
			{
				console.Print("no local player found, join a world first");
				return;
			}
			Vector3 position = ((Component)Player.m_localPlayer).transform.position;
			LoadedObjectScanSummary loadedObjectScanSummary = LoadedObjectSceneScanner.Scan(Object.FindObjectsByType<GameObject>((FindObjectsInactive)1, (FindObjectsSortMode)0), position, ((Component)Player.m_localPlayer).transform, radius, all, AutoMapPins.Common.Constants.ParseInternalName, Registry.ConfiguredPins.ContainsKey);
			string text = $"player position: {position}\n" + loadedObjectScanSummary.Render(radius, all);
			HasLogger.Log.LogInfo((object)text);
			console.Print(text);
		}

		private static void ScanNearbyObjects(Console console, float radius, bool listAll)
		{
			//IL_0022: Unknown result type (might be due to invalid IL or missing references)
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			//IL_0186: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d8: Unknown result type (might be due to invalid IL or missing references)
			//IL_020d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0215: Unknown result type (might be due to invalid IL or missing references)
			if (!Object.op_Implicit((Object)(object)Player.m_localPlayer))
			{
				console.Print("no local player found, join a world first");
				return;
			}
			Vector3 position = ((Component)Player.m_localPlayer).transform.position;
			List<string> list = new List<string>();
			int num = 0;
			MonoBehaviour[] array = Object.FindObjectsByType<MonoBehaviour>((FindObjectsInactive)1, (FindObjectsSortMode)0);
			foreach (MonoBehaviour val in array)
			{
				num++;
				if ((val is Destructible || val is TreeBase || val is Beehive || val is MineRock || val is MineRock5 || val is Location || val is Leviathan || val is TeleportWorld || val is PickableItem || val is Container || val is Pickable || val is SpawnOnDamaged || val is ResourceRoot) ? true : false)
				{
					float num2 = Vector3.Distance(position, ((Component)val).transform.position);
					if (!(num2 > radius))
					{
						string text = AutoMapPins.Common.Constants.ParseInternalName(((Object)val).name);
						string text2 = (Registry.ConfiguredPins.ContainsKey(text) ? "configured" : "NOT configured");
						list.Add($"{num2,6:F1}m  '{((Object)val).name}' (internal '{text}') " + "[" + ((object)val).GetType().Name + "] " + text2);
					}
				}
			}
			list.Sort(StringComparer.Ordinal);
			string text3 = $"player position: {position}\n" + $"scanned {num} MonoBehaviour components (including inactive)\n" + $"pinnable objects within {radius}m of the player:\n" + string.Join("\n", list);
			if (listAll)
			{
				Transform transform = ((Component)Player.m_localPlayer).transform;
				List<string> list2 = new List<string>();
				List<string> list3 = new List<string>();
				GameObject[] array2 = Object.FindObjectsByType<GameObject>((FindObjectsInactive)1, (FindObjectsSortMode)0);
				foreach (GameObject val2 in array2)
				{
					if (val2.transform.IsChildOf(transform))
					{
						continue;
					}
					float num3 = Vector3.Distance(position, val2.transform.position);
					if (num3 > radius)
					{
						continue;
					}
					bool flag = Object.op_Implicit((Object)(object)val2.GetComponent<ZNetView>());
					if (flag || !((Object)(object)val2.transform.parent != (Object)null))
					{
						string text4 = string.Join(", ", from c in val2.GetComponents<Component>()
							select (!Object.op_Implicit((Object)(object)c)) ? "null" : ((object)c).GetType().Name);
						string item = $"{num3,6:F1}m  '{((Object)val2).name}' active={val2.activeInHierarchy} [{text4}]";
						(flag ? list2 : list3).Add(item);
					}
				}
				list2.Sort(StringComparer.Ordinal);
				list3.Sort(StringComparer.Ordinal);
				text3 = text3 + $"\nnetworked objects (ZNetView) within {radius}m ({list2.Count}):\n" + string.Join("\n", list2) + $"\nother root objects within {radius}m (showing {Math.Min(30, list3.Count)} of {list3.Count}):\n" + string.Join("\n", list3.Take(30));
			}
			HasLogger.Log.LogInfo((object)text3);
			console.Print(text3);
		}

		private static void WriteMissingConfigs()
		{
			Dictionary<string, Config.Category> dictionary = (from config in Registry.MissingConfigs
				select new KeyValuePair<string, string>("category", config) into kv
				group kv by kv.Key).ToDictionary((IGrouping<string, KeyValuePair<string, string>> group) => group.Key, (IGrouping<string, KeyValuePair<string, string>> group) => new Config.Category
			{
				IsActive = false,
				IndividualConfiguredObjects = new Dictionary<string, Config.Pin> { 
				{
					"example",
					new Config.Pin
					{
						Name = "example name",
						IconName = "mine",
						IconColorRGBA = Config.PinColor.White
					}
				} },
				CategoryConfiguredObjects = (from kv in @group
					select kv.Value into x
					orderby x
					select x).ToList()
			});
			if (dictionary.Count > 0)
			{
				AutoMapPinsPlugin.FileIO.WriteFile(AutoMapPinsPlugin.FileIO.GetSingleFile("write_missing_configs_file"), dictionary);
			}
			else
			{
				HasLogger.Log.LogWarning((object)"could not print any configs, since no config was recorded during game play");
			}
		}

		private static List<string> OptionFetcher()
		{
			return new List<string> { "print_effective_config", "write_missing_configs_file", "debug_log_pins", "clear_pins", "scan_nearby", "scan", "debug_radius" };
		}
	}
	[HarmonyPatch(typeof(Minimap))]
	internal abstract class MinimapPatch : HasLogger
	{
		private sealed class IconDisplayState
		{
			internal Sprite? OriginalIcon;

			internal Sprite? AppliedIcon;

			internal object? AppliedElement;

			internal RectTransform? ScaledElement;

			internal Vector3 OriginalScale;

			internal Vector3 AppliedScale;

			internal bool HasVanillaOverride;

			internal bool SuppressedVanillaOverride;
		}

		private static readonly Dictionary<PinData, IconDisplayState> IconDisplayStates = new Dictionary<PinData, IconDisplayState>();

		private static readonly Dictionary<PinData, string> LocationPinNames = new Dictionary<PinData, string>();

		private static Minimap? _locationPinOwner;

		private static float _nextLocationPinScan;

		private static float _nextIconDisplayCleanup;

		private static readonly FieldRef<Minimap, List<PinData>> PinsRef = AccessTools.FieldRefAccess<Minimap, List<PinData>>("m_pins");

		private static readonly FieldRef<Minimap, bool> PinUpdateRequiredRef = AccessTools.FieldRefAccess<Minimap, bool>("m_pinUpdateRequired");

		private static readonly FieldInfo? LocationPinsField = AccessTools.Field(typeof(Minimap), "m_locationPins");

		private static readonly MethodInfo? GetLocationIconsMethod = AccessTools.Method(typeof(ZoneSystem), "GetLocationIcons", new Type[1] { typeof(Dictionary<Vector3, string>) }, (Type[])null);

		private static bool _warnedUnavailableLocations;

		[UsedImplicitly]
		[HarmonyPatch("Start")]
		[HarmonyPostfix]
		internal static void StartPickerPostfix(Minimap __instance)
		{
			PickerIconOverrides.Refresh(__instance);
		}

		[UsedImplicitly]
		[HarmonyPatch("LoadMapData")]
		[HarmonyPostfix]
		internal static void LoadMapDataPostfix(ref Minimap __instance)
		{
			List<PinData> list = PinsRef.Invoke(__instance);
			List<PinData> list2 = new List<PinData>();
			List<MapPin> list3 = new List<MapPin>();
			HasLogger.Log.LogInfo((object)$"loading map data with '{list.Count}' pins");
			foreach (PinData item2 in list)
			{
				if (TryGetSavedAmpPinInternalName(item2, out string internalName))
				{
					if (TryGetSavedPinConfig(item2, internalName, out Config.Pin config))
					{
						list2.Add(item2);
						MapPin item = new MapPin(item2, internalName, config);
						list3.Add(item);
					}
					else if (SavedAmpPinHasLoadedNonPermanentOrInactiveConfig(internalName))
					{
						list2.Add(item2);
					}
				}
			}
			if (list2.Count > 0)
			{
				HasLogger.Log.LogInfo((object)$"removing {list2.Count} pins due to config updates and/or replacement by loading from player save file");
				foreach (PinData item3 in list2)
				{
					__instance.RemovePin(item3);
				}
			}
			if (list3.Count > 0)
			{
				HasLogger.Log.LogInfo((object)$"adding {list3.Count} AMP pins to replace vanilla stored pins");
				foreach (MapPin item4 in list3)
				{
					list.Add((PinData)(object)item4);
				}
			}
			HasLogger.Log.LogInfo((object)$"Loaded map with {list.Count} existing pins");
		}

		private static bool TryGetSavedAmpPinInternalName(PinData pin, out string internalName)
		{
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			//IL_000e: Invalid comparison between Unknown and I4
			internalName = "";
			if ((int)pin.m_type == 8 && pin.m_ownerID == 0L)
			{
				return MapPin.TryGetSavedInternalName(pin, out internalName);
			}
			return false;
		}

		private static bool TryGetSavedPinConfig(PinData pin, out string internalName, out Config.Pin config)
		{
			config = null;
			if (!TryGetSavedAmpPinInternalName(pin, out internalName))
			{
				return false;
			}
			return TryGetSavedPinConfig(pin, internalName, out config);
		}

		private static bool TryGetSavedPinConfig(PinData pin, string internalName, out Config.Pin config)
		{
			config = null;
			if (!Registry.ConfiguredPins.TryGetValue(internalName, out config))
			{
				if (Registry.HasConfiguredObject(internalName))
				{
					HasLogger.Log.LogWarning((object)("removing saved AMP pin '" + pin.m_name + "' with internal name '" + internalName + "' because its loaded config is not active and permanent"));
				}
				else
				{
					HasLogger.Log.LogWarning((object)("preserving saved AMP pin '" + pin.m_name + "' with internal name '" + internalName + "' because its config is not loaded yet"));
				}
				config = null;
				return false;
			}
			if (config.IsActive == true && config.IsPermanent == true)
			{
				return true;
			}
			HasLogger.Log.LogWarning((object)("removing saved AMP pin '" + pin.m_name + "' with internal name '" + internalName + "' because its loaded config is not active and permanent"));
			config = null;
			return false;
		}

		private static bool SavedAmpPinHasLoadedNonPermanentOrInactiveConfig(string internalName)
		{
			if (Registry.ConfiguredPins.TryGetValue(internalName, out Config.Pin value))
			{
				if (value.IsActive == true)
				{
					return value.IsPermanent != true;
				}
				return true;
			}
			return Registry.HasConfiguredObject(internalName);
		}

		[UsedImplicitly]
		[HarmonyPatch("UpdateExplore")]
		[HarmonyPostfix]
		internal static void UpdateExploreSkillPostfix()
		{
			ExplorationSkillGate.Tick();
		}

		[UsedImplicitly]
		[HarmonyPatch("Explore", new Type[]
		{
			typeof(Vector3),
			typeof(float)
		})]
		[HarmonyPostfix]
		internal static void ExplorePostfix(Vector3 __0, float __1)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			DiscoveryRadiusService.CaptureGameExploreRadius(__0, __1);
		}

		[UsedImplicitly]
		[HarmonyPatch("UpdatePins")]
		[HarmonyPostfix]
		internal static void UpdatePinsPostfix(ref Minimap __instance)
		{
			//IL_00b2: Unknown result type (might be due to invalid IL or missing references)
			RefreshLocationPinNames(__instance);
			List<PinData> list = PinsRef.Invoke(__instance);
			foreach (PinData item in list)
			{
				string value;
				Sprite icon;
				float scale;
				Sprite icon2;
				float scale2;
				if (item is MapPin mapPin)
				{
					if (Object.op_Implicit((Object)(object)((PinData)mapPin).m_iconElement))
					{
						if (((PinData)mapPin).m_iconElement.sprite != ((PinData)mapPin).m_icon)
						{
							((PinData)mapPin).m_iconElement.sprite = ((PinData)mapPin).m_icon;
						}
						mapPin.UpdatePinColor();
					}
					mapPin.RefreshPinLabelText();
					ApplyIconScale(item, Assets.GetIconScale(mapPin.Config.IconName));
				}
				else if (LocationPinNames.TryGetValue(item, out value) && Assets.TryGetLocationMapOverride(value, out icon, out scale))
				{
					ApplyVanillaIconOverride(item, icon, scale);
				}
				else if (Assets.TryGetVanillaMapOverride(item.m_type, out icon2, out scale2))
				{
					ApplyVanillaIconOverride(item, icon2, scale2);
				}
				else
				{
					RestoreIconDisplay(item);
				}
			}
			if (IconDisplayStates.Count <= 0 || !(Time.time >= _nextIconDisplayCleanup))
			{
				return;
			}
			_nextIconDisplayCleanup = Time.time + 15f;
			HashSet<PinData> currentPins = new HashSet<PinData>(list);
			foreach (PinData item2 in IconDisplayStates.Keys.Where((PinData pin) => !currentPins.Contains(pin)).ToList())
			{
				IconDisplayStates.Remove(item2);
			}
		}

		private static void RefreshLocationPinNames(Minimap minimap, bool force = false)
		{
			//IL_00d7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00dd: Invalid comparison between Unknown and I4
			//IL_00e2: Unknown result type (might be due to invalid IL or missing references)
			if (!force && _locationPinOwner == minimap && Time.time < _nextLocationPinScan)
			{
				return;
			}
			_locationPinOwner = minimap;
			_nextLocationPinScan = Time.time + 5f;
			LocationPinNames.Clear();
			if (!Assets.HasLocationMapOverrides || !Object.op_Implicit((Object)(object)ZoneSystem.instance))
			{
				return;
			}
			try
			{
				if (!(LocationPinsField?.GetValue(minimap) is Dictionary<Vector3, PinData> dictionary) || GetLocationIconsMethod == null)
				{
					if (!_warnedUnavailableLocations)
					{
						HasLogger.Log.LogWarning((object)"location icon overrides unavailable in this game build; ordinary map pins remain unchanged");
						_warnedUnavailableLocations = true;
					}
					return;
				}
				Dictionary<Vector3, string> dictionary2 = new Dictionary<Vector3, string>();
				GetLocationIconsMethod.Invoke(ZoneSystem.instance, new object[1] { dictionary2 });
				foreach (KeyValuePair<Vector3, PinData> item in dictionary)
				{
					if (item.Value != null && (int)item.Value.m_type == 8 && dictionary2.TryGetValue(item.Key, out var value))
					{
						LocationPinNames[item.Value] = value;
					}
				}
			}
			catch (Exception ex)
			{
				LocationPinNames.Clear();
				if (!_warnedUnavailableLocations)
				{
					HasLogger.Log.LogWarning((object)("location icon lookup failed: " + ex.GetBaseException().Message + "; ordinary map pins remain unchanged"));
					_warnedUnavailableLocations = true;
				}
			}
		}

		private static void ApplyVanillaIconOverride(PinData pin, Sprite overrideIcon, float scale)
		{
			if (IconDisplayStates.TryGetValue(pin, out IconDisplayState value))
			{
				if (value.SuppressedVanillaOverride)
				{
					return;
				}
				if (value.HasVanillaOverride && (pin.m_icon != value.AppliedIcon || ((Object)(object)pin.m_iconElement != (Object)null && pin.m_iconElement.sprite != value.AppliedIcon && (pin.m_iconElement == value.AppliedElement || pin.m_iconElement.sprite != value.OriginalIcon))))
				{
					RestoreIconDisplay(pin);
					IconDisplayStates[pin] = new IconDisplayState
					{
						SuppressedVanillaOverride = true
					};
					return;
				}
			}
			else
			{
				if ((Object)(object)pin.m_iconElement != (Object)null && pin.m_iconElement.sprite != pin.m_icon)
				{
					return;
				}
				value = (IconDisplayStates[pin] = new IconDisplayState
				{
					OriginalIcon = pin.m_icon
				});
			}
			value.HasVanillaOverride = true;
			value.AppliedIcon = overrideIcon;
			pin.m_icon = overrideIcon;
			if ((Object)(object)pin.m_iconElement != (Object)null)
			{
				if (pin.m_iconElement.sprite != overrideIcon)
				{
					pin.m_iconElement.sprite = overrideIcon;
				}
				value.AppliedElement = pin.m_iconElement;
			}
			ApplyIconScale(pin, scale);
		}

		internal static void RefreshIconVisuals()
		{
			if (Object.op_Implicit((Object)(object)Minimap.instance))
			{
				Minimap __instance = Minimap.instance;
				PickerIconOverrides.Refresh(__instance);
				RefreshLocationPinNames(__instance, force: true);
				UpdatePinsPostfix(ref __instance);
			}
		}

		private static bool SameScale(Vector3 a, Vector3 b)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0014: Unknown result type (might be due to invalid IL or missing references)
			//IL_001c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0022: Unknown result type (might be due to invalid IL or missing references)
			if (a.x == b.x && a.y == b.y)
			{
				return a.z == b.z;
			}
			return false;
		}

		private static void RestoreIconScale(IconDisplayState state)
		{
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			//IL_001b: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Unknown result type (might be due to invalid IL or missing references)
			if (!((Object)(object)state.ScaledElement == (Object)null))
			{
				if (SameScale(((Transform)state.ScaledElement).localScale, state.AppliedScale))
				{
					((Transform)state.ScaledElement).localScale = state.OriginalScale;
				}
				state.ScaledElement = null;
			}
		}

		private static void ApplyIconScale(PinData pin, float scale)
		{
			//IL_00dc: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ca: 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_0101: Unknown result type (might be due to invalid IL or missing references)
			//IL_0107: Unknown result type (might be due to invalid IL or missing references)
			//IL_010c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0118: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fa: Unknown result type (might be due to invalid IL or missing references)
			if (!IconDisplayStates.TryGetValue(pin, out IconDisplayState value))
			{
				if (scale == 1f || (Object)(object)pin.m_uiElement == (Object)null)
				{
					return;
				}
				value = (IconDisplayStates[pin] = new IconDisplayState());
			}
			if ((Object)(object)value.ScaledElement != (Object)null && (Object)(object)value.ScaledElement != (Object)(object)pin.m_uiElement)
			{
				RestoreIconScale(value);
			}
			if (scale == 1f || (Object)(object)pin.m_uiElement == (Object)null)
			{
				if ((Object)(object)value.ScaledElement != (Object)null)
				{
					OffsetLabelForScale(pin, 1f);
				}
				RestoreIconScale(value);
				if (!value.HasVanillaOverride)
				{
					IconDisplayStates.Remove(pin);
				}
				return;
			}
			if ((Object)(object)value.ScaledElement == (Object)null)
			{
				value.ScaledElement = pin.m_uiElement;
				value.OriginalScale = ((Transform)pin.m_uiElement).localScale;
			}
			else if (!SameScale(((Transform)value.ScaledElement).localScale, value.AppliedScale))
			{
				value.OriginalScale = ((Transform)value.ScaledElement).localScale;
			}
			value.AppliedScale = value.OriginalScale * scale;
			((Transform)pin.m_uiElement).localScale = value.AppliedScale;
			OffsetLabelForScale(pin, scale);
		}

		private static void OffsetLabelForScale(PinData pin, float scale)
		{
			//IL_0031: Unknown result type (might be due to invalid IL or missing references)
			//IL_0036: Unknown result type (might be due to invalid IL or missing references)
			//IL_0064: 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_006b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0071: Unknown result type (might be due to invalid IL or missing references)
			//IL_0079: Unknown result type (might be due to invalid IL or missing references)
			PinNameData namePinData = pin.m_NamePinData;
			RectTransform val = ((namePinData != null) ? namePinData.PinNameRectTransform : null);
			if (!((Object)(object)val == (Object)null) && !((Object)(object)pin.m_uiElement == (Object)null))
			{
				Rect rect = pin.m_uiElement.rect;
				float num = ((Rect)(ref rect)).height * (scale - 1f) * 0.5f;
				if (!float.IsNaN(num) && !float.IsInfinity(num))
				{
					Vector2 anchoredPosition = pin.m_uiElement.anchoredPosition;
					val.anchoredPosition = new Vector2(anchoredPosition.x, anchoredPosition.y - num);
				}
			}
		}

		private static void RestoreIconDisplay(PinData pin)
		{
			if (IconDisplayStates.TryGetValue(pin, out IconDisplayState value))
			{
				Sprite val = (Sprite)((pin.m_icon == value.AppliedIcon) ? ((object)value.OriginalIcon) : ((object)pin.m_icon));
				if (value.HasVanillaOverride && pin.m_icon == value.AppliedIcon)
				{
					pin.m_icon = val;
				}
				if (value.HasVanillaOverride && (Object)(object)pin.m_iconElement != (Object)null && pin.m_iconElement.sprite == value.AppliedIcon)
				{
					pin.m_iconElement.sprite = val;
				}
				RestoreIconScale(value);
				IconDisplayStates.Remove(pin);
			}
		}

		[UsedImplicitly]
		[HarmonyPatch("GetSharedMapData")]
		[HarmonyPrefix]
		internal static void GetSharedMapDataPrefix(ref Minimap __instance, out List<PinData> __state)
		{
			List<PinData> list = PinsRef.Invoke(__instance);
			__state = list.Where(IsAmpPinData).ToList();
			foreach (PinData item in __state)
			{
				list.Remove(item);
			}
		}

		[UsedImplicitly]
		[HarmonyPatch("GetSharedMapData")]
		[HarmonyPostfix]
		internal static void GetSharedMapDataPostfix(ref Minimap __instance, List<PinData>? __state)
		{
			RestoreMapTablePins(__instance, __state);
		}

		[UsedImplicitly]
		[HarmonyPatch("GetSharedMapData")]
		[HarmonyFinalizer]
		internal static Exception? GetSharedMapDataFinalizer(ref Minimap __instance, Exception? __exception, List<PinData>? __state)
		{
			RestoreMapTablePins(__instance, __state);
			return __exception;
		}

		private static void RestoreMapTablePins(Minimap minimap, List<PinData>? state)
		{
			if (state == null || state.Count == 0)
			{
				return;
			}
			List<PinData> list = PinsRef.Invoke(minimap);
			foreach (PinData item in state)
			{
				if (!list.Contains(item))
				{
					list.Add(item);
				}
			}
			state.Clear();
		}

		private static bool IsAmpPinData(PinData pin)
		{
			string internalName;
			if (!(pin is MapPin))
			{
				return TryGetSavedAmpPinInternalName(pin, out internalName);
			}
			return true;
		}

		internal static int ClearAmpPins()
		{
			if (!Object.op_Implicit((Object)(object)Minimap.instance))
			{
				return 0;
			}
			List<PinData> list = PinsRef.Invoke(Minimap.instance).Where(IsAmpPinData).ToList();
			foreach (PinData item in list)
			{
				Minimap.instance.RemovePin(item);
			}
			return list.Count;
		}

		private static void ConvertSavedAmpPins()
		{
			if (!Object.op_Implicit((Object)(object)Minimap.instance))
			{
				return;
			}
			List<PinData> list = PinsRef.Invoke(Minimap.instance);
			List<(PinData, MapPin)> list2 = new List<(PinData, MapPin)>();
			List<PinData> list3 = new List<PinData>();
			foreach (PinData item in list.ToList())
			{
				if (!(item is MapPin) && TryGetSavedAmpPinInternalName(item, out string internalName))
				{
					if (TryGetSavedPinConfig(item, internalName, out Config.Pin config))
					{
						list2.Add((item, new MapPin(item, internalName, config)));
					}
					else if (SavedAmpPinHasLoadedNonPermanentOrInactiveConfig(internalName))
					{
						list3.Add(item);
					}
				}
			}
			foreach (PinData item2 in list3)
			{
				Minimap.instance.RemovePin(item2);
			}
			foreach (var item3 in list2)
			{
				Minimap.instance.RemovePin(item3.Item1);
				list.Add((PinData)(object)item3.Item2);
			}
		}

		internal static void UpsertPin(GameObject objectToPin)
		{
			//IL_0063: Unknown result type (might be due to invalid IL or missing references)
			if (!Object.op_Implicit((Object)(object)Minimap.instance))
			{
				return;
			}
			List<PinData> list = PinsRef.Invoke(Minimap.instance);
			if (list == null)
			{
				return;
			}
			string text = AutoMapPins.Common.Constants.ParseInternalName(((Object)objectToPin).name);
			if (!Registry.ConfiguredPins.TryGetValue(text, out Config.Pin value) || value.IsActive != true)
			{
				Registry.AddMissingConfig(text);
			}
			else
			{
				if (!ExplorationSkillGate.IsUnlocked(value))
				{
					return;
				}
				PositionedObject positionedObject = new PositionedObject(text, objectToPin.transform.position);
				MapPin mapPin = null;
				bool flag = value.IsPermanent != true && value.Groupable == true;
				foreach (PinData item in list)
				{
					if (item is MapPin mapPin2 && !(mapPin2.InternalName != text))
					{
						if (mapPin2.RepresentsObject(positionedObject))
						{
							return;
						}
						if (flag && mapPin == null && mapPin2.AcceptsObject(positionedObject))
						{
							mapPin = mapPin2;
						}
					}
				}
				if (mapPin != null)
				{
					mapPin.AddObjectToPin(positionedObject);
				}
				else
				{
					list.Add((PinData)(object)new MapPin(positionedObject, value));
				}
			}
		}

		internal static MapPin? UpsertDistantPin(PositionedObject position)
		{
			if (!Object.op_Implicit((Object)(object)Minimap.instance) || !Registry.ConfiguredPins.TryGetValue(position.ObjectName, out Config.Pin value) || value.IsActive != true || !ExplorationSkillGate.IsUnlocked(value))
			{
				return null;
			}
			List<PinData> list = PinsRef.Invoke(Minimap.instance);
			if (list.OfType<MapPin>().Any((MapPin pin) => pin.RepresentsObject(position)))
			{
				return null;
			}
			MapPin mapPin = new MapPin(position, value);
			list.Add((PinData)(object)mapPin);
			return mapPin;
		}

		internal static bool ContainsDistantPin(MapPin pin)
		{
			if (Object.op_Implicit((Object)(object)Minimap.instance))
			{
				return PinsRef.Invoke(Minimap.instance).Contains((PinData)(object)pin);
			}
			return false;
		}

		internal static void RemoveDistantPin(MapPin pin)
		{
			if (Object.op_Implicit((Object)(object)Minimap.instance) && pin.Config.IsPermanent != true && PinsRef.Invoke(Minimap.instance).Contains((PinData)(object)pin))
			{
				Minimap.instance.RemovePin((PinData)(object)pin);
			}
		}

		internal static void UnpinObject(GameObject objectToRemove)
		{
			UnpinObject(PositionedObject.FromGameObject(objectToRemove));
		}

		internal static void UnpinObject(PositionedObject positionToRemove)
		{
			if (!Object.op_Implicit((Object)(object)Minimap.instance))
			{
				return;
			}
			List<PinData> list = PinsRef.Invoke(Minimap.instance);
			for (int i = 0; i < list.Count; i++)
			{
				if (list[i] is MapPin mapPin && !(mapPin.InternalName != positionToRemove.ObjectName) && !AutoMapPinsPlugin.OwnsDistantPin(mapPin) && mapPin.RemoveObjectFromPin(positionToRemove, out var pinIsEmpty))
				{
					if (pinIsEmpty)
					{
						Minimap.instance.RemovePin((PinData)(object)mapPin);
					}
					break;
				}
			}
		}

		internal static void UpdatePins()
		{
			//IL_00e9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ee: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f6: Unknown result type (might be due to invalid IL or missing references)
			if (!Object.op_Implicit((Object)(object)Minimap.instance))
			{
				return;
			}
			HasLogger.Log.LogInfo((object)"updating pins");
			ConvertSavedAmpPins();
			List<MapPin> list = new List<MapPin>();
			List<MapPin> list2 = new List<MapPin>();
			foreach (MapPin item in PinsRef.Invoke(Minimap.instance).OfType<MapPin>())
			{
				if (Registry.ConfiguredPins.TryGetValue(item.InternalName, out Config.Pin value))
				{
					if (value.IsPermanent != true && !ExplorationSkillGate.IsUnlocked(value))
					{
						list.Add(item);
					}
					else if (item.Config.IsPermanent == true && value.IsPermanent != true)
					{
						list.Add(item);
					}
					else if (value.IsPermanent == true && item.InstanceCount > 1)
					{
						list.Add(item);
						Vector3[] instancePositions = item.GetInstancePositions();
						foreach (Vector3 objectPosition in instancePositions)
						{
							MapPin mapPin = new MapPin(new PositionedObject(item.InternalName, objectPosition), value);
							((PinData)mapPin).m_checked = ((PinData)item).m_checked;
							list2.Add(mapPin);
						}
					}
					else
					{
						item.ApplyConfigUpdate(value);
					}
				}
				else if (item.Config.IsPermanent == true && !Registry.HasConfiguredObject(item.InternalName))
				{
					item.RefreshIcon();
				}
				else
				{
					list.Add(item);
				}
			}
			foreach (MapPin item2 in list)
			{
				Minimap.instance.RemovePin((PinData)(object)item2);
			}
			PinsRef.Invoke(Minimap.instance).AddRange((IEnumerable<PinData>)list2);
			PinUpdateRequiredRef.Invoke(Minimap.instance) = true;
		}

		internal static string PrintMapPins()
		{
			//IL_00e0: Unknown result type (might be due to invalid IL or missing references)
			string text = "";
			if (!Object.op_Implicit((Object)(object)Minimap.instance))
			{
				return text;
			}
			foreach (var item in from entry in PinsRef.Invoke(Minimap.instance).Select(delegate(PinData pin, int index)
				{
					//IL_0028: Unknown result type (might be due to invalid IL or missing references)
					PinNameData namePinData = pin.m_NamePinData;
					object obj;
					if (namePinData == null)
					{
						obj = null;
					}
					else
					{
						TMP_Text pinNameText = namePinData.PinNameText;
						obj = ((pinNameText != null) ? pinNameText.text : null);
					}
					if (obj == null)
					{
						obj = "no name";
					}
					return new
					{
						Position = new PositionedObject((string)obj, pin.m_pos),
						Pin = pin,
						Index = index
					};
				})
				orderby entry.Position, entry.Index
				select entry)
			{
				text = ((!(item.Pin is MapPin mapPin)) ? (text + $"vanilla pin: {item.Position} of type '{item.Pin.m_type}'\n") : (text + ((object)mapPin)?.ToString() + "\n"));
			}
			return text;
		}
	}
	[HarmonyPatch(typeof(Pickable), "Awake")]
	internal class PickablePatch
	{
		private static readonly FieldRef<Pickable, bool> PickedRef = AccessTools.FieldRefAccess<Pickable, bool>("m_picked");

		[UsedImplicitly]
		[HarmonyPriority(600)]
		private static void Postfix(ref Pickable __instance)
		{
			if (!PickedRef.Invoke(__instance))
			{
				CommonPatchLogic.Patch(((Component)__instance).gameObject);
			}
		}
	}
	[HarmonyPatch(typeof(Pickable), "SetPicked")]
	public class PickableDropPatch
	{
		[UsedImplicitly]
		private static void Postfix(ref Pickable __instance, bool picked)
		{
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			GameObject gameObject = ((Component)__instance).gameObject;
			if (gameObject.transform.position.y > AutoMapPinsPlugin.MaxDetectionHeight.Value)
			{
				return;
			}
			if (picked)
			{
				PinComponent pinComponent = default(PinComponent);
				if (gameObject.TryGetComponent<PinComponent>(ref pinComponent))
				{
					Object.Destroy((Object)(object)pinComponent);
				}
			}
			else
			{
				CommonPatchLogic.Patch(gameObject);
			}
		}
	}
}
namespace AutoMapPins.Model
{
	public class MapPin : PinData
	{
		private const string SavedPinAuthorPrefix = "FixItFelix.AutoMapPins_";

		private static readonly FieldRef<Minimap, bool> PinUpdateRequiredRef = AccessTools.FieldRefAccess<Minimap, bool>("m_pinUpdateRequired");

		private static readonly MethodInfo? CreateMapNamePinMethod = AccessTools.DeclaredMethod(typeof(Minimap), "CreateMapNamePin", (Type[])null, (Type[])null);

		private static readonly MethodInfo? DestroyMapMarkerMethod = AccessTools.DeclaredMethod(typeof(PinNameData), "DestroyMapMarker", (Type[])null, (Type[])null);

		internal readonly string InternalName;

		internal readonly bool LoadedFromSave;

		internal Config.Pin Config;

		private readonly List<Vector3> InstancePositions = new List<Vector3>();

		internal int InstanceCount => InstancePositions.Count;

		internal MapPin(PositionedObject positionedObject, Config.Pin config)
		{
			//IL_002b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0037: Unknown result type (might be due to invalid IL or missing references)
			InternalName = positionedObject.ObjectName;
			LoadedFromSave = false;
			InstancePositions.Add(positionedObject.ObjectPosition);
			base.m_type = (PinType)8;
			base.m_checked = false;
			base.m_ownerID = 0L;
			ApplyConfigUpdate(config);
		}

		internal MapPin(PinData fromVanilla, string internalName, Config.Pin config)
		{
			//IL_0026: Unknown result type (might be due to invalid IL or missing references)
			//IL_0032: Unknown result type (might be due to invalid IL or missing references)
			//IL_0037: Unknown result type (might be due to invalid IL or missing references)
			InternalName = internalName;
			LoadedFromSave = true;
			InstancePositions.Add(fromVanilla.m_pos);
			base.m_type = fromVanilla.m_type;
			base.m_checked = fromVanilla.m_checked;
			base.m_ownerID = fromVanilla.m_ownerID;
			ApplyConfigUpdate(config);
		}

		internal Vector3[] GetInstancePositions()
		{
			return InstancePositions.ToArray();
		}

		internal PositionedObject GetPinnedPosition()
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			return new PositionedObject(InternalName, base.m_pos);
		}

		internal static bool TryGetSavedInternalName(PinData pin, out string internalName)
		{
			internalName = "";
			string text = ((object)Unsafe.As<PlatformUserID, PlatformUserID>(ref pin.m_author)/*cast due to .constrained prefix*/).ToString();
			if (string.IsNullOrEmpty(text) || !text.StartsWith("FixItFelix.AutoMapPins_"))
			{
				return false;
			}
			internalName = text.Substring("FixItFelix.AutoMapPins_".Length);
			return !string.IsNullOrWhiteSpace(internalName);
		}

		internal void ApplyConfigUpdate(Config.Pin config)
		{
			//IL_00a4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ae: Expected O, but got Unknown
			Config = config;
			Config.IconName = (string.IsNullOrWhiteSpace(Config.IconName) ? "n_a" : Config.IconName);
			base.m_name = Config.Name;
			base.m_save = Config.IsPermanent == true;
			ApplySavedIdentity();
			base.m_icon = Assets.GetIcon(Config.IconName ?? "n_a");
			if (base.m_NamePinData != null)
			{
				DestroyMapMarkerMethod?.Invoke(base.m_NamePinData, null);
			}
			base.m_NamePinData = new PinNameData((PinData)(object)this);
			UpdatePin();
		}

		internal void RefreshIcon()
		{
			base.m_icon = Assets.GetIcon(Config.IconName ?? "n_a");
			if (Object.op_Implicit((Object)(object)Minimap.instance))
			{
				PinUpdateRequiredRef.Invoke(Minimap.instance) = true;
			}
		}

		private void ApplySavedIdentity()
		{
			//IL_002a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			//IL_002f: Unknown result type (might be due to invalid IL or missing references)
			base.m_author = (PlatformUserID)((Config.IsPermanent == true) ? new PlatformUserID("FixItFelix.AutoMapPins_" + InternalName) : PlatformUserID.None);
		}

		private void UpdatePin()
		{
			UpdatePosition();
			UpdatePinText();
			UpdatePinColor();
			if (Object.op_Implicit((Object)(object)Minimap.instance))
			{
				PinUpdateRequiredRef.Invoke(Minimap.instance) = true;
			}
		}

		private void UpdatePosition()
		{
			//IL_009b: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a0: Unknown result type (might be due to invalid IL or missing references)
			//IL_0034: Unknown result type (might be due to invalid IL or missing references)
			//IL_0039: Unknown result type (might be due to invalid IL or missing references)
			//IL_003c: 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_0050: Unknown result type (might be due to invalid IL or missing references)
			//IL_0089: Unknown result type (might be due to invalid IL or missing references)
			//IL_008e: Unknown result type (might be due to invalid IL or missing references)
			if (InstancePositions.Count > 1)
			{
				float num = 0f;
				float num2 = 0f;
				float num3 = 0f;
				foreach (Vector3 instancePosition in InstancePositions)
				{
					num += instancePosition.x;
					num2 += instancePosition.y;
					num3 += instancePosition.z;
				}
				float num4 = InstancePositions.Count;
				base.m_pos = new Vector3(num / num4, num2 / num4, num3 / num4);
			}
			else
			{
				base.m_pos = InstancePositions.First();
			}
		}

		private void UpdatePinText()
		{
			//IL_00d4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00da: Invalid comparison between Unknown and I4
			if (InstancePositions.Count > 1)
			{
				string text = InstancePositions.Count.ToString() ?? "";
				base.m_name = (string.IsNullOrEmpty(Config.Name) ? text : ((text == "") ? Config.Name : (text + " " + Config.Name)));
			}
			else
			{
				base.m_name = (string.IsNullOrEmpty(Config.Name) ? " " : Config.Name);
			}
			if (base.m_NamePinData != null)
			{
				DestroyMapMarkerMethod?.Invoke(base.m_NamePinData, null);
			}
			if (Object.op_Implicit((Object)(object)Minimap.instance))
			{
				RectTransform val = (((int)Minimap.instance.m_mode == 2) ? Minimap.instance.m_pinNameRootLarge : Minimap.instance.m_pinNameRootSmall);
				CreateMapNamePinMethod?.Invoke(Minimap.instance, new object[2] { this, val });
				RefreshPinLabelText();
			}
		}

		internal void RefreshPinLabelText()
		{
			PinNameData namePinData = base.m_NamePinData;
			if (!((Object)(object)((namePinData != null) ? namePinData.PinNameText : null) == (Object)null))
			{
				string text = Localization.instance.Localize(base.m_name);
				if (base.m_NamePinData.PinNameText.text != text)
				{
					base.m_NamePinData.PinNameText.text = text;
				}
			}
		}

		internal bool RepresentsObject(PositionedObject positionedObject)
		{
			//IL_001a: Unknown result type (might be due to invalid IL or missing references)
			if (InternalName == positionedObject.ObjectName)
			{
				return InstancePositions.Contains(positionedObject.ObjectPosition);
			}
			return false;
		}

		internal void UpdatePinColor()
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_001d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0029: Unknown result type (might be due to invalid IL or missing references)
			//IL_0030: 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_0043: Unknown result type (might be due to invalid IL or missing references)
			//IL_006e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0073: Unknown result type (might be due to invalid IL or missing references)
			//IL_0086: Unknown result type (might be due to invalid IL or missing references)
			if (Object.op_Implicit((Object)(object)base.m_iconElement))
			{
				Color val = Config.IconColorRGBA?.FromConfig() ?? Color.white;
				if (!SameColor(((Graphic)base.m_iconElement).color, val))
				{
					((Graphic)base.m_iconElement).color = val;
				}
				PinNameData namePinData = base.m_NamePinData;
				if ((Object)(object)((namePinData != null) ? namePinData.PinNameText : null) != (Object)null && !SameColor(((Graphic)base.m_NamePinData.PinNameText).color, val))
				{
					((Graphic)base.m_NamePinData.PinNameText).color = val;
				}
			}
		}

		private static bool SameColor(Color a, Color b)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0014: Unknown result type (might be due to invalid IL or missing references)
			//IL_001c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0022: Unknown result type (might be due to invalid IL or missing references)
			//IL_002a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0030: Unknown result type (might be due to invalid IL or missing references)
			if (a.r == b.r && a.g == b.g && a.b == b.b)
			{
				return a.a == b.a;
			}
			return false;
		}

		internal bool AcceptsObject(PositionedObject objectToGroup)
		{
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			if (Config.Groupable == true && InternalName == objectToGroup.ObjectName)
			{
				return WithinGroupDistance(objectToGroup.ObjectPosition);
			}
			return false;
		}

		private bool WithinGroupDistance(Vector3 newPosition)
		{
			//IL_0046: Unknown result type (might be due to invalid IL or missing references)
			//IL_004b: Unknown result type (might be due to invalid IL or missing references)
			Config.Pin config = Config;
			float value;
			if (config != null)
			{
				float? groupingDistance = config.GroupingDistance;
				if (groupingDistance.HasValue && groupingDistance.GetValueOrDefault() > 0f)
				{
					value = Config.GroupingDistance.Value;
					goto IL_0044;
				}
			}
			value = AutoMapPinsPlugin.GroupingRadius.Value;
			goto IL_0044;
			IL_0044:
			float num = value;
			return Utils.DistanceXZ(base.m_pos, newPosition) < num;
		}

		internal void AddObjectToPin(PositionedObject objectToAdd)
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_001b: Unknown result type (might be due to invalid IL or missing references)
			if (!InstancePositions.Contains(objectToAdd.ObjectPosition))
			{
				InstancePositions.Add(objectToAdd.ObjectPosition);
				UpdatePin();
			}
		}

		internal bool RemoveObjectFromPin(PositionedObject positionedObject, out bool pinIsEmpty)
		{
			//IL_0033: Unknown result type (might be due to invalid IL or missing references)
			pinIsEmpty = false;
			if (Config.IsPermanent == true)
			{
				return false;
			}
			if (InternalName != positionedObject.ObjectName)
			{
				return false;
			}
			if (!InstancePositions.Remove(positionedObject.ObjectPosition))
			{
				return false;
			}
			pinIsEmpty = InstancePositions.Count == 0;
			if (!pinIsEmpty)
			{
				UpdatePin();
			}
			return true;
		}

		public unsafe override string ToString()
		{
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			//IL_0078: Unknown result type (might be due to invalid IL or missing references)
			//IL_007d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0084: Unknown result type (might be due to invalid IL or missing references)
			//IL_0085: Unknown result type (might be due to invalid IL or missing references)
			string text = $"custom AMP pin: '{base.m_name}' (game object name '{InternalName}') at position '{base.m_pos}' " + $"with icon '{Config.IconName}', permanent '{Config.IsPermanent}'";
			if (InstancePositions.Count <= 1)
			{
				return text;
			}
			text += "; grouped pin, containing positions:";
			foreach (Vector3 instancePosition in InstancePositions)
			{
				string text2 = text;
				Vector3 val = instancePosition;
				text = text2 + "\n  " + ((object)(*(Vector3*)(&val))/*cast due to .constrained prefix*/).ToString();
			}
			return text;
		}
	}
	internal class PinComponent : MonoBehaviour
	{
		private const float VisibilityCheckIntervalSeconds = 0.5f;

		private static readonly WaitForSeconds VisibilityCheckWait = new WaitForSeconds(0.5f);

		private static readonly MethodInfo? IsExploredMethod = AccessTools.DeclaredMethod(typeof(Minimap), "IsExplored", new Type[1] { typeof(Vector3) }, (Type[])null);

		private static readonly Func<Minimap, Vector3, bool>? IsExploredFunc = CreateIsExploredFunc();

		private static readonly HashSet<PinComponent> VisibleComponents = new HashSet<PinComponent>();

		private Vector3 Position;

		private PositionedObject? PinnedIdentity;

		private bool IsVisible;

		private Coroutine? Routine;

		internal static bool IsExploredReflectionAvailable => IsExploredMethod != null;

		private bool DynamicVisibility
		{
			get
			{
				if (AutoMapPinsPlugin.TemporaryPinsWithinDiscoveryRadiusOnly.Value)
				{
					return IsTemporaryPin();
				}
				return false;
			}
		}

		private static Func<Minimap, Vector3, bool>? CreateIsExploredFunc()
		{
			if (IsExploredMethod == null)
			{
				return null;
			}
			try
			{
				return (Func<Minimap, Vector3, bool>)Delegate.CreateDelegate(typeof(Func<Minimap, Vector3, bool>), IsExploredMethod);
			}
			catch (Exception)
			{
				return null;
			}
		}

		private PinComponent()
		{
		}

		internal void Awake()
		{
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			Position = ((Component)this).gameObject.transform.position;
			IsVisible = EvaluateVisibility();
			if (IsVisible)
			{
				ShowPin();
			}
			if (!IsVisible || DynamicVisibility)
			{
				Routine = ((MonoBehaviour)this).StartCoroutine(VisibleCheck());
			}
		}

		internal void OnDestroy()
		{
			VisibleComponents.Remove(this);
			if (Routine != null)
			{
				((MonoBehaviour)this).StopCoroutine(Routine);
			}
			if (PinnedIdentity.HasValue)
			{
				MinimapPatch.UnpinObject(PinnedIdentity.Value);
			}
			PinnedIdentity = null;
		}

		private bool IsTemporaryPin()
		{
			string key = AutoMapPins.Common.Constants.ParseInternalName(((Object)((Component)this).gameObject).name);
			if (Registry.ConfiguredPins.TryGetValue(key, out Config.Pin value))
			{
				return value.IsPermanent != true;
			}
			return true;
		}

		private bool EvaluateVisibility()
		{
			//IL_0009: Unknown result type (might be due to invalid IL or missing references)
			//IL_0033: Unknown result type (might be due to invalid IL or missing references)
			//IL_0026: Unknown result type (might be due to invalid IL or missing references)
			if (DynamicVisibility)
			{
				return DiscoveryRadiusService.IsWithinDiscoveryRadius(Position);
			}
			if (!Object.op_Implicit((Object)(object)Minimap.instance) || !CallIsExplored(Minimap.instance, Position))
			{
				return DiscoveryRadiusService.IsWithinDiscoveryRadius(Position);
			}
			return true;
		}

		private IEnumerator VisibleCheck()
		{
			yield return (object)new WaitForSeconds(Random.Range(0f, 0.5f));
			while (true)
			{
				bool flag = EvaluateVisibility();
				if (flag != IsVisible)
				{
					IsVisible = flag;
					if (IsVisible)
					{
						ShowPin();
					}
					else
					{
						HidePin();
					}
				}
				if (IsVisible && !DynamicVisibility)
				{
					break;
				}
				yield return VisibilityCheckWait;
			}
			Routine = null;
		}

		internal static void RefreshVisiblePinsAfterConfigChange()
		{
			foreach (PinComponent item in VisibleComponents.ToList())
			{
				if (!Object.op_Implicit((Object)(object)item) || !Object.op_Implicit((Object)(object)((Component)item).gameObject))
				{
					VisibleComponents.Remove(item);
					continue;
				}
				if (!item.EvaluateVisibility())
				{
					item.IsVisible = false;
					item.HidePin();
				}
				if (item.Routine == null && (!item.IsVisible || item.DynamicVisibility))
				{
					item.Routine = ((MonoBehaviour)item).StartCoroutine(item.VisibleCheck());
				}
			}
		}

		private void ShowPin()
		{
			VisibleComponents.Add(this);
			PositionedObject positionedObject = PositionedObject.FromGameObject(((Component)this).gameObject);
			if (PinnedIdentity.HasValue && !PinnedIdentity.Value.Equals(positionedObject))
			{
				MinimapPatch.UnpinObject(PinnedIdentity.Value);
			}
			MinimapPatch.UpsertPin(((Component)this).gameObject);
			PinnedIdentity = positionedObject;
		}

		private void HidePin()
		{
			VisibleComponents.Remove(this);
			if (PinnedIdentity.HasValue)
			{
				MinimapPatch.UnpinObject(PinnedIdentity.Value);
			}
			PinnedIdentity = null;
		}

		internal static void RescanRegisteredVisiblePins()
		{
			foreach (PinComponent item in VisibleComponents.ToList())
			{
				if (!Object.op_Implicit((Object)(object)item) || !Object.op_Implicit((Object)(object)((Component)item).gameObject))
				{
					VisibleComponents.Remove(item);
				}
				else if (item.IsVisible)
				{
					item.ShowPin();
				}
			}
		}

		private static bool CallIsExplored(Minimap minimap, Vector3 position)
		{
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0031: Unknown result type (might be due to invalid IL or missing references)
			if (IsExploredFunc != null)
			{
				return IsExploredFunc(minimap, position);
			}
			if (IsExploredMethod == null)
			{
				return false;
			}
			object obj = IsExploredMethod.Invoke(minimap, new object[1] { position });
			bool flag = default(bool);
			int num;
			if (obj is bool)
			{
				flag = (bool)obj;
				num = 1;
			}
			else
			{
				num = 0;
			}
			return (byte)((uint)num & (flag ? 1u : 0u)) != 0;
		}
	}
	internal readonly struct PositionedObject : IComparable
	{
		internal readonly string ObjectName;

		internal readonly Vector3 ObjectPosition;

		public PositionedObject(string objectName, Vector3 objectPosition)
		{
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			//IL_0009: Unknown result type (might be due to invalid IL or missing references)
			ObjectName = objectName;
			ObjectPosition = objectPosition;
		}

		internal static PositionedObject FromGameObject(GameObject pinnedObject)
		{
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			return new PositionedObject(AutoMapPins.Common.Constants.ParseInternalName(((Object)pinnedObject).name), pinnedObject.transform.position);
		}

		public override bool Equals(object? obj)
		{
			if (obj is PositionedObject other)
			{
				return Equals(other);
			}
			return base.Equals(obj);
		}

		private bool Equals(PositionedObject other)
		{
			//IL_0014: Unknown result type (might be due to invalid IL or missing references)
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			//IL_001d: Unknown result type (might be due to invalid IL or missing references)
			if (ObjectName == other.ObjectName)
			{
				Vector3 objectPosition = ObjectPosition;
				return ((Vector3)(ref objectPosition)).Equals(other.ObjectPosition);
			}
			return false;
		}

		public override int GetHashCode()
		{
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			return (ObjectName.GetHashCode() * 397) ^ ((object)ObjectPosition/*cast due to .constrained prefix*/).GetHashCode();
		}

		public int CompareTo(object obj)
		{
			if (obj is PositionedObject other)
			{
				return CompareTo(other);
			}
			throw new NotImplementedException();
		}

		private int CompareTo(PositionedObject other)
		{
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			int num = string.Compare(ObjectName, other.ObjectName, StringComparison.Ordinal);
			if (num != 0)
			{
				return num;
			}
			float x = ObjectPosition.x;
			return x.CompareTo(other.ObjectPosition.x);
		}

		public override string ToString()
		{
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			return $"'{ObjectName}' at '{ObjectPosition}'";
		}
	}
}
namespace AutoMapPins.Properties
{
	[GeneratedCode("System.Resources.Tools.StronglyTypedResourceBuilder", "17.0.0.0")]
	[DebuggerNonUserCode]
	[CompilerGenerated]
	internal class Resources
	{
		private static ResourceManager resourceMan;

		private static CultureInfo resourceCulture;

		[EditorBrowsable(EditorBrowsableState.Advanced)]
		internal static ResourceManager ResourceManager
		{
			get
			{
				if (resourceMan == null)
				{
					resourceMan = new ResourceManager("AutoMapPins.Icons.Resources", typeof(Resources).Assembly);
				}
				return resourceMan;
			}
		}

		[EditorBrowsable(EditorBrowsableState.Advanced)]
		internal static CultureInfo Culture
		{
			get
			{
				return resourceCulture;
			}
			set
			{
				resourceCulture = value;
			}
		}

		internal static byte[] AMP => (byte[])ResourceManager.GetObject("AMP", resourceCulture);

		internal static byte[] Axe => (byte[])ResourceManager.GetObject("Axe", resourceCulture);

		internal static byte[] Axe48 => (byte[])ResourceManager.GetObject("Axe48", resourceCulture);

		internal static byte[] Berry => (byte[])ResourceManager.GetObject("Berry", resourceCulture);

		internal static byte[] Berry48 => (byte[])ResourceManager.GetObject("Berry48", resourceCulture);

		internal static byte[] Bones => (byte[])ResourceManager.GetObject("Bones", resourceCulture);

		internal static byte[] Bones48 => (byte[])ResourceManager.GetObject("Bones48", resourceCulture);

		internal static byte[] Dot => (byte[])ResourceManager.GetObject("Dot", resourceCulture);

		internal static byte[] Dot48 => (byte[])ResourceManager.GetObject("Dot48", resourceCulture);

		internal static byte[] Dungeon => (byte[])ResourceManager.GetObject("Dungeon", resourceCulture);

		internal static byte[] Dungeon48 => (byte[])ResourceManager.GetObject("Dungeon48", resourceCulture);

		internal static byte[] Fire => (byte[])ResourceManager.GetObject("Fire", resourceCulture);

		internal static byte[] Fire48 => (byte[])ResourceManager.GetObject("Fire48", resourceCulture);

		internal static byte[] Flower => (byte[])ResourceManager.GetObject("Flower", resourceCulture);

		internal static byte[] Flower48 => (byte[])ResourceManager.GetObject("Flower48", resourceCulture);

		internal static byte[] Hand => (byte[])ResourceManager.GetObject("Hand", resourceCulture);

		internal static byte[] Hand48 => (byte[])ResourceManager.GetObject("Hand48", resourceCulture);

		internal static byte[] Hay => (byte[])ResourceManager.GetObject("Hay", resourceCulture);

		internal static byte[] Hay48 => (byte[])ResourceManager.GetObject("Hay48", resourceCulture);

		internal static byte[] Herb => (byte[])ResourceManager.GetObject("Herb", resourceCulture);

		internal static byte[] Herb48 => (byte[])ResourceManager.GetObject("Herb48", resourceCulture);

		internal static byte[] Island => (byte[])ResourceManager.GetObject("Island", resourceCulture);

		internal static byte[] Island48 => (byte[])ResourceManager.GetObject("Island48", resourceCulture);

		internal static byte[] Mine => (byte[])ResourceManager.GetObject("Mine", resourceCulture);

		internal static byte[] Mine48 => (byte[])ResourceManager.GetObject("Mine48", resourceCulture);

		internal static byte[] Monument => (byte[])ResourceManager.GetObject("Monument", resourceCulture);

		internal static byte[] Monument48 => (byte[])ResourceManager.GetObject("Monument48", resourceCulture);

		internal static byte[] Mushroom => (byte[])ResourceManager.GetObject("Mushroom", resourceCulture);

		internal static byte[] Mushroom48 => (byte[])ResourceManager.GetObject("Mushroom48", resourceCulture);

		internal static byte[] Portal => (byte[])ResourceManager.GetObject("Portal", resourceCulture);

		internal static byte[] Portal48 => (byte[])ResourceManager.GetObject("Portal48", resourceCulture);

		internal static byte[] Rune => (byte[])ResourceManager.GetObject("Rune", resourceCulture);

		internal static byte[] Rune48 => (byte[])ResourceManager.GetObject("Rune48", resourceCulture);

		internal static byte[] Seed => (byte[])ResourceManager.GetObject("Seed", resourceCulture);

		internal static byte[] Seed48 => (byte[])ResourceManager.GetObject("Seed48", resourceCulture);

		internal static byte[] Spawner => (byte[])ResourceManager.GetObject("Spawner", resourceCulture);

		internal static byte[] Spawner48 => (byte[])ResourceManager.GetObject("Spawner48", resourceCulture);

		internal static byte[] Temple => (byte[])ResourceManager.GetObject("Temple", resourceCulture);

		internal static byte[] Temple48 => (byte[])ResourceManager.GetObject("Temple48", resourceCulture);

		internal static byte[] Treasure => (byte[])ResourceManager.GetObject("Treasure", resourceCulture);

		internal static byte[] Treasure48 => (byte[])ResourceManager.GetObject("Treasure48", resourceCulture);

		internal static byte[] Tree => (byte[])ResourceManager.GetObject("Tree", resourceCulture);

		internal static byte[] Tree48 => (byte[])ResourceManager.GetObject("Tree48", resourceCulture);

		internal static byte[] Village => (byte[])ResourceManager.GetObject("Village", resourceCulture);

		internal static byte[] Village48 => (byte[])ResourceManager.GetObject("Village48", resourceCulture);

		internal static byte[] Whale => (byte[])ResourceManager.GetObject("Whale", resourceCulture);

		internal static byte[] Whale48 => (byte[])ResourceManager.GetObject("Whale48", resourceCulture);

		internal Resources()
		{
		}
	}
}
namespace AutoMapPins.Icons
{
	internal abstract class Assets
	{
		private sealed class LoadedFile
		{
			internal readonly Sprite Sprite;

			internal readonly Texture2D Texture;

			internal readonly float Scale;

			internal LoadedFile(Sprite sprite, Texture2D texture, float scale)
			{
				Sprite = sprite;
				Texture = texture;
				Scale = scale;
			}
		}

		private static readonly MethodInfo? LoadImageMethod = Type.GetType("UnityEngine.ImageConversion, UnityEngine.ImageConversionModule")?.GetMethod("LoadImage", new Type[2]
		{
			typeof(Texture2D),
			typeof(byte[])
		});

		private static readonly Sprite DefaultIcon = LoadSpriteFromTexture(Resources.Dot);

		private static readonly HashSet<string> WarnedMissingIcons = new HashSet<string>(StringComparer.OrdinalIgnoreCase);

		private static readonly Dictionary<string, Sprite> CustomIcons = new Dictionary<string, Sprite>(StringComparer.OrdinalIgnoreCase);

		private static readonly Dictionary<string, Sprite> IconOverrides = new Dictionary<string, Sprite>(StringComparer.OrdinalIgnoreCase);

		private static readonly Dictionary<string, float> CustomIconScales = new Dictionary<string, float>(StringComparer.OrdinalIgnoreCase);

		private static readonly Dictionary<PinType, (Sprite Icon, float Scale)> VanillaMapOverrides = new Dictionary<PinType, (Sprite, float)>();

		private static readonly Dictionary<string, (Sprite Icon, float Scale)> LocationMapOverrides = new Dictionary<string, (Sprite, float)>(StringComparer.Ordinal);

		private static readonly Dictionary<string, LoadedFile> LoadedCustomFiles = new Dictionary<string, LoadedFile>(StringComparer.OrdinalIgnoreCase);

		private static readonly Dictionary<string, LoadedFile> LoadedOverrideFiles = new Dictionary<string, LoadedFile>(StringComparer.OrdinalIgnoreCase);

		private static readonly Dictionary<string, Sprite> Icons = new Dictionary<string, Sprite>(StringComparer.OrdinalIgnoreCase)
		{
			{
				"amp",
				LoadSpriteFromTexture(Resources.AMP)
			},
			{
				"axe",
				LoadSpriteFromTexture(Resources.Axe)
			},
			{
				"axe48",
				LoadSpriteFromTexture(Resources.Axe48)
			},
			{
				"berry",
				LoadSpriteFromTexture(Resources.Berry)
			},
			{
				"berry48",
				LoadSpriteFromTexture(Resources.Berry48)
			},
			{
				"bones",
				LoadSpriteFromTexture(Resources.Bones)
			},
			{
				"bones48",
				LoadSpriteFromTexture(Resources.Bones48)
			},
			{
				"dot",
				LoadSpriteFromTexture(Resources.Dot)
			},
			{
				"dot48",
				LoadSpriteFromTexture(Resources.Dot48)
			},
			{
				"dungeon",
				LoadSpriteFromTexture(Resources.Dungeon)
			},
			{
				"dungeon48",
				LoadSpriteFromTexture(Resources.Dungeon48)
			},
			{
				"fire",
				LoadSpriteFromTexture(Resources.Fire)
			},
			{
				"fire48",
				LoadSpriteFromTexture(Resources.Fire48)
			},
			{
				"flower",
				LoadSpriteFromTexture(Resources.Flower)
			},
			{
				"flower48",
				LoadSpriteFromTexture(Resources.Flower48)
			},
			{
				"hand",
				LoadSpriteFromTexture(Resources.Hand)
			},
			{
				"hand48",
				LoadSpriteFromTexture(Resources.Hand48)
			},
			{
				"hay",
				LoadSpriteFromTexture(Resources.Hay)
			},
			{
				"hay48",
				LoadSpriteFromTexture(Resources.Hay48)
			},
			{
				"herb",
				LoadSpriteFromTexture(Resources.Herb)
			},
			{
				"herb48",
				LoadSpriteFromTexture(Resources.Herb48)
			},
			{
				"island",
				LoadSpriteFromTexture(Resources.Island)
			},
			{
				"island48",
				LoadSpriteFromTexture(Resources.Island48)
			},
			{
				"mine",
				LoadSpriteFromTexture(Resources.Mine)
			},
			{
				"mine48",
				LoadSpriteFromTexture(Resources.Mine48)
			},
			{
				"monument",
				LoadSpriteFromTexture(Resources.Monument)
			},
			{
				"monument48",
				LoadSpriteFromTexture(Resources.Monument48)
			},
			{
				"mushroom",
				LoadSpriteFromTexture(Resources.Mushroom)
			},
			{
				"mushroom48",
				LoadSpriteFromTexture(Resources.Mushroom48)
			},
			{
				"portal",
				LoadSpriteFromTexture(Resources.Portal)
			},
			{
				"portal48",
				LoadSpriteFromTexture(Resources.Portal48)
			},
			{
				"rune",
				LoadSpriteFromTexture(Resources.Rune)
			},
			{
				"rune48",
				LoadSpriteFromTexture(Resources.Rune48)
			},
			{
				"seed",
				LoadSpriteFromTexture(Resources.Seed)
			},
			{
				"seed48",
				LoadSpriteFromTexture(Resources.Seed48)
			},
			{
				"spawner",
				LoadSpriteFromTexture(Resources.Spawner)
			},
			{
				"spawner48",
				LoadSpriteFromTexture(Resources.Spawner48)
			},
			{
				"temple",
				LoadSpriteFromTexture(Resources.Temple)
			},
			{
				"temple48",
				LoadSpriteFromTexture(Resources.Temple48)
			},
			{
				"treasure",
				LoadSpriteFromTexture(Resources.Treasure)
			},
			{
				"treasure48",
				LoadSpriteFromTexture(Resources.Treasure48)
			},
			{
				"tree",
				LoadSpriteFromTexture(Resources.Tree)
			},
			{
				"tree48",
				LoadSpriteFromTexture(Resources.Tree48)
			},
			{
				"village",
				LoadSpriteFromTexture(Resources.Village)
			},
			{
				"village48",
				LoadSpriteFromTexture(Resources.Village48)
			},
			{
				"whale",
				LoadSpriteFromTexture(Resources.Whale)
			},
			{
				"whale48",
				LoadSpriteFromTexture(Resources.Whale48)
			}
		};

		internal static bool HasLocationMapOverrides => LocationMapOverrides.Count > 0;

		internal static Sprite GetIcon(string iconName)
		{
			if (string.IsNullOrWhiteSpace(iconName) || string.Equals(iconName, "n_a", StringComparison.OrdinalIgnoreCase))
			{
				return DefaultIcon;
			}
			if (IconOverrides.TryGetValue(iconName, out Sprite value))
			{
				return value;
			}
			if (CustomIcons.TryGetValue(iconName, out Sprite value2))
			{
				return value2;
			}
			if (Icons.TryGetValue(iconName, out Sprite value3))
			{
				return value3;
			}
			if (WarnedMissingIcons.Add(iconName))
			{
				AutoMapPinsPlugin.Log.LogWarning((object)("icon '" + iconName + "' was not found; using default icon"));
			}
			return DefaultIcon;
		}

		internal static float GetIconScale(string? iconName)
		{
			if (iconName == null || !CustomIconScales.TryGetValue(iconName, out var value))
			{
				return 1f;
			}
			return value;
		}

		internal static bool TryGetVanillaMapOverride(PinType type, out Sprite icon, out float scale)
		{
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			if (VanillaMapOverrides.TryGetValue(type, out (Sprite, float) value))
			{
				(icon, scale) = value;
				return true;
			}
			icon = null;
			scale = 1f;
			return false;
		}

		internal static bool TryGetLocationMapOverride(string locationId, out Sprite icon, out float scale)
		{
			if (LocationMapOverrides.TryGetValue(locationId, out (Sprite, float) value))
			{
				(icon, scale) = value;
				return true;
			}
			icon = null;
			scale = 1f;
			return false;
		}

		private static float GetConfiguredScale(Config.CustomIconConfig? config)
		{
			if (config == null || !config.Size.HasValue)
			{
				return 1f;
			}
			int? size = config.Size;
			if (size.HasValue)
			{
				int valueOrDefault = size.GetValueOrDefault();
				if (valueOrDefault >= 1 && valueOrDefault <= 300)
				{
					return (float)config.Size.Value / 100f;
				}
			}
			AutoMapPinsPlugin.Log.LogWarning((object)$"icon size '{config.Size}' is outside 1..300%; using 100%");
			return 1f;
		}

		internal static bool LoadCustomIconConfig(Config.IconConfigFile iconConfig)
		{
			//IL_0267: 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_0278: Invalid comparison between Unknown and I4
			//IL_0292: Unknown result type (might be due to invalid IL or missing references)
			Dictionary<string, Sprite> dictionary = new Dictionary<string, Sprite>(StringComparer.OrdinalIgnoreCase);
			Dictionary<string, Sprite> dictionary2 = new Dictionary<string, Sprite>(StringComparer.OrdinalIgnoreCase);
			Dictionary<string, LoadedFile> dictionary3 = new Dictionary<string, LoadedFile>(StringComparer.OrdinalIgnoreCase);
			Dictionary<string, LoadedFile> dictionary4 = new Dictionary<string, LoadedFile>(StringComparer.OrdinalIgnoreCase);
			int loaded;
			bool flag = LoadIconGroup(iconConfig.Icons, dictionary, dictionary3, LoadedCustomFiles, "custom icon", out loaded);
			int loaded2;
			bool flag2 = LoadIconGroup(iconConfig.VanillaOverrides, dictionary2, dictionary4, LoadedOverrideFiles, "vanilla icon override", out loaded2);
			for (int i = 0; i < dictionary.Count + dictionary2.Count; i++)
			{
				if (!(RepairFallbackIcons(iconConfig.Icons, dictionary, dictionary3, dictionary2, dictionary) | RepairFallbackIcons(iconConfig.VanillaOverrides, dictionary2, dictionary4, dictionary2, dictionary)))
				{
					break;
				}
			}
			WarnUnresolvedFallbacks(iconConfig.Icons, dictionary, dictionary3);
			WarnUnresolvedFallbacks(iconConfig.VanillaOverrides, dictionary2, dictionary4);
			Dictionary<Sprite, Texture2D> dictionary5 = OwnedImages();
			CustomIcons.Clear();
			IconOverrides.Clear();
			CustomIconScales.Clear();
			VanillaMapOverrides.Clear();
			LocationMapOverrides.Clear();
			LoadedCustomFiles.Clear();
			LoadedOverrideFiles.Clear();
			foreach (KeyValuePair<string, LoadedFile> item in dictionary3)
			{
				LoadedCustomFiles[item.Key] = item.Value;
			}
			foreach (KeyValuePair<string, LoadedFile> item2 in dictionary4)
			{
				LoadedOverrideFiles[item2.Key] = item2.Value;
			}
			foreach (KeyValuePair<string, Sprite> item3 in dictionary)
			{
				CustomIcons[item3.Key] = item3.Value;
				CustomIconScales[item3.Key] = GetEntryScale(item3.Key, iconConfig.Icons, dictionary3);
			}
			foreach (KeyValuePair<string, Sprite> item4 in dictionary2)
			{
				IconOverrides[item4.Key] = item4.Value;
				float entryScale = GetEntryScale(item4.Key, iconConfig.VanillaOverrides, dictionary4);
				CustomIconScales[item4.Key] = entryScale;
				if (Enum.TryParse<PinType>(item4.Key, ignoreCase: true, out PinType result) && Enum.IsDefined(typeof(PinType), result))
				{
					if ((int)result != 8 && (Object)(object)item4.Value != (Object)(object)DefaultIcon)
					{
						VanillaMapOverrides[result] = (item4.Value, entryScale);
					}
				}
				else if ((Object)(object)item4.Value != (Object)(object)DefaultIcon)
				{
					LocationMapOverrides[item4.Key] = (item4.Value, entryScale);
				}
			}
			Dictionary<Sprite, Texture2D> dictionary6 = OwnedImages();
			foreach (KeyValuePair<Sprite, Texture2D> item5 in dictionary5)
			{
				if (!dictionary6.ContainsKey(item5.Key))
				{
					DestroyUnityObject((Object?)(object)item5.Key);
					DestroyUnityObject((Object?)(object)item5.Value);
				}
			}
			AutoMapPinsPlugin.Log.LogInfo((object)$"loaded '{loaded}' custom icons and '{loaded2}' vanilla icon overrides");
			return flag && flag2;
		}

		private static Dictionary<Sprite, Texture2D> OwnedImages()
		{
			Dictionary<Sprite, Texture2D> dictionary = new Dictionary<Sprite, Texture2D>();
			foreach (LoadedFile value in LoadedCustomFiles.Values)
			{
				dictionary[value.Sprite] = value.Texture;
			}
			foreach (LoadedFile value2 in LoadedOverrideFiles.Values)
			{
				dictionary[value2.Sprite] = value2.Texture;
			}
			return dictionary;
		}

		private static float GetEntryScale(string key, Dictionary<string, Config.CustomIconConfig>? configs, Dictionary<string, LoadedFile> files)
		{
			if (files.TryGetValue(key, out LoadedFile value))
			{
				return value.Scale;
			}
			if (configs == null || !configs.TryGetValue(key, out Config.CustomIconConfig value2))
			{
				return 1f;
			}
			return GetConfiguredScale(value2);
		}

		private static void WarnUnresolvedFallbacks(Dictionary<string, Config.CustomIconConfig>? configs, Dictionary<string, Sprite> loaded, Dictionary<string, LoadedFile> files)
		{
			if (configs == null)
			{
				return;
			}
			foreach (KeyValuePair<string, Config.CustomIconConfig> config in configs)
			{
				string text = config.Value?.FallbackIcon;
				if (!string.IsNullOrWhiteSpace(text) && !files.ContainsKey(config.Key) && (!loaded.TryGetValue(config.Key, out Sprite value) || (Object)(object)value == (Object)(object)DefaultIcon))
				{
					AutoMapPinsPlugin.Log.LogWarning((object)("fallback icon '" + text + "' of icon '" + config.Key + "' was not found; using default icon"));
				}
			}
		}

		private static bool RepairFallbackIcons(Dictionary<string, Config.CustomIconConfig>? iconConfigs, Dictionary<string, Sprite> targetGroup, Dictionary<string, LoadedFile> targetFiles, Dictionary<string, Sprite> overridesLookup, Dictionary<string, Sprite> customLookup)
		{
			if (iconConfigs == null)
			{
				return false;
			}
			bool result = false;
			foreach (KeyValuePair<string, Config.CustomIconConfig> iconConfig in iconConfigs)
			{
				Config.CustomIconConfig value = iconConfig.Value;
				if (value != null && !string.IsNullOrWhiteSpace(value.FallbackIcon) && targetGroup.TryGetValue(iconConfig.Key, out Sprite value2) && !targetFiles.ContainsKey(iconConfig.Key))
				{
					string fallbackIcon = value.FallbackIcon;
					if ((overridesLookup.TryGetValue(fallbackIcon, out Sprite value3) || customLookup.TryGetValue(fallbackIcon, out value3) || Icons.TryGetValue(fallbackIcon, out value3)) && (Object)(object)value3 != (Object)(object)DefaultIcon && value3 != value2)
					{
						targetGroup[iconConfig.Key] = value3;
						result = true;
					}
				}
			}
			return result;
		}

		private static bool LoadIconGroup(Dictionary<string, Config.CustomIconConfig>? iconConfigs, Dictionary<string, Sprite> target, Dictionary<string, LoadedFile> loadedFiles, Dictionary<string, LoadedFile> previousFiles, string groupName, out int loaded)
		{
			loaded = 0;
			if (iconConfigs == null || iconConfigs.Count == 0)
			{
				return true;
			}
			bool result = true;
			foreach (KeyValuePair<string, Config.CustomIconConfig> iconConfig in iconConfigs)
			{
				if (string.IsNullOrWhiteSpace(iconConfig.Key))
				{
					AutoMapPinsPlugin.Log.LogWarning((object)("skipping " + groupName + " with empty name"));
					continue;
				}
				Config.CustomIconConfig value = iconConfig.Value;
				target[iconConfig.Key] = DefaultIcon;
				loaded++;
				if (value == null || string.IsNullOrWhiteSpace(value.File))
				{
					if (string.IsNullOrWhiteSpace(value?.FallbackIcon))
					{
						AutoMapPinsPlugin.Log.LogWarning((object)(groupName + " '" + iconConfig.Key + "' defines neither a PNG file nor a fallback icon; using default icon"));
					}
					continue;
				}
				if (TryLoadConfiguredSprite(iconConfig.Key, value.File, out Sprite sprite, out Texture2D texture))
				{
					target[iconConfig.Key] = sprite;
					loadedFiles[iconConfig.Key] = new LoadedFile(sprite, texture, GetConfiguredScale(value));
					continue;
				}
				result = false;
				if (previousFiles.TryGetValue(iconConfig.Key, out LoadedFile value2))
				{
					AutoMapPinsPlugin.Log.LogWarning((object)("keeping last working image and size of " + groupName + " '" + iconConfig.Key + "' until its PNG can be read"));
					target[iconConfig.Key] = value2.Sprite;
					loadedFiles[iconConfig.Key] = value2;
				}
			}
			return result;
		}

		private static bool TryLoadConfiguredSprite(string iconName, string configuredFile, out Sprite sprite, out Texture2D texture)
		{
			sprite = DefaultIcon;
			texture = null;
			string iconPath = configuredFile;
			try
			{
				if (!TryResolveIconPath(configuredFile, out iconPath))
				{
					AutoMapPinsPlugin.Log.LogWarning((object)("icon '" + iconName + "' file path '" + configuredFile + "' is not allowed; using fallback"));
					return false;
				}
				if (!string.Equals(Path.GetExtension(iconPath), ".png", StringComparison.OrdinalIgnoreCase))
				{
					AutoMapPinsPlugin.Log.LogWarning((object)("icon '" + iconName + "' file '" + iconPath + "' is not a PNG file; using fallback"));
					return false;
				}
				if (!File.Exists(iconPath))
				{
					AutoMapPinsPlugin.Log.LogWarning((object)("icon '" + iconName + "' file '" + iconPath + "' does not exist; using fallback"));
					return false;
				}
				Texture2D val = LoadTextureFromRaw(File.ReadAllBytes(iconPath));
				try
				{
					sprite = LoadSpriteFromTexture(val);
					texture = val;
					return true;
				}
				catch
				{
					DestroyUnityObject((Object?)(object)val);
					throw;
				}
			}
			catch (Exception ex)
			{
				AutoMapPinsPlugin.Log.LogWarning((object)("failed loading icon '" + iconName + "' from '" + iconPath + "': " + ex.GetBaseException().Message + "; using fallback"));
				sprite = DefaultIcon;
				return false;
			}
		}

		private static bool TryResolveIconPath(string configuredPath, out string iconPath)
		{
			string fullPath = Path.GetFullPath(Paths.ConfigPath);
			string fullPath2 = Path.GetFullPath(Path.Combine(fullPath, configuredPath));
			string text = fullPath.TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar);
			char directorySeparatorChar = Path.DirectorySeparatorChar;
			string value = text + directorySeparatorChar;
			bool num = fullPath2.StartsWith(value, StringComparison.OrdinalIgnoreCase) || string.Equals(fullPath2, fullPath, StringComparison.OrdinalIgnoreCase);
			iconPath = "";
			if (!num)
			{
				return false;
			}
			string b = fullPath.TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar);
			string text2 = fullPath2;
			while (!string.Equals(text2?.TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar), b, StringComparison.OrdinalIgnoreCase))
			{
				if (string.IsNullOrEmpty(text2))
				{
					return false;
				}
				if ((File.Exists(text2) || Directory.Exists(text2)) && (File.GetAttributes(text2) & FileAttributes.ReparsePoint) != FileAttributes.None)
				{
					return false;
				}
				text2 = Path.GetDirectoryName(text2);
			}
			iconPath = fullPath2;
			return true;
		}

		private static void DestroyUnityObject(Object? unityObject)
		{
			if (!(unityObject == (Object)null))
			{
				Object.Destroy(unityObject);
			}
		}

		private static Texture2D LoadTextureFromRaw(byte[] bytes)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0008: Expected O, but got Unknown
			Texture2D val = new Texture2D(2, 2);
			try
			{
				if (LoadImageMethod == null)
				{
					throw new InvalidOperationException("Could not find UnityEngine.ImageConversion.LoadImage at runtime.");
				}
				object obj = LoadImageMethod.Invoke(null, new object[2] { val, bytes });
				if (obj is bool && !(bool)obj)
				{
					throw new InvalidOperationException("UnityEngine.ImageConversion.LoadImage returned false.");
				}
				return val;
			}
			catch
			{
				DestroyUnityObject((Object?)(object)val);
				throw;
			}
		}

		private static Sprite LoadSpriteFromTexture(Texture2D spriteTexture, float p