Decompiled source of DurabilityBegone v1.0.4

BepInEx/plugins/DurabilityBegone/DurabilityBegone.dll

Decompiled a month ago
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Runtime.CompilerServices;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using UnityEngine;

[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: CompilationRelaxations(8)]
[assembly: AssemblyVersion("0.0.0.0")]
namespace DurabilityBegone;

[BepInPlugin("DurabilityBegone.Valheim", "DurabilityBegone", "1.0.4")]
[BepInProcess("valheim.exe")]
public sealed class Plugin : BaseUnityPlugin
{
	public const string PluginGuid = "DurabilityBegone.Valheim";

	public const string PluginName = "DurabilityBegone";

	public const string PluginVersion = "1.0.4";

	internal static ConfigEntry<bool> ModEnabled;

	internal static ConfigEntry<bool> AreaRepairEnabled;

	internal static ConfigEntry<float> RepairRadius;

	internal static ManualLogSource Log;

	private Harmony _harmony;

	private static readonly Collider[] InitialColliderBuffer = (Collider[])(object)new Collider[2048];

	private static Collider[] _colliderBuffer = InitialColliderBuffer;

	private static readonly HashSet<int> SeenWearNTear = new HashSet<int>();

	private static bool _areaRepairRunning;

	private static MethodInfo _wearRepairMethod;

	private static MethodInfo _wearHealthPercentMethod;

	private void Awake()
	{
		//IL_0028: Unknown result type (might be due to invalid IL or missing references)
		//IL_0032: Expected O, but got Unknown
		//IL_0054: Unknown result type (might be due to invalid IL or missing references)
		//IL_005e: Expected O, but got Unknown
		//IL_0084: Unknown result type (might be due to invalid IL or missing references)
		//IL_008e: Expected O, but got Unknown
		//IL_00cf: Unknown result type (might be due to invalid IL or missing references)
		//IL_00d9: Expected O, but got Unknown
		//IL_00fc: Unknown result type (might be due to invalid IL or missing references)
		//IL_0108: Expected O, but got Unknown
		//IL_012b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0137: Expected O, but got Unknown
		//IL_015a: Unknown result type (might be due to invalid IL or missing references)
		//IL_0165: Expected O, but got Unknown
		Log = ((BaseUnityPlugin)this).Logger;
		ModEnabled = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "Enabled", true, new ConfigDescription("Enable DurabilityBegone. Mod default: enabled.", (AcceptableValueBase)null, new object[0]));
		AreaRepairEnabled = ((BaseUnityPlugin)this).Config.Bind<bool>("Area Repair", "Enabled", true, new ConfigDescription("When a manual hammer repair succeeds, also repair damaged structures within Repair Radius. This runs only from an actual repair action; it never polls structures in Update. Mod default: enabled.", (AcceptableValueBase)null, new object[0]));
		RepairRadius = ((BaseUnityPlugin)this).Config.Bind<float>("Area Repair", "Repair Radius (m)", 30f, new ConfigDescription("Radius in meters for the manual Area Repair burst. No vanilla equivalent. Mod default: 30 m. Enter any numeric value directly; 0 or less disables the extra radius repair.", (AcceptableValueBase)null, new object[0]));
		_wearRepairMethod = AccessTools.Method(typeof(WearNTear), "Repair", (Type[])null, (Type[])null);
		_wearHealthPercentMethod = AccessTools.Method(typeof(WearNTear), "GetHealthPercentage", (Type[])null, (Type[])null);
		_harmony = new Harmony("DurabilityBegone.Valheim");
		int num = 0;
		num += PatchNamedMethods(typeof(Player), "DrainEquipedItemDurability", new HarmonyMethod(typeof(Plugin), "SkipDurabilityPrefix", (Type[])null), null, requireBoolReturn: false);
		num += PatchNamedMethods(typeof(Player), "DamageArmorDurability", new HarmonyMethod(typeof(Plugin), "SkipDurabilityPrefix", (Type[])null), null, requireBoolReturn: false);
		int num2 = PatchNamedMethods(typeof(Player), "Repair", null, new HarmonyMethod(typeof(Plugin), "RepairPostfix", (Type[])null), requireBoolReturn: true);
		((BaseUnityPlugin)this).Logger.LogInfo((object)("DurabilityBegone 1.0.4 loaded. Durability patches=" + num + ", manual Area Repair hooks=" + num2 + "."));
		((BaseUnityPlugin)this).Logger.LogInfo((object)"Area Repair is event-driven only; there is no per-frame repair scan or automatic repair loop.");
	}

	private void OnDestroy()
	{
		if (_harmony != null)
		{
			_harmony.UnpatchSelf();
		}
	}

	private int PatchNamedMethods(Type type, string methodName, HarmonyMethod prefix, HarmonyMethod postfix, bool requireBoolReturn)
	{
		int num = 0;
		MethodInfo[] methods;
		try
		{
			methods = type.GetMethods(BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
		}
		catch
		{
			return 0;
		}
		foreach (MethodInfo methodInfo in methods)
		{
			if (!(methodInfo == null) && !(methodInfo.Name != methodName) && (!requireBoolReturn || !(methodInfo.ReturnType != typeof(bool))))
			{
				try
				{
					_harmony.Patch((MethodBase)methodInfo, prefix, postfix, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
					num++;
				}
				catch (Exception ex)
				{
					((BaseUnityPlugin)this).Logger.LogWarning((object)("Could not patch " + type.Name + "." + methodName + ": " + ex.Message));
				}
			}
		}
		return num;
	}

	private static bool SkipDurabilityPrefix()
	{
		if (ModEnabled != null)
		{
			return !ModEnabled.Value;
		}
		return true;
	}

	private static void RepairPostfix(Player __instance, bool __result)
	{
		//IL_0094: Unknown result type (might be due to invalid IL or missing references)
		if (!__result || _areaRepairRunning || ModEnabled == null || !ModEnabled.Value || AreaRepairEnabled == null || !AreaRepairEnabled.Value || (Object)(object)__instance == (Object)null || (Object)(object)Player.m_localPlayer == (Object)null || !object.ReferenceEquals(__instance, Player.m_localPlayer))
		{
			return;
		}
		float num = ((RepairRadius != null) ? RepairRadius.Value : 30f);
		if (float.IsNaN(num) || float.IsInfinity(num) || num <= 0f)
		{
			return;
		}
		_areaRepairRunning = true;
		try
		{
			RepairNearbyDamagedPieces(((Component)__instance).transform.position, num);
		}
		catch (Exception ex)
		{
			if (Log != null)
			{
				Log.LogWarning((object)("Area Repair failed: " + ex.Message));
			}
		}
		finally
		{
			_areaRepairRunning = false;
		}
	}

	private static void RepairNearbyDamagedPieces(Vector3 center, float radius)
	{
		//IL_000e: Unknown result type (might be due to invalid IL or missing references)
		//IL_004a: Unknown result type (might be due to invalid IL or missing references)
		if (_wearRepairMethod == null)
		{
			return;
		}
		int num = Physics.OverlapSphereNonAlloc(center, radius, _colliderBuffer, -1, (QueryTriggerInteraction)2);
		if (num >= _colliderBuffer.Length)
		{
			int num2 = _colliderBuffer.Length * 2;
			if (num2 < 4096)
			{
				num2 = 4096;
			}
			_colliderBuffer = (Collider[])(object)new Collider[num2];
			num = Physics.OverlapSphereNonAlloc(center, radius, _colliderBuffer, -1, (QueryTriggerInteraction)2);
		}
		SeenWearNTear.Clear();
		for (int i = 0; i < num; i++)
		{
			Collider val = _colliderBuffer[i];
			if ((Object)(object)val == (Object)null)
			{
				continue;
			}
			WearNTear val2 = null;
			try
			{
				val2 = ((Component)val).GetComponentInParent<WearNTear>();
			}
			catch
			{
			}
			if ((Object)(object)val2 == (Object)null)
			{
				continue;
			}
			int instanceID = ((Object)val2).GetInstanceID();
			if (SeenWearNTear.Add(instanceID) && IsDamaged(val2))
			{
				try
				{
					_wearRepairMethod.Invoke(val2, null);
				}
				catch
				{
				}
			}
		}
	}

	private static bool IsDamaged(WearNTear wear)
	{
		if ((Object)(object)wear == (Object)null)
		{
			return false;
		}
		if (_wearHealthPercentMethod != null)
		{
			try
			{
				object obj = _wearHealthPercentMethod.Invoke(wear, null);
				if (obj is float)
				{
					return (float)obj < 0.9999f;
				}
				if (obj is double)
				{
					return (double)obj < 0.9999;
				}
			}
			catch
			{
			}
		}
		return false;
	}
}