Decompiled source of PeakFinder v1.1.0

PeakFinder.dll

Decompiled 14 hours ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using Splatform;
using TMPro;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.UI;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")]
[assembly: AssemblyCompany("PeakFinder")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.1.0.0")]
[assembly: AssemblyInformationalVersion("1.1.0+d86e4fd656406b822b1402834faae9028c6dd06c")]
[assembly: AssemblyProduct("PeakFinder")]
[assembly: AssemblyTitle("PeakFinder")]
[assembly: AssemblyVersion("1.1.0.0")]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace PeakFinder
{
	[HarmonyPatch(typeof(PlayerProfile), "SetStat")]
	internal static class HeightMessages
	{
		private static void Postfix(PlayerProfile __instance, PlayerStatType stat, float amount)
		{
			//IL_002e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0034: Invalid comparison between Unknown and I4
			//IL_0053: Unknown result type (might be due to invalid IL or missing references)
			//IL_0059: Invalid comparison between Unknown and I4
			if (!PeakFinderPlugin.HeightMessages.Value || (Object)(object)Player.m_localPlayer == (Object)null)
			{
				return;
			}
			Game instance = Game.instance;
			if (__instance != ((instance != null) ? instance.GetPlayerProfile() : null))
			{
				return;
			}
			string text;
			if ((int)stat == 131)
			{
				text = Line("Highest build so far", amount, "", "Top of the World", 432f);
			}
			else
			{
				if ((int)stat != 130)
				{
					return;
				}
				text = Line("Tallest build so far", amount, " above the ground", "Mighty Halls", 49f);
			}
			((Character)Player.m_localPlayer).Message((MessageType)1, text, 0, (Sprite)null, false);
		}

		private static string Line(string what, float height, string where, string achievement, float needed)
		{
			if (!(height >= needed))
			{
				return $"{what}: {height:0} m{where} ({achievement} needs {needed:0} m)";
			}
			return $"{what}: {height:0} m{where}, high enough for {achievement}!";
		}
	}
	[HarmonyPatch(typeof(Minimap))]
	internal static class MapPeaks
	{
		private static readonly FieldRef<Minimap, List<PinData>> PinsRef = AccessTools.FieldRefAccess<Minimap, List<PinData>>("m_pins");

		private static readonly Func<Minimap, Vector3, bool> IsExplored = AccessTools.MethodDelegate<Func<Minimap, Vector3, bool>>(AccessTools.Method(typeof(Minimap), "IsExplored", (Type[])null, (Type[])null), (object)null, true);

		private static readonly List<PinData> s_pins = new List<PinData>();

		private static string s_shown = "";

		private static float s_nextCheck;

		[HarmonyPostfix]
		[HarmonyPatch("Update")]
		private unsafe static void UpdatePins(Minimap __instance)
		{
			//IL_00bb: 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_0199: Unknown result type (might be due to invalid IL or missing references)
			//IL_019f: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)Player.m_localPlayer == (Object)null || Time.time < s_nextCheck)
			{
				return;
			}
			s_nextCheck = Time.time + 2f;
			List<PinData> pins = PinsRef.Invoke(__instance);
			bool flag = s_pins.Exists((PinData p) => !pins.Contains(p));
			List<Peak> list = new List<Peak>();
			if (PeakFinderPlugin.ShowPeaks.Value)
			{
				Peaks.EnsureScan();
				foreach (Peak item in Peaks.All)
				{
					if (list.Count >= PeakFinderPlugin.PeakCount.Value)
					{
						break;
					}
					if (!PeakFinderPlugin.OnlyExplored.Value || PeakFinderPlugin.ShowWholeMap.Value || IsExplored(__instance, item.Position))
					{
						list.Add(item);
					}
				}
			}
			string text = string.Join(";", list.ConvertAll((Peak p) => ((object)(*(Vector3*)(&p.Position))/*cast due to .constrained prefix*/).ToString()));
			if (text == s_shown && !flag)
			{
				return;
			}
			foreach (PinData s_pin in s_pins)
			{
				__instance.RemovePin(s_pin);
			}
			s_pins.Clear();
			foreach (Peak item2 in list)
			{
				s_pins.Add(__instance.AddPin(item2.Position, (PinType)3, PinName(item2), false, false, 0L, default(PlatformUserID)));
			}
			s_shown = text;
		}

		private static string PinName(Peak peak)
		{
			float num = 432f - peak.Height;
			if (!(num > 0f))
			{
				return $"Peak {peak.Height:0} m";
			}
			return $"Peak {peak.Height:0} m (+{Mathf.Ceil(num):0} m)";
		}
	}
	[HarmonyPatch(typeof(Minimap))]
	internal static class MapToggles
	{
		private sealed class MapToggle
		{
			public string Label;

			public string Tooltip;

			public ConfigEntry<bool> Setting;

			public RectTransform Panel;

			public Toggle Toggle;
		}

		private const float Spacing = 50f;

		private static readonly FieldRef<Minimap, Material> LargeMapMaterialRef = AccessTools.FieldRefAccess<Minimap, Material>("m_mapLargeShader");

		private static readonly FieldRef<Minimap, Texture2D> FogTextureRef = AccessTools.FieldRefAccess<Minimap, Texture2D>("m_fogTexture");

		private static readonly List<MapToggle> s_toggles = new List<MapToggle>();

		private static bool s_subscribed;

		private static Minimap s_clearedMap;

		private static void Define()
		{
			if (s_toggles.Count <= 0)
			{
				s_toggles.Add(new MapToggle
				{
					Label = "Show high points",
					Tooltip = "Pins on the highest peaks, for Top of the World (build at 432 m)",
					Setting = PeakFinderPlugin.ShowPeaks
				});
				s_toggles.Add(new MapToggle
				{
					Label = "Show whole map",
					Tooltip = "Lift the fog from the whole map while this is on. What you explored doesn't change.",
					Setting = PeakFinderPlugin.ShowWholeMap
				});
			}
		}

		[HarmonyPostfix]
		[HarmonyPatch("Start")]
		private static void CreateToggles(Minimap __instance)
		{
			Define();
			s_clearedMap = null;
			GameObject sharedMapHint = __instance.m_sharedMapHint;
			foreach (MapToggle s_toggle in s_toggles)
			{
				s_toggle.Panel = null;
				s_toggle.Toggle = null;
				if (!((Object)(object)sharedMapHint == (Object)null))
				{
					try
					{
						CreateToggle(sharedMapHint, s_toggle);
					}
					catch (Exception ex)
					{
						PeakFinderPlugin.Log.LogWarning((object)("Couldn't add the '" + s_toggle.Label + "' map toggle (use the config): " + ex.Message));
					}
				}
			}
			if (s_subscribed)
			{
				return;
			}
			s_subscribed = true;
			foreach (MapToggle s_toggle2 in s_toggles)
			{
				MapToggle current3 = s_toggle2;
				current3.Setting.SettingChanged += delegate
				{
					if ((Object)(object)current3.Toggle != (Object)null && current3.Toggle.isOn != current3.Setting.Value)
					{
						current3.Toggle.isOn = current3.Setting.Value;
					}
				};
			}
		}

		private static void CreateToggle(GameObject original, MapToggle mapToggle)
		{
			//IL_01ad: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b3: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d4: Unknown result type (might be due to invalid IL or missing references)
			//IL_01de: Expected O, but got Unknown
			GameObject val = Object.Instantiate<GameObject>(original, original.transform.parent);
			((Object)val).name = "PeakFinder_" + ((ConfigEntryBase)mapToggle.Setting).Definition.Key;
			val.SetActive(true);
			UIGamePad[] componentsInChildren = val.GetComponentsInChildren<UIGamePad>(true);
			foreach (UIGamePad val2 in componentsInChildren)
			{
				if ((Object)(object)val2.m_hint != (Object)null)
				{
					val2.m_hint.SetActive(false);
				}
				Object.Destroy((Object)(object)val2);
			}
			Toggle componentInChildren = val.GetComponentInChildren<Toggle>(true);
			for (int j = 0; j < ((UnityEventBase)componentInChildren.onValueChanged).GetPersistentEventCount(); j++)
			{
				((UnityEventBase)componentInChildren.onValueChanged).SetPersistentListenerState(j, (UnityEventCallState)0);
			}
			componentInChildren.isOn = mapToggle.Setting.Value;
			((UnityEvent<bool>)(object)componentInChildren.onValueChanged).AddListener((UnityAction<bool>)delegate(bool on)
			{
				mapToggle.Setting.Value = on;
			});
			Transform val3 = ((Component)componentInChildren).transform.Find("Label");
			TMP_Text val4 = (((Object)(object)val3 != (Object)null) ? ((Component)val3).GetComponent<TMP_Text>() : val.GetComponentInChildren<TMP_Text>(true));
			if ((Object)(object)val4 != (Object)null)
			{
				Component[] components = ((Component)val4).GetComponents<Component>();
				foreach (Component val5 in components)
				{
					if ((Object)(object)val5 != (Object)null && ((object)val5).GetType().Name == "Localize")
					{
						Object.Destroy((Object)(object)val5);
					}
				}
				val4.text = mapToggle.Label;
			}
			UITooltip[] componentsInChildren2 = val.GetComponentsInChildren<UITooltip>(true);
			for (int i = 0; i < componentsInChildren2.Length; i++)
			{
				componentsInChildren2[i].Set(mapToggle.Label, mapToggle.Tooltip, (RectTransform)null, default(Vector2));
			}
			mapToggle.Panel = (RectTransform)val.transform;
			mapToggle.Toggle = componentInChildren;
		}

		[HarmonyPostfix]
		[HarmonyPatch("Update")]
		private static void UpdateToggles(Minimap __instance)
		{
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			//IL_001e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			//IL_0065: Unknown result type (might be due to invalid IL or missing references)
			GameObject sharedMapHint = __instance.m_sharedMapHint;
			if ((Object)(object)sharedMapHint != (Object)null)
			{
				Vector2 anchoredPosition = ((RectTransform)sharedMapHint.transform).anchoredPosition;
				if (sharedMapHint.activeSelf)
				{
					anchoredPosition.y += 50f;
				}
				foreach (MapToggle s_toggle in s_toggles)
				{
					if (!((Object)(object)s_toggle.Panel == (Object)null))
					{
						s_toggle.Panel.anchoredPosition = anchoredPosition;
						anchoredPosition.y += 50f;
					}
				}
			}
			ShowWholeMap(__instance, PeakFinderPlugin.ShowWholeMap.Value);
		}

		private static void ShowWholeMap(Minimap map, bool show)
		{
			if (show != ((Object)(object)s_clearedMap == (Object)(object)map))
			{
				Material val = LargeMapMaterialRef.Invoke(map);
				if (!((Object)(object)val == (Object)null))
				{
					val.SetTexture("_FogTex", (Texture)(object)(show ? Texture2D.blackTexture : FogTextureRef.Invoke(map)));
					s_clearedMap = (show ? map : null);
				}
			}
		}
	}
	internal struct Peak
	{
		public Vector3 Position;

		public float Height => Position.y;
	}
	internal static class Peaks
	{
		private const float WorldRadius = 10000f;

		private const float Step = 64f;

		private const double BudgetMs = 2.0;

		private const int Candidates = 200;

		private static List<Peak> s_peaks;

		private static int s_seed;

		private static bool s_scanning;

		internal static bool Ready
		{
			get
			{
				if (s_peaks != null && WorldGenerator.instance != null)
				{
					return s_seed == Seed;
				}
				return false;
			}
		}

		internal static List<Peak> All
		{
			get
			{
				if (!Ready)
				{
					return new List<Peak>();
				}
				return s_peaks;
			}
		}

		private static int Seed => (WorldGenerator.instance?.m_world?.m_seed).GetValueOrDefault();

		internal static void EnsureScan()
		{
			if (!Ready && !s_scanning && WorldGenerator.instance != null && !((Object)(object)PeakFinderPlugin.Instance == (Object)null))
			{
				s_scanning = true;
				((MonoBehaviour)PeakFinderPlugin.Instance).StartCoroutine(Scan());
			}
		}

		private static IEnumerator Scan()
		{
			WorldGenerator generator = WorldGenerator.instance;
			int seed = Seed;
			int size = Mathf.CeilToInt(312.5f) + 1;
			float[,] heights = new float[size, size];
			Stopwatch frame = Stopwatch.StartNew();
			for (int i = 0; i < size; i++)
			{
				for (int j = 0; j < size; j++)
				{
					float num = -10000f + (float)i * 64f;
					float num2 = -10000f + (float)j * 64f;
					heights[i, j] = ((num * num + num2 * num2 > 100000000f) ? float.MinValue : generator.GetHeight(num, num2));
				}
				if (frame.Elapsed.TotalMilliseconds > 2.0)
				{
					yield return null;
					if (WorldGenerator.instance != generator)
					{
						s_scanning = false;
						yield break;
					}
					frame.Restart();
				}
			}
			List<Peak> list = new List<Peak>();
			for (int k = 1; k < size - 1; k++)
			{
				for (int l = 1; l < size - 1; l++)
				{
					float num3 = heights[k, l];
					if (num3 <= 100f)
					{
						continue;
					}
					bool flag = true;
					for (int m = -1; m <= 1 && flag; m++)
					{
						for (int n = -1; n <= 1; n++)
						{
							if ((m != 0 || n != 0) && heights[k + m, l + n] > num3)
							{
								flag = false;
								break;
							}
						}
					}
					if (flag)
					{
						list.Add(new Peak
						{
							Position = new Vector3(-10000f + (float)k * 64f, num3, -10000f + (float)l * 64f)
						});
					}
				}
			}
			list.Sort((Peak a, Peak b) => b.Height.CompareTo(a.Height));
			float minDistance = PeakFinderPlugin.MinDistance.Value;
			List<Peak> peaks = new List<Peak>();
			foreach (Peak item2 in list)
			{
				if (peaks.Count >= 200)
				{
					break;
				}
				if (TooClose(peaks, item2.Position, minDistance - 64f))
				{
					continue;
				}
				Peak item = Refine(generator, item2.Position);
				if (!TooClose(peaks, item.Position, minDistance))
				{
					peaks.Add(item);
				}
				if (frame.Elapsed.TotalMilliseconds > 2.0)
				{
					yield return null;
					if (WorldGenerator.instance != generator)
					{
						s_scanning = false;
						yield break;
					}
					frame.Restart();
				}
			}
			peaks.Sort((Peak a, Peak b) => b.Height.CompareTo(a.Height));
			s_peaks = peaks;
			s_seed = seed;
			s_scanning = false;
			PeakFinderPlugin.Log.LogInfo((object)((peaks.Count > 0) ? $"Found {peaks.Count} peaks; the highest is {peaks[0].Height:0} m." : "Found no peaks."));
		}

		private static bool TooClose(List<Peak> peaks, Vector3 position, float distance)
		{
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			foreach (Peak peak in peaks)
			{
				if (Flat(peak.Position - position) < distance)
				{
					return true;
				}
			}
			return false;
		}

		private static Peak Refine(WorldGenerator generator, Vector3 around)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0051: Unknown result type (might be due to invalid IL or missing references)
			//IL_0052: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d3: Unknown result type (might be due to invalid IL or missing references)
			//IL_0061: 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_007e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0088: Unknown result type (might be due to invalid IL or missing references)
			//IL_0094: Unknown result type (might be due to invalid IL or missing references)
			Vector3 val = around;
			(float, float)[] array = new(float, float)[2]
			{
				(64f, 8f),
				(8f, 1f)
			};
			for (int i = 0; i < array.Length; i++)
			{
				(float, float) tuple = array[i];
				float item = tuple.Item1;
				float item2 = tuple.Item2;
				Vector3 val2 = val;
				for (float num = 0f - item; num <= item; num += item2)
				{
					for (float num2 = 0f - item; num2 <= item; num2 += item2)
					{
						float height = generator.GetHeight(val2.x + num, val2.z + num2);
						if (height > val.y)
						{
							((Vector3)(ref val))..ctor(val2.x + num, height, val2.z + num2);
						}
					}
				}
			}
			return new Peak
			{
				Position = val
			};
		}

		private static float Flat(Vector3 v)
		{
			//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_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)
			Vector2 val = new Vector2(v.x, v.z);
			return ((Vector2)(ref val)).magnitude;
		}
	}
	[BepInPlugin("com.koendertjh.peakfinder", "PeakFinder", "1.1.0")]
	public class PeakFinderPlugin : BaseUnityPlugin
	{
		public const string ModGuid = "com.koendertjh.peakfinder";

		public const string ModName = "PeakFinder";

		public const string ModVersion = "1.1.0";

		internal const float TopOfTheWorld = 432f;

		internal const float MightyHalls = 49f;

		internal static ManualLogSource Log;

		internal static PeakFinderPlugin Instance;

		internal static ConfigEntry<bool> ShowPeaks;

		internal static ConfigEntry<int> PeakCount;

		internal static ConfigEntry<float> MinDistance;

		internal static ConfigEntry<bool> OnlyExplored;

		internal static ConfigEntry<bool> ShowWholeMap;

		internal static ConfigEntry<bool> HeightMessages;

		private Harmony _harmony;

		private void Awake()
		{
			//IL_0055: Unknown result type (might be due to invalid IL or missing references)
			//IL_005f: Expected O, but got Unknown
			//IL_0092: Unknown result type (might be due to invalid IL or missing references)
			//IL_009c: Expected O, but got Unknown
			//IL_0107: Unknown result type (might be due to invalid IL or missing references)
			//IL_0111: Expected O, but got Unknown
			Log = ((BaseUnityPlugin)this).Logger;
			Instance = this;
			ShowPeaks = ((BaseUnityPlugin)this).Config.Bind<bool>("1 - Map", "ShowPeaks", false, "Show the highest peaks on the map. Also switched with the toggle on the big map.");
			PeakCount = ((BaseUnityPlugin)this).Config.Bind<int>("1 - Map", "PeakCount", 10, new ConfigDescription("Number of peaks to show.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(1, 50), Array.Empty<object>()));
			MinDistance = ((BaseUnityPlugin)this).Config.Bind<float>("1 - Map", "MinDistance", 500f, new ConfigDescription("Peaks are at least this many metres apart, so one mountain doesn't fill the list.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(100f, 3000f), Array.Empty<object>()));
			OnlyExplored = ((BaseUnityPlugin)this).Config.Bind<bool>("1 - Map", "OnlyExplored", true, "Only show peaks in parts of the map you (or players you shared the map with) have explored. Ignored while ShowWholeMap is on.");
			ShowWholeMap = ((BaseUnityPlugin)this).Config.Bind<bool>("1 - Map", "ShowWholeMap", false, "Lift the fog from the whole big map while this is on; what you explored doesn't change. Also switched with the toggle on the big map.");
			HeightMessages = ((BaseUnityPlugin)this).Config.Bind<bool>("2 - Messages", "HeightMessages", true, "A message when you place your highest or tallest piece so far, with how far you are from Top of the World (432 m) and Mighty Halls (49 m).");
			_harmony = new Harmony("com.koendertjh.peakfinder");
			_harmony.PatchAll(typeof(PeakFinderPlugin).Assembly);
		}

		private void OnDestroy()
		{
			Harmony harmony = _harmony;
			if (harmony != null)
			{
				harmony.UnpatchSelf();
			}
		}
	}
	internal static class PluginInfo
	{
		public const string Version = "1.1.0";
	}
}