Decompiled source of ValheimWeaponGems v0.1.3

plugins/ValheimWeaponGems/ValheimWeaponGems.dll

Decompiled 3 days ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security.Cryptography;
using System.Text;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using TMPro;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.Events;
using UnityEngine.Rendering;
using UnityEngine.UI;

[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("ValheimWeaponGems")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("0.1.3.0")]
[assembly: AssemblyInformationalVersion("0.1.3+27ddec7333dc976045ffa1b7d7a4651c9f08abf0")]
[assembly: AssemblyProduct("ValheimWeaponGems")]
[assembly: AssemblyTitle("ValheimWeaponGems")]
[assembly: AssemblyVersion("0.1.3.0")]
namespace ValheimWeaponGems;

internal static class AffixCatalogueDiagnostics
{
	private static readonly HashSet<string> StaffIds = new HashSet<string>(MagicStaffFamilies.Definitions.Select((MagicStaffFamilies.Base b) => b.Id), StringComparer.Ordinal);

	private static ManualLogSource log;

	private static Func<ItemData, int> itemLevel;

	private static Func<ItemData, IReadOnlyList<string>> tagsOf;

	private static MethodInfo rarityOf;

	private static MethodInfo rollableOn;

	private static PropertyInfo familiesOf;

	private static ItemData lastWeapon;

	private static string lastReport;

	private static float nextCheck;

	private static bool active;

	internal static void Initialize(ConfigFile config, ManualLogSource logger)
	{
		if (!config.Bind<bool>("Diagnostics", "LogFireStaffAffixCatalogue", false, "Log PoV item level, rarity, tags, eligible affix families, and already stored native implicit rolls for equipped VWG magical staffs. Restart after changing.").Value)
		{
			return;
		}
		log = logger;
		try
		{
			Assembly assembly = ((object)Chainloader.PluginInfos["treextr.pathofvalheiman"].Instance).GetType().Assembly;
			if (!(bool)PublicMethod(assembly.GetType("Valheiman.Api.Pov", throwOnError: true), "Has", typeof(string)).Invoke(null, new object[1] { "affixes.catalog" }))
			{
				throw new InvalidOperationException("PoV does not advertise affixes.catalog.");
			}
			Type type = assembly.GetType("Valheiman.Api.Items", throwOnError: true);
			Type type2 = assembly.GetType("Valheiman.Api.AffixCatalog", throwOnError: true);
			Type type3 = assembly.GetType("Valheiman.Api.AffixDefinition", throwOnError: true);
			Type typeFromHandle = typeof(ItemData);
			itemLevel = (Func<ItemData, int>)PublicMethod(type, "ItemLevel", typeFromHandle).CreateDelegate(typeof(Func<ItemData, int>));
			tagsOf = (Func<ItemData, IReadOnlyList<string>>)PublicMethod(type2, "TagsOf", typeFromHandle).CreateDelegate(typeof(Func<ItemData, IReadOnlyList<string>>));
			rarityOf = PublicMethod(type, "RarityOf", typeFromHandle);
			rollableOn = PublicMethod(type2, "RollableOn", typeFromHandle, typeof(int));
			familiesOf = type3.GetProperty("Families", BindingFlags.Instance | BindingFlags.Public) ?? throw new MissingMemberException(type3.FullName, "Families");
			active = true;
		}
		catch (Exception ex)
		{
			log.LogWarning((object)("Fire staff catalogue diagnostic unavailable: " + ex.GetBaseException().Message));
		}
	}

	private static MethodInfo PublicMethod(Type type, string name, params Type[] parameters)
	{
		return type.GetMethod(name, BindingFlags.Static | BindingFlags.Public, null, parameters, null) ?? throw new MissingMethodException(type.FullName, name);
	}

	internal static void CheckEquippedStaff()
	{
		if (!active || Time.unscaledTime < nextCheck)
		{
			return;
		}
		nextCheck = Time.unscaledTime + 2f;
		Player localPlayer = Player.m_localPlayer;
		ItemData val = (((Object)(object)localPlayer != (Object)null) ? ((Humanoid)localPlayer).GetCurrentWeapon() : null);
		object obj;
		if (val == null)
		{
			obj = null;
		}
		else
		{
			GameObject dropPrefab = val.m_dropPrefab;
			obj = ((dropPrefab != null) ? ((Object)dropPrefab).name : null);
		}
		string text = (string)obj;
		if (!StaffIds.Contains(text))
		{
			lastWeapon = null;
			return;
		}
		try
		{
			SortedSet<string> sortedSet = new SortedSet<string>(StringComparer.Ordinal);
			foreach (object item in (IEnumerable)rollableOn.Invoke(null, new object[2] { val, -1 }))
			{
				sortedSet.UnionWith((IReadOnlyList<string>)familiesOf.GetValue(item));
			}
			string value;
			string text2 = ((val.m_customData != null && val.m_customData.TryGetValue("pt.implicit", out value) && !string.IsNullOrEmpty(value)) ? value : "(none stored)");
			string text3 = $"{text}: PoV item level {itemLevel(val)}, rarity {rarityOf.Invoke(null, new object[1] { val })}; " + "tags [" + string.Join(", ", tagsOf(val)) + "]; eligible affix families [" + string.Join(", ", sortedSet) + "]; stored native implicit rolls [" + text2 + "].";
			if (lastWeapon != val || lastReport != text3)
			{
				log.LogInfo((object)("Fire staff catalogue: " + text3));
			}
			lastWeapon = val;
			lastReport = text3;
		}
		catch (Exception ex)
		{
			active = false;
			log.LogWarning((object)("Fire staff catalogue diagnostic disabled: " + ex.GetBaseException().Message));
		}
	}
}
internal static class AttackBleedingChance
{
	private sealed class Grant
	{
		internal float Flat;

		internal bool Written;

		internal bool Forwarded;
	}

	private static readonly ConditionalWeakTable<Attack, Grant> Attacks = new ConditionalWeakTable<Attack, Grant>();

	private static readonly ConditionalWeakTable<HitData, Grant> Hits = new ConditionalWeakTable<HitData, Grant>();

	private static Action<HitData, float[]> put;

	private static int payloadSize;

	private static int bleedSlot;

	private static ManualLogSource logger;

	private static Func<HitData, float> nativeFlat;

	private static Func<Character, bool> nativeBleeding;

	private static float[] lastChance;

	private static Func<HitData> currentHit;

	internal static ConfigEntry<bool> Diagnostics;

	internal static bool TraceEnabled => Diagnostics?.Value ?? false;

	internal static bool Ready { get; private set; }

	internal static void Initialize(ManualLogSource log)
	{
		logger = log;
		Ready = Plugin.Install(log, "attack-bleed-chance", "skill-scoped native bleeding chance", delegate(Harmony harmony)
		{
			//IL_0359: Unknown result type (might be due to invalid IL or missing references)
			//IL_0366: Expected O, but got Unknown
			//IL_037b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0388: Expected O, but got Unknown
			//IL_03e5: Unknown result type (might be due to invalid IL or missing references)
			//IL_03f2: Expected O, but got Unknown
			//IL_041d: Unknown result type (might be due to invalid IL or missing references)
			//IL_042a: Expected O, but got Unknown
			//IL_048e: Unknown result type (might be due to invalid IL or missing references)
			//IL_049b: Expected O, but got Unknown
			Assembly povAssembly = Plugin.PovAssembly;
			Type type = povAssembly.GetType("PassiveTree.CrossAilments", throwOnError: true);
			Type type2 = povAssembly.GetType("PassiveTree.Subject", throwOnError: true);
			Array array = (AccessTools.DeclaredField(type, "Kinds")?.GetValue(null) as Array) ?? throw new MissingFieldException(type.FullName, "Kinds");
			int num = Array.IndexOf(ToEnums(array), (Enum)Enum.Parse(type2, "Bleeding"));
			if (num < 0 || array.Length == 0)
			{
				throw new InvalidOperationException("Native bleeding payload kind unavailable.");
			}
			MethodInfo read = AccessTools.DeclaredMethod(type, "ReadFlat", new Type[2]
			{
				typeof(HitData),
				type2
			}, (Type[])null);
			MethodInfo methodInfo = AccessTools.DeclaredMethod(type, "Capture", new Type[4]
			{
				typeof(Character),
				typeof(HitData),
				povAssembly.GetType("PassiveTree.StatSet", throwOnError: true),
				povAssembly.GetType("PassiveTree.Subjects", throwOnError: true)
			}, (Type[])null);
			MethodInfo methodInfo2 = AccessTools.DeclaredMethod(type, "Put", new Type[2]
			{
				typeof(HitData),
				typeof(float[])
			}, (Type[])null);
			if (read?.ReturnType != typeof(float) || methodInfo?.ReturnType != typeof(void) || methodInfo2?.ReturnType != typeof(void))
			{
				throw new MissingMethodException("Native cross-ailment payload contract changed.");
			}
			FieldInfo field = AccessTools.DeclaredField(type, "Kinds");
			List<CodeInstruction> readCode = Original(read);
			List<CodeInstruction> putCode = Original(methodInfo2);
			int num2 = Enumerable.Range(0, Math.Max(0, readCode.Count - 7)).Count((int i) => readCode[i].opcode == OpCodes.Ldc_I4_3 && CodeInstructionExtensions.LoadsField(readCode[i + 1], field, false) && readCode[i + 2].opcode == OpCodes.Ldlen && readCode[i + 3].opcode == OpCodes.Conv_I4 && readCode[i + 4].opcode == OpCodes.Mul && readCode[i + 5].opcode == OpCodes.Ldloc_0 && readCode[i + 6].opcode == OpCodes.Add && readCode[i + 7].opcode == OpCodes.Ldelem_R4);
			int num3 = Enumerable.Range(0, Math.Max(0, putCode.Count - 4)).Count((int i) => CodeInstructionExtensions.LoadsField(putCode[i], field, false) && putCode[i + 1].opcode == OpCodes.Ldlen && putCode[i + 2].opcode == OpCodes.Conv_I4 && putCode[i + 3].opcode == OpCodes.Ldc_I4_5 && putCode[i + 4].opcode == OpCodes.Mul);
			if (num2 != 1 || num3 != 1)
			{
				throw new InvalidOperationException("Native bleeding flat payload layout changed; skill adapter not installed.");
			}
			put = AccessTools.MethodDelegate<Action<HitData, float[]>>(methodInfo2, (object)null, true);
			object bleedingSubject = Enum.Parse(type2, "Bleeding");
			nativeFlat = (HitData hit) => (float)read.Invoke(null, new object[2] { hit, bleedingSubject });
			nativeBleeding = AccessTools.MethodDelegate<Func<Character, bool>>(AccessTools.DeclaredMethod(povAssembly.GetType("PassiveTree.Combat", throwOnError: true), "Bleeding", new Type[1] { typeof(Character) }, (Type[])null), (object)null, true);
			currentHit = AccessTools.MethodDelegate<Func<HitData>>(AccessTools.DeclaredMethod(povAssembly.GetType("PassiveTree.Ailments", throwOnError: true), "get_Hit", Type.EmptyTypes, (Type[])null), (object)null, true);
			lastChance = AccessTools.DeclaredField(povAssembly.GetType("PassiveTree.AilmentGauges", throwOnError: true), "LastChance")?.GetValue(null) as float[];
			payloadSize = array.Length * 5;
			bleedSlot = array.Length * 3 + num;
			harmony.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(Attack), "ModifyDamage", new Type[2]
			{
				typeof(HitData),
				typeof(float)
			}, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(typeof(AttackBleedingChance), "Stamp", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			harmony.Patch((MethodBase)methodInfo, (HarmonyMethod)null, new HarmonyMethod(typeof(AttackBleedingChance), "AfterCapture", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			MethodInfo methodInfo3 = AccessTools.DeclaredMethod(povAssembly.GetType("PassiveTree.CriticalHits", throwOnError: true), "CopyBudget", new Type[2]
			{
				typeof(HitData),
				typeof(HitData)
			}, (Type[])null) ?? throw new MissingMethodException("CriticalHits.CopyBudget");
			harmony.Patch((MethodBase)methodInfo3, (HarmonyMethod)null, new HarmonyMethod(typeof(AttackBleedingChance), "CopyPending", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			harmony.Patch((MethodBase)AccessTools.DeclaredMethod(povAssembly.GetType("PassiveTree.AilmentGauges+Physical", throwOnError: true), "Postfix", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(typeof(AttackBleedingChance), "AfterPhysical", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			harmony.Patch((MethodBase)AccessTools.DeclaredMethod(povAssembly.GetType("PassiveTree.Combat", throwOnError: true), "Wounded", new Type[4]
			{
				typeof(Character),
				typeof(Player),
				typeof(float),
				typeof(float)
			}, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(typeof(AttackBleedingChance), "AfterWounded", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			log.LogInfo((object)"VWG bleeding chance uses native CrossAilments flat payload, captured after native stats; no custom wound or DoT.");
		});
	}

	private static List<CodeInstruction> Original(MethodInfo method)
	{
		return ((IEnumerable<CodeInstruction>)typeof(PatchProcessor).GetMethods(BindingFlags.Static | BindingFlags.Public).Single((MethodInfo m) => m.Name == "GetOriginalInstructions" && m.GetParameters().Length == 2 && !m.GetParameters()[1].ParameterType.IsByRef).Invoke(null, new object[2] { method, null })).ToList();
	}

	private static Enum[] ToEnums(Array values)
	{
		Enum[] array = new Enum[values.Length];
		for (int i = 0; i < values.Length; i++)
		{
			array[i] = (Enum)values.GetValue(i);
		}
		return array;
	}

	internal static void Track(Attack attack, float flat)
	{
		if (Ready && flat > 0f && !float.IsNaN(flat) && !float.IsInfinity(flat))
		{
			Attacks.GetValue(attack, (Attack _) => new Grant()).Flat += flat;
		}
	}

	internal static void GrantHit(HitData hit, float flat)
	{
		if (Ready && hit != null && flat > 0f && !Hits.TryGetValue(hit, out var _))
		{
			Hits.Add(hit, new Grant
			{
				Flat = flat
			});
		}
	}

	private static void Stamp(Attack __instance, HitData __0)
	{
		if (__0 != null && Attacks.TryGetValue(__instance, out var value) && !Hits.TryGetValue(__0, out var _))
		{
			Hits.Add(__0, new Grant
			{
				Flat = value.Flat
			});
		}
	}

	private static void AfterCapture(HitData __1)
	{
		if (__1 != null && Hits.TryGetValue(__1, out var value) && !value.Written && !value.Forwarded)
		{
			float[] array = new float[payloadSize];
			array[bleedSlot] = value.Flat;
			put(__1, array);
			value.Written = true;
			if (TraceEnabled)
			{
				logger.LogInfo((object)$"VWG bleed contribution accepted on prepared hit: +{value.Flat:P0}, native flat={nativeFlat(__1):P0}, Slash={__1.m_damage.m_slash:0.##}.");
			}
		}
	}

	private static void CopyPending(HitData __0, HitData __1)
	{
		if (__0 != null && __1 != null && Hits.TryGetValue(__0, out var value) && !value.Written && !value.Forwarded && !Hits.TryGetValue(__1, out var _))
		{
			Hits.Add(__1, new Grant
			{
				Flat = value.Flat
			});
			value.Forwarded = true;
			if (TraceEnabled)
			{
				logger.LogInfo((object)"VWG pending bleed contribution transferred to native damage clone.");
			}
		}
	}

	private static void AfterPhysical(Character __0, HitData __1)
	{
		if (TraceEnabled && __1 != null && !((Object)(object)__0 == (Object)null) && !(nativeFlat(__1) < 1f))
		{
			logger.LogInfo((object)($"VWG/native physical ailment hook entered: Slash={__1.m_damage.m_slash:0.##}, " + $"flat={nativeFlat(__1):P0}, last bleed chance={((lastChance != null && lastChance.Length > 2) ? lastChance[2] : (-1f)):P0}, " + $"native wound active={nativeBleeding(__0)}. Native defenses/source rules still apply."));
		}
	}

	private static void AfterWounded(Character __0, float __2, float __3, bool __result)
	{
		if (TraceEnabled && __result)
		{
			HitData val = currentHit();
			if (val != null && nativeFlat(val) >= 1f)
			{
				logger.LogInfo((object)$"VWG/native wound created/refreshed: target={((Object)__0).name}, native DPS={__2:0.##}, duration={__3:0.##}s.");
			}
		}
	}
}
internal static class AttackPoisonChance
{
	private sealed class VisualReceipt
	{
		internal bool Used;
	}

	private sealed class Grant
	{
		internal bool Written;

		internal bool Forwarded;

		internal VisualReceipt Visual;
	}

	private static readonly ConditionalWeakTable<Attack, VisualReceipt> Attacks = new ConditionalWeakTable<Attack, VisualReceipt>();

	private static readonly ConditionalWeakTable<HitData, Grant> Hits = new ConditionalWeakTable<HitData, Grant>();

	private static Action<HitData, float[]> put;

	private static Func<string, float> tuning;

	private static int payloadSize;

	private static int slot;

	private static ManualLogSource log;

	internal static bool Ready { get; private set; }

	internal static void Initialize(ManualLogSource logger)
	{
		log = logger;
		Ready = Plugin.Install(log, "viper-poison-chance", "Viper Strike native Poison chance", delegate(Harmony harmony)
		{
			//IL_0161: Unknown result type (might be due to invalid IL or missing references)
			//IL_016e: Expected O, but got Unknown
			//IL_018e: Unknown result type (might be due to invalid IL or missing references)
			//IL_019b: Expected O, but got Unknown
			//IL_01c6: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d3: Expected O, but got Unknown
			Assembly povAssembly = Plugin.PovAssembly;
			BindNative(povAssembly);
			Type type = povAssembly.GetType("PassiveTree.CrossAilments", throwOnError: true);
			MethodInfo methodInfo = AccessTools.DeclaredMethod(type, "ReadFlat", (Type[])null, (Type[])null);
			FieldInfo field = AccessTools.DeclaredField(type, "Kinds");
			MethodInfo methodInfo2 = AccessTools.DeclaredMethod(type, "Put", (Type[])null, (Type[])null);
			MethodInfo methodInfo3 = typeof(PatchProcessor).GetMethods(BindingFlags.Static | BindingFlags.Public).Single((MethodInfo m) => m.Name == "GetOriginalInstructions" && m.GetParameters().Length == 2 && !m.GetParameters()[1].ParameterType.IsByRef);
			List<CodeInstruction> code = ((IEnumerable<CodeInstruction>)methodInfo3.Invoke(null, new object[2] { methodInfo, null })).ToList();
			if (Enumerable.Range(0, Math.Max(0, code.Count - 7)).Count((int i) => code[i].opcode == OpCodes.Ldc_I4_3 && CodeInstructionExtensions.LoadsField(code[i + 1], field, false) && code[i + 2].opcode == OpCodes.Ldlen && code[i + 3].opcode == OpCodes.Conv_I4 && code[i + 4].opcode == OpCodes.Mul && code[i + 5].opcode == OpCodes.Ldloc_0 && code[i + 6].opcode == OpCodes.Add && code[i + 7].opcode == OpCodes.Ldelem_R4) != 1)
			{
				throw new InvalidOperationException("Native Poison flat chance payload layout changed.");
			}
			List<CodeInstruction> putCode = ((IEnumerable<CodeInstruction>)methodInfo3.Invoke(null, new object[2] { methodInfo2, null })).ToList();
			if (Enumerable.Range(0, Math.Max(0, putCode.Count - 4)).Count((int i) => CodeInstructionExtensions.LoadsField(putCode[i], field, false) && putCode[i + 1].opcode == OpCodes.Ldlen && putCode[i + 2].opcode == OpCodes.Conv_I4 && putCode[i + 3].opcode == OpCodes.Ldc_I4_5 && putCode[i + 4].opcode == OpCodes.Mul) != 1)
			{
				throw new InvalidOperationException("Native Poison payload size contract changed.");
			}
			harmony.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(Attack), "ModifyDamage", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(typeof(AttackPoisonChance), "Mark", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			harmony.Patch((MethodBase)AccessTools.DeclaredMethod(type, "Capture", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(typeof(AttackPoisonChance), "AfterCapture", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			harmony.Patch((MethodBase)AccessTools.DeclaredMethod(povAssembly.GetType("PassiveTree.CriticalHits", throwOnError: true), "CopyBudget", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(typeof(AttackPoisonChance), "CopyPending", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
		});
	}

	internal static void BindNative(Assembly pov)
	{
		Type type = pov.GetType("PassiveTree.CrossAilments", throwOnError: true);
		Type type2 = pov.GetType("PassiveTree.Subject", throwOnError: true);
		if (!(type.GetField("Kinds", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic).GetValue(null) is Array { Length: not 0 } array))
		{
			throw new MissingFieldException("CrossAilments.Kinds");
		}
		int num = -1;
		for (int i = 0; i < array.Length; i++)
		{
			if (array.GetValue(i).Equals(Enum.Parse(type2, "Poisoning")))
			{
				num = i;
			}
		}
		if (num < 0)
		{
			throw new InvalidOperationException("Native Poisoning subject unavailable.");
		}
		payloadSize = array.Length * 5;
		slot = array.Length * 3 + num;
		MethodInfo method = type.GetMethod("Put", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic, null, new Type[2]
		{
			typeof(HitData),
			typeof(float[])
		}, null);
		put = (Action<HitData, float[]>)Delegate.CreateDelegate(typeof(Action<HitData, float[]>), method);
		MethodInfo method2 = pov.GetType("PassiveTree.Tunables", throwOnError: true).GetMethod("Of", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic, null, new Type[1] { typeof(string) }, null);
		tuning = (Func<string, float>)Delegate.CreateDelegate(typeof(Func<string, float>), method2);
	}

	internal static float BaseContribution(float nativeBase)
	{
		return 0.6f - nativeBase;
	}

	internal static void Track(Attack attack)
	{
		Attacks.Add(attack, new VisualReceipt());
	}

	private static void Mark(Attack __instance, HitData __0)
	{
		if (__0 != null && Attacks.TryGetValue(__instance, out var value) && !Hits.TryGetValue(__0, out var _))
		{
			Hits.Add(__0, new Grant
			{
				Visual = value
			});
		}
	}

	private static void CopyPending(HitData __0, HitData __1)
	{
		if (__0 != null && __1 != null && Hits.TryGetValue(__0, out var value) && !value.Forwarded && !Hits.TryGetValue(__1, out var _))
		{
			Hits.Add(__1, new Grant
			{
				Visual = value.Visual,
				Written = value.Written
			});
			value.Forwarded = true;
		}
	}

	private static void AfterCapture(HitData __1)
	{
		if (__1 != null && Hits.TryGetValue(__1, out var value) && !value.Written && !value.Forwarded)
		{
			float[] array = new float[payloadSize];
			array[slot] = BaseContribution(tuning("ailment.poison.base-chance"));
			put(__1, array);
			value.Written = true;
			ManualLogSource obj = log;
			if (obj != null)
			{
				obj.LogDebug((object)"VWG Viper Strike: 60% skill base Poison chance captured once before native flat/increased/more chance and defenses.");
			}
		}
	}

	internal static bool TakeVisual(HitData hit)
	{
		if (hit == null || !Hits.TryGetValue(hit, out var value) || value.Visual.Used)
		{
			return false;
		}
		value.Visual.Used = true;
		return true;
	}

	internal static bool HasVisual(HitData hit)
	{
		if (hit != null && Hits.TryGetValue(hit, out var value))
		{
			return !value.Visual.Used;
		}
		return false;
	}
}
internal static class AttackSupportDamage
{
	private sealed class Context
	{
		internal readonly string Skill;

		internal readonly int Rank;

		internal readonly ItemData Weapon;

		internal readonly ResolvedSupports Supports;

		internal readonly bool ConvertBase;

		internal readonly ConditionalWeakTable<HitData, object> Hits = new ConditionalWeakTable<HitData, object>();

		internal Context(string skill, int rank, ItemData weapon, ResolvedSupports supports, bool convertBase)
		{
			Skill = skill;
			Rank = rank;
			Weapon = weapon;
			Supports = supports;
			ConvertBase = convertBase;
		}
	}

	private static readonly ConditionalWeakTable<Attack, Context> Attacks = new ConditionalWeakTable<Attack, Context>();

	private static readonly object Applied = new object();

	private static bool ready;

	private static bool initializationAttempted;

	internal static bool Ready => ready;

	internal static void Initialize(ManualLogSource log)
	{
		if (initializationAttempted)
		{
			return;
		}
		initializationAttempted = true;
		ready = Plugin.Install(log, "attack-support-damage", "flat damage for VWG Attack Supports", delegate(Harmony harmony)
		{
			//IL_007b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0089: Expected O, but got Unknown
			MethodInfo methodInfo = AccessTools.DeclaredMethod(typeof(Attack), "ModifyDamage", new Type[2]
			{
				typeof(HitData),
				typeof(float)
			}, (Type[])null);
			if (methodInfo == null || methodInfo.IsStatic || methodInfo.ReturnType != typeof(void))
			{
				throw new MissingMethodException("Attack.ModifyDamage(HitData, float)");
			}
			harmony.Patch((MethodBase)methodInfo, new HarmonyMethod(typeof(AttackSupportDamage), "AddFlatDamage", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
		});
	}

	internal static void Track(Attack attack, string skill, int rank, ItemData weapon, ResolvedSupports supports, bool convertBase = false)
	{
		if (ready && (supports.FlatCold != 0f || supports.FlatLightning != 0f || (convertBase && (supports.ColdConverted != 0f || supports.ColdExtraFire != 0f))))
		{
			if (convertBase && FrostBladesConversion.Ready && (supports.ColdConverted != 0f || supports.ColdExtraFire != 0f))
			{
				FrostBladesConversion.Track(attack, new FrostBladesConversion.Context
				{
					Supports = supports,
					SupportsOnly = true
				});
				convertBase = false;
			}
			Attacks.Add(attack, new Context(skill, rank, weapon, supports, convertBase));
		}
	}

	private static void AddFlatDamage(Attack __instance, HitData __0)
	{
		//IL_005d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0062: Unknown result type (might be due to invalid IL or missing references)
		//IL_0047: Unknown result type (might be due to invalid IL or missing references)
		//IL_004c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0067: Unknown result type (might be due to invalid IL or missing references)
		if (__0 != null && Attacks.TryGetValue(__instance, out var value) && !value.Hits.TryGetValue(__0, out var _))
		{
			value.Hits.Add(__0, Applied);
			__0.m_damage = (value.ConvertBase ? value.Supports.ApplyBaseDamage(__0.m_damage) : value.Supports.AddFlatDamage(__0.m_damage));
		}
	}
}
internal static class BowProjectileHits
{
	internal delegate void Observer(Projectile projectile, IDestructible target, HitData hit, Vector3 incoming);

	private sealed class Hooks
	{
		internal string Name;

		internal Observer Before;

		internal Observer After;
	}

	private sealed class Frame
	{
		internal Projectile Projectile;

		internal Vector3 Incoming;
	}

	private static readonly List<Hooks> Observers = new List<Hooks>();

	private static FieldRef<Projectile, Vector3> velocity;

	[ThreadStatic]
	private static Frame frame;

	private static ManualLogSource log;

	private static bool attempted;

	private static bool installed;

	internal static bool Ready
	{
		get
		{
			if (installed)
			{
				return CombatPatchSafety.ProjectileHealthy;
			}
			return false;
		}
	}

	internal static bool Subscribed(string name)
	{
		return Observers.Exists((Hooks h) => h.Name == name);
	}

	internal static void Initialize(ManualLogSource logger)
	{
		if (!attempted)
		{
			attempted = true;
			log = logger;
			installed = Plugin.Install(log, "bow-projectile-impact", "native bow projectile hit dispatch", delegate(Harmony h)
			{
				//IL_003e: Unknown result type (might be due to invalid IL or missing references)
				//IL_0043: Unknown result type (might be due to invalid IL or missing references)
				//IL_005f: Unknown result type (might be due to invalid IL or missing references)
				//IL_0065: Expected O, but got Unknown
				//IL_0075: Unknown result type (might be due to invalid IL or missing references)
				//IL_0080: Expected O, but got Unknown
				//IL_0080: Expected O, but got Unknown
				velocity = AccessTools.FieldRefAccess<Projectile, Vector3>("m_vel");
				MethodInfo target = AccessTools.DeclaredMethod(typeof(Projectile), "OnHit", (Type[])null, (Type[])null);
				CombatHitObservation.Prevalidate(target);
				HarmonyMethod val = new HarmonyMethod(typeof(BowProjectileHits), "Begin", (Type[])null)
				{
					priority = 800
				};
				CombatPatchSafety.Patch(postfix: null, finalizer: new HarmonyMethod(typeof(BowProjectileHits), "End", (Type[])null), h: h, target: target, prefix: val, transpiler: new HarmonyMethod(typeof(BowProjectileHits), "ImpactHit", (Type[])null));
			});
		}
	}

	internal static void Subscribe(string name, Observer before, Observer after)
	{
		Observers.RemoveAll((Hooks x) => x.Name == name);
		Observers.Add(new Hooks
		{
			Name = name,
			Before = before,
			After = after
		});
	}

	private static void Begin(Projectile __instance, out Frame __state)
	{
		//IL_001f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0024: Unknown result type (might be due to invalid IL or missing references)
		__state = frame;
		frame = new Frame
		{
			Projectile = __instance,
			Incoming = velocity.Invoke(__instance)
		};
	}

	private static void End(Frame __state)
	{
		frame = __state;
	}

	private static void Notify(bool before, Projectile projectile, IDestructible target, HitData hit, Vector3 incoming)
	{
		//IL_0035: Unknown result type (might be due to invalid IL or missing references)
		for (int num = Observers.Count - 1; num >= 0; num--)
		{
			Hooks hooks = Observers[num];
			try
			{
				(before ? hooks.Before : hooks.After)?.Invoke(projectile, target, hit, incoming);
			}
			catch (Exception arg)
			{
				log.LogError((object)$"VWG {hooks.Name} impact observer disabled after failure: {arg}");
				Observers.RemoveAt(num);
			}
		}
	}

	private static void BeforeDamage(IDestructible target, HitData hit, Projectile projectile)
	{
		//IL_001f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0017: 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)
		//IL_0030: Unknown result type (might be due to invalid IL or missing references)
		//IL_0035: Unknown result type (might be due to invalid IL or missing references)
		Vector3 incoming = ((frame != null && frame.Projectile == projectile) ? frame.Incoming : (hit?.m_dir ?? Vector3.zero));
		Notify(before: true, projectile, target, hit, incoming);
	}

	private static void AfterDamage(IDestructible target, HitData hit, Projectile projectile)
	{
		//IL_001f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0017: 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)
		//IL_0030: Unknown result type (might be due to invalid IL or missing references)
		//IL_0035: Unknown result type (might be due to invalid IL or missing references)
		Vector3 incoming = ((frame != null && frame.Projectile == projectile) ? frame.Incoming : (hit?.m_dir ?? Vector3.zero));
		Notify(before: false, projectile, target, hit, incoming);
	}

	private static IEnumerable<CodeInstruction> ImpactHit(IEnumerable<CodeInstruction> instructions, ILGenerator generator)
	{
		return CombatHitObservation.Inject(instructions, generator, AccessTools.DeclaredMethod(typeof(BowProjectileHits), "BeforeDamage", (Type[])null, (Type[])null), AccessTools.DeclaredMethod(typeof(BowProjectileHits), "AfterDamage", (Type[])null, (Type[])null));
	}
}
internal static class ChainFlightDiagnostics
{
	private sealed class Selection
	{
		internal Vector3 From;

		internal int Checks;

		internal Character Target;

		internal string Mode = "Chain";
	}

	internal sealed class Flight
	{
		internal Projectile Projectile;

		internal Character Target;

		internal Action<string> Log;

		internal float Born;

		internal float Next;

		internal int Samples;

		internal int Id;

		internal int ValidChecks;

		internal string Mode;

		internal bool Impact;
	}

	[ThreadStatic]
	private static Selection selection;

	[ThreadStatic]
	private static Projectile spawning;

	private static readonly ConditionalWeakTable<Projectile, Flight> Flights = new ConditionalWeakTable<Projectile, Flight>();

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

	private static readonly Dictionary<string, FieldInfo> Cached = typeof(Projectile).GetFields(Fields).ToDictionary((FieldInfo f) => f.Name);

	private static bool compared;

	internal static Func<bool> Enabled;

	internal static Func<Action<string>> Logger;

	internal static Action<Projectile> Register;

	[ThreadStatic]
	private static Character selected;

	private static bool Active => Enabled?.Invoke() ?? false;

	private static void Safe(Action a)
	{
		if (!Active)
		{
			return;
		}
		try
		{
			a();
		}
		catch (Exception ex)
		{
			Logger?.Invoke()?.Invoke("Flight diagnostic unavailable: " + ex.GetBaseException().Message);
		}
	}

	private static object Field(Projectile p, string name)
	{
		if (!Cached.TryGetValue(name, out var value))
		{
			return "missing";
		}
		return value.GetValue(p);
	}

	private static string Target(Character c)
	{
		//IL_0038: 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_0054: Unknown result type (might be due to invalid IL or missing references)
		if (!Object.op_Implicit((Object)(object)c))
		{
			return "none/destroyed";
		}
		return $"C{((Object)c).GetInstanceID()} {((Object)c).name} pos={((Component)c).transform.position} center={c.GetCenterPoint()} velocity={c.GetVelocity()}";
	}

	private static string State(Projectile p)
	{
		//IL_008f: Unknown result type (might be due to invalid IL or missing references)
		ZNetView component = ((Component)p).GetComponent<ZNetView>();
		Component pm = ((Component)p).GetComponent(Plugin.PovAssembly.GetType("PassiveTree.ProjMods"));
		HashSet<Character> hashSet = (Object.op_Implicit((Object)(object)pm) ? (((object)pm).GetType().GetField("Hit", Fields)?.GetValue(pm) as HashSet<Character>) : null);
		return string.Format("P{0} pos={1} vel={2} ttl={3} radius={4} gravity={5} drag={6} layer={7} ", ((Object)p).GetInstanceID(), ((Component)p).transform.position, Field(p, "m_vel"), p.m_ttl, p.m_rayRadius, p.m_gravity, p.m_drag, ((Component)p).gameObject.layer) + string.Format("netValid={0} owner={1} didHit={2} start={3} haveStart={4} ", Object.op_Implicit((Object)(object)component) && component.IsValid(), Object.op_Implicit((Object)(object)component) && component.IsValid() && component.IsOwner(), Field(p, "m_didHit"), Field(p, "m_startPoint"), Field(p, "m_haveStartPoint")) + "CH=" + Mod("Chain") + " PI=" + Mod("Pierce") + " BO=" + Mod("Bounce") + " volley=" + Mod("Volley") + " continuation=" + Mod("Continuation") + " ignore=" + Mod("Ignore") + " kind=" + Mod("Kind") + " history=[" + ((hashSet == null) ? "absent" : string.Join(",", hashSet.Select((Character c) => (!Object.op_Implicit((Object)(object)c)) ? "destroyed" : ("C" + ((Object)c).GetInstanceID())))) + "]";
		string Mod(string n)
		{
			if (!Object.op_Implicit((Object)(object)pm))
			{
				return "absent";
			}
			return Convert.ToString(((object)pm).GetType().GetField(n, Fields)?.GetValue(pm));
		}
	}

	internal static void Install(Action<string, MethodInfo, string, string, string> bind)
	{
		Assembly povAssembly = Plugin.PovAssembly;
		Type type = povAssembly.GetType("PassiveTree.ProjectileMods");
		Type type2 = povAssembly.GetType("PassiveTree.ProjectileMods+Projectile_OnHit");
		bind("flight-link", type2.GetMethod("NextLink", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic), "LinkBegin", null, "LinkEnd");
		bind("flight-aim-dir", type.GetMethod("AimDir", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic), null, "Aimed", null);
		bind("flight-aim-point", type.GetMethod("AimPoint", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic), null, "AimPoint", null);
		bind("flight-hostile", type.GetMethod("Hostile", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic), null, "Hostile", null);
		bind("flight-visible", type.GetMethod("Reachable", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic), null, "Visible", null);
		bind("flight-bounce", type2.GetMethod("Ricochet", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic), "BounceBegin", null, "LinkEnd");
		bind("flight-spawn", type2.GetMethod("Spawn", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic), "SpawnBegin", "SpawnEnd", "SpawnFinally");
		bind("flight-tick", typeof(Projectile).GetMethod("FixedUpdate", Fields), null, "Tick", null);
		bind("flight-valid", typeof(Projectile).GetMethod("IsValidTarget", Fields), null, "Valid", null);
		bind("flight-impact", typeof(Projectile).GetMethod("OnHit", Fields), "Impact", "ImpactDone", null);
		bind("flight-destroy", typeof(ZNetScene).GetMethod("Destroy", Fields, null, new Type[1] { typeof(GameObject) }, null), "Destroying", null, null);
	}

	private static void LinkBegin(Vector3 __0, HashSet<Character> __2, out object __state)
	{
		//IL_0007: Unknown result type (might be due to invalid IL or missing references)
		//IL_0008: 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_002f: Unknown result type (might be due to invalid IL or missing references)
		__state = selection;
		if (!Active)
		{
			return;
		}
		selection = new Selection
		{
			From = __0
		};
		selected = null;
		Safe(delegate
		{
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ba: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c0: Unknown result type (might be due to invalid IL or missing references)
			Vector3 from = __0;
			foreach (Character item in (from c in Character.GetAllCharacters()
				where Object.op_Implicit((Object)(object)c)
				select c).OrderBy(delegate(Character c)
			{
				//IL_0001: Unknown result type (might be due to invalid IL or missing references)
				//IL_0007: Unknown result type (might be due to invalid IL or missing references)
				//IL_000c: Unknown result type (might be due to invalid IL or missing references)
				//IL_0011: Unknown result type (might be due to invalid IL or missing references)
				Vector3 val = c.GetCenterPoint() - from;
				return ((Vector3)(ref val)).sqrMagnitude;
			}).Take(6))
			{
				Logger()?.Invoke($"NextLink candidate {Target(item)} distance={Vector3.Distance(from, item.GetCenterPoint()):0.###} in14m={Vector3.Distance(from, item.GetCenterPoint()) <= 14f} history={__2?.Contains(item)}");
			}
		});
	}

	private static void BounceBegin(out object __state)
	{
		__state = selection;
		if (Active)
		{
			selection = new Selection
			{
				Mode = "Bounce"
			};
		}
	}

	private static void LinkEnd(object __state)
	{
		selection = __state as Selection;
	}

	private static void Aimed(Vector3 __0, Character __1, float __2, Vector3 __result)
	{
		//IL_000d: Unknown result type (might be due to invalid IL or missing references)
		//IL_000e: Unknown result type (might be due to invalid IL or missing references)
		//IL_001b: Unknown result type (might be due to invalid IL or missing references)
		//IL_001c: Unknown result type (might be due to invalid IL or missing references)
		Safe(delegate
		{
			//IL_0047: Unknown result type (might be due to invalid IL or missing references)
			//IL_0063: Unknown result type (might be due to invalid IL or missing references)
			if (selection != null && Logger() != null)
			{
				selected = __1;
				selection.Target = __1;
				Logger()($"AimDir origin={__0} speed={__2} result={__result} target={Target(__1)}");
			}
		});
	}

	private static void AimPoint(Vector3 __0, Vector3 __1, Vector3 __result)
	{
		//IL_0006: Unknown result type (might be due to invalid IL or missing references)
		//IL_0007: Unknown result type (might be due to invalid IL or missing references)
		//IL_000d: Unknown result type (might be due to invalid IL or missing references)
		//IL_000e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0014: Unknown result type (might be due to invalid IL or missing references)
		//IL_0015: Unknown result type (might be due to invalid IL or missing references)
		Safe(delegate
		{
			//IL_001c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			//IL_0032: Unknown result type (might be due to invalid IL or missing references)
			if (selection != null)
			{
				Logger()?.Invoke($"AimPoint origin={__0} requestedPoint={__1} resultDir={__result}");
			}
		});
	}

	private static void Hostile(Character __0, Character __1, bool __result)
	{
		Safe(delegate
		{
			//IL_0020: 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)
			if (selection != null && Object.op_Implicit((Object)(object)__0) && Vector3.Distance(__0.GetCenterPoint(), selection.From) < 20f && selection.Checks++ < 16)
			{
				Logger()?.Invoke(string.Format("native Hostile={0} candidate={1} caster={2}", __result, Target(__0), Object.op_Implicit((Object)(object)__1) ? ("C" + ((Object)__1).GetInstanceID()) : "null"));
			}
		});
	}

	private static void Visible(Vector3 __0, Character __1, bool __result)
	{
		//IL_000d: Unknown result type (might be due to invalid IL or missing references)
		//IL_000e: Unknown result type (might be due to invalid IL or missing references)
		Safe(delegate
		{
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			if (selection != null)
			{
				Logger()?.Invoke($"native Reachable={__result} from={__0} candidate={Target(__1)}");
			}
		});
	}

	private static void SpawnBegin(Projectile __0, Vector3 __2, Vector3 __3, GameObject __4, out object __state)
	{
		//IL_000e: Unknown result type (might be due to invalid IL or missing references)
		//IL_000f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0015: Unknown result type (might be due to invalid IL or missing references)
		//IL_0016: Unknown result type (might be due to invalid IL or missing references)
		__state = spawning;
		if (Active)
		{
			spawning = __0;
			Safe(delegate
			{
				//IL_004e: Unknown result type (might be due to invalid IL or missing references)
				//IL_005c: Unknown result type (might be due to invalid IL or missing references)
				Logger()?.Invoke(string.Format("Spawn requested parent=P{0} mode={1} impact-origin={2} velocity={3} ignore={4} target={5}", ((Object)__0).GetInstanceID(), selection?.Mode ?? "Chain/other", __2, __3, __4, Target(selected)));
			});
		}
	}

	private static void SpawnFinally(object __state)
	{
		spawning = (Projectile)((__state is Projectile) ? __state : null);
		selected = null;
	}

	private static void SpawnEnd(Component __result)
	{
		Safe(delegate
		{
			if (Object.op_Implicit((Object)(object)__result) && Object.op_Implicit((Object)(object)spawning))
			{
				Action<string> action = Logger();
				if (action != null)
				{
					Projectile component = __result.GetComponent<Projectile>();
					if (Object.op_Implicit((Object)(object)component))
					{
						Register(component);
						Flight flight = new Flight
						{
							Projectile = component,
							Target = ((selection?.Mode == "Bounce") ? null : selected),
							Log = action,
							Born = Time.time,
							Next = Time.time,
							Id = ((Object)component).GetInstanceID(),
							Mode = (selection?.Mode ?? "Chain/other")
						};
						Flights.Remove(component);
						Flights.Add(component, flight);
						((Component)component).gameObject.AddComponent<ChainFlightWatcher>().Record = flight;
						action(string.Format("Spawn complete parent=P{0} mode={1} {2} target={3} components=[{4}]", ((Object)spawning).GetInstanceID(), flight.Mode, State(component), Target(flight.Target), string.Join(",", from c in ((Component)component).GetComponents<Component>()
							select ((object)c).GetType().Name)));
					}
				}
			}
		});
	}

	private static void Tick(Projectile __instance)
	{
		Safe(delegate
		{
			if (Flights.TryGetValue(__instance, out var value) && value.Samples < 6 && !(Time.time < value.Next))
			{
				value.Samples++;
				value.Next = Time.time + ((value.Samples == 1) ? 0.05f : ((value.Samples == 2) ? 0.1f : 0.3f));
				value.Log($"Flight sample {value.Samples} age={Time.time - value.Born:0.###} mode={value.Mode} {State(__instance)} target={Target(value.Target)}");
			}
		});
	}

	private static void Valid(Projectile __instance, IDestructible __0, bool __result)
	{
		Safe(delegate
		{
			if (Flights.TryGetValue(__instance, out var value) && value.ValidChecks++ < 12)
			{
				value.Log($"IsValidTarget P{value.Id} result={__result} candidate={__0}");
			}
		});
	}

	private static void Impact(Projectile __instance, Collider __0)
	{
		Safe(delegate
		{
			if (Flights.TryGetValue(__instance, out var value))
			{
				value.Impact = true;
				value.Log($"Flight impact P{value.Id} collider={__0} intended={Target(value.Target)} {State(__instance)}");
			}
		});
	}

	private static void ImpactDone(Projectile __instance, Collider __0, bool __runOriginal)
	{
		Safe(delegate
		{
			if (Flights.TryGetValue(__instance, out var value))
			{
				object obj;
				if (!Object.op_Implicit((Object)(object)__0))
				{
					obj = null;
				}
				else
				{
					GameObject obj2 = Projectile.FindHitObject(__0);
					obj = ((obj2 != null) ? obj2.GetComponentInParent<Character>() : null);
				}
				Character val = (Character)obj;
				value.Log(string.Format("Flight impact exit P{0} originalRan={1} didHit={2} actual={3} intendedMatch={4}; acceptance follows native processing", value.Id, __runOriginal, Field(__instance, "m_didHit"), Target(val), Object.op_Implicit((Object)(object)value.Target) && (Object)(object)val == (Object)(object)value.Target));
			}
		});
	}

	private static void Destroying(GameObject __0)
	{
		Safe(delegate
		{
			Projectile val = (Object.op_Implicit((Object)(object)__0) ? __0.GetComponent<Projectile>() : null);
			if (Object.op_Implicit((Object)(object)val) && Flights.TryGetValue(val, out var value))
			{
				value.Log($"Destroy requested P{value.Id} ttlExpired={val.m_ttl <= 0f} impactObserved={value.Impact} {State(val)}");
			}
		});
	}

	internal static void Destroyed(Flight f)
	{
		Safe(delegate
		{
			f.Log($"OnDestroy P{f.Id} age={Time.time - f.Born:0.###} impactObserved={f.Impact}; destruction observed, cause requires preceding Destroy/tick events");
		});
	}

	internal static void Compare(Attack attack, Action<string> write)
	{
		Safe(delegate
		{
			//IL_00fa: Unknown result type (might be due to invalid IL or missing references)
			if (!compared && Object.op_Implicit((Object)(object)ZNetScene.instance))
			{
				compared = true;
				ObjectDB instance = ObjectDB.instance;
				if (Object.op_Implicit((Object)(object)instance))
				{
					foreach (ItemDrop item in (from go in instance.m_items
						select go.GetComponent<ItemDrop>() into i
						where Object.op_Implicit((Object)(object)i) && Object.op_Implicit((Object)(object)i.m_itemData.m_shared.m_attack?.m_attackProjectile)
						where ((Object)((Component)i).gameObject).name == "StaffIceShards" || ((int)i.m_itemData.m_shared.m_skillType == 9 && i.m_itemData.m_shared.m_damages.m_frost > 0f)
						select i).Take(10))
					{
						Attack attack2 = item.m_itemData.m_shared.m_attack;
						Projectile component = attack2.m_attackProjectile.GetComponent<Projectile>();
						write(string.Format("live native frost candidate {0} attack={1} animation={2} speed={3} min={4} offset={5} count={6} burst={7} projectile={8}", ((Object)((Component)item).gameObject).name, attack2.m_attackType, attack2.m_attackAnimation, attack2.m_projectileVel, attack2.m_projectileVelMin, attack2.m_attackOffset, attack2.m_projectiles, attack2.m_projectileBursts, Object.op_Implicit((Object)(object)component) ? State(component) : "none"));
					}
				}
				foreach (FieldInfo item2 in from f in typeof(Projectile).GetFields(BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic)
					where f.FieldType == typeof(int) && (f.Name.ToLowerInvariant().Contains("mask") || f.Name.ToLowerInvariant().Contains("layer"))
					select f)
				{
					write($"native Projectile mask {item2.Name}={item2.GetValue(null)}");
				}
				GameObject attackProjectile = attack.m_attackProjectile;
				Projectile val = ((attackProjectile != null) ? attackProjectile.GetComponent<Projectile>() : null);
				if (Object.op_Implicit((Object)(object)val))
				{
					write("VWG template " + State(val));
				}
				write("Physics layer matrix is native; no VWG layer/mask writes. Static Projectile masks listed above; donor serialized asset values are observed live, not inferred from assembly names.");
			}
		});
	}
}
internal sealed class ChainFlightWatcher : MonoBehaviour
{
	internal ChainFlightDiagnostics.Flight Record;

	private void OnDestroy()
	{
		if (Record != null)
		{
			ChainFlightDiagnostics.Destroyed(Record);
		}
	}
}
internal static class CleaveAttack
{
	private struct ReleaseScope
	{
		internal bool Entered;

		internal int Previous;
	}

	private sealed class Cast
	{
		internal Player Player;

		internal ItemData Weapon;

		internal int Rank;

		internal ResolvedSupports Supports;

		internal bool Triggered;

		internal bool SweepShown;
	}

	internal const string PrefabId = "VWG_GemActiveCleave";

	private const float Stamina = 14f;

	private const float SweepAngle = 180f;

	private static readonly ConditionalWeakTable<Attack, Cast> Live = new ConditionalWeakTable<Attack, Cast>();

	private static ManualLogSource log;

	private static bool ready;

	private static Cast request;

	private static Func<int> enterArea;

	private static Action<int> leaveArea;

	internal static void Initialize(ManualLogSource logger)
	{
		log = logger;
		ready = Plugin.Install(log, "cleave", "Cleave native melee attack", delegate(Harmony harmony)
		{
			//IL_0176: Unknown result type (might be due to invalid IL or missing references)
			//IL_0184: Expected O, but got Unknown
			//IL_0197: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ae: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b9: Expected O, but got Unknown
			//IL_01b9: Expected O, but got Unknown
			MethodInfo methodInfo = AccessTools.DeclaredMethod(typeof(Attack), "Start", (Type[])null, (Type[])null);
			MethodInfo methodInfo2 = AccessTools.DeclaredMethod(typeof(Attack), "OnAttackTrigger", Type.EmptyTypes, (Type[])null);
			if (methodInfo?.ReturnType != typeof(bool) || methodInfo2?.ReturnType != typeof(void))
			{
				throw new MissingMethodException("Attack.Start or Attack.OnAttackTrigger");
			}
			Type type = Plugin.PovAssembly.GetType("PassiveTree.HitContext", throwOnError: true);
			Type type2 = Plugin.PovAssembly.GetType("PassiveTree.HitTag", throwOnError: true);
			MethodInfo method = AccessTools.DeclaredMethod(type, "Push", new Type[1] { type2 }, (Type[])null) ?? throw new MissingMethodException(type.FullName, "Push");
			MethodInfo method2 = AccessTools.DeclaredMethod(type, "Pop", new Type[1] { type2 }, (Type[])null) ?? throw new MissingMethodException(type.FullName, "Pop");
			ParameterExpression parameterExpression = Expression.Parameter(typeof(int));
			enterArea = Expression.Lambda<Func<int>>(Expression.Convert(Expression.Call(method, Expression.Constant(Enum.Parse(type2, "Area"), type2)), typeof(int)), Array.Empty<ParameterExpression>()).Compile();
			leaveArea = Expression.Lambda<Action<int>>(Expression.Call(method2, Expression.Convert(parameterExpression, type2)), new ParameterExpression[1] { parameterExpression }).Compile();
			harmony.Patch((MethodBase)methodInfo, new HarmonyMethod(typeof(CleaveAttack), "OnlyRequestedAttack", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			harmony.Patch((MethodBase)methodInfo2, new HarmonyMethod(typeof(CleaveAttack), "FirstRelease", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, new HarmonyMethod(typeof(CleaveAttack), "RestoreReleaseContext", (Type[])null), (HarmonyMethod)null);
		});
		if (ready)
		{
			CleaveSweep.Initialize(log);
		}
	}

	internal static bool SupportsWeapon(ItemData item)
	{
		//IL_001e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0024: Invalid comparison between Unknown and I4
		//IL_0031: Unknown result type (might be due to invalid IL or missing references)
		//IL_0037: Invalid comparison between Unknown and I4
		//IL_0027: Unknown result type (might be due to invalid IL or missing references)
		//IL_002e: Invalid comparison between Unknown and I4
		//IL_003a: Unknown result type (might be due to invalid IL or missing references)
		//IL_0040: Invalid comparison between Unknown and I4
		//IL_0046: Unknown result type (might be due to invalid IL or missing references)
		SharedData val = item?.m_shared;
		Attack val2 = val?.m_attack;
		if (val != null && ((int)val.m_itemType == 3 || (int)val.m_itemType == 14) && ((int)val.m_skillType == 1 || (int)val.m_skillType == 7) && val2 != null && (int)val2.m_attackType == 0 && val2.m_attackRange > 0f)
		{
			return !string.IsNullOrEmpty(val2.m_attackAnimation);
		}
		return false;
	}

	internal static bool CanStart(ItemData weapon)
	{
		if (ready && StaffBasicAttack.AttackSelectionReady && request == null)
		{
			return SupportsWeapon(weapon);
		}
		return false;
	}

	internal static bool IsCast(Attack attack)
	{
		Cast value;
		if (attack != null)
		{
			return Live.TryGetValue(attack, out value);
		}
		return false;
	}

	internal static bool BeginSweepVisual(Attack attack, out Player player)
	{
		player = null;
		if (!Live.TryGetValue(attack, out var value) || !value.Triggered || value.SweepShown)
		{
			return false;
		}
		value.SweepShown = true;
		player = value.Player;
		return (Object)(object)player != (Object)null;
	}

	internal static string Describe(int rank)
	{
		return $"Active Skill Gem · Attack · Melee · Area\n\nSkill Level: {rank}\n" + $"Weapon Damage: {SocketGemKinds.Cleave.At(rank):P0}\nBase Stamina Cost: {14f:0}\n" + "Sweeps a frontal area with a compatible sword or axe.";
	}

	internal static void TryStart(Player player, ItemData weapon, int rank)
	{
		if (!CanStart(weapon))
		{
			return;
		}
		try
		{
			ResolvedSupports supports = ResolvedSupports.Resolve(weapon, "VWG_GemActiveCleave", SupportsCleave);
			request = new Cast
			{
				Player = player,
				Weapon = weapon,
				Rank = rank,
				Supports = supports
			};
			if (((Character)player).StartAttack((Character)null, false))
			{
				log.LogInfo((object)($"VWG Cleave rank {rank} started with {((Object)weapon.m_dropPrefab).name} Q{weapon.m_quality}, " + $"{SocketGemKinds.Cleave.At(rank):P0} weapon damage and {14f:0} base stamina. " + $"Linked Supports: {supports.FlatCold:0.##} Frost, {supports.FlatLightning:0.##} Lightning, {supports.IncreasedArea:P0} increased area."));
			}
		}
		catch (Exception ex)
		{
			log.LogWarning((object)("VWG Cleave could not start: " + ex.GetBaseException().Message));
		}
		finally
		{
			request = null;
		}
	}

	private static bool SupportsCleave(SocketGemKinds.Definition support)
	{
		if (support != SocketGemKinds.AddedCold && support != SocketGemKinds.AddedLightning)
		{
			return support == SocketGemKinds.IncreasedArea;
		}
		return true;
	}

	internal static Attack GetRequestedAttack(Humanoid caster, ItemData weapon)
	{
		//IL_0059: Unknown result type (might be due to invalid IL or missing references)
		//IL_005e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0060: Unknown result type (might be due to invalid IL or missing references)
		//IL_0065: Unknown result type (might be due to invalid IL or missing references)
		//IL_006c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0078: Unknown result type (might be due to invalid IL or missing references)
		//IL_0084: Unknown result type (might be due to invalid IL or missing references)
		//IL_0090: Unknown result type (might be due to invalid IL or missing references)
		//IL_00a7: Unknown result type (might be due to invalid IL or missing references)
		//IL_00b3: Unknown result type (might be due to invalid IL or missing references)
		//IL_00be: Unknown result type (might be due to invalid IL or missing references)
		//IL_00c5: Unknown result type (might be due to invalid IL or missing references)
		//IL_00cc: Unknown result type (might be due to invalid IL or missing references)
		//IL_00d7: Unknown result type (might be due to invalid IL or missing references)
		//IL_00ee: Expected O, but got Unknown
		Cast cast = request;
		if (cast == null || (Object)(object)cast.Player != (Object)(object)caster || cast.Weapon != weapon)
		{
			return null;
		}
		Attack attack = weapon.m_shared.m_attack;
		string attackAnimation = ((attack.m_attackChainLevels > 1 || attack.m_attackRandomAnimations > 1) ? (attack.m_attackAnimation + "0") : attack.m_attackAnimation);
		Attack val = new Attack
		{
			m_attackType = (AttackType)0,
			m_attackAnimation = attackAnimation,
			m_attackOriginJoint = attack.m_attackOriginJoint,
			m_attackHeight = attack.m_attackHeight,
			m_attackOffset = attack.m_attackOffset,
			m_attackRange = cast.Supports.AreaRadius(attack.m_attackRange),
			m_attackRayWidth = attack.m_attackRayWidth,
			m_attackAngle = 180f,
			m_multiHit = true,
			m_lowerDamagePerHit = false,
			m_attackStamina = 14f,
			m_damageMultiplier = SocketGemKinds.Cleave.At(cast.Rank)
		};
		Live.Add(val, cast);
		AttackSupportDamage.Track(val, "VWG_GemActiveCleave", cast.Rank, weapon, cast.Supports);
		return val;
	}

	private static bool OnlyRequestedAttack(Attack __instance, Humanoid __0, ref bool __result)
	{
		if (request == null || (Object)(object)request.Player != (Object)(object)__0 || IsCast(__instance))
		{
			return true;
		}
		__result = false;
		return false;
	}

	private static bool FirstRelease(Attack __instance, out ReleaseScope __state)
	{
		__state = default(ReleaseScope);
		if (!Live.TryGetValue(__instance, out var value))
		{
			return true;
		}
		if (value.Triggered)
		{
			return false;
		}
		value.Triggered = true;
		__state.Previous = enterArea();
		__state.Entered = true;
		return true;
	}

	private static void RestoreReleaseContext(ReleaseScope __state)
	{
		if (__state.Entered)
		{
			leaveArea(__state.Previous);
		}
	}
}
internal sealed class CleaveSweep : MonoBehaviour
{
	private delegate void MeleeDirection(Attack attack, out Transform origin, out Vector3 forward);

	private const float Lifetime = 0.28f;

	private const int Segments = 28;

	private const int Across = 5;

	private static readonly float[] Bands = new float[5] { 0f, 0.48f, 0.78f, 0.93f, 1f };

	private static readonly float[] Opacities = new float[5] { 0f, 0.14f, 0.29f, 0.63f, 0f };

	private static MeleeDirection direction;

	private static ManualLogSource log;

	private static bool warned;

	private Mesh mesh;

	private Color32[] colors;

	private byte[] initialOpacity;

	private float started;

	internal static void Initialize(ManualLogSource logger)
	{
		log = logger;
		Plugin.Install(log, "cleave-sweep", "Cleave sweep visual", delegate(Harmony harmony)
		{
			//IL_00bd: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ca: Expected O, but got Unknown
			MethodInfo methodInfo = AccessTools.DeclaredMethod(typeof(Attack), "DoMeleeAttack", Type.EmptyTypes, (Type[])null);
			MethodInfo methodInfo2 = AccessTools.DeclaredMethod(typeof(Attack), "GetMeleeAttackDir", new Type[2]
			{
				typeof(Transform).MakeByRefType(),
				typeof(Vector3).MakeByRefType()
			}, (Type[])null);
			if (methodInfo?.ReturnType != typeof(void) || methodInfo2?.ReturnType != typeof(void))
			{
				throw new MissingMethodException("Attack.DoMeleeAttack or Attack.GetMeleeAttackDir");
			}
			direction = AccessTools.MethodDelegate<MeleeDirection>(methodInfo2, (object)null, true);
			HarmonyMethod val = new HarmonyMethod(typeof(CleaveSweep), "BeforeSwing", (Type[])null)
			{
				priority = 0
			};
			harmony.Patch((MethodBase)methodInfo, val, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
		});
	}

	private static void BeforeSwing(Attack __instance)
	{
		//IL_0069: 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)
		//IL_0079: Unknown result type (might be due to invalid IL or missing references)
		//IL_007e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0089: Unknown result type (might be due to invalid IL or missing references)
		//IL_0094: Unknown result type (might be due to invalid IL or missing references)
		//IL_0099: Unknown result type (might be due to invalid IL or missing references)
		//IL_009e: Unknown result type (might be due to invalid IL or missing references)
		//IL_00a5: Unknown result type (might be due to invalid IL or missing references)
		//IL_00ab: Expected O, but got Unknown
		//IL_00b1: Unknown result type (might be due to invalid IL or missing references)
		//IL_00b3: Unknown result type (might be due to invalid IL or missing references)
		//IL_00b5: Unknown result type (might be due to invalid IL or missing references)
		//IL_00ba: Unknown result type (might be due to invalid IL or missing references)
		if (!CleaveAttack.BeginSweepVisual(__instance, out var player))
		{
			return;
		}
		GameObject val = null;
		try
		{
			Material defaultGraphicMaterial = Graphic.defaultGraphicMaterial;
			if ((Object)(object)defaultGraphicMaterial == (Object)null || (Object)(object)defaultGraphicMaterial.shader == (Object)null || !defaultGraphicMaterial.shader.isSupported || ((Object)defaultGraphicMaterial.shader).name == "Hidden/InternalErrorShader")
			{
				throw new InvalidOperationException("The native transparent UI material is unavailable.");
			}
			direction(__instance, out var origin, out var forward);
			Vector3 val2 = origin.position + Vector3.up * __instance.m_attackHeight + ((Component)player).transform.right * __instance.m_attackOffset;
			val = new GameObject("VWG Cleave sweep");
			val.transform.SetPositionAndRotation(val2, Quaternion.LookRotation(forward, Vector3.up));
			val.AddComponent<CleaveSweep>().Build(defaultGraphicMaterial, __instance.m_attackRange, __instance.m_attackAngle);
			Object.Destroy((Object)(object)val, 0.28f);
		}
		catch (Exception ex)
		{
			if ((Object)(object)val != (Object)null)
			{
				Object.Destroy((Object)(object)val);
			}
			if (!warned)
			{
				warned = true;
				log.LogWarning((object)("VWG Cleave sweep visual unavailable: " + ex.GetBaseException().Message));
			}
		}
	}

	private void Build(Material material, float reach, float arc)
	{
		//IL_00b1: Unknown result type (might be due to invalid IL or missing references)
		//IL_00c9: Unknown result type (might be due to invalid IL or missing references)
		//IL_00ce: Unknown result type (might be due to invalid IL or missing references)
		//IL_00de: Unknown result type (might be due to invalid IL or missing references)
		//IL_00e3: Unknown result type (might be due to invalid IL or missing references)
		//IL_00e8: 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)
		//IL_00ff: Unknown result type (might be due to invalid IL or missing references)
		//IL_0205: Unknown result type (might be due to invalid IL or missing references)
		//IL_020a: Unknown result type (might be due to invalid IL or missing references)
		//IL_021a: Expected O, but got Unknown
		//IL_0171: Unknown result type (might be due to invalid IL or missing references)
		//IL_0159: Unknown result type (might be due to invalid IL or missing references)
		//IL_0176: Unknown result type (might be due to invalid IL or missing references)
		Vector3[] array = (Vector3[])(object)new Vector3[145];
		Vector2[] array2 = (Vector2[])(object)new Vector2[array.Length];
		int[] array3 = new int[672];
		colors = (Color32[])(object)new Color32[array.Length];
		initialOpacity = new byte[array.Length];
		Vector3 val = default(Vector3);
		for (int i = 0; i <= 28; i++)
		{
			float num = (float)i / 28f;
			float num2 = Mathf.Sin(num * MathF.PI);
			float num3 = (num - 0.5f) * arc * (MathF.PI / 180f);
			((Vector3)(ref val))..ctor(Mathf.Sin(num3), 0f, Mathf.Cos(num3));
			float num4 = reach * (0.82f + 0.18f * num2);
			for (int j = 0; j < 5; j++)
			{
				int num5 = i * 5 + j;
				float num6 = Bands[j];
				array[num5] = val * (num4 - reach * 0.28f * num2 * (1f - num6)) + Vector3.up * (0.11f * num6 * num2);
				array2[num5] = new Vector2(0.5f, 0.5f);
				byte b = (byte)Mathf.RoundToInt(255f * Opacities[j] * Mathf.Sqrt(Mathf.Max(0f, num2)));
				initialOpacity[num5] = b;
				colors[num5] = ((num6 >= 0.9f) ? new Color32((byte)241, (byte)244, (byte)245, b) : new Color32((byte)184, (byte)194, (byte)200, b));
			}
		}
		for (int k = 0; k < 28; k++)
		{
			for (int l = 0; l < 4; l++)
			{
				int num7 = k * 5 + l;
				int num8 = (k * 4 + l) * 6;
				array3[num8] = num7;
				array3[num8 + 1] = num7 + 1;
				array3[num8 + 2] = num7 + 5;
				array3[num8 + 3] = num7 + 1;
				array3[num8 + 4] = num7 + 5 + 1;
				array3[num8 + 5] = num7 + 5;
			}
		}
		mesh = new Mesh
		{
			name = "VWG Cleave crescent"
		};
		mesh.MarkDynamic();
		mesh.vertices = array;
		mesh.uv = array2;
		mesh.colors32 = colors;
		mesh.triangles = array3;
		((Component)this).gameObject.AddComponent<MeshFilter>().sharedMesh = mesh;
		MeshRenderer obj = ((Component)this).gameObject.AddComponent<MeshRenderer>();
		((Renderer)obj).sharedMaterial = material;
		((Renderer)obj).shadowCastingMode = (ShadowCastingMode)0;
		((Renderer)obj).receiveShadows = false;
		started = Time.time;
	}

	private void Update()
	{
		float num = Mathf.Clamp01((Time.time - started) / 0.28f);
		float num2 = (1f - num) * (1f - num);
		for (int i = 0; i < colors.Length; i++)
		{
			colors[i].a = (byte)Mathf.RoundToInt((float)(int)initialOpacity[i] * num2);
		}
		mesh.colors32 = colors;
	}

	private void OnDestroy()
	{
		if ((Object)(object)mesh != (Object)null)
		{
			Object.Destroy((Object)(object)mesh);
		}
	}
}
internal static class CombatHitObservation
{
	private static bool Native(MethodInfo m)
	{
		if (m != null && m.DeclaringType == typeof(IDestructible) && m.Name == "Damage" && m.ReturnType == typeof(void))
		{
			return (from p in m.GetParameters()
				select p.ParameterType).SequenceEqual(new Type[1] { typeof(HitData) });
		}
		return false;
	}

	private static bool Protected(MethodInfo m)
	{
		if (m != null && m.IsStatic && m.DeclaringType?.FullName == "Beyond.Plugin.World.MirrorSceneryProtection" && m.Name == "Dispatch" && m.ReturnType == typeof(void))
		{
			return (from p in m.GetParameters()
				select p.ParameterType).SequenceEqual(new Type[3]
			{
				typeof(IDestructible),
				typeof(HitData),
				typeof(object)
			});
		}
		return false;
	}

	private static int Site(IList<CodeInstruction> code)
	{
		int[] array = (from i in Enumerable.Range(0, code.Count)
			where (code[i].opcode == OpCodes.Call || code[i].opcode == OpCodes.Callvirt) && code[i].operand is MethodInfo m && (Native(m) || Protected(m))
			select i).ToArray();
		if (array.Length != 1)
		{
			throw new InvalidOperationException($"Damage observation preflight: expected one native or protected dispatch, found {array.Length}; no transformation emitted.");
		}
		return array[0];
	}

	internal static void Prevalidate(MethodBase target)
	{
		CombatPatchSafety.RequireHealthy(target);
		Site(CombatPatchSafety.Instructions(target));
	}

	internal static IEnumerable<CodeInstruction> Inject(IEnumerable<CodeInstruction> input, ILGenerator generator, MethodInfo before, MethodInfo after)
	{
		//IL_00d3: Unknown result type (might be due to invalid IL or missing references)
		//IL_00dd: Expected O, but got Unknown
		//IL_00e5: Unknown result type (might be due to invalid IL or missing references)
		//IL_00ef: Expected O, but got Unknown
		//IL_00f7: Unknown result type (might be due to invalid IL or missing references)
		//IL_0101: Expected O, but got Unknown
		//IL_010a: Unknown result type (might be due to invalid IL or missing references)
		//IL_0114: Expected O, but got Unknown
		//IL_011c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0126: Expected O, but got Unknown
		//IL_012e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0138: Expected O, but got Unknown
		//IL_00c0: Unknown result type (might be due to invalid IL or missing references)
		//IL_00ca: Expected O, but got Unknown
		//IL_0157: Unknown result type (might be due to invalid IL or missing references)
		//IL_0161: Expected O, but got Unknown
		//IL_016a: Unknown result type (might be due to invalid IL or missing references)
		//IL_0174: Expected O, but got Unknown
		//IL_0145: Unknown result type (might be due to invalid IL or missing references)
		//IL_014f: Expected O, but got Unknown
		//IL_01c1: Unknown result type (might be due to invalid IL or missing references)
		//IL_01cb: Expected O, but got Unknown
		//IL_01d3: Unknown result type (might be due to invalid IL or missing references)
		//IL_01dd: Expected O, but got Unknown
		//IL_01e4: Unknown result type (might be due to invalid IL or missing references)
		//IL_01ee: Expected O, but got Unknown
		//IL_0181: Unknown result type (might be due to invalid IL or missing references)
		//IL_018b: Expected O, but got Unknown
		//IL_020f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0219: Expected O, but got Unknown
		//IL_01fd: Unknown result type (might be due to invalid IL or missing references)
		//IL_0207: Expected O, but got Unknown
		List<CodeInstruction> list = input.Select((Func<CodeInstruction, CodeInstruction>)((CodeInstruction c) => new CodeInstruction(c))).ToList();
		int num = Site(list);
		MethodInfo methodInfo = (MethodInfo)list[num].operand;
		LocalBuilder localBuilder = generator.DeclareLocal(typeof(IDestructible));
		LocalBuilder localBuilder2 = generator.DeclareLocal(typeof(HitData));
		LocalBuilder localBuilder3 = (Protected(methodInfo) ? generator.DeclareLocal(typeof(object)) : null);
		LocalBuilder localBuilder4 = ((before.ReturnType == typeof(void)) ? null : generator.DeclareLocal(before.ReturnType));
		List<CodeInstruction> list2 = new List<CodeInstruction>();
		if (localBuilder3 != null)
		{
			list2.Add(new CodeInstruction(OpCodes.Stloc, (object)localBuilder3));
		}
		list2.Add(new CodeInstruction(OpCodes.Stloc, (object)localBuilder2));
		list2.Add(new CodeInstruction(OpCodes.Stloc, (object)localBuilder));
		list2.Add(new CodeInstruction(OpCodes.Ldloc, (object)localBuilder));
		list2.Add(new CodeInstruction(OpCodes.Ldloc, (object)localBuilder2));
		list2.Add(new CodeInstruction(OpCodes.Ldarg_0, (object)null));
		list2.Add(new CodeInstruction(OpCodes.Call, (object)before));
		if (localBuilder4 != null)
		{
			list2.Add(new CodeInstruction(OpCodes.Stloc, (object)localBuilder4));
		}
		list2.Add(new CodeInstruction(OpCodes.Ldloc, (object)localBuilder));
		list2.Add(new CodeInstruction(OpCodes.Ldloc, (object)localBuilder2));
		if (localBuilder3 != null)
		{
			list2.Add(new CodeInstruction(OpCodes.Ldloc, (object)localBuilder3));
		}
		CodeInstructionExtensions.MoveLabelsTo(list[num], list2[0]);
		CodeInstructionExtensions.MoveBlocksTo(list[num], list2[0]);
		List<CodeInstruction> list3 = new List<CodeInstruction>
		{
			new CodeInstruction(OpCodes.Ldloc, (object)localBuilder),
			new CodeInstruction(OpCodes.Ldloc, (object)localBuilder2),
			new CodeInstruction(OpCodes.Ldarg_0, (object)null)
		};
		if (localBuilder4 != null)
		{
			list3.Add(new CodeInstruction(OpCodes.Ldloc, (object)localBuilder4));
		}
		list3.Add(new CodeInstruction(OpCodes.Call, (object)after));
		list.InsertRange(num + 1, list3);
		list.InsertRange(num, list2);
		if (Site(list) != num + list2.Count || !object.Equals(list[num + list2.Count].operand, methodInfo))
		{
			throw new InvalidOperationException("Damage dispatch was not preserved.");
		}
		return list;
	}
}
internal static class CombatPatchSafety
{
	private static readonly MethodInfo ProjectileHit = typeof(Projectile).GetMethod("OnHit", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);

	private static readonly MethodInfo ProjectileSetup = typeof(Projectile).GetMethod("Setup", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);

	private static readonly MethodInfo MeleeHit = typeof(Attack).GetMethod("DoMeleeAttack", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);

	private static readonly MethodInfo Current = typeof(PatchProcessor).GetMethods().Single((MethodInfo m) => m.Name == "GetCurrentInstructions" && m.GetParameters().Length == 3 && m.GetParameters()[1].ParameterType == typeof(int));

	private static readonly HashSet<MethodBase> Blocked = new HashSet<MethodBase>();

	private static readonly Dictionary<string, HashSet<MethodBase>> Touched = new Dictionary<string, HashSet<MethodBase>>();

	internal static bool ProjectileHealthy => Healthy(ProjectileHit);

	internal static bool MeleeHealthy => Healthy(MeleeHit);

	internal static bool NativeContinuationPath
	{
		get
		{
			if (ProjectileHealthy && Healthy(ProjectileSetup) && HasPostfix(ProjectileSetup, "PassiveTree.ProjectileMods+Projectile_Setup"))
			{
				return HasPostfix(ProjectileHit, "PassiveTree.ProjectileMods+Projectile_OnHit");
			}
			return false;
		}
	}

	private static bool HasPostfix(MethodBase target, string owner)
	{
		return Harmony.GetPatchInfo(target)?.Postfixes.Any((Patch p) => p.PatchMethod.DeclaringType?.FullName == owner && p.PatchMethod.Name == "Postfix") ?? false;
	}

	internal static List<CodeInstruction> Instructions(MethodBase method)
	{
		return (List<CodeInstruction>)Current.Invoke(null, new object[3]
		{
			method,
			int.MaxValue,
			null
		});
	}

	internal static bool Healthy(MethodBase method)
	{
		if (method != null)
		{
			return !Blocked.Contains(method);
		}
		return false;
	}

	internal static void RequireHealthy(MethodBase method)
	{
		if (!Healthy(method))
		{
			throw new InvalidOperationException($"Unsafe patch destination {method}; further VWG modifications blocked until restart.");
		}
	}

	internal static void Patch(Harmony h, MethodBase target, HarmonyMethod prefix = null, HarmonyMethod postfix = null, HarmonyMethod transpiler = null, HarmonyMethod finalizer = null)
	{
		RequireHealthy(target);
		if (!Touched.TryGetValue(h.Id, out var value))
		{
			value = (Touched[h.Id] = new HashSet<MethodBase>());
		}
		value.Add(target);
		h.Patch(target, prefix, postfix, transpiler, finalizer, (HarmonyMethod)null);
	}

	internal static void Rollback(Harmony h, ManualLogSource log)
	{
		HashSet<MethodBase> hashSet = new HashSet<MethodBase>(Harmony.GetAllPatchedMethods().Where(delegate(MethodBase m)
		{
			Patches patchInfo2 = Harmony.GetPatchInfo(m);
			return patchInfo2 != null && patchInfo2.Owners.Contains(h.Id);
		}));
		if (Touched.TryGetValue(h.Id, out var value))
		{
			hashSet.UnionWith(value);
		}
		foreach (MethodBase item in hashSet)
		{
			try
			{
				h.Unpatch(item, (HarmonyPatchType)3, h.Id);
				h.Unpatch(item, (HarmonyPatchType)0, h.Id);
				Patches patchInfo = Harmony.GetPatchInfo(item);
				if (patchInfo != null && patchInfo.Owners.Contains(h.Id))
				{
					throw new InvalidOperationException("Owner metadata remains after cleanup.");
				}
				Instructions(item);
				log.LogInfo((object)("VWG cleanup verified: " + item.DeclaringType?.FullName + "." + item.Name + "; independent adapters may continue."));
			}
			catch (Exception ex)
			{
				Blocked.Add(item);
				log.LogError((object)("VWG patch destination quarantined: " + item.DeclaringType?.FullName + "." + item.Name + ". Cleanup/revalidation failed: " + ex.GetBaseException().Message + ". No further guarded VWG patches on this method; restart required."));
			}
		}
	}
}
internal sealed class CycloneChannel
{
	private enum State
	{
		Idle,
		Channeling,
		WaitForRelease
	}

	internal const string PrefabId = "VWG_GemActiveCyclone";

	private static bool ready;

	private static Player inputOwner;

	private static State state;

	private static CycloneChannel active;

	private static ManualLogSource log;

	private static ConfigEntry<float> movement;

	private static ConfigEntry<float> basePeriod;

	private static ConfigEntry<float> baseRadius;

	private static ConfigEntry<float> damageEffectiveness;

	private static ConfigEntry<float> baseStaminaPerSecond;

	private static ConfigEntry<int> pulsesPerRevolution;

	private static CyclonePovStats.ReadStats readStats;

	private static Func<Player, bool> takeInput;

	private static FieldRef<Character, bool> run;

	private static FieldRef<Character, bool> block;

	private static FieldRef<Character, Vector3> pushForce;

	private static FieldRef<Humanoid, Attack> currentAttack;

	private readonly Player player;

	private readonly ZNetView view;

	private readonly ItemData weapon;

	private readonly string socket;

	private readonly int rank;

	private CycloneVisual visual;

	private float nextStatsAt;

	private float speed;

	private float area;

	private float reach;

	private int areaRank;

	private (string Current, string Legacy) storedRecords;

	private ResolvedSupports supports;

	private Attack staminaQuote;

	private float effectiveStamina;

	private float effectiveness;

	private double paidThrough;

	private long pulseBoundary;

	private int pulseCount;

	internal double Revolutions { get; private set; }

	internal float RevolutionDuration { get; private set; }

	internal float Radius { get; private set; }

	internal float AngularPhase => (float)(Revolutions % 1.0 * 360.0);

	internal static CycloneChannel Current(Player owner)
	{
		if (!((Object)(object)active?.player == (Object)(object)owner))
		{
			return null;
		}
		return active;
	}

	private CycloneChannel(Player player, ItemData weapon, string socket, int rank)
	{
		this.player = player;
		view = ((Component)player).GetComponent<ZNetView>();
		this.weapon = weapon;
		this.socket = socket;
		this.rank = rank;
		storedRecords = WeaponSockets.StoredRecords(weapon);
		supports = ResolvedSupports.Resolve(weapon, "VWG_GemActiveCyclone", AcceptsSupport);
	}

	internal static void Initialize(ConfigFile config, ManualLogSource logger)
	{
		//IL_002f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0039: Expected O, but got Unknown
		//IL_0067: Unknown result type (might be due to invalid IL or missing references)
		//IL_0071: Expected O, but got Unknown
		//IL_009f: Unknown result type (might be due to invalid IL or missing references)
		//IL_00a9: Expected O, but got Unknown
		//IL_00cb: Unknown result type (might be due to invalid IL or missing references)
		//IL_00d5: Expected O, but got Unknown
		//IL_0103: Unknown result type (might be due to invalid IL or missing references)
		//IL_010d: Expected O, but got Unknown
		//IL_013b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0145: Expected O, but got Unknown
		log = logger;
		movement = config.Bind<float>("Cyclone", "MovementMultiplier", 0.7f, new ConfigDescription("Multiplier for effective walking speed while channeling Cyclone.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.1f, 1f), Array.Empty<object>()));
		basePeriod = config.Bind<float>("Cyclone", "BaseRevolutionSeconds", 1f, new ConfigDescription("Seconds per Cyclone revolution at normal attack speed.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.2f, 10f), Array.Empty<object>()));
		baseRadius = config.Bind<float>("Cyclone", "BaseRadius", 2.5f, new ConfigDescription("Unmodified Cyclone radius in meters.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.5f, 10f), Array.Empty<object>()));
		pulsesPerRevolution = config.Bind<int>("Cyclone", "PulsesPerRevolution", 2, new ConfigDescription("Native melee pulses per full revolution.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(1, 4), Array.Empty<object>()));
		damageEffectiveness = config.Bind<float>("Cyclone", "DamageEffectiveness", 0.5f, new ConfigDescription("Provisional native damage effectiveness per pulse at every gem rank.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.01f, 4f), Array.Empty<object>()));
		baseStaminaPerSecond = config.Bind<float>("Cyclone", "BaseStaminaPerSecond", 12f, new ConfigDescription("Stamina per second before native modifiers.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.1f, 100f), Array.Empty<object>()));
		if (!CycloneMelee.Initialize(logger))
		{
			return;
		}
		ready = Plugin.Install(logger, "cyclone", "Cyclone channel", delegate(Harmony harmony)
		{
			//IL_00d4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e0: Expected O, but got Unknown
			readStats = CyclonePovStats.Bind(Plugin.PovAssembly);
			MethodInfo methodInfo = AccessTools.DeclaredMethod(typeof(Player), "TakeInput", Type.EmptyTypes, (Type[])null);
			if (methodInfo?.ReturnType != typeof(bool))
			{
				throw new MissingMethodException("Player.TakeInput()");
			}
			takeInput = AccessTools.MethodDelegate<Func<Player, bool>>(methodInfo, (object)null, true);
			run = AccessTools.FieldRefAccess<Character, bool>("m_run");
			block = AccessTools.FieldRefAccess<Character, bool>("m_blocking");
			pushForce = AccessTools.FieldRefAccess<Character, Vector3>("m_pushForce");
			currentAttack = AccessTools.FieldRefAccess<Humanoid, Attack>("m_currentAttack");
			MethodInfo methodInfo2 = AccessTools.DeclaredMethod(typeof(Character), "UpdateWalking", (Type[])null, (Type[])null) ?? throw new MissingMethodException("Character.UpdateWalking");
			harmony.Patch((MethodBase)methodInfo2, (HarmonyMethod)null, (HarmonyMethod)null, new HarmonyMethod(typeof(CycloneChannel), "ScaleWalking", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null);
		});
	}

	internal static bool CanRoute(int rank)
	{
		if (ready && rank >= 1)
		{
			return rank <= 15;
		}
		return false;
	}

	internal static string Describe(int rank)
	{
		return $"Active Skill Gem · Attack · Melee · Area · Channelling\n\nSkill Level: {rank}\n" + "Hold the primary attack button to channel a circular sweep while moving.";
	}

	internal static void Route(Player player, ItemData weapon, string socket, int rank, bool primaryPress, bool primaryHold, bool middle)
	{
		if ((Object)(object)inputOwner != (Object)(object)player)
		{
			Stop("local player changed", held: false);
			inputOwner = player;
		}
		if (middle)
		{
			Interrupt("native primary requested", primaryPress || primaryHold);
		}
		else if (state == State.WaitForRelease)
		{
			if (!primaryPress && !primaryHold && !PrimaryDown())
			{
				state = State.Idle;
			}
		}
		else if (state == State.Channeling)
		{
			if (!primaryPress && !primaryHold)
			{
				Stop("released", held: false);
			}
		}
		else
		{
			if (!primaryPress)
			{
				return;
			}
			state = State.WaitForRelease;
			CycloneChannel cycloneChannel = new CycloneChannel(player, weapon, socket, rank);
			string text = cycloneChannel.InvalidReason();
			if (text == null)
			{
				try
				{
					cycloneChannel.pulseCount = pulsesPerRevolution.Value;
					cycloneChannel.staminaQuote = CycloneMelee.NewAction(player, weapon);
					cycloneChannel.ResolveStats();
					if (cycloneChannel.effectiveStamina * Game.m_staminaRate > 0f && !((Character)player).HaveStamina(0f))
					{
						log.LogInfo((object)"VWG Cyclone start rejected: insufficient stamina.");
					}
					else
					{
						cycloneChannel.visual = CycloneVisual.Create();
						cycloneChannel.Render();
						cycloneChannel.paidThrough = Time.realtimeSinceStartupAsDouble;
						active = cycloneChannel;
						state = State.Channeling;
						CyclonePose.Begin(player, weapon);
						cycloneChannel.Report("started");
					}
					return;
				}
				catch (Exception ex)
				{
					cycloneChannel.visual?.Remove();
					log.LogWarning((object)("VWG Cyclone could not start: " + ex.GetBaseException().Message));
					return;
				}
			}
			log.LogDebug((object)$"VWG Cyclone rank {rank} start rejected: {text}.");
		}
	}

	internal static void Interrupt(string reason, bool held)
	{
		if (active != null)
		{
			Stop(reason, held);
		}
		else if (held)
		{
			state = State.WaitForRelease;
		}
	}

	internal static void Update()
	{
		if (!ready)
		{
			return;
		}
		if ((Object)(object)inputOwner != (Object)(object)Player.m_localPlayer)
		{
			Stop("local player changed", held: false);
			inputOwner = null;
		}
		CycloneChannel cycloneChannel = active;
		if (cycloneChannel == null)
		{
			if (state == State.WaitForRelease && !PrimaryDown())
			{
				state = State.Idle;
			}
			return;
		}
		string text = cycloneChannel.InvalidReason();
		bool flag = PrimaryDown();
		if (text != null || !flag)
		{
			Stop(text ?? "released", flag);
			return;
		}
		try
		{
			double realtimeSinceStartupAsDouble = Time.realtimeSinceStartupAsDouble;
			double num = realtimeSinceStartupAsDouble - cycloneChannel.paidThrough;
			if (Time.timeScale == 0f || num > 0.5)
			{
				Stop("paused or interrupted by a frame stall", flag);
				return;
			}
			float num2 = cycloneChannel.effectiveStamina * (float)num;
			if (num2 > 0f)
			{
				float num3 = num2 * Game.m_staminaRate;
				if (num3 > 0f && !((Character)cycloneChannel.player).HaveStamina(num3))
				{
					Stop("insufficient stamina", flag);
					return;
				}
				((Character)cycloneChannel.player).UseStamina(num2);
			}
			cycloneChannel.paidThrough = realtimeSinceStartupAsDouble;
			if (Time.unscaledTime >= cycloneChannel.nextStatsAt)
			{
				cycloneChannel.ResolveStats();
			}
			cycloneChannel.Revolutions += Math.Min(Time.deltaTime, 0.05f) / cycloneChannel.RevolutionDuration;
			cycloneChannel.Render();
			long num4 = (long)Math.Floor(cycloneChannel.Revolutions * (double)cycloneChannel.pulseCount);
			if (num4 > cycloneChannel.pulseBoundary)
			{
				cycloneChannel.pulseBoundary = num4;
				CycloneMelee.Pulse(cycloneChannel.player, cycloneChannel.weapon, cycloneChannel.rank, cycloneChannel.effectiveness, cycloneChannel.Radius, cycloneChannel.supports);
			}
		}
		catch (Exception ex)
		{
			Stop("runtime binding failed: " + ex.GetBaseException().Message, flag);
		}
	}

	internal static void Shutdown()
	{
		Stop("plugin teardown", held: false);
	}

	private static bool PrimaryDown()
	{
		if (!ZInput.GetButton("Attack"))
		{
			return ZInput.GetButton("JoyAttack");
		}
		return true;
	}

	private string InvalidReason()
	{
		if (!Object.op_Implicit((Object)(object)player) || (Object)(object)player != (Object)(object)Player.m_localPlayer || !Object.op_Implicit((Object)(object)view) || !view.IsValid() || !view.IsOwner())
		{
			return "local ownership lost";
		}
		if (((Character)player).IsDead() || ((Character)player).IsTeleporting())
		{
			return "death or teleport";
		}
		if (((Humanoid)player).GetCurrentWeapon() != weapon)
		{
			return "equipped weapon changed";
		}
		(string, string) tuple = WeaponSockets.StoredRecords(weapon);
		(string, string) tuple2 = tuple;
		(string, string) tuple3 = storedRecords;
		if (tuple2.Item1 != tuple3.Item1 || tuple2.Item2 != tuple3.Item2)
		{
			if (!string.Equals(WeaponSockets.ActiveGem(weapon), socket, StringComparison.Ordinal))
			{
				return "active gem changed";
			}
			storedRecords = tuple;
			supports = ResolvedSupports.Resolve(weapon, "VWG_GemActiveCyclone", AcceptsSupport);
			nextStatsAt = 0f;
		}
		if (((Character)player).InPlaceMode() || !takeInput(player))
		{
			return "input context changed";
		}
		if (((Character)player).IsStaggering() || ((Vector3)(ref pushForce.Invoke((Character)(object)player))).sqrMagnitude >= 1f)
		{
			return "stagger or knockback";
		}
		if (!((Character)player).InDodge() && !((Character)player).IsAttached() && !((Character)player).InEmote() && !((Character)player).IsSitting() && !((Character)player).InMinorAction() && !((Character)player).InAttack())
		{
			Attack obj = currentAttack.Invoke((Humanoid)(object)player);
			if (obj == null || obj.IsDone())
			{
				if (block.Invoke((Character)(object)player) || ((Character)player).IsBlocking())
				{
					return "blocking";
				}
				if (run.Invoke((Character)(object)player) || ((Character)player).IsRunning() || ((Character)player).IsCrouching())
				{
					return "sprint or crouch";
				}
				if (!((Character)player).IsOnGround() || ((Character)player).IsSwimming() || ((Character)player).IsFlying())
				{
					return "left grounded movement";
				}
				return null;
			}
		}
		return "native action or attack recovery";
	}

	private void ResolveStats()
	{
		nextStatsAt = Time.unscaledTime + 0.2f;
		(float, float, float, float) tuple = readStats(player, weapon);
		int num = supports.Linked?.Find(((SocketGemKinds.Definition Gem, int Level) entry) => entry.Gem == SocketGemKinds.IncreasedArea).Level ?? 0;
		float num2 = ClampFinite(CycloneMelee.CostPerSecond(staminaQuote, baseStaminaPerSecond.Value), 0f, 1000f);
		float num3 = damageEffectiveness.Value * GemProgression.AttackMultiplier(rank);
		float value = (1f + tuple.Item2 + supports.IncreasedArea) * tuple.Item3;
		float num4 = ClampFinite(tuple.Item1, 0.2f, 4f);
		float num5 = ClampFinite(value, 0.1f, 16f);
		float num6 = ClampFinite(tuple.Item4, 0.1f, 4f);
		float num7 = ClampFinite(baseRadius.Value * Mathf.Sqrt(num5) * num6, 0.1f, 25f);
		bool flag = Math.Abs(speed - num4) >= 0.01f || Math.Abs(area - num5) >= 0.01f || Math.Abs(Radius - num7) >= 0.02f || areaRank != num || Math.Abs(effectiveStamina - num2) >= 0.01f || effectiveness != num3;
		speed = num4;
		area = num5;
		reach = num6;
		areaRank = num;
		effectiveStamina = num2;
		effectiveness = num3;
		Radius = num7;
		RevolutionDuration = ClampFinite(basePeriod.Value / speed, 0.16f, 50f);
		if (active == this && flag)
		{
			Report("stats changed");
		}
	}

	private static bool AcceptsSupport(SocketGemKinds.Definition support)
	{
		if (support != SocketGemKinds.IncreasedArea && support != SocketGemKinds.AddedCold)
		{
			return support == SocketGemKinds.AddedLightning;
		}
		return true;
	}

	private static float ClampFinite(float value, float min, float max)
	{
		if (float.IsNaN(value) || float.IsInfinity(value))
		{
			throw new InvalidOperationException("Cyclone received a non-finite stat.");
		}
		return Mathf.Clamp(value, min, max);
	}

	private void Report(string action)
	{
		log.LogInfo((object)($"VWG Cyclone {action}, rank {rank}, movement ×{movement.Value:0.00}, " + $"Attack Speed ×{speed:0.00}, revolution {RevolutionDuration:0.00}s, " + $"{pulseCount} pulses/rev ({(float)pulseCount / RevolutionDuration:0.00}/s), " + $"stamina {effectiveStamina * Game.m_staminaRate:0.00}/s including world rate, effectiveness {effectiveness:P0}, " + $"+{supports.FlatCold:0.##} Frost, +{supports.FlatLightning:0.##} Lightning, " + $"area ×{area:0.00}, reach ×{reach:0.00}, radius {Radius:0.00}m, linked Increased AoE rank {areaRank}."));
	}

	private void Render()
	{
		//IL_0011: Unknown result type (might be due to invalid IL or missing references)
		visual.Place(((Component)player).transform.position, Radius, AngularPhase);
	}

	private static void Stop(string reason, bool held)
	{
		CycloneChannel cycloneChannel = active;
		active = null;
		state = (held ? State.WaitForRelease : State.Idle);
		if (cycloneChannel != null)
		{
			CyclonePose.Stop();
			cycloneChannel.visual?.Remove();
			log.LogInfo((object)("VWG Cyclone stopped: " + reason + "."));
		}
	}

	private static IEnumerable<CodeInstruction> ScaleWalking(IEnumerable<CodeInstruction> instructions)
	{
		//IL_01e9: Unknown result type (might be due to invalid IL or missing references)
		//IL_01ef: Expected O, but got Unknown
		//IL_01ff: Unknown result type (might be due to invalid IL or missing references)
		//IL_0205: Expected O, but got Unknown
		//IL_0222: Unknown result type (might be due to invalid IL or missing references)
		//IL_0228: Expected O, but got Unknown
		List<CodeInstruction> list = instructions.ToList();
		MethodInfo methodInfo = AccessTools.DeclaredMethod(typeof(Character), "GetAttackSpeedFactorMovement", Type.EmptyTypes, (Type[])null);
		MethodInfo methodInfo2 = AccessTools.DeclaredMethod(typeof(SEMan), "ApplyStatusEffectSpeedMods", new Type[2]
		{
			typeof(float).MakeByRefType(),
			typeof(Vector3)
		}, (Type[])null);
		if (methodInfo == null || methodInfo2 == null)
		{
			throw new MissingMethodException("Character.GetAttackSpeedFactorMovement or SEMan.ApplyStatusEffectSpeedMods");
		}
		List<int> list2 = new List<int>();
		for (int i = 0; i + 7 < list.Count; i++)
		{
			if (CodeInstructionExtensions.Calls(list[i], methodInfo) && !(list[i + 1].opcode != OpCodes.Mul) && CodeInstructionExtensions.Calls(list[i + 7], methodInfo2))
			{
				CodeInstruction val = list[i + 5];
				CodeInstruction val2 = list[i + 2];
				if ((val.opcode == OpCodes.Ldloca_S || val.opcode == OpCodes.Ldloca) && val.operand is LocalBuilder localBuilder && localBuilder.LocalType == typeof(float) && (val2.opcode == OpCodes.Stloc_S || val2.opcode == OpCodes.Stloc) && val2.operand is LocalBuilder localBuilder2 && localBuilder2.LocalIndex == localBuilder.LocalIndex)
				{
					list2.Add(i + 7);
				}
			}
		}
		if (list2.Count != 1)
		{
			throw new InvalidOperationException($"Expected one walking-speed calculation in Character.UpdateWalking, found {list2.Count}.");
		}
		int num = list2[0];
		CodeInstruction val3 = list[num - 2];
		list.InsertRange(num + 1, (IEnumerable<CodeInstruction>)(object)new CodeInstruction[3]
		{
			new CodeInstruction(OpCodes.Ldarg_0, (object)null),
			new CodeInstruction(val3.opcode, val3.operand),
			new CodeInstruction(OpCodes.Call, (object)AccessTools.DeclaredMethod(typeof(CycloneChannel), "ScaleSpeed", (Type[])null, (Type[])null))
		});
		return list;
	}

	private static void ScaleSpeed(Character character, ref float speed)
	{
		CycloneChannel cycloneChannel = active;
		if (cycloneChannel != null && (Object)(object)character == (Object)(object)cycloneChannel.player && Object.op_Implicit((Object)(object)cycloneChannel.view) && cycloneChannel.view.IsOwner() && !run.Invoke(character) && !block.Invoke(character))
		{
			speed *= movement.Value;
		}
	}
}
internal static class CycloneMelee
{
	private static Func<Attack, float> stamina;

	private static Action<Attack> release;

	private static Func<int> enterArea;

	private static Action<int> leaveArea;

	private static FieldRef<int> actionOverride;

	private static Attack costProbe;

	private static Attack releasing;

	private static int actionId = int.MinValue;

	private static float radius;

	private static Vector3 origin;

	internal static bool Initialize(ManualLogSource log)
	{
		return Plugin.Install(log, "cyclone-melee", "Cyclone native melee pulses", delegate(Harmony harmony)
		{
			//IL_01a6: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ca: Expected O, but got Unknown
			MethodInfo methodInfo = Method(typeof(CycloneMelee), "Prepare");
			Type[] signature = (from parameter in methodInfo.GetParameters().Skip(1)
				select parameter.ParameterType).ToArray();
			MethodInfo methodInfo2 = Method(typeof(Attack), "Start", signature);
			release = AccessTools.MethodDelegate<Action<Attack>>(Method(typeof(Attack), "OnAttackTrigger", Type.EmptyTypes), (object)null, true);
			stamina = AccessTools.MethodDelegate<Func<Attack, float>>(Method(typeof(Attack), "GetAttackStamina", Type.EmptyTypes), (object)null, true);
			Assembly povAssembly = Plugin.PovAssembly;
			Type type = povAssembly.GetType("PassiveTree.HitContext", throwOnError: true);
			Type type2 = povAssembly.GetType("PassiveTree.HitTag", throwOnError: true);
			MethodInfo method = Method(type, "Push", type2);
			MethodInfo method2 = Method(type, "Pop", type2);
			ParameterExpression parameterExpression = Expression.Parameter(typeof(int));
			enterArea = Expression.Lambda<Func<int>>(Expression.Convert(Expression.Call(method, Expression.Constant(Enum.Parse(type2, "Area"), type2)), typeof(int)), Array.Empty<ParameterExpression>()).Compile();
			leaveArea = Expression.Lambda<Action<int>>(Expression.Call(method2, Expression.Convert(parameterExpression, type2)), new ParameterExpression[1] { parameterExpression }).Compile();
			actionOverride = AccessTools.StaticFieldRefAccess<int>(AccessTools.DeclaredField(type, "ActionOverride") ?? throw new MissingFieldException(type.FullName, "ActionOverride"));
			Harmony.ReversePatch((MethodBase)methodInfo2, new HarmonyMethod(methodInfo), Method(typeof(CycloneMelee), "InitializationOnly"), (MethodInfo)null);
			Type type3 = povAssembly.GetType("PassiveTree.NextAttack+Cost", throwOnError: true);
			CombatPatchSafety.Patch(harmony, Method(type3, "Postfix", typeof(Attack), typeof(float).MakeByRefType()), Hook("SkipNextAttackCost"));
			Type type4 = povAssembly.GetType("PassiveTree.ChargedAttacks", throwOnError: true);
			CombatPatchSafety.Patch(harmony, Method(type4, "get_Ready", Type.EmptyTypes), Hook("QuoteUncharged"));
			HarmonyMethod val = Hook("RestorePulseGeometry");
			val.priority = 0;
			CombatPatchSafety.Patch(harmony, Method(typeof(Attack), "DoMeleeAttack", Type.EmptyTypes), val);
			CombatPatchSafety.Patch(harmony, Method(typeof(Attack), "AddHitPoint"), Hook("InsideRadius"));
		});
	}

	internal static Attack NewAction(Player player, ItemData weapon)
	{
		//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_0024: 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_0034: Unknown result type (might be due to invalid IL or missing references)
		//IL_003f: 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)
		//IL_0055: Unknown result type (might be due to invalid IL or missing references)
		//IL_0060: Unknown result type (might be due to invalid IL or missing references)
		//IL_006b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0076: Unknown result type (might be due to invalid IL or missing references)
		//IL_007d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0084: Unknown result type (might be due to invalid IL or missing references)
		//IL_00af: Expected O, but got Unknown
		//IL_00bd: Expected O, but got Unknown
		if (!string.IsNullOrWhiteSpace(weapon.m_shared.m_ammoType))
		{
			throw new InvalidOperationException("Cyclone requires a melee weapon without ammunition.");
		}
		Attack val = new Attack
		{
			m_attackType = (AttackType)0,
			m_attackAnimation = "VWG_GemActiveCyclone",
			m_attackOriginJoint = "",
			m_attackAngle = 360f,
			m_attackHeight = 0.22f,
			m_attackHeightChar1 = 0.6f,
			m_attackHeightChar2 = -0.3f,
			m_maxYAngle = 0f,
			m_multiHit = true,
			m_lowerDamagePerHit = false
		};
		if (!Prepare(val, (Humanoid)(object)player, ((Component)player).GetComponent<Rigidbody>(), ((Component)player).GetComponent<ZSyncAnimation>(), ((Component)player).GetComponentInChildren<CharacterAnimEvent>(), ((Component)player).GetComponent<VisEquipment>(), weapon, null, 0f, 0f))
		{
			throw new InvalidOperationException("Valheim rejected Cyclone pulse initialization.");
		}
		return val;
	}

	internal static float CostPerSecond(Attack quote, float baseCost)
	{
		costProbe = quote;
		quote.m_attackStamina = baseCost;
		try
		{
			return stamina(quote);
		}
		finally
		{
			quote.m_attackStamina = 0f;
			costProbe = null;
		}
	}

	internal static void Pulse(Player player, ItemData weapon, int rank, float effectiveness, float resolvedRadius, ResolvedSupports supports)
	{
		//IL_0063: Unknown result type (might be due to invalid IL or missing references)
		//IL_0068: Unknown result type (might be due to invalid IL or missing references)
		Attack val = NewAction(player, weapon);
		val.m_damageMultiplier = effectiveness;
		val.m_attackRange = resolvedRadius;
		AttackSupportDamage.Track(val, "VWG_GemActiveCyclone", rank, weapon, supports);
		int num = actionOverride.Invoke();
		int obj = enterArea();
		actionOverride.Invoke() = actionId++;
		radius = resolvedRadius;
		origin = ((Component)player).transform.position;
		releasing = val;
		try
		{
			release(val);
		}
		finally
		{
			releasing = null;
			actionOverride.Invoke() = num;
			leaveArea(obj);
		}
	}

	private static bool SkipNextAttackCost(Attack __0)
	{
		return __0 != costProbe;
	}

	private static bool QuoteUncharged(ref bool __result)
	{
		if (costProbe == null)
		{
			return true;
		}
		__result = false;
		return false;
	}

	private static void RestorePulseGeometry(Attack __instance)
	{
		if (__instance == releasing)
		{
			__instance.m_attackRange = radius;
			__instance.m_attackAngle = 360f;
			__instance.m_attackRayWidth = Mathf.Max(0.16f, radius * Mathf.Sin(MathF.PI / 90f));
			__instance.m_attackRayWidthCharExtra = 0f;
		}
	}

	private static bool InsideRadius(Attack __instance, Vector3 __3)
	{
		//IL_000a: Unknown result type (might be due to invalid IL or missing references)
		//IL_000b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0010: Unknown result type (might be due to invalid IL or missing references)
		//IL_0015: Unknown result type (might be due to invalid IL or missing references)
		//IL_0016: Unknown result type (might be due to invalid IL or missing references)
		//IL_001c: 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_0029: Un