Decompiled source of WeaponGroundGlow v0.1.5

BepInEx/plugins/FanTeam-WeaponGroundGlow/WeaponGroundGlow.dll

Decompiled 2 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 Microsoft.CodeAnalysis;
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("WeaponGroundGlow")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0")]
[assembly: AssemblyProduct("WeaponGroundGlow")]
[assembly: AssemblyTitle("WeaponGroundGlow")]
[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 FanTeam.WeaponGroundGlow
{
	[BepInPlugin("fanteam.weapon-ground-glow", "Weapon Ground Glow", "0.1.5")]
	public sealed class WeaponGroundGlowPlugin : BaseUnityPlugin
	{
		private sealed class HighlightState
		{
			public Component Source;

			public GameObject LightObject;

			public Light Light;
		}

		public const string PluginGuid = "fanteam.weapon-ground-glow";

		public const string PluginName = "Weapon Ground Glow";

		public const string PluginVersion = "0.1.5";

		private static readonly BindingFlags AnyInstance = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;

		private static readonly string[] WeaponPrefixes = new string[10] { "ItemGun", "ItemMelee", "ItemGrenade", "ItemMine", "ItemStaff", "ItemCrossbow", "ItemCartCannon", "ItemCartLaser", "ItemStunBaton", "ItemShockwave" };

		private ConfigEntry<bool> _enabled;

		private ConfigEntry<float> _scanInterval;

		private ConfigEntry<float> _lightRange;

		private ConfigEntry<float> _lightIntensity;

		private readonly Dictionary<int, HighlightState> _highlighted = new Dictionary<int, HighlightState>();

		private Type _physGrabObjectType;

		private float _nextScan;

		private bool _reportedTypeError;

		private bool _reportedScanError;

		private void Awake()
		{
			_enabled = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "Enabled", true, "Включает или выключает подсветку оружия на земле.");
			_scanInterval = ((BaseUnityPlugin)this).Config.Bind<float>("Performance", "ScanInterval", 1.25f, "Как часто искать оружие на уровне. Больше значение — меньше нагрузка.");
			_lightRange = ((BaseUnityPlugin)this).Config.Bind<float>("Glow", "LightRange", 2.5f, "Радиус мягкой фиолетовой подсветки вокруг лежащего оружия.");
			_lightIntensity = ((BaseUnityPlugin)this).Config.Bind<float>("Glow", "LightIntensity", 2f, "Яркость фиолетовой подсветки. Уменьши при слишком сильном свете.");
			_physGrabObjectType = ResolveGameType("PhysGrabObject");
			if (_physGrabObjectType == null)
			{
				((BaseUnityPlugin)this).Logger.LogError((object)"Не удалось найти игровой класс PhysGrabObject. Подсветка не сможет искать оружие.");
				_reportedTypeError = true;
			}
			((BaseUnityPlugin)this).Logger.LogInfo((object)"Weapon Ground Glow 0.1.5 загружен. Используется мягкая фиолетовая локальная подсветка без изменения материалов, теней и контуров.");
		}

		private static Type ResolveGameType(string typeName)
		{
			Type type = Type.GetType(typeName + ", Assembly-CSharp", throwOnError: false);
			if (type != null)
			{
				return type;
			}
			Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();
			for (int i = 0; i < assemblies.Length; i++)
			{
				try
				{
					Type type2 = assemblies[i].GetType(typeName, throwOnError: false);
					if (type2 != null)
					{
						return type2;
					}
				}
				catch
				{
				}
			}
			return null;
		}

		private void Update()
		{
			if (!_enabled.Value)
			{
				if (_highlighted.Count > 0)
				{
					ClearAllHighlights();
				}
			}
			else if (_physGrabObjectType == null)
			{
				if (!_reportedTypeError)
				{
					((BaseUnityPlugin)this).Logger.LogError((object)"PhysGrabObject недоступен; сканирование пропущено.");
					_reportedTypeError = true;
				}
			}
			else if (!(Time.unscaledTime < _nextScan))
			{
				_nextScan = Time.unscaledTime + Mathf.Clamp(_scanInterval.Value, 0.75f, 5f);
				ScanWeapons();
			}
		}

		private void ScanWeapons()
		{
			//IL_0075: 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)
			HashSet<int> hashSet = new HashSet<int>();
			try
			{
				Object[] array = Object.FindObjectsOfType(_physGrabObjectType);
				foreach (Object obj in array)
				{
					Component val = (Component)(object)((obj is Component) ? obj : null);
					if (!((Object)(object)val == (Object)null) && !((Object)(object)val.gameObject == (Object)null) && !((Object)(object)FindWeaponComponent(val) == (Object)null))
					{
						int instanceID = ((Object)val).GetInstanceID();
						hashSet.Add(instanceID);
						int num;
						if (val.gameObject.activeInHierarchy)
						{
							Scene scene = val.gameObject.scene;
							num = (((Scene)(ref scene)).IsValid() ? 1 : 0);
						}
						else
						{
							num = 0;
						}
						bool flag = IsHeld(val);
						bool flag2 = IsInInventory(val);
						if (num != 0 && !flag && !flag2)
						{
							AddHighlightIfNeeded(instanceID, val);
						}
						else
						{
							RemoveHighlight(instanceID);
						}
					}
				}
				List<int> list = null;
				foreach (KeyValuePair<int, HighlightState> item in _highlighted)
				{
					if (!hashSet.Contains(item.Key) || item.Value == null || (Object)(object)item.Value.Source == (Object)null)
					{
						if (list == null)
						{
							list = new List<int>();
						}
						list.Add(item.Key);
					}
				}
				if (list != null)
				{
					for (int j = 0; j < list.Count; j++)
					{
						RemoveHighlight(list[j]);
					}
				}
			}
			catch (Exception ex)
			{
				if (!_reportedScanError)
				{
					((BaseUnityPlugin)this).Logger.LogError((object)("Ошибка поиска оружия: " + ex));
					_reportedScanError = true;
				}
			}
		}

		private static Component FindWeaponComponent(Component physics)
		{
			Component[] components = physics.GetComponents<Component>();
			foreach (Component val in components)
			{
				if ((Object)(object)val != (Object)null && IsWeaponComponent(((object)val).GetType()))
				{
					return val;
				}
			}
			Transform parent = physics.transform.parent;
			while ((Object)(object)parent != (Object)null)
			{
				Component[] components2 = ((Component)parent).GetComponents<Component>();
				foreach (Component val2 in components2)
				{
					if ((Object)(object)val2 != (Object)null && IsWeaponComponent(((object)val2).GetType()))
					{
						return val2;
					}
				}
				parent = parent.parent;
			}
			Component[] componentsInChildren = physics.GetComponentsInChildren<Component>(true);
			foreach (Component val3 in componentsInChildren)
			{
				if ((Object)(object)val3 != (Object)null && IsWeaponComponent(((object)val3).GetType()))
				{
					return val3;
				}
			}
			return null;
		}

		private static bool IsWeaponComponent(Type type)
		{
			Type type2 = type;
			while (type2 != null)
			{
				string name = type2.Name;
				for (int i = 0; i < WeaponPrefixes.Length; i++)
				{
					if (name.StartsWith(WeaponPrefixes[i], StringComparison.Ordinal))
					{
						return true;
					}
				}
				type2 = type2.BaseType;
			}
			return false;
		}

		private static bool IsHeld(Component physics)
		{
			if (GetCollectionCount(ReadMember(physics, "playerGrabbing")) > 0)
			{
				return true;
			}
			if (!ReadBool(physics, "grabbed") && !ReadBool(physics, "grabbedLocal"))
			{
				return ReadBool(physics, "grabbedByLocalPlayer");
			}
			return true;
		}

		private static bool IsInInventory(Component physics)
		{
			Component val = FindRelatedComponent(physics.gameObject, "ItemEquippable");
			if ((Object)(object)val == (Object)null)
			{
				return false;
			}
			if (ReadBool(val, "isEquipped") || ReadBool(val, "isEquipping") || ReadBool(val, "isUnequipping") || ReadBool(val, "isForceUnequipping"))
			{
				return true;
			}
			if (InvokeBoolMethod(val, "IsEquipped"))
			{
				return true;
			}
			return ReadMember(val, "equippedSpot") != null;
		}

		private static Component FindRelatedComponent(GameObject source, string componentTypeName)
		{
			if ((Object)(object)source == (Object)null)
			{
				return null;
			}
			Transform val = source.transform;
			while ((Object)(object)val != (Object)null)
			{
				Component[] components = ((Component)val).GetComponents<Component>();
				foreach (Component val2 in components)
				{
					if ((Object)(object)val2 != (Object)null && HasTypeName(((object)val2).GetType(), componentTypeName))
					{
						return val2;
					}
				}
				val = val.parent;
			}
			Component[] componentsInChildren = source.GetComponentsInChildren<Component>(true);
			foreach (Component val3 in componentsInChildren)
			{
				if ((Object)(object)val3 != (Object)null && HasTypeName(((object)val3).GetType(), componentTypeName))
				{
					return val3;
				}
			}
			return null;
		}

		private static bool HasTypeName(Type type, string expectedName)
		{
			Type type2 = type;
			while (type2 != null)
			{
				if (type2.Name == expectedName)
				{
					return true;
				}
				type2 = type2.BaseType;
			}
			return false;
		}

		private static object ReadMember(object instance, string name)
		{
			if (instance == null)
			{
				return null;
			}
			Type type = instance.GetType();
			while (type != null)
			{
				FieldInfo field = type.GetField(name, AnyInstance);
				if (field != null)
				{
					try
					{
						return field.GetValue(instance);
					}
					catch
					{
						return null;
					}
				}
				PropertyInfo property = type.GetProperty(name, AnyInstance);
				if (property != null && property.GetIndexParameters().Length == 0)
				{
					try
					{
						return property.GetValue(instance, null);
					}
					catch
					{
						return null;
					}
				}
				type = type.BaseType;
			}
			return null;
		}

		private static bool ReadBool(object instance, string name)
		{
			object obj = ReadMember(instance, name);
			if (obj is bool)
			{
				return (bool)obj;
			}
			return false;
		}

		private static bool InvokeBoolMethod(object instance, string name)
		{
			if (instance == null)
			{
				return false;
			}
			Type type = instance.GetType();
			while (type != null)
			{
				MethodInfo method = type.GetMethod(name, AnyInstance, null, Type.EmptyTypes, null);
				if (!(method == null) && !(method.ReturnType != typeof(bool)))
				{
					try
					{
						return (bool)method.Invoke(instance, null);
					}
					catch
					{
						return false;
					}
				}
				type = type.BaseType;
			}
			return false;
		}

		private static int GetCollectionCount(object collection)
		{
			if (collection == null)
			{
				return 0;
			}
			if (collection is ICollection collection2)
			{
				return collection2.Count;
			}
			object obj = ReadMember(collection, "Count");
			if (!(obj is int))
			{
				return 0;
			}
			return (int)obj;
		}

		private void AddHighlightIfNeeded(int id, Component physics)
		{
			if (_highlighted.TryGetValue(id, out var value) && value != null)
			{
				UpdateLightSettings(value);
				return;
			}
			HighlightState highlightState = CreateHighlight(physics);
			if (highlightState != null)
			{
				_highlighted[id] = highlightState;
			}
		}

		private HighlightState CreateHighlight(Component physics)
		{
			//IL_001d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0023: Expected O, but got Unknown
			//IL_004a: 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)
			if ((Object)(object)physics == (Object)null)
			{
				return null;
			}
			HighlightState highlightState = new HighlightState();
			highlightState.Source = physics;
			try
			{
				GameObject val = new GameObject("WeaponGroundGlow_PurpleLight");
				val.transform.SetParent(physics.transform, false);
				val.transform.localPosition = new Vector3(0f, 0.12f, 0f);
				Light val2 = val.AddComponent<Light>();
				val2.type = (LightType)2;
				val2.color = new Color(0.62f, 0.22f, 1f, 1f);
				val2.shadows = (LightShadows)0;
				val2.renderMode = (LightRenderMode)2;
				highlightState.LightObject = val;
				highlightState.Light = val2;
				UpdateLightSettings(highlightState);
				return highlightState;
			}
			catch (Exception ex)
			{
				((BaseUnityPlugin)this).Logger.LogWarning((object)("Не удалось создать фиолетовую подсветку для одного оружия: " + ex.Message));
				RestoreHighlight(highlightState);
				return null;
			}
		}

		private void UpdateLightSettings(HighlightState state)
		{
			//IL_0076: Unknown result type (might be due to invalid IL or missing references)
			if (state != null && !((Object)(object)state.Light == (Object)null))
			{
				state.Light.range = Mathf.Clamp(_lightRange.Value, 0.75f, 4f);
				state.Light.intensity = Mathf.Clamp(_lightIntensity.Value, 0.1f, 4f);
				state.Light.color = new Color(0.62f, 0.22f, 1f, 1f);
			}
		}

		private void RemoveHighlight(int id)
		{
			if (_highlighted.TryGetValue(id, out var value))
			{
				_highlighted.Remove(id);
				RestoreHighlight(value);
			}
		}

		private void ClearAllHighlights()
		{
			List<int> list = new List<int>(_highlighted.Keys);
			for (int i = 0; i < list.Count; i++)
			{
				RemoveHighlight(list[i]);
			}
		}

		private static void RestoreHighlight(HighlightState state)
		{
			if (state != null && (Object)(object)state.LightObject != (Object)null)
			{
				Object.Destroy((Object)(object)state.LightObject);
			}
		}

		private void OnDestroy()
		{
			ClearAllHighlights();
		}
	}
}