Decompiled source of WackyDBSecondaryAttacks v1.0.2

plugins/WackysSecondaryAttacks.dll

Decompiled 9 hours ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using API;
using BepInEx;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using ServerSync;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: AssemblyFileVersion("1.0.2")]
[assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")]
[assembly: AssemblyVersion("1.0.2.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 WackysSecondaryAttacks
{
	[BepInPlugin("WackyMole.WackysSecondaryAttacks", "WackyDBSecondaryAttacks", "1.0.2")]
	[BepInDependency("WackyMole.WackysDatabase", "2.6.14")]
	public sealed class WackyDBSecondaryAttacks : BaseUnityPlugin
	{
		public const string Version = "1.0.2";

		private readonly Harmony harmony = new Harmony("WackyMole.WackysSecondaryAttacks");

		private ConfigSync configSync;

		private void Awake()
		{
			//IL_0020: 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_0030: Unknown result type (might be due to invalid IL or missing references)
			//IL_003b: 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_0052: Expected O, but got Unknown
			harmony.PatchAll(typeof(WackyDBSecondaryAttacks).Assembly);
			configSync = new ConfigSync("WackyMole.WackysSecondaryAttacks")
			{
				DisplayName = "WackyMole.WackyDBSecondaryAttacks",
				CurrentVersion = "1.0.2",
				MinimumRequiredVersion = "1.0.2",
				ModRequired = true
			};
			SecondaryAttackDamage.ProviderAvailable = true;
		}

		private void OnDestroy()
		{
			SecondaryAttackDamage.ProviderAvailable = false;
		}
	}
	internal static class DamageContext
	{
		private static readonly ConditionalWeakTable<Attack, Attack> Origins = new ConditionalWeakTable<Attack, Attack>();

		[ThreadStatic]
		private static Definition current;

		[ThreadStatic]
		private static ItemData currentWeapon;

		internal static void TrackClone(Attack source, Attack clone)
		{
			Origins.Add(clone, source);
		}

		internal static bool TryGet(Attack attack, ItemData weapon, out Definition definition)
		{
			while (attack != null)
			{
				if (attack == weapon.m_shared.m_secondaryAttack)
				{
					return SecondaryAttackDamage.TryGet(weapon, ref definition);
				}
				if (SecondaryAttackDamage.TryGet(attack, ref definition))
				{
					return true;
				}
				if (!Origins.TryGetValue(attack, out attack))
				{
					break;
				}
			}
			definition = null;
			return false;
		}

		internal static DamageTypes GetWeaponDamage(ItemData weapon, Attack attack)
		{
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			return GetDamage(weapon, attack, weapon.m_quality, weapon.m_worldLevel, useItemQuality: true);
		}

		internal static DamageTypes GetDamage(ItemData weapon, Attack attack, int quality, float worldLevel, bool useItemQuality = false)
		{
			//IL_0031: Unknown result type (might be due to invalid IL or missing references)
			//IL_0029: Unknown result type (might be due to invalid IL or missing references)
			//IL_0036: 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)
			TryGet(attack, weapon, out var definition);
			Definition val = current;
			ItemData val2 = currentWeapon;
			current = definition;
			currentWeapon = weapon;
			try
			{
				return useItemQuality ? weapon.GetDamage() : weapon.GetDamage(quality, worldLevel);
			}
			finally
			{
				current = val;
				currentWeapon = val2;
			}
		}

		internal static DamageTypes GetBaseDamage(SharedData shared, ItemData item)
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_0037: Unknown result type (might be due to invalid IL or missing references)
			if (item == currentWeapon)
			{
				Definition obj = current;
				if (obj != null && obj.BaseDamage.HasValue)
				{
					return current.BaseDamage.Value;
				}
			}
			return shared.m_damages;
		}

		internal static DamageTypes GetPerLevelDamage(SharedData shared, ItemData item)
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_0037: Unknown result type (might be due to invalid IL or missing references)
			if (item == currentWeapon)
			{
				Definition obj = current;
				if (obj != null && obj.PerLevelDamage.HasValue)
				{
					return current.PerLevelDamage.Value;
				}
			}
			return shared.m_damagesPerLevel;
		}
	}
	internal static class PatchInstructions
	{
		internal static void ReplaceWithInstanceCall(List<CodeInstruction> codes, int index, MethodInfo replacement)
		{
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0014: Expected O, but got Unknown
			CodeInstruction val = codes[index];
			CodeInstruction val2 = new CodeInstruction(OpCodes.Ldarg_0, (object)null);
			val2.labels.AddRange(val.labels);
			val.labels.Clear();
			val2.blocks.AddRange(val.blocks.Where((ExceptionBlock block) => (int)block.blockType != 5));
			val.blocks.RemoveAll((ExceptionBlock block) => (int)block.blockType != 5);
			val.opcode = OpCodes.Call;
			val.operand = replacement;
			codes.Insert(index, val2);
		}
	}
	[HarmonyPatch(typeof(Attack), "Clone")]
	internal static class ClonePatch
	{
		private static void Postfix(Attack __instance, Attack __result)
		{
			DamageContext.TrackClone(__instance, __result);
		}
	}
	[HarmonyPatch]
	internal static class AttackDamagePatch
	{
		private static IEnumerable<MethodBase> TargetMethods()
		{
			yield return AccessTools.DeclaredMethod(typeof(Attack), "DoMeleeAttack", (Type[])null, (Type[])null);
			yield return AccessTools.DeclaredMethod(typeof(Attack), "FireProjectileBurst", (Type[])null, (Type[])null);
			yield return AccessTools.GetDeclaredMethods(typeof(Attack)).Single((MethodInfo method) => !method.IsStatic && method.Name.StartsWith("<DoAreaAttack>g__checkHits|", StringComparison.Ordinal));
		}

		internal static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions)
		{
			List<CodeInstruction> list = instructions.ToList();
			FieldInfo fieldInfo = AccessTools.Field(typeof(Attack), "m_weapon");
			MethodInfo methodInfo = AccessTools.DeclaredMethod(typeof(ItemData), "GetDamage", Type.EmptyTypes, (Type[])null);
			MethodInfo replacement = AccessTools.DeclaredMethod(typeof(DamageContext), "GetWeaponDamage", (Type[])null, (Type[])null);
			int num = 0;
			for (int i = 2; i < list.Count; i++)
			{
				if (CodeInstructionExtensions.Calls(list[i], methodInfo) && CodeInstructionExtensions.LoadsField(list[i - 1], fieldInfo, false) && !(list[i - 2].opcode != OpCodes.Ldarg_0))
				{
					PatchInstructions.ReplaceWithInstanceCall(list, i++, replacement);
					num++;
				}
			}
			if (num != 1)
			{
				throw new InvalidOperationException($"Secondary damage patch expected one weapon GetDamage call, found {num}. Check Valheim/mod versions.");
			}
			return list;
		}
	}
	[HarmonyPatch(typeof(ItemData), "GetDamage", new Type[]
	{
		typeof(int),
		typeof(float)
	})]
	internal static class DamageFieldsPatch
	{
		internal static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions)
		{
			FieldInfo fieldInfo = AccessTools.Field(typeof(SharedData), "m_damages");
			FieldInfo fieldInfo2 = AccessTools.Field(typeof(SharedData), "m_damagesPerLevel");
			int num = 0;
			int num2 = 0;
			List<CodeInstruction> list = instructions.ToList();
			for (int i = 0; i < list.Count; i++)
			{
				if (CodeInstructionExtensions.LoadsField(list[i], fieldInfo, false))
				{
					PatchInstructions.ReplaceWithInstanceCall(list, i++, AccessTools.DeclaredMethod(typeof(DamageContext), "GetBaseDamage", (Type[])null, (Type[])null));
					num++;
				}
				else if (CodeInstructionExtensions.LoadsField(list[i], fieldInfo2, false))
				{
					PatchInstructions.ReplaceWithInstanceCall(list, i++, AccessTools.DeclaredMethod(typeof(DamageContext), "GetPerLevelDamage", (Type[])null, (Type[])null));
					num2++;
				}
			}
			if (num != 1 || num2 != 1)
			{
				throw new InvalidOperationException($"Secondary damage patch expected one base/per-level field read, found {num}/{num2}. Check Valheim/mod versions.");
			}
			return list;
		}
	}
	[HarmonyPatch(typeof(ItemData), "GetTooltip", new Type[]
	{
		typeof(ItemData),
		typeof(int),
		typeof(bool),
		typeof(float),
		typeof(int),
		typeof(bool)
	})]
	internal static class TooltipPatch
	{
		private static void Postfix(ItemData item, int qualityLevel, float worldLevel, ref string __result)
		{
			//IL_001d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0022: Unknown result type (might be due to invalid IL or missing references)
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			//IL_002a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0050: Unknown result type (might be due to invalid IL or missing references)
			//IL_0057: Unknown result type (might be due to invalid IL or missing references)
			Attack secondaryAttack = item.m_shared.m_secondaryAttack;
			if (DamageContext.TryGet(secondaryAttack, item, out var _))
			{
				DamageTypes damage = DamageContext.GetDamage(item, secondaryAttack, qualityLevel, worldLevel);
				string text = GetDamageTooltip(damage, item.m_shared.m_skillType);
				if (secondaryAttack.m_damageMultiplier > 1f)
				{
					((DamageTypes)(ref damage)).Modify(secondaryAttack.m_damageMultiplier);
					text = AppendMultipliedValues(text, GetDamageTooltip(damage, item.m_shared.m_skillType));
				}
				__result = __result + "\n\n<color=orange>Secondary base damage</color>" + text + $"\nSecondary damage multiplier: <color=#66B2FF>{secondaryAttack.m_damageMultiplier:0.###}x</color>";
			}
		}

		internal static string GetDamageTooltip(DamageTypes damage, SkillType skill)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0009: Unknown result type (might be due to invalid IL or missing references)
			//IL_0049: Unknown result type (might be due to invalid IL or missing references)
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			//IL_0021: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0059: Unknown result type (might be due to invalid IL or missing references)
			//IL_0061: Unknown result type (might be due to invalid IL or missing references)
			//IL_006e: Unknown result type (might be due to invalid IL or missing references)
			string text = ((DamageTypes)(ref damage)).GetTooltipString(skill);
			DamageTypes val;
			if (damage.m_chop != 0f)
			{
				string text2 = text;
				val = new DamageTypes
				{
					m_damage = damage.m_chop
				};
				text = text2 + ((DamageTypes)(ref val)).GetTooltipString(skill).Replace("$inventory_damage", "Chop");
			}
			if (damage.m_pickaxe != 0f)
			{
				string text3 = text;
				val = new DamageTypes
				{
					m_damage = damage.m_pickaxe
				};
				text = text3 + ((DamageTypes)(ref val)).GetTooltipString(skill).Replace("$inventory_damage", "Pickaxe");
			}
			return text;
		}

		internal static string AppendMultipliedValues(string baseTooltip, string multipliedTooltip)
		{
			string[] array = baseTooltip.Split(new char[1] { '\n' });
			string[] array2 = multipliedTooltip.Split(new char[1] { '\n' });
			if (array.Length != array2.Length)
			{
				throw new InvalidOperationException("Secondary damage tooltip rows do not match the multiplied damage rows.");
			}
			for (int i = 0; i < array.Length; i++)
			{
				int num = array2[i].IndexOf("<color=orange>", StringComparison.Ordinal);
				if (num >= 0)
				{
					string text = array2[i].Substring(num).TrimEnd(Array.Empty<char>()).Replace("<color=orange>", "<color=#66B2FF>");
					array[i] = array[i].TrimEnd(Array.Empty<char>()) + " " + text;
				}
			}
			return string.Join("\n", array);
		}
	}
}