Decompiled source of RepoChargingPadRegen v0.4.4

BepInEx/plugins/RepoChargingPadRegen.dll

Decompiled a month ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using BepInEx;
using BepInEx.Configuration;
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("RepoChargingPadRegen")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0")]
[assembly: AssemblyProduct("RepoChargingPadRegen")]
[assembly: AssemblyTitle("RepoChargingPadRegen")]
[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 RepoChargingPadRegen
{
	[BepInPlugin("com.chatgpt.repochargingpadregen", "REPO Charging Pad Regen", "0.4.2")]
	public sealed class Plugin : BaseUnityPlugin
	{
		private sealed class ColliderCache
		{
			public Collider[] Colliders = (Collider[])(object)new Collider[0];

			public float NextRefresh;
		}

		private sealed class MemberGetter
		{
			private readonly FieldInfo _field;

			private readonly PropertyInfo _property;

			private MemberGetter(FieldInfo field, PropertyInfo property)
			{
				_field = field;
				_property = property;
			}

			public static MemberGetter Create(Type type, params string[] names)
			{
				foreach (string name in names)
				{
					FieldInfo field = type.GetField(name, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
					if (field != null)
					{
						return new MemberGetter(field, null);
					}
					PropertyInfo property = type.GetProperty(name, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
					if (property != null && property.CanRead)
					{
						return new MemberGetter(null, property);
					}
				}
				return null;
			}

			public object Get(object target)
			{
				if (target == null)
				{
					return null;
				}
				try
				{
					if (_field != null)
					{
						return _field.GetValue(target);
					}
					return _property.GetValue(target, null);
				}
				catch
				{
					return null;
				}
			}
		}

		internal static Plugin Instance;

		private static readonly Harmony Harmony = new Harmony("com.chatgpt.repochargingpadregen");

		internal static ConfigEntry<bool> EnabledConfig;

		internal static ConfigEntry<int> HealAmountConfig;

		internal static ConfigEntry<float> HealIntervalConfig;

		internal static ConfigEntry<bool> LogHealsConfig;

		private const BindingFlags InstanceFlags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;

		private const float StationCheckInterval = 0.2f;

		private const float PlayerListRefreshInterval = 3f;

		private const float ColliderRefreshInterval = 5f;

		private const float HostCheckInterval = 1f;

		private const float BroadPhaseDistance = 6f;

		private const float ResolveRetryInterval = 5f;

		private static readonly Dictionary<int, float> LastHeal = new Dictionary<int, float>();

		private static readonly Dictionary<int, float> LastStationTick = new Dictionary<int, float>();

		private static readonly Dictionary<int, ColliderCache> StationColliders = new Dictionary<int, ColliderCache>();

		private static readonly Dictionary<int, ColliderCache> PlayerColliders = new Dictionary<int, ColliderCache>();

		private static readonly List<Collider> ColliderScratch = new List<Collider>(16);

		private static bool _resolved;

		private static float _nextResolveAttempt;

		private static Type _healthType;

		private static MethodInfo _healOther;

		private static MemberGetter _healthGetter;

		private static MemberGetter _maxHealthGetter;

		private static MemberGetter _avatarGetter;

		private static MemberGetter _deadSetGetter;

		private static Type _deadSetOwnerType;

		private static PropertyInfo _photonInRoom;

		private static PropertyInfo _photonIsMaster;

		private static bool _photonResolved;

		private static Component[] _players = (Component[])(object)new Component[0];

		private static float _nextPlayerRefresh;

		private static bool _isHost = true;

		private static float _nextHostCheck;

		private static readonly List<int> PruneScratch = new List<int>();

		private void Awake()
		{
			//IL_0049: Unknown result type (might be due to invalid IL or missing references)
			//IL_0053: Expected O, but got Unknown
			//IL_0086: Unknown result type (might be due to invalid IL or missing references)
			//IL_0090: Expected O, but got Unknown
			//IL_011c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0129: Expected O, but got Unknown
			Instance = this;
			EnabledConfig = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "Enabled", true, "Turn charging-pad healing on or off. Only the host's setting matters in multiplayer.");
			HealAmountConfig = ((BaseUnityPlugin)this).Config.Bind<int>("General", "Heal Amount", 1, new ConfigDescription("Health restored per tick while standing on the charging pad.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(1, 50), Array.Empty<object>()));
			HealIntervalConfig = ((BaseUnityPlugin)this).Config.Bind<float>("General", "Heal Interval", 1f, new ConfigDescription("Seconds between heal ticks for each player on the pad.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.25f, 10f), Array.Empty<object>()));
			LogHealsConfig = ((BaseUnityPlugin)this).Config.Bind<bool>("Debug", "Log Heals", false, "Write a log line for every heal tick. Useful for troubleshooting; leave off normally.");
			((BaseUnityPlugin)this).Logger.LogInfo((object)"REPO Charging Pad Regen 0.4.2 loaded.");
			try
			{
				Type type = AccessTools.TypeByName("ChargingStation");
				MethodInfo methodInfo = ((type == null) ? null : AccessTools.Method(type, "Update", (Type[])null, (Type[])null));
				if (methodInfo == null)
				{
					((BaseUnityPlugin)this).Logger.LogError((object)"Could not find ChargingStation.Update.");
					return;
				}
				Harmony.Patch((MethodBase)methodInfo, (HarmonyMethod)null, new HarmonyMethod(typeof(Plugin), "ChargingStationUpdatePostfix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				((BaseUnityPlugin)this).Logger.LogInfo((object)"Patched ChargingStation.Update.");
			}
			catch (Exception ex)
			{
				((BaseUnityPlugin)this).Logger.LogError((object)("Patch setup failed: " + ex));
			}
		}

		private static void ChargingStationUpdatePostfix(object __instance)
		{
			//IL_00a9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ae: 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_00f3: 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)
			try
			{
				if (!EnabledConfig.Value)
				{
					return;
				}
				Component val = (Component)((__instance is Component) ? __instance : null);
				if ((Object)(object)val == (Object)null)
				{
					return;
				}
				float unscaledTime = Time.unscaledTime;
				int instanceID = ((Object)val).GetInstanceID();
				if (LastStationTick.TryGetValue(instanceID, out var value) && unscaledTime - value < 0.2f)
				{
					return;
				}
				LastStationTick[instanceID] = unscaledTime;
				if (!IsHostCached(unscaledTime) || !EnsureResolved(unscaledTime))
				{
					return;
				}
				RefreshPlayersIfNeeded(unscaledTime);
				if (_players.Length == 0)
				{
					return;
				}
				Collider[] colliders = GetColliders(StationColliders, val, instanceID, unscaledTime);
				if (colliders.Length == 0)
				{
					return;
				}
				Vector3 position = val.transform.position;
				float num = 36f;
				for (int i = 0; i < _players.Length; i++)
				{
					Component val2 = _players[i];
					if ((Object)(object)val2 == (Object)null || !val2.gameObject.activeInHierarchy)
					{
						continue;
					}
					Vector3 val3 = val2.transform.position - position;
					val3.y = 0f;
					if (((Vector3)(ref val3)).sqrMagnitude > num || !TryReadInt(_healthGetter, val2, out var value2) || !TryReadInt(_maxHealthGetter, val2, out var value3) || value2 <= 0 || value3 <= 0 || value2 >= value3 || IsDead(val2))
					{
						continue;
					}
					int instanceID2 = ((Object)val2).GetInstanceID();
					if ((LastHeal.TryGetValue(instanceID2, out var value4) && unscaledTime - value4 < HealIntervalConfig.Value) || !IsPlayerOnStation(val2, instanceID2, colliders, unscaledTime))
					{
						continue;
					}
					if (TryInvokeHealOther(val2, HealAmountConfig.Value))
					{
						LastHeal[instanceID2] = unscaledTime;
						if (LogHealsConfig.Value)
						{
							int value5;
							bool flag = TryReadInt(_healthGetter, val2, out value5);
							((BaseUnityPlugin)Instance).Logger.LogInfo((object)("Charging-pad heal call returned. Before=" + value2 + "/" + value3 + ", after=" + (flag ? value5.ToString() : "unreadable") + ", station=" + ((Object)val).name + ", player=" + ((Object)val2).name + "."));
						}
					}
					else
					{
						((BaseUnityPlugin)Instance).Logger.LogWarning((object)"PlayerHealth.HealOther(int, bool) was not found; no health changed.");
					}
				}
			}
			catch (Exception ex)
			{
				if ((Object)(object)Instance != (Object)null)
				{
					((BaseUnityPlugin)Instance).Logger.LogError((object)("Regen tick failed: " + ex));
				}
			}
		}

		private static bool EnsureResolved(float now)
		{
			if (_resolved)
			{
				return true;
			}
			if (now < _nextResolveAttempt)
			{
				return false;
			}
			_nextResolveAttempt = now + 5f;
			Type type = AccessTools.TypeByName("PlayerHealth");
			if (type == null)
			{
				return false;
			}
			_healthType = type;
			_healOther = type.GetMethod("HealOther", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, new Type[2]
			{
				typeof(int),
				typeof(bool)
			}, null);
			_healthGetter = MemberGetter.Create(type, "health", "playerHealth", "currentHealth");
			_maxHealthGetter = MemberGetter.Create(type, "maxHealth", "playerMaxHealth", "maximumHealth");
			_avatarGetter = MemberGetter.Create(type, "playerAvatar", "playerAvatarScript", "playerAvatarReference");
			_resolved = true;
			return true;
		}

		private static bool IsHostCached(float now)
		{
			if (now < _nextHostCheck)
			{
				return _isHost;
			}
			_nextHostCheck = now + 1f;
			if (!_photonResolved)
			{
				_photonResolved = true;
				Type type = AccessTools.TypeByName("Photon.Pun.PhotonNetwork");
				if (type != null)
				{
					_photonInRoom = type.GetProperty("InRoom", BindingFlags.Static | BindingFlags.Public);
					_photonIsMaster = type.GetProperty("IsMasterClient", BindingFlags.Static | BindingFlags.Public);
				}
			}
			if (_photonInRoom == null && _photonIsMaster == null)
			{
				_isHost = true;
				return _isHost;
			}
			try
			{
				_isHost = !(_photonInRoom != null) || !(bool)_photonInRoom.GetValue(null, null) || (_photonIsMaster != null && (bool)_photonIsMaster.GetValue(null, null));
			}
			catch
			{
				_isHost = false;
			}
			return _isHost;
		}

		private static void RefreshPlayersIfNeeded(float now)
		{
			if (now < _nextPlayerRefresh)
			{
				return;
			}
			_nextPlayerRefresh = now + 3f;
			Object[] array = Object.FindObjectsOfType(_healthType);
			Component[] array2 = (Component[])(object)new Component[array.Length];
			int num = 0;
			foreach (Object obj in array)
			{
				Component val = (Component)(object)((obj is Component) ? obj : null);
				if ((Object)(object)val != (Object)null)
				{
					array2[num++] = val;
				}
			}
			if (num != array2.Length)
			{
				Array.Resize(ref array2, num);
			}
			_players = array2;
			PruneStale(LastStationTick, now);
			PruneStale(LastHeal, now);
			PruneColliderCache(StationColliders, now);
			PruneColliderCache(PlayerColliders, now);
		}

		private static void PruneStale(Dictionary<int, float> map, float now)
		{
			if (map.Count < 32)
			{
				return;
			}
			PruneScratch.Clear();
			foreach (KeyValuePair<int, float> item in map)
			{
				if (now - item.Value > 60f)
				{
					PruneScratch.Add(item.Key);
				}
			}
			for (int i = 0; i < PruneScratch.Count; i++)
			{
				map.Remove(PruneScratch[i]);
			}
		}

		private static void PruneColliderCache(Dictionary<int, ColliderCache> map, float now)
		{
			if (map.Count < 32)
			{
				return;
			}
			PruneScratch.Clear();
			foreach (KeyValuePair<int, ColliderCache> item in map)
			{
				if (now - item.Value.NextRefresh > 60f)
				{
					PruneScratch.Add(item.Key);
				}
			}
			for (int i = 0; i < PruneScratch.Count; i++)
			{
				map.Remove(PruneScratch[i]);
			}
		}

		private static Collider[] GetColliders(Dictionary<int, ColliderCache> cache, Component owner, int id, float now)
		{
			if (!cache.TryGetValue(id, out var value))
			{
				value = (cache[id] = new ColliderCache());
			}
			if (now >= value.NextRefresh)
			{
				value.NextRefresh = now + 5f;
				ColliderScratch.Clear();
				owner.GetComponentsInChildren<Collider>(true, ColliderScratch);
				value.Colliders = ColliderScratch.ToArray();
				ColliderScratch.Clear();
			}
			return value.Colliders;
		}

		private static bool TryInvokeHealOther(Component health, int amount)
		{
			if (_healOther == null)
			{
				return false;
			}
			try
			{
				_healOther.Invoke(health, new object[2] { amount, true });
				return true;
			}
			catch (Exception ex)
			{
				((BaseUnityPlugin)Instance).Logger.LogWarning((object)("HealOther failed: " + ex.GetBaseException().Message));
				return false;
			}
		}

		private static bool IsDead(Component health)
		{
			object obj = ((_avatarGetter == null) ? null : _avatarGetter.Get(health));
			if (obj == null)
			{
				return false;
			}
			Type type = obj.GetType();
			if (_deadSetGetter == null || _deadSetOwnerType != type)
			{
				_deadSetGetter = MemberGetter.Create(type, "deadSet");
				_deadSetOwnerType = type;
			}
			object obj2 = ((_deadSetGetter == null) ? null : _deadSetGetter.Get(obj));
			if (obj2 is bool)
			{
				return (bool)obj2;
			}
			return false;
		}

		private static bool IsPlayerOnStation(Component player, int playerId, Collider[] stationColliders, float now)
		{
			//IL_0041: 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_008d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0092: Unknown result type (might be due to invalid IL or missing references)
			//IL_0096: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bc: Unknown result type (might be due to invalid IL or missing references)
			//IL_0104: Unknown result type (might be due to invalid IL or missing references)
			//IL_0114: 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_00d6: Unknown result type (might be due to invalid IL or missing references)
			//IL_012a: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f0: Unknown result type (might be due to invalid IL or missing references)
			Collider[] colliders = GetColliders(PlayerColliders, player, playerId, now);
			foreach (Collider val in colliders)
			{
				if ((Object)(object)val == (Object)null || !val.enabled || !((Component)val).gameObject.activeInHierarchy)
				{
					continue;
				}
				Bounds bounds = val.bounds;
				foreach (Collider val2 in stationColliders)
				{
					if (!((Object)(object)val2 == (Object)null) && val2.enabled && ((Component)val2).gameObject.activeInHierarchy && !val2.isTrigger)
					{
						Bounds bounds2 = val2.bounds;
						bool num = ((Bounds)(ref bounds)).max.x >= ((Bounds)(ref bounds2)).min.x && ((Bounds)(ref bounds)).min.x <= ((Bounds)(ref bounds2)).max.x && ((Bounds)(ref bounds)).max.z >= ((Bounds)(ref bounds2)).min.z && ((Bounds)(ref bounds)).min.z <= ((Bounds)(ref bounds2)).max.z;
						float y = ((Bounds)(ref bounds)).min.y;
						bool flag = y >= ((Bounds)(ref bounds2)).min.y - 0.25f && y <= ((Bounds)(ref bounds2)).max.y + 0.45f;
						if (num && flag)
						{
							return true;
						}
					}
				}
			}
			return false;
		}

		private static bool TryReadInt(MemberGetter getter, object target, out int value)
		{
			value = 0;
			if (getter == null)
			{
				return false;
			}
			object obj = getter.Get(target);
			if (obj == null)
			{
				return false;
			}
			try
			{
				value = Convert.ToInt32(obj);
				return true;
			}
			catch
			{
				return false;
			}
		}
	}
}