Decompiled source of TacticalLandmine v1.0.0

doomahreal.ultrakill.tacticallandmine/TacticalLandmine.dll

Decompiled 8 months ago
using System;
using System.Collections;
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 System.Threading.Tasks;
using BepInEx;
using Configgy;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using UnityEngine;
using UnityEngine.AI;
using UnityEngine.AddressableAssets;
using UnityEngine.Events;
using UnityEngine.ResourceManagement.AsyncOperations;
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.0", FrameworkDisplayName = ".NET Standard 2.0")]
[assembly: AssemblyCompany("TacticalLandmine")]
[assembly: AssemblyConfiguration("Debug")]
[assembly: AssemblyDescription("My first plugin")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0")]
[assembly: AssemblyProduct("TacticalLandmine")]
[assembly: AssemblyTitle("TacticalLandmine")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.0.0.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.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;
		}
	}
}
public static class UnityExtensions
{
	public static Task WaitForEndOfFrameAsync()
	{
		//IL_001a: Unknown result type (might be due to invalid IL or missing references)
		//IL_0024: Expected O, but got Unknown
		TaskCompletionSource<object> tcs = new TaskCompletionSource<object>();
		Application.onBeforeRender += new UnityAction(EndOfFrameHandler);
		return tcs.Task;
		void EndOfFrameHandler()
		{
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			//IL_0012: Expected O, but got Unknown
			Application.onBeforeRender -= new UnityAction(EndOfFrameHandler);
			tcs.TrySetResult(null);
		}
	}
}
[HarmonyPatch(typeof(Landmine))]
[HarmonyPatch("Start")]
public class LandminePatch
{
	public static int explosionDamage = 35;

	private static async void Postfix(Landmine __instance)
	{
		AsyncOperationHandle<GameObject> explosionHandle = Addressables.LoadAssetAsync<GameObject>((object)"Assets/Prefabs/Attacks and Projectiles/Explosions/Explosion Landmine.prefab");
		await explosionHandle.Task;
		FieldInfo explosionField = typeof(Landmine).GetField("explosion", BindingFlags.Instance | BindingFlags.NonPublic);
		FieldInfo activatedField = typeof(Landmine).GetField("activated", BindingFlags.Instance | BindingFlags.NonPublic);
		if (explosionField != null && activatedField != null)
		{
			GameObject explosionPrefab = explosionHandle.Result;
			explosionField.SetValue(__instance, explosionPrefab);
			((MonoBehaviour)__instance).StartCoroutine(UpdateNavMeshAgent(__instance, activatedField));
			if (((Object)explosionPrefab).name == "Explosion Landmine")
			{
				SetExplosionProperties(explosionPrefab);
			}
		}
		else
		{
			Debug.LogError((object)"Failed to access one of the required fields of Landmine.");
		}
		Addressables.Release<GameObject>(explosionHandle);
	}

	private static IEnumerator UpdateNavMeshAgent(Landmine landmine, FieldInfo activatedField)
	{
		do
		{
			yield return (object)new WaitForSeconds(0.1f);
		}
		while (!(bool)activatedField.GetValue(landmine));
		NavMeshAgent navMeshAgent = ((Component)landmine).GetComponent<NavMeshAgent>();
		if ((Object)(object)navMeshAgent != (Object)null)
		{
			((Behaviour)navMeshAgent).enabled = false;
		}
		else
		{
			Debug.LogError((object)"NavMeshAgent component not found on Landmine object.");
		}
	}

	private static void SetExplosionProperties(GameObject explosionPrefab)
	{
		//IL_002e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0034: Expected O, but got Unknown
		if (!(((Object)explosionPrefab).name == "Explosion Landmine"))
		{
			return;
		}
		foreach (Transform item in explosionPrefab.transform)
		{
			Transform val = item;
			if (((Object)val).name.StartsWith("Sphere_8"))
			{
				Explosion component = ((Component)val).GetComponent<Explosion>();
				if ((Object)(object)component != (Object)null)
				{
					component.maxSize = 45f;
					component.damage = explosionDamage;
					component.speed = 50f;
				}
				else
				{
					Debug.LogError((object)("Explosion component not found on " + ((Object)val).name + "."));
				}
			}
		}
	}

	public static void SetExplosionDamage(int damage)
	{
		explosionDamage = damage;
	}
}
namespace TacticalLandmine
{
	[BepInPlugin("doomahreal.ultrakill.tacticallandmine", "Tactical Landmine", "1.0.0")]
	public class Plugin : BaseUnityPlugin
	{
		[Configgable("", "Distance at which Landmine begins to chase", 0, null)]
		private static IntegerSlider activationDistance = new IntegerSlider(50, 0, 100);

		[Configgable("", "Instantly Kill?", 0, null)]
		private static ConfigToggle instakill = new ConfigToggle(false);

		private AssetBundle assetBundle;

		private List<GameObject> ignoreList = new List<GameObject>();

		private const string assetBundleName = "tacticallandmineassets.bundle";

		private Dictionary<NavMeshAgent, bool> navMeshAgentActivationStates = new Dictionary<NavMeshAgent, bool>();

		private Coroutine instakillListenerCoroutine;

		public static ConfigBuilder ConfigBuilder { get; private set; }

		private async void Awake()
		{
			ConfigBuilder = new ConfigBuilder("doomahreal.ultrakill.tacticallandmine", "Tactical Landmine");
			ConfigBuilder.BuildAll();
			assetBundle = await LoadAssetBundleFromResources("tacticallandmineassets.bundle");
			if ((Object)(object)assetBundle == (Object)null)
			{
				((BaseUnityPlugin)this).Logger.LogError((object)"Failed to load asset bundle.");
				return;
			}
			((BaseUnityPlugin)this).Logger.LogInfo((object)"Asset bundle loaded successfully.");
			Harmony harmony = new Harmony("doomahreal.ultrakill.tacticallandmine");
			harmony.PatchAll();
			((BaseUnityPlugin)this).Logger.LogInfo((object)"Plugin TacticalLandmine is loaded!");
			instakillListenerCoroutine = ((MonoBehaviour)this).StartCoroutine(InstakillListener());
		}

		private void Update()
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			Scene activeScene = SceneManager.GetActiveScene();
			if (((Scene)(ref activeScene)).buildIndex == 0 || ((Scene)(ref activeScene)).name == "241a6a8caec7a13438a5ee786040de32" || ((Scene)(ref activeScene)).name == "b3e7f2f8052488a45b35549efb98d902")
			{
				return;
			}
			FindAndAssignNavMeshAgents();
			GameObject[] array = FindGameObjectsWithNamePrefix("Landmine");
			GameObject[] array2 = array;
			foreach (GameObject val in array2)
			{
				NavMeshAgent component = val.GetComponent<NavMeshAgent>();
				if ((Object)(object)component != (Object)null)
				{
					UpdateNavMeshAgentActivation(component);
				}
			}
		}

		private void FindAndAssignNavMeshAgents()
		{
			GameObject[] array = FindGameObjectsWithNamePrefix("Landmine");
			GameObject[] array2 = array;
			foreach (GameObject val in array2)
			{
				if (ignoreList.Contains(val))
				{
					continue;
				}
				Landmine component = val.GetComponent<Landmine>();
				if ((Object)(object)component == (Object)null)
				{
					ignoreList.Add(val);
					continue;
				}
				LoadAndInstantiatePrefab(val);
				NavMeshAgent component2 = val.GetComponent<NavMeshAgent>();
				if ((Object)(object)component2 == (Object)null)
				{
					component2 = val.gameObject.AddComponent<NavMeshAgent>();
					component2.obstacleAvoidanceType = (ObstacleAvoidanceType)1;
					component2.walkableMask = 13;
					((Behaviour)component2).enabled = false;
					((MonoBehaviour)this).StartCoroutine(DelayedSetDestination(component2));
				}
				else
				{
					SetDestinationIfValid(component2);
				}
			}
		}

		private void UpdateNavMeshAgentActivation(NavMeshAgent navMeshAgent)
		{
			//IL_001a: 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_0020: 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)
			if ((Object)(object)Camera.main != (Object)null)
			{
				Vector3 position = ((Component)navMeshAgent).transform.position;
				int num = (int)Vector3.Distance(position, ((Component)Camera.main).transform.position);
				if (!navMeshAgentActivationStates.ContainsKey(navMeshAgent))
				{
					navMeshAgentActivationStates.Add(navMeshAgent, value: false);
				}
				if (!navMeshAgentActivationStates[navMeshAgent] && num <= ((ConfigValueElement<int>)(object)activationDistance).Value)
				{
					((Behaviour)navMeshAgent).enabled = true;
					navMeshAgentActivationStates[navMeshAgent] = true;
				}
			}
		}

		private IEnumerator DelayedSetDestination(NavMeshAgent navMeshAgent)
		{
			yield return (object)new WaitUntil((Func<bool>)(() => navMeshAgent.isOnNavMesh));
			SetDestinationIfValid(navMeshAgent);
		}

		private void SetDestinationIfValid(NavMeshAgent navMeshAgent)
		{
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)Camera.main != (Object)null && ((Behaviour)navMeshAgent).isActiveAndEnabled)
			{
				navMeshAgent.SetDestination(((Component)Camera.main).transform.position);
			}
		}

		private async Task<AssetBundle> LoadAssetBundleFromResources(string bundleName)
		{
			byte[] bundleData = await LoadEmbeddedResourceAsync(bundleName);
			if (bundleData == null)
			{
				((BaseUnityPlugin)this).Logger.LogError((object)("Failed to load embedded resource: " + bundleName));
				return null;
			}
			return AssetBundle.LoadFromMemory(bundleData);
		}

		private async Task<byte[]> LoadEmbeddedResourceAsync(string resourceName)
		{
			Assembly assembly = Assembly.GetExecutingAssembly();
			string[] resourceNames = assembly.GetManifestResourceNames();
			string fullResourceName = resourceNames.FirstOrDefault((string rn) => rn.EndsWith(resourceName));
			if (fullResourceName == null)
			{
				((BaseUnityPlugin)this).Logger.LogError((object)("Resource not found: " + resourceName));
				return null;
			}
			using Stream stream = assembly.GetManifestResourceStream(fullResourceName);
			if (stream == null)
			{
				((BaseUnityPlugin)this).Logger.LogError((object)("Failed to load resource stream: " + resourceName));
				return null;
			}
			byte[] buffer = new byte[stream.Length];
			await stream.ReadAsync(buffer, 0, buffer.Length);
			return buffer;
		}

		private GameObject[] FindGameObjectsWithNamePrefix(string prefix)
		{
			return (from go in Object.FindObjectsOfType<GameObject>()
				where ((Object)go).name.StartsWith(prefix)
				select go).ToArray();
		}

		private void LoadAndInstantiatePrefab(GameObject parentObject)
		{
			if ((Object)(object)assetBundle == (Object)null)
			{
				((BaseUnityPlugin)this).Logger.LogError((object)"Asset bundle is not loaded.");
				return;
			}
			Transform val = parentObject.transform.Find("knife(Clone)");
			if ((Object)(object)val != (Object)null)
			{
				return;
			}
			GameObject val2 = assetBundle.LoadAsset<GameObject>("knife");
			if ((Object)(object)val2 == (Object)null)
			{
				((BaseUnityPlugin)this).Logger.LogError((object)"Failed to load prefab from asset bundle.");
				return;
			}
			GameObject val3 = Object.Instantiate<GameObject>(val2, parentObject.transform);
			if ((Object)(object)val3 == (Object)null)
			{
				((BaseUnityPlugin)this).Logger.LogError((object)"Failed to instantiate prefab.");
			}
		}

		private IEnumerator InstakillListener()
		{
			while (true)
			{
				yield return (object)new WaitForSeconds(0.5f);
				if (((ConfigValueElement<bool>)(object)instakill).Value)
				{
					UpdateExplosionDamage(isInstakill: true);
				}
				else
				{
					UpdateExplosionDamage(isInstakill: false);
				}
			}
		}

		private void UpdateExplosionDamage(bool isInstakill)
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002a: Expected O, but got Unknown
			if (isInstakill)
			{
				LandminePatch.SetExplosionDamage(9999);
			}
			else
			{
				LandminePatch.SetExplosionDamage(35);
			}
			Harmony val = new Harmony("doomahreal.ultrakill.tacticallandmine");
			val.UnpatchSelf();
			val.PatchAll();
		}
	}
	public static class PluginInfo
	{
		public const string PLUGIN_GUID = "TacticalLandmine";

		public const string PLUGIN_NAME = "TacticalLandmine";

		public const string PLUGIN_VERSION = "1.0.0";
	}
}