Decompiled source of AutoDoors v1.0.20

AutoDoors.dll

Decompiled 3 weeks 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 System.Text;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("AutoDoors")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0")]
[assembly: AssemblyProduct("AutoDoors")]
[assembly: AssemblyTitle("AutoDoors")]
[assembly: AssemblyVersion("1.0.0.0")]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace AutoDoors
{
	[BepInPlugin("zenox.autodoors", "AutoDoors", "1.0.20")]
	public class AutoDoorsPlugin : BaseUnityPlugin
	{
		private class DoorTracking
		{
			public bool WasInRange;

			public bool OpenedByMod;

			public bool IsManual;

			public bool WasOpenLastTick;

			public float OutOfRangeTimer;

			public bool SuppressNextEffect;

			public List<Door> Partners;

			public float PartnersLastScanned = -999f;

			public float LastCloseSuppressLogTime = -999f;
		}

		[HarmonyPatch(typeof(Door), "Interact")]
		private static class Door_Interact_ShiftLock_Patch
		{
			private static bool Prefix(Door __instance, Humanoid character, bool hold, bool alt)
			{
				if (!alt || hold || !AllowShiftELock.Value)
				{
					return true;
				}
				ZNetView component = ((Component)__instance).GetComponent<ZNetView>();
				if ((Object)(object)component == (Object)null || !component.IsValid())
				{
					return true;
				}
				component.ClaimOwnership();
				ZDO zDO = component.GetZDO();
				bool flag = !zDO.GetBool("AutoDoorsLocked", false);
				zDO.Set("AutoDoorsLocked", flag);
				((Character)character).Message((MessageType)2, flag ? "Door: auto open/close OFF (Shift+E to re-enable)" : "Door: auto open/close ON", 0, (Sprite)null, false);
				return false;
			}
		}

		[HarmonyPatch(typeof(Door), "UpdateState")]
		private static class Door_UpdateState_Patch
		{
			private static void Postfix(Door __instance)
			{
				if ((Object)(object)Instance != (Object)null)
				{
					Instance.RegisterDoor(__instance);
				}
			}
		}

		[HarmonyPatch(typeof(Door), "SetState")]
		private static class Door_SetState_MuteSound_Patch
		{
			private static readonly FieldInfo AnimatorField = AccessTools.Field(typeof(Door), "m_animator");

			private static bool Prefix(Door __instance, int state)
			{
				//IL_003d: Unknown result type (might be due to invalid IL or missing references)
				//IL_0043: Expected O, but got Unknown
				if ((Object)(object)Instance == (Object)null || !Instance.trackedDoors.TryGetValue(__instance, out var value) || !value.SuppressNextEffect)
				{
					return true;
				}
				value.SuppressNextEffect = false;
				Animator val = (Animator)AnimatorField.GetValue(__instance);
				if (val.GetInteger("state") != state)
				{
					val.SetInteger("state", state);
				}
				if ((Object)(object)__instance.m_openEnable != (Object)null)
				{
					__instance.m_openEnable.SetActive(state != 0);
				}
				return false;
			}
		}

		public const string PluginGUID = "zenox.autodoors";

		public const string PluginName = "AutoDoors";

		public const string PluginVersion = "1.0.20";

		public static AutoDoorsPlugin Instance;

		public static ConfigEntry<bool> ModEnabled;

		public static ConfigEntry<float> RangeMultiplier;

		public static ConfigEntry<float> UpdateInterval;

		public static ConfigEntry<bool> IgnoreLockedDoors;

		public static ConfigEntry<float> CloseDelaySeconds;

		public static ConfigEntry<bool> MuteAutoDoorSound;

		public static ConfigEntry<bool> PairDoubleDoors;

		public static ConfigEntry<float> MaxPairDistance;

		public static ConfigEntry<bool> PauseDuringRaids;

		public static ConfigEntry<bool> AllowShiftELock;

		private const string LockedZdoKey = "AutoDoorsLocked";

		public static ConfigEntry<bool> PauseOpenDuringRaids;

		public static ConfigEntry<string> ExcludePrefabNames;

		private readonly Harmony harmony = new Harmony("zenox.autodoors");

		private readonly Dictionary<Door, DoorTracking> trackedDoors = new Dictionary<Door, DoorTracking>();

		private float timeSinceLastCheck;

		private readonly Dictionary<Door, (int state, bool inRange, bool inCloseRange)> tickData = new Dictionary<Door, (int, bool, bool)>();

		private void Awake()
		{
			ConfigLogDump.Schedule((BaseUnityPlugin)(object)this, ((BaseUnityPlugin)this).Logger);
			Instance = this;
			ModEnabled = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "Enabled", true, "Enable/disable automatic opening and closing of doors and gates.");
			RangeMultiplier = ((BaseUnityPlugin)this).Config.Bind<float>("General", "RangeMultiplier", 1f, "Multiplier applied to the player's normal interaction distance to decide how close you need to be for a door to open automatically.");
			UpdateInterval = ((BaseUnityPlugin)this).Config.Bind<float>("General", "UpdateInterval", 0.1f, "Minimum time in seconds between range checks. Lower = more responsive, higher = better performance.");
			IgnoreLockedDoors = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "IgnoreLockedDoors", true, "If true, doors that require a key are left alone (you still need to unlock them by hand).");
			CloseDelaySeconds = ((BaseUnityPlugin)this).Config.Bind<float>("General", "CloseDelaySeconds", 0.5f, "Seconds to wait after leaving range before auto-closing a door. 0 = close immediately (original behavior).");
			MuteAutoDoorSound = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "MuteAutoDoorSound", false, "If true, suppresses the door's open/close sound and particle effect when triggered automatically by this mod. Doors opened/closed by hand still play the normal sound.");
			PairDoubleDoors = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "PairDoubleDoors", true, "If true, two door pieces snapped close together (a double door) are treated as one unit: if either half would open, both open; both only close once neither half is in range/facing anymore.");
			MaxPairDistance = ((BaseUnityPlugin)this).Config.Bind<float>("General", "MaxPairDistance", 2.5f, "Max gap in meters between two door/gate pieces (measured between their own edges, not their pivots) to be treated as a double-door pair. Only used if PairDoubleDoors is true.");
			PauseDuringRaids = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "PauseDuringRaids", false, "If true, no door is auto-opened or auto-closed while a raid/random event (troll attack, skeleton surprise, etc.) is active - every door just stays in whatever state it's already in until the event ends. Useful for gates/portcullises/drawbridges that would otherwise flicker open/closed as monsters run past them during an attack.");
			AllowShiftELock = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "AllowShiftELock", true, "If true, pressing Shift+E on a door toggles auto open/close for that single door (saved with the door).");
			PauseOpenDuringRaids = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "PauseOpenDuringRaids", false, "Only used if PauseDuringRaids is true. If true, doors are also not auto-OPENED during a raid (the whole open/close logic is paused, doors stay as they are). If false (default), only auto-closing is paused, so doors still open for you. Turn this on if you'd rather keep gates from being left open for mobs when you walk past during an attack.");
			ExcludePrefabNames = ((BaseUnityPlugin)this).Config.Bind<string>("General", "ExcludePrefabNames", "", "Comma-separated, case-insensitive prefab name substrings (e.g. from another mod's gates/portcullises/drawbridges, such as More Gates Extended) that this mod should never auto-open or auto-close. Checked against the piece's prefab name, not the display name shown in-game.");
			ExcludePrefabNames.SettingChanged += OnExcludePrefabNamesChanged;
			harmony.PatchAll(Assembly.GetExecutingAssembly());
			((BaseUnityPlugin)this).Logger.LogInfo((object)"AutoDoors v1.0.20 loaded.");
		}

		private void OnDestroy()
		{
			Harmony obj = harmony;
			if (obj != null)
			{
				obj.UnpatchSelf();
			}
		}

		internal void RegisterDoor(Door door)
		{
			if (!trackedDoors.ContainsKey(door) && !IsExcludedPrefab(door))
			{
				trackedDoors[door] = new DoorTracking();
			}
		}

		private void OnExcludePrefabNamesChanged(object sender, EventArgs e)
		{
			List<Door> list = null;
			foreach (Door key in trackedDoors.Keys)
			{
				if ((Object)(object)key != (Object)null && IsExcludedPrefab(key))
				{
					(list ?? (list = new List<Door>())).Add(key);
				}
			}
			if (list == null)
			{
				return;
			}
			foreach (Door item in list)
			{
				trackedDoors.Remove(item);
			}
			((BaseUnityPlugin)this).Logger.LogInfo((object)$"[AutoDoors] ExcludePrefabNames changed - stopped auto-controlling {list.Count} already-tracked door(s) that now match it.");
		}

		private static string StripClone(string rawName)
		{
			int num = rawName.IndexOf("(Clone)", StringComparison.Ordinal);
			if (num < 0)
			{
				return rawName;
			}
			return rawName.Substring(0, num);
		}

		private static bool IsExcludedPrefab(Door door)
		{
			string value = ExcludePrefabNames.Value;
			if (string.IsNullOrWhiteSpace(value))
			{
				return false;
			}
			List<string> list = new List<string>();
			Transform val = ((Component)door).transform;
			while ((Object)(object)val != (Object)null)
			{
				list.Add(StripClone(((Object)((Component)val).gameObject).name));
				val = val.parent;
			}
			ZNetView componentInParent = ((Component)door).GetComponentInParent<ZNetView>();
			if ((Object)(object)componentInParent != (Object)null)
			{
				list.Add(StripClone(((Object)((Component)componentInParent).gameObject).name));
			}
			string[] array = value.Split(',');
			for (int i = 0; i < array.Length; i++)
			{
				string text = array[i].Trim();
				if (text.Length == 0)
				{
					continue;
				}
				foreach (string item in list)
				{
					if (item.IndexOf(text, StringComparison.OrdinalIgnoreCase) >= 0)
					{
						return true;
					}
				}
			}
			return false;
		}

		private static Vector3 GetClosestDoorPoint(Component door, Vector3 playerPos)
		{
			//IL_001d: 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_0016: Unknown result type (might be due to invalid IL or missing references)
			Collider componentInChildren = door.GetComponentInChildren<Collider>();
			if (!((Object)(object)componentInChildren != (Object)null))
			{
				return door.transform.position;
			}
			return componentInChildren.ClosestPoint(playerPos);
		}

		private void Update()
		{
			//IL_00bb: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c0: 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_01b8: Unknown result type (might be due to invalid IL or missing references)
			//IL_01be: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c3: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d8: Unknown result type (might be due to invalid IL or missing references)
			//IL_01dd: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e3: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e8: Unknown result type (might be due to invalid IL or missing references)
			if (!ModEnabled.Value)
			{
				return;
			}
			Player localPlayer = Player.m_localPlayer;
			if ((Object)(object)localPlayer == (Object)null || ((Character)localPlayer).IsDead())
			{
				return;
			}
			bool flag = PauseDuringRaids.Value && (Object)(object)RandEventSystem.instance != (Object)null && RandEventSystem.instance.GetCurrentRandomEvent() != null;
			timeSinceLastCheck += Time.deltaTime;
			if (timeSinceLastCheck < UpdateInterval.Value)
			{
				return;
			}
			timeSinceLastCheck = 0f;
			float num = localPlayer.m_maxInteractDistance * RangeMultiplier.Value;
			float num2 = num * num;
			float num3 = num * 1.15f;
			float closeRadiusSq = num3 * num3;
			Vector3 playerPos = ((Component)localPlayer).transform.position;
			List<Door> list = null;
			tickData.Clear();
			foreach (KeyValuePair<Door, DoorTracking> trackedDoor in trackedDoors)
			{
				Door key = trackedDoor.Key;
				DoorTracking value = trackedDoor.Value;
				if ((Object)(object)key == (Object)null)
				{
					(list ?? (list = new List<Door>())).Add(key);
					continue;
				}
				ZNetView component = ((Component)key).GetComponent<ZNetView>();
				if ((Object)(object)component == (Object)null || !component.IsValid())
				{
					continue;
				}
				ZDO zDO = component.GetZDO();
				int num4 = zDO.GetInt("state", 0);
				if ((IgnoreLockedDoors.Value && (Object)(object)key.m_keyItem != (Object)null) || (AllowShiftELock.Value && zDO.GetBool("AutoDoorsLocked", false)))
				{
					continue;
				}
				if (PairDoubleDoors.Value)
				{
					ScanForPartners(key, value);
				}
				bool flag2 = Vector3.SqrMagnitude(GetClosestDoorPoint((Component)(object)key, playerPos) - playerPos) <= num2;
				bool flag3 = Vector3.SqrMagnitude(GetClosestDoorPoint((Component)(object)key, playerPos) - playerPos) <= closeRadiusSq;
				if (flag2)
				{
					if (!value.WasInRange)
					{
						if (num4 != 0 && !value.OpenedByMod)
						{
							value.IsManual = true;
						}
						else
						{
							value.IsManual = false;
						}
					}
					else if (value.OpenedByMod && value.WasOpenLastTick && num4 == 0)
					{
						value.IsManual = true;
						value.OpenedByMod = false;
					}
				}
				else if (num4 == 0)
				{
					value.OpenedByMod = false;
					value.IsManual = false;
				}
				bool flag4 = value.Partners != null && value.Partners.Exists((Door p) => (Object)(object)p != (Object)null && Vector3.SqrMagnitude(GetClosestDoorPoint((Component)(object)p, playerPos) - playerPos) <= closeRadiusSq);
				if (flag3 || flag4)
				{
					value.OutOfRangeTimer = 0f;
				}
				else
				{
					value.OutOfRangeTimer += UpdateInterval.Value;
				}
				tickData[key] = (num4, flag2, flag3);
				value.WasOpenLastTick = num4 != 0;
				value.WasInRange = flag2;
			}
			foreach (KeyValuePair<Door, (int, bool, bool)> tickDatum in tickData)
			{
				Door key2 = tickDatum.Key;
				(int, bool, bool) value2 = tickDatum.Value;
				int item = value2.Item1;
				bool item2 = value2.Item2;
				bool item3 = value2.Item3;
				DoorTracking doorTracking = trackedDoors[key2];
				(int, bool, bool) value3;
				bool flag5 = doorTracking.Partners != null && doorTracking.Partners.Exists((Door p) => tickData.TryGetValue(p, out value3) && value3.Item2);
				bool num5 = item2 || flag5;
				bool flag6 = doorTracking.Partners != null && doorTracking.Partners.Exists((Door p) => tickData.TryGetValue(p, out value3) && value3.Item3);
				bool flag7 = item3 || flag6;
				if (num5 && !doorTracking.IsManual && item == 0 && (!flag || !PauseOpenDuringRaids.Value))
				{
					if (MuteAutoDoorSound.Value)
					{
						doorTracking.SuppressNextEffect = true;
					}
					key2.Interact((Humanoid)(object)localPlayer, false, false);
					doorTracking.OpenedByMod = true;
				}
				if (flag7 || flag)
				{
					continue;
				}
				bool flag8 = doorTracking.Partners == null || doorTracking.Partners.TrueForAll((Door p) => !tickData.TryGetValue(p, out value3) || !value3.Item3);
				if (doorTracking.IsManual || !doorTracking.OpenedByMod || item == 0 || !(doorTracking.OutOfRangeTimer >= CloseDelaySeconds.Value))
				{
					continue;
				}
				if (!flag8)
				{
					if (Time.time - doorTracking.LastCloseSuppressLogTime > 3f)
					{
						doorTracking.LastCloseSuppressLogTime = Time.time;
						((BaseUnityPlugin)this).Logger.LogInfo((object)("[AutoDoors] Door '" + ((Object)key2).name + "' close suppressed - a paired partner door is still in range."));
					}
				}
				else
				{
					if (MuteAutoDoorSound.Value)
					{
						doorTracking.SuppressNextEffect = true;
					}
					key2.Interact((Humanoid)(object)localPlayer, false, false);
				}
			}
			if (list == null)
			{
				return;
			}
			foreach (Door item4 in list)
			{
				trackedDoors.Remove(item4);
			}
		}

		private void ScanForPartners(Door door, DoorTracking tracking)
		{
			//IL_0079: 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_00fc: Unknown result type (might be due to invalid IL or missing references)
			if ((tracking.Partners != null && tracking.Partners.Count > 0) || Time.time - tracking.PartnersLastScanned < 5f)
			{
				return;
			}
			tracking.PartnersLastScanned = Time.time;
			float horizontalHalfWidth = GetHorizontalHalfWidth(door);
			List<Door> list = null;
			foreach (KeyValuePair<Door, DoorTracking> trackedDoor in trackedDoors)
			{
				Door key = trackedDoor.Key;
				if (!((Object)(object)key == (Object)null) && !((Object)(object)key == (Object)(object)door) && Vector3.Distance(((Component)key).transform.position, ((Component)door).transform.position) - horizontalHalfWidth - GetHorizontalHalfWidth(key) <= MaxPairDistance.Value)
				{
					(list ?? (list = new List<Door>())).Add(key);
				}
			}
			if (list != null)
			{
				tracking.Partners = list;
				((BaseUnityPlugin)this).Logger.LogInfo((object)$"[AutoDoors] Paired door '{((Object)door).name}' at {((Component)door).transform.position} with {list.Count} partner(s) (gap <= {MaxPairDistance.Value}m).");
			}
		}

		private static float GetHorizontalHalfWidth(Door door)
		{
			//IL_0017: 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_001f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_0025: Unknown result type (might be due to invalid IL or missing references)
			//IL_002b: Unknown result type (might be due to invalid IL or missing references)
			Collider componentInChildren = ((Component)door).GetComponentInChildren<Collider>();
			if ((Object)(object)componentInChildren == (Object)null)
			{
				return 0f;
			}
			Bounds bounds = componentInChildren.bounds;
			Vector3 size = ((Bounds)(ref bounds)).size;
			return Mathf.Max(size.x, size.z) * 0.5f;
		}
	}
	internal static class ConfigLogDump
	{
		internal static void Schedule(BaseUnityPlugin plugin, ManualLogSource log)
		{
			((MonoBehaviour)plugin).StartCoroutine(Run(plugin, log));
		}

		private static IEnumerator Run(BaseUnityPlugin plugin, ManualLogSource log)
		{
			yield return null;
			yield return null;
			try
			{
				StringBuilder stringBuilder = new StringBuilder();
				foreach (ConfigDefinition key in plugin.Config.Keys)
				{
					string text = key.Key.ToLowerInvariant();
					if (text.Contains("pass") || text.Contains("token") || text.Contains("secret"))
					{
						continue;
					}
					ConfigEntryBase val = plugin.Config[key];
					if (!object.Equals(val.BoxedValue, val.DefaultValue))
					{
						if (stringBuilder.Length > 0)
						{
							stringBuilder.Append("; ");
						}
						stringBuilder.Append(key.Section).Append('.').Append(key.Key)
							.Append('=')
							.Append(val.BoxedValue);
						if (stringBuilder.Length > 1500)
						{
							stringBuilder.Append("; ...");
							break;
						}
					}
				}
				log.LogInfo((object)("[AutoDoors] config (changed from default): " + ((stringBuilder.Length == 0) ? "none" : stringBuilder.ToString())));
			}
			catch (Exception ex)
			{
				log.LogWarning((object)("[AutoDoors] config dump failed: " + ex.Message));
			}
		}
	}
}