Decompiled source of ShowAllPossibleNewtLocations v1.1.0

ShowAllPossibleNewtLocations.dll

Decompiled a month 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.Bootstrap;
using BepInEx.Configuration;
using Microsoft.CodeAnalysis;
using RoR2;
using RoR2.UI;
using UnityEngine;
using UnityEngine.SceneManagement;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("ShowAllPossibleNewtLocations")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.1.0.0")]
[assembly: AssemblyInformationalVersion("1.1.0")]
[assembly: AssemblyProduct("ShowAllPossibleNewtLocations")]
[assembly: AssemblyTitle("ShowAllPossibleNewtLocations")]
[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 NewtRoutes
{
	internal sealed class ScenePoints
	{
		internal readonly List<Vector3> Real = new List<Vector3>();

		internal readonly List<Vector3> All = new List<Vector3>();
	}
	internal static class CandidateCollector
	{
		internal static bool IsAltarModel(string name)
		{
			if (!string.Equals(name, "mdlNewtStatue", StringComparison.OrdinalIgnoreCase) && !string.Equals(name, "mdlNewtStatue(Clone)", StringComparison.OrdinalIgnoreCase))
			{
				return name?.StartsWith("mdlNewtStatue (", StringComparison.OrdinalIgnoreCase) ?? false;
			}
			return true;
		}

		internal static bool BelongsToRealAltar(Transform model)
		{
			Transform val = model;
			while ((Object)(object)val != (Object)null)
			{
				if ((Object)(object)((Component)val).GetComponent<PortalStatueBehavior>() != (Object)null)
				{
					return true;
				}
				val = val.parent;
			}
			return false;
		}

		internal static ScenePoints Collect(Scene scene)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			ScenePoints scenePoints = new ScenePoints();
			CollectInto(scene, scenePoints);
			return scenePoints;
		}

		internal static void CollectInto(Scene scene, ScenePoints points)
		{
			//IL_0042: Unknown result type (might be due to invalid IL or missing references)
			//IL_0047: Unknown result type (might be due to invalid IL or missing references)
			//IL_004f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0066: Unknown result type (might be due to invalid IL or missing references)
			if (!((Scene)(ref scene)).IsValid() || !((Scene)(ref scene)).isLoaded)
			{
				return;
			}
			GameObject[] rootGameObjects = ((Scene)(ref scene)).GetRootGameObjects();
			for (int i = 0; i < rootGameObjects.Length; i++)
			{
				Transform[] componentsInChildren = rootGameObjects[i].GetComponentsInChildren<Transform>(true);
				foreach (Transform val in componentsInChildren)
				{
					if (IsAltarModel(((Object)val).name))
					{
						Vector3 position = val.position;
						AddUnique(points.All, position);
						if (BelongsToRealAltar(val))
						{
							AddUnique(points.Real, position);
						}
					}
				}
			}
		}

		internal static bool AddUnique(List<Vector3> points, Vector3 point)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			//IL_001a: 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_0034: Unknown result type (might be due to invalid IL or missing references)
			//IL_0041: Unknown result type (might be due to invalid IL or missing references)
			//IL_005b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0060: 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_0066: Unknown result type (might be due to invalid IL or missing references)
			//IL_0093: Unknown result type (might be due to invalid IL or missing references)
			if (float.IsNaN(point.x) || float.IsNaN(point.y) || float.IsNaN(point.z) || float.IsInfinity(point.x) || float.IsInfinity(point.y) || float.IsInfinity(point.z))
			{
				return false;
			}
			foreach (Vector3 point2 in points)
			{
				Vector3 val = point2 - point;
				if (((Vector3)(ref val)).sqrMagnitude < 0.25f)
				{
					return false;
				}
			}
			points.Add(point);
			return true;
		}

		internal static bool SamePoints(List<Vector3> first, List<Vector3> second)
		{
			//IL_0016: 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_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)
			if (first.Count != second.Count)
			{
				return false;
			}
			for (int i = 0; i < first.Count; i++)
			{
				Vector3 val = first[i] - second[i];
				if (((Vector3)(ref val)).sqrMagnitude >= 0.25f)
				{
					return false;
				}
			}
			return true;
		}
	}
	[BepInPlugin("com.slapprt.newtroutes", "ShowAllPossibleNewtLocations", "1.1.0")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	public sealed class NewtRoutesPlugin : BaseUnityPlugin
	{
		public const string Guid = "com.slapprt.newtroutes";

		public const string Version = "1.1.0";

		private const string LocateNewtGuid = "com.yourname.NewtAltarBeacon";

		private const string IndicatorPath = "Prefabs/PositionIndicators/TeleporterChargingPositionIndicator";

		private const int MinRealAltars = 2;

		private static readonly string[] StagesWithoutNewtAltars = new string[3] { "bazaar", "limbo", "mysteryspace" };

		private readonly Dictionary<int, ScenePoints> candidatesByScene = new Dictionary<int, ScenePoints>();

		private readonly List<GameObject> markers = new List<GameObject>();

		private ConfigEntry<float> iconScale;

		private Coroutine refreshCoroutine;

		private Action<Stage> originalLocateNewtHandler;

		private BaseUnityPlugin originalLocateNewt;

		private void Awake()
		{
			//IL_002f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0039: Expected O, but got Unknown
			iconScale = ((BaseUnityPlugin)this).Config.Bind<float>("Markers", "IconScale", 0.5f, new ConfigDescription("Icon width and height relative to LocateNewt/vanilla. 0.5 = 50% smaller.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.1f, 2f), Array.Empty<object>()));
			iconScale.SettingChanged += OnScaleChanged;
			SuppressOriginalLocator();
			SceneManager.sceneLoaded += OnSceneLoaded;
			SceneManager.sceneUnloaded += OnSceneUnloaded;
			Stage.onStageStartGlobal += OnStageStart;
			Run.onRunDestroyGlobal += OnRunDestroyed;
			((BaseUnityPlugin)this).Logger.LogInfo((object)("ShowAllPossibleNewtLocations 1.1.0: todos os pontos possíveis, sem revelar o altar sorteado. Escala: " + iconScale.Value));
		}

		private void OnDestroy()
		{
			SceneManager.sceneLoaded -= OnSceneLoaded;
			SceneManager.sceneUnloaded -= OnSceneUnloaded;
			Stage.onStageStartGlobal -= OnStageStart;
			Run.onRunDestroyGlobal -= OnRunDestroyed;
			if (iconScale != null)
			{
				iconScale.SettingChanged -= OnScaleChanged;
			}
			OnRunDestroyed(null);
			if ((Object)(object)originalLocateNewt != (Object)null && originalLocateNewtHandler != null)
			{
				Stage.onStageStartGlobal += originalLocateNewtHandler;
			}
		}

		private void SuppressOriginalLocator()
		{
			if (!Chainloader.PluginInfos.TryGetValue("com.yourname.NewtAltarBeacon", out var value))
			{
				return;
			}
			try
			{
				BaseUnityPlugin instance = value.Instance;
				MethodInfo method = ((object)instance).GetType().GetMethod("OnStageStart", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, new Type[1] { typeof(Stage) }, null);
				if (method == null)
				{
					throw new MissingMethodException("LocateNewt.OnStageStart");
				}
				Action<Stage> action = (Action<Stage>)Delegate.CreateDelegate(typeof(Action<Stage>), instance, method);
				Stage.onStageStartGlobal -= action;
				originalLocateNewt = instance;
				originalLocateNewtHandler = action;
				object? obj = ((object)instance).GetType().GetField("altarIndicator", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)?.GetValue(instance);
				Component val = (Component)((obj is Component) ? obj : null);
				if ((Object)(object)val != (Object)null)
				{
					Object.Destroy((Object)(object)val.gameObject);
				}
				((BaseUnityPlugin)this).Logger.LogInfo((object)"Marcador do LocateNewt original suprimido nesta sessão; DLL original preservada.");
			}
			catch (Exception ex)
			{
				((BaseUnityPlugin)this).Logger.LogError((object)("Não foi possível suprimir esta versão do LocateNewt. Desative-o no gerenciador para não revelar o altar real. " + ex.Message));
			}
		}

		private void OnSceneLoaded(Scene scene, LoadSceneMode mode)
		{
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			candidatesByScene[((Scene)(ref scene)).handle] = CandidateCollector.Collect(scene);
		}

		private void OnSceneUnloaded(Scene scene)
		{
			candidatesByScene.Remove(((Scene)(ref scene)).handle);
			ClearMarkers();
			if (CanShowForStage(Stage.instance))
			{
				BuildMarkers();
			}
		}

		private void OnStageStart(Stage stage)
		{
			ClearMarkers();
			if (refreshCoroutine != null)
			{
				((MonoBehaviour)this).StopCoroutine(refreshCoroutine);
			}
			refreshCoroutine = ((MonoBehaviour)this).StartCoroutine(RefreshStage(stage));
		}

		private IEnumerator RefreshStage(Stage stage)
		{
			yield return null;
			if (!CanShowForStage(stage))
			{
				refreshCoroutine = null;
				yield break;
			}
			ScanLoadedScenes();
			BuildMarkers();
			yield return (object)new WaitForSecondsRealtime(1f);
			if (CanShowForStage(stage))
			{
				List<Vector3> candidatePoints = GetCandidatePoints();
				ScanLoadedScenes();
				bool usedAllModels;
				List<Vector3> candidatePoints2 = GetCandidatePoints(out usedAllModels);
				if (!CandidateCollector.SamePoints(candidatePoints, candidatePoints2))
				{
					BuildMarkers();
				}
				string format = (usedAllModels ? "{0}: {1} locais possíveis marcados (mapa sem altares do jogo suficientes; usando todos os modelos de altar)." : "{0}: {1} locais possíveis marcados.");
				((BaseUnityPlugin)this).Logger.LogInfo((object)string.Format(format, stage.sceneDef.baseSceneName, markers.Count));
			}
			refreshCoroutine = null;
		}

		private static bool CanShowForStage(Stage stage)
		{
			if ((Object)(object)Run.instance == (Object)null || (Object)(object)stage == (Object)null || (Object)(object)Stage.instance != (Object)(object)stage || (Object)(object)stage.sceneDef == (Object)null)
			{
				return false;
			}
			string baseSceneName = stage.sceneDef.baseSceneName;
			string[] stagesWithoutNewtAltars = StagesWithoutNewtAltars;
			foreach (string b in stagesWithoutNewtAltars)
			{
				if (string.Equals(baseSceneName, b, StringComparison.OrdinalIgnoreCase))
				{
					return false;
				}
			}
			return true;
		}

		private void ScanLoadedScenes()
		{
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			//IL_000a: Unknown result type (might be due to invalid IL or missing references)
			//IL_004c: Unknown result type (might be due to invalid IL or missing references)
			for (int i = 0; i < SceneManager.sceneCount; i++)
			{
				Scene sceneAt = SceneManager.GetSceneAt(i);
				if (((Scene)(ref sceneAt)).IsValid() && ((Scene)(ref sceneAt)).isLoaded)
				{
					if (!candidatesByScene.TryGetValue(((Scene)(ref sceneAt)).handle, out var value))
					{
						value = new ScenePoints();
						candidatesByScene.Add(((Scene)(ref sceneAt)).handle, value);
					}
					CandidateCollector.CollectInto(sceneAt, value);
				}
			}
		}

		private List<Vector3> GetCandidatePoints()
		{
			bool usedAllModels;
			return GetCandidatePoints(out usedAllModels);
		}

		private List<Vector3> GetCandidatePoints(out bool usedAllModels)
		{
			//IL_0038: Unknown result type (might be due to invalid IL or missing references)
			//IL_003d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0040: Unknown result type (might be due to invalid IL or missing references)
			//IL_0072: Unknown result type (might be due to invalid IL or missing references)
			//IL_0077: Unknown result type (might be due to invalid IL or missing references)
			//IL_007a: Unknown result type (might be due to invalid IL or missing references)
			List<Vector3> list = new List<Vector3>();
			List<Vector3> list2 = new List<Vector3>();
			foreach (ScenePoints value in candidatesByScene.Values)
			{
				foreach (Vector3 item in value.Real)
				{
					CandidateCollector.AddUnique(list, item);
				}
				foreach (Vector3 item2 in value.All)
				{
					CandidateCollector.AddUnique(list2, item2);
				}
			}
			if (list.Count >= 2)
			{
				usedAllModels = false;
				return list;
			}
			usedAllModels = list2.Count > list.Count;
			return list2;
		}

		private void BuildMarkers()
		{
			//IL_0049: Unknown result type (might be due to invalid IL or missing references)
			//IL_004e: 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_0051: Unknown result type (might be due to invalid IL or missing references)
			//IL_005b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0060: 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)
			//IL_00bf: 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_0184: Unknown result type (might be due to invalid IL or missing references)
			ClearMarkers();
			GameObject val = LegacyResourcesAPI.Load<GameObject>("Prefabs/PositionIndicators/TeleporterChargingPositionIndicator");
			if ((Object)(object)val == (Object)null)
			{
				((BaseUnityPlugin)this).Logger.LogError((object)"Indicador nativo indisponível.");
				return;
			}
			Sprite val2 = LegacyResourcesAPI.Load<Sprite>("Textures/MiscIcons/texShopPortalIcon");
			foreach (Vector3 candidatePoint in GetCandidatePoints())
			{
				GameObject val3 = Object.Instantiate<GameObject>(val, candidatePoint + Vector3.up * 2f, Quaternion.identity);
				((Object)val3).name = "NewtRoutes_Candidate";
				markers.Add(val3);
				PositionIndicator component = val3.GetComponent<PositionIndicator>();
				if ((Object)(object)component == (Object)null)
				{
					Object.Destroy((Object)(object)val3);
					continue;
				}
				component.targetTransform = null;
				val3.transform.localScale = val3.transform.localScale * iconScale.Value;
				ChargeIndicatorController[] componentsInChildren = val3.GetComponentsInChildren<ChargeIndicatorController>(true);
				SpriteRenderer[] iconSprites;
				foreach (ChargeIndicatorController val4 in componentsInChildren)
				{
					((Behaviour)val4).enabled = false;
					if ((Object)(object)val4.chargingText != (Object)null)
					{
						((Component)val4.chargingText).gameObject.SetActive(false);
					}
					if (!((Object)(object)val2 != (Object)null) || val4.iconSprites == null)
					{
						continue;
					}
					iconSprites = val4.iconSprites;
					foreach (SpriteRenderer val5 in iconSprites)
					{
						if ((Object)(object)val5 != (Object)null)
						{
							val5.sprite = val2;
						}
					}
				}
				iconSprites = val3.GetComponentsInChildren<SpriteRenderer>(true);
				for (int i = 0; i < iconSprites.Length; i++)
				{
					iconSprites[i].color = Color.cyan;
				}
			}
		}

		private void OnScaleChanged(object sender, EventArgs args)
		{
			if (CanShowForStage(Stage.instance))
			{
				BuildMarkers();
			}
		}

		private void ClearMarkers()
		{
			foreach (GameObject marker in markers)
			{
				if ((Object)(object)marker != (Object)null)
				{
					Object.Destroy((Object)(object)marker);
				}
			}
			markers.Clear();
		}

		private void OnRunDestroyed(Run run)
		{
			if (refreshCoroutine != null)
			{
				((MonoBehaviour)this).StopCoroutine(refreshCoroutine);
			}
			refreshCoroutine = null;
			ClearMarkers();
			candidatesByScene.Clear();
		}
	}
}