Decompiled source of NPCDisabler v1.0.3

NPCDisabler.dll

Decompiled a week ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using Nessie.ATLYSS.EasySettings;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.SceneManagement;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("com.NPCDisabler.sftwre")]
[assembly: AssemblyConfiguration("Debug")]
[assembly: AssemblyFileVersion("1.0.3.0")]
[assembly: AssemblyInformationalVersion("1.0.3+56848eebe45096155e8b6a94f791b119f828ccde")]
[assembly: AssemblyProduct("Player Moderation")]
[assembly: AssemblyTitle("NPCDisabler")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.0.3.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
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;
		}
	}
	[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 NPCDisabler
{
	[BepInPlugin("com.NPCDisabler.sftwre", "NPCDisabler", "1.0.3")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	public class Plugin : BaseUnityPlugin
	{
		public static Plugin Instance;

		internal static ManualLogSource Log;

		private readonly Harmony harmony = new Harmony("com.NPCDisabler.sftwre");

		private const string NpcSection = "NPCs";

		private static readonly char[] InvalidKeyChars = new char[8] { '=', '\n', '\t', '\\', '"', '\'', '[', ']' };

		private static readonly Dictionary<string, ConfigEntry<bool>> NpcToggles = new Dictionary<string, ConfigEntry<bool>>();

		private static ConfigEntry<bool> DisableAllNpcs;

		private static readonly Dictionary<string, List<GameObject>> NpcRegistry = new Dictionary<string, List<GameObject>>();

		private static readonly Dictionary<string, bool> LastAppliedHiddenState = new Dictionary<string, bool>();

		private float _rescanTimer;

		private const float RescanInterval = 5f;

		private bool _settingsInitialized;

		private bool _globalToggleAdded;

		private SettingsTab _modTab;

		private Scene _currentTargetScene;

		private readonly HashSet<string> _npcNamesAddedToTab = new HashSet<string>();

		private void Awake()
		{
			Instance = this;
			Log = ((BaseUnityPlugin)this).Logger;
			harmony.PatchAll();
			DisableAllNpcs = ((BaseUnityPlugin)this).Config.Bind<bool>("Global", "Disable All NetNPCs", false, "Hides every NetNPC discovered in your current map instance, client-side only. Overrides individual NPC toggles below while enabled.");
			DisableAllNpcs.SettingChanged += delegate
			{
				ReapplyHiddenState();
			};
			PreBindKnownNpcs();
			Log.LogInfo((object)string.Format("{0} v{1} Loaded. ({2} known NPC(s) from config)", "NPCDisabler", "1.0.3", NpcToggles.Count));
			SceneManager.sceneLoaded += OnSceneLoaded;
			InitEasySettingsSafe();
		}

		private void OnDestroy()
		{
			SceneManager.sceneLoaded -= OnSceneLoaded;
		}

		private void Update()
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_0008: 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_001a: 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)
			Scene currentMapScene = GetCurrentMapScene();
			if (currentMapScene != _currentTargetScene)
			{
				_currentTargetScene = currentMapScene;
				NpcRegistry.Clear();
				LastAppliedHiddenState.Clear();
				ScanForNetNPCs();
			}
			_rescanTimer += Time.deltaTime;
			if (!(_rescanTimer < 5f))
			{
				_rescanTimer = 0f;
				ScanForNetNPCs();
			}
		}

		private void OnSceneLoaded(Scene scene, LoadSceneMode mode)
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			_currentTargetScene = default(Scene);
		}

		private static string SanitizeKey(string name)
		{
			if (string.IsNullOrEmpty(name))
			{
				return "Unknown";
			}
			string text = string.Concat(name.Select((char c) => InvalidKeyChars.Contains(c) ? '_' : c)).Trim();
			return (text.Length == 0) ? "Unknown" : text;
		}

		private void PreBindKnownNpcs()
		{
			try
			{
				string configFilePath = ((BaseUnityPlugin)this).Config.ConfigFilePath;
				if (string.IsNullOrEmpty(configFilePath) || !File.Exists(configFilePath))
				{
					return;
				}
				List<string> list = new List<string>();
				bool flag = false;
				string[] array = File.ReadAllLines(configFilePath);
				foreach (string text in array)
				{
					string text2 = text.Trim();
					if (text2.Length == 0 || text2.StartsWith("#"))
					{
						continue;
					}
					if (text2.StartsWith("[") && text2.EndsWith("]"))
					{
						flag = text2.Substring(1, text2.Length - 2) == "NPCs";
					}
					else if (flag)
					{
						int num = text2.IndexOf('=');
						if (num > 0)
						{
							list.Add(text2.Substring(0, num).Trim());
						}
					}
				}
				foreach (string item in list)
				{
					EnsureNpcEntry(item);
				}
			}
			catch (Exception ex)
			{
				Log.LogWarning((object)("Failed to pre-bind NPCs from config: " + ex.Message));
			}
		}

		private bool EnsureNpcEntry(string npcName)
		{
			if (NpcToggles.ContainsKey(npcName))
			{
				return false;
			}
			ConfigEntry<bool> val;
			try
			{
				val = ((BaseUnityPlugin)this).Config.Bind<bool>("NPCs", npcName, false, "Hide '" + npcName + "' client-side when encountered. Does not affect other players. Overridden by 'Disable All NetNPCs' above while that's enabled.");
			}
			catch (Exception ex)
			{
				Log.LogWarning((object)("Couldn't bind config for NPC '" + npcName + "': " + ex.Message));
				return false;
			}
			NpcToggles[npcName] = val;
			val.SettingChanged += delegate
			{
				SetNpcHidden(npcName, IsEffectivelyHidden(npcName));
			};
			return true;
		}

		private void InitEasySettingsSafe()
		{
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0017: Expected O, but got Unknown
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Expected O, but got Unknown
			Settings.OnInitialized.AddListener(new UnityAction(OnSettingsInitialized));
			Settings.OnApplySettings.AddListener(new UnityAction(OnSettingsApplied));
		}

		private void OnSettingsInitialized()
		{
			_settingsInitialized = true;
			RefreshSettingsTab();
		}

		private void OnSettingsApplied()
		{
			((BaseUnityPlugin)this).Config.Save();
			ReapplyHiddenState();
			Log.LogInfo((object)"[NPCDisabler] Settings applied and saved.");
		}

		private void RefreshSettingsTab()
		{
			if (_modTab == null)
			{
				_modTab = Settings.GetOrAddCustomTab("NPCDisabler");
			}
			if (_modTab == null)
			{
				Log.LogWarning((object)"Failed to get or add EasySettings tab.");
				return;
			}
			if (!_globalToggleAdded)
			{
				_modTab.AddHeader("Global");
				_modTab.AddToggle("Disable All NetNPCs", DisableAllNpcs);
				_globalToggleAdded = true;
			}
			List<KeyValuePair<string, ConfigEntry<bool>>> list = (from kvp in NpcToggles
				where !_npcNamesAddedToTab.Contains(kvp.Key)
				orderby kvp.Key
				select kvp).ToList();
			if (list.Count > 0 && _npcNamesAddedToTab.Count == 0)
			{
				_modTab.AddHeader("NPCs");
			}
			foreach (KeyValuePair<string, ConfigEntry<bool>> item in list)
			{
				try
				{
					_modTab.AddToggle(item.Key, item.Value);
					_npcNamesAddedToTab.Add(item.Key);
				}
				catch (Exception ex)
				{
					Log.LogWarning((object)("Failed to add toggle for '" + item.Key + "': " + ex.Message));
				}
			}
		}

		private Scene GetCurrentMapScene()
		{
			//IL_0035: Unknown result type (might be due to invalid IL or missing references)
			//IL_003a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0097: Unknown result type (might be due to invalid IL or missing references)
			//IL_009c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0067: Unknown result type (might be due to invalid IL or missing references)
			//IL_006c: 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_0047: Unknown result type (might be due to invalid IL or missing references)
			//IL_009f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0091: 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 ((Object)(object)Player._mainPlayer != (Object)null && (Object)(object)Player._mainPlayer.Network_playerMapInstance != (Object)null)
			{
				Scene scene = ((Component)Player._mainPlayer.Network_playerMapInstance).gameObject.scene;
				if (((Scene)(ref scene)).isLoaded)
				{
					return scene;
				}
			}
			if ((Object)(object)Player._mainPlayer != (Object)null)
			{
				Scene scene2 = ((Component)Player._mainPlayer).gameObject.scene;
				if (((Scene)(ref scene2)).isLoaded && ((Scene)(ref scene2)).name != "DontDestroyOnLoad")
				{
					return scene2;
				}
			}
			return SceneManager.GetActiveScene();
		}

		private void ScanForNetNPCs()
		{
			//IL_0009: 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_007e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0083: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c6: Unknown result type (might be due to invalid IL or missing references)
			Scene targetScene = GetCurrentMapScene();
			if (!((Scene)(ref targetScene)).isLoaded)
			{
				return;
			}
			MapInstance targetInstance = (((Object)(object)Player._mainPlayer != (Object)null) ? Player._mainPlayer.Network_playerMapInstance : null);
			NetNPC[] array = Object.FindObjectsOfType<NetNPC>(true);
			string text = "null";
			string text2 = "null";
			if ((Object)(object)Player._mainPlayer != (Object)null)
			{
				Scene scene = ((Component)Player._mainPlayer).gameObject.scene;
				text = $"{((Scene)(ref scene)).name} (handle={((Scene)(ref scene)).handle})";
				if ((Object)(object)targetInstance != (Object)null)
				{
					Scene scene2 = ((Component)targetInstance).gameObject.scene;
					text2 = $"{((Scene)(ref scene2)).name} (handle={((Scene)(ref scene2)).handle}, instanceID={((Object)targetInstance).GetInstanceID()})";
				}
			}
			Log.LogDebug((object)($"[DEBUG] targetScene={((Scene)(ref targetScene)).name} (handle={((Scene)(ref targetScene)).handle}) | " + "playerScene=" + text + " | assignedMapInstance=" + text2 + " | " + $"totalNetNPCsInMemory={array.Length}"));
			IEnumerable<NetNPC> enumerable = array.Where(delegate(NetNPC npc)
			{
				//IL_003b: 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)
				if ((Object)(object)targetInstance != (Object)null)
				{
					MapInstance componentInParent = ((Component)npc).GetComponentInParent<MapInstance>(true);
					if ((Object)(object)componentInParent != (Object)null)
					{
						return (Object)(object)componentInParent == (Object)(object)targetInstance;
					}
				}
				return ((Component)npc).gameObject.scene == targetScene;
			});
			bool flag = false;
			foreach (NetNPC item in enumerable)
			{
				string npcIdentifier = GetNpcIdentifier(item);
				if (!NpcRegistry.TryGetValue(npcIdentifier, out List<GameObject> value))
				{
					value = new List<GameObject>();
					NpcRegistry[npcIdentifier] = value;
				}
				if (!value.Contains(((Component)item).gameObject))
				{
					value.Add(((Component)item).gameObject);
				}
				if (EnsureNpcEntry(npcIdentifier))
				{
					flag = true;
				}
			}
			if (flag)
			{
				Log.LogInfo((object)string.Format("[{0}] Discovered new NPC type(s); {1} known in total. Scene: {2}", "NPCDisabler", NpcToggles.Count, ((Scene)(ref targetScene)).name));
				if (_settingsInitialized)
				{
					RefreshSettingsTab();
				}
			}
			ReapplyHiddenState();
		}

		private string GetNpcIdentifier(NetNPC npc)
		{
			return SanitizeKey(((Object)((Component)npc).gameObject).name.Replace("(Clone)", string.Empty).Trim());
		}

		private bool IsEffectivelyHidden(string npcName)
		{
			if (DisableAllNpcs.Value)
			{
				return true;
			}
			ConfigEntry<bool> value;
			return NpcToggles.TryGetValue(npcName, out value) && value.Value;
		}

		private void SetNpcHidden(string npcName, bool hide)
		{
			if (!NpcRegistry.TryGetValue(npcName, out List<GameObject> value) || (LastAppliedHiddenState.TryGetValue(npcName, out var value2) && value2 == hide))
			{
				return;
			}
			foreach (GameObject item in value)
			{
				if (!((Object)(object)item == (Object)null))
				{
					ApplyHiddenState(item, hide);
				}
			}
			LastAppliedHiddenState[npcName] = hide;
			Log.LogInfo((object)("[NPCDisabler] " + (hide ? "Hid" : "Restored") + " '" + npcName + "' " + $"({value.Count} instance(s))."));
		}

		private void ApplyHiddenState(GameObject npcGo, bool hide)
		{
			if (!((Object)(object)Player._mainPlayer != (Object)null) || !Player._mainPlayer._isHostPlayer)
			{
				npcGo.SetActive(!hide);
				return;
			}
			Renderer[] componentsInChildren = npcGo.GetComponentsInChildren<Renderer>(true);
			foreach (Renderer val in componentsInChildren)
			{
				val.enabled = !hide;
			}
			Canvas[] componentsInChildren2 = npcGo.GetComponentsInChildren<Canvas>(true);
			foreach (Canvas val2 in componentsInChildren2)
			{
				((Behaviour)val2).enabled = !hide;
			}
			CanvasGroup[] componentsInChildren3 = npcGo.GetComponentsInChildren<CanvasGroup>(true);
			foreach (CanvasGroup val3 in componentsInChildren3)
			{
				((Behaviour)val3).enabled = !hide;
			}
			Animator[] componentsInChildren4 = npcGo.GetComponentsInChildren<Animator>(true);
			foreach (Animator val4 in componentsInChildren4)
			{
				((Behaviour)val4).enabled = !hide;
			}
			Collider[] componentsInChildren5 = npcGo.GetComponentsInChildren<Collider>(true);
			foreach (Collider val5 in componentsInChildren5)
			{
				val5.enabled = !hide;
			}
		}

		private void ReapplyHiddenState()
		{
			foreach (string item in NpcRegistry.Keys.ToList())
			{
				SetNpcHidden(item, IsEffectivelyHidden(item));
			}
		}
	}
	internal static class ModInfo
	{
		public const string GUID = "com.NPCDisabler.sftwre";

		public const string NAME = "NPCDisabler";

		public const string VERSION = "1.0.3";
	}
}
namespace System.Runtime.CompilerServices
{
	[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)]
	internal sealed class IgnoresAccessChecksToAttribute : Attribute
	{
		public IgnoresAccessChecksToAttribute(string assemblyName)
		{
		}
	}
}