Decompiled source of P1DefensePlus v1.0.1

plugins/P1DefensePlus.dll

Decompiled 2 weeks ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Security;
using System.Security.Permissions;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using BepInEx.Unity.IL2CPP;
using BepInEx.Unity.IL2CPP.Hook;
using HarmonyLib;
using Il2CppInterop.Runtime.InteropTypes;
using Il2CppInterop.Runtime.InteropTypes.Arrays;
using Il2CppInterop.Runtime.Runtime;
using Il2CppInterop.Runtime.Runtime.VersionSpecific.MethodInfo;
using Il2CppSystem;
using Microsoft.CodeAnalysis;
using P1.Game;
using P1.Game.Actor;
using P1.Game.Unit;
using P1.GameSystem;
using P1.GameSystem.Actor;
using P1.GameSystem.Actor.Status;
using P1.Sound;
using P1.Sound.PowerEvaluateParam;
using P1S.Game;
using P1S.Game.Actor;
using P1S.Game.Unit;
using P1S.GameSystem;
using P1S.GameSystem.Actor;
using P1S.GameSystem.Actor.Status;
using P1S.Sound;
using P1S.Sound.PowerEvaluateParam;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: AssemblyFileVersion("0.1.4.0")]
[assembly: AssemblyInformationalVersion("0.1.4-beta")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("0.1.4.0")]
[module: UnverifiableCode]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

		public NullableAttribute(byte P_0)
		{
			NullableFlags = new byte[1] { P_0 };
		}

		public NullableAttribute(byte[] P_0)
		{
			NullableFlags = P_0;
		}
	}
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableContextAttribute : Attribute
	{
		public readonly byte Flag;

		public NullableContextAttribute(byte P_0)
		{
			Flag = P_0;
		}
	}
}
namespace P1DefensePlus
{
	internal static class BossRushDefense
	{
		private sealed class BattleContext
		{
			internal readonly Game Game;

			internal readonly DefenseMapping Mapping;

			internal readonly int[] LoggedHits = new int[3];

			internal bool HookObserved;

			internal readonly bool ReadAtImpact;

			internal BattleContext(Game game, DefenseMapping mapping, bool readAtImpact)
			{
				Game = game;
				Mapping = mapping;
				ReadAtImpact = readAtImpact;
			}
		}

		private sealed class HitSnapshot
		{
			internal BattleContext Battle;

			internal HitInfo? Copy;

			internal bool ShouldLog;

			internal string Unit = "";

			internal HitType HitType;

			internal int Command;

			internal int LastAction;

			internal DefenseMode Mode;

			internal bool RhythmFailed;

			internal float OriginalPower;

			internal float AppliedPower;

			internal int HpBefore;
		}

		private static ManualLogSource? logger;

		private static ConfigEntry<bool>? enabled;

		private static ConfigEntry<float>? normalMultiplier;

		private static ConfigEntry<float>? chargedMultiplier;

		private static ConfigEntry<bool>? protectHatapon;

		private static ConfigEntry<int>? diagnosticHits;

		private static Harmony? harmony;

		private static NativeCalculatorHook? calculatorHook;

		private static bool damageEntryObserved;

		private static bool nativeEntryObserved;

		private static readonly Dictionary<IntPtr, BattleContext> Battles = new Dictionary<IntPtr, BattleContext>();

		private static readonly HashSet<string> Errors = new HashSet<string>();

		internal static void Start(ManualLogSource source, ConfigEntry<bool> enabledSetting, ConfigEntry<float> normalSetting, ConfigEntry<float> chargedSetting, ConfigEntry<bool> hataponSetting, ConfigEntry<int> diagnosticsSetting)
		{
			//IL_0037: Unknown result type (might be due to invalid IL or missing references)
			//IL_0041: Expected O, but got Unknown
			logger = source;
			enabled = enabledSetting;
			normalMultiplier = normalSetting;
			chargedMultiplier = chargedSetting;
			protectHatapon = hataponSetting;
			diagnosticHits = diagnosticsSetting;
			damageEntryObserved = false;
			nativeEntryObserved = false;
			harmony = new Harmony("com.cpuffles.patapon1.defenseplus.bossrush");
			Patch(typeof(Game), "terminate", "BattleEnded", null);
			calculatorHook = new NativeCalculatorHook();
			calculatorHook.InstallBossRush(CalculateNative);
			logger.LogInfo((object)"[Boss Rush P1] Soporte P1S conectado; comparte los ajustes de defensa normal y cargada de la campana.");
		}

		private static void Patch(Type type, string name, string? before, string? after)
		{
			//IL_0030: 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)
			MethodInfo methodInfo = AccessTools.DeclaredMethod(type, name, (Type[])null, (Type[])null) ?? throw new MissingMethodException(type.FullName, name);
			harmony.Patch((MethodBase)methodInfo, (before == null) ? ((HarmonyMethod)null) : new HarmonyMethod(typeof(BossRushDefense), before, (Type[])null), (after == null) ? ((HarmonyMethod)null) : new HarmonyMethod(typeof(BossRushDefense), after, (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
		}

		private static string F(float value)
		{
			return value.ToString("0.###", CultureInfo.InvariantCulture);
		}

		private static void BattleEnded(Game __instance)
		{
			Battles.Remove(((Il2CppObjectBase)__instance).Pointer);
		}

		private static BattleContext? GetBattle(Game game, bool fromImpact = false)
		{
			if (Battles.TryGetValue(((Il2CppObjectBase)game).Pointer, out BattleContext value))
			{
				if (value.Mapping.IsValid || !fromImpact || value.ReadAtImpact)
				{
					return value;
				}
				Battles.Remove(((Il2CppObjectBase)game).Pointer);
			}
			Director soundDirector_ = game.soundDirector_;
			ParamFileHolder val = ((soundDirector_ != null) ? soundDirector_.paramHolder_ : null);
			if (val == null)
			{
				return null;
			}
			uint cPECommandParamNum = val.getCPECommandParamNum();
			if (cPECommandParamNum == 0)
			{
				return null;
			}
			if (cPECommandParamNum > 256)
			{
				throw new InvalidOperationException("La tabla de canciones tiene un tamano inesperado.");
			}
			DefenseMapping defenseMapping = new DefenseMapping();
			List<string> list = new List<string>();
			for (uint num = 0u; num < cPECommandParamNum; num++)
			{
				CommandParam cPECommandParam = val.getCPECommandParam(num);
				Il2CppStructArray<short> val2 = ((cPECommandParam != null) ? cPECommandParam.key : null);
				if (cPECommandParam != null && val2 != null && ((Il2CppArrayBase<short>)(object)val2).Length <= 64)
				{
					short[] array = new short[((Il2CppArrayBase<short>)(object)val2).Length];
					for (int i = 0; i < array.Length; i++)
					{
						array[i] = ((Il2CppArrayBase<short>)(object)val2)[i];
					}
					defenseMapping.Observe(cPECommandParam.command, array);
					list.Add("id=" + cPECommandParam.id + ", cmd=" + cPECommandParam.command + ", keys=[" + string.Join(",", array) + "]");
				}
			}
			BattleContext battleContext = new BattleContext(game, defenseMapping, fromImpact);
			Battles[((Il2CppObjectBase)game).Pointer] = battleContext;
			if (defenseMapping.IsValid)
			{
				ManualLogSource? obj = logger;
				if (obj != null)
				{
					obj.LogInfo((object)("[Boss Rush P1] Chaka Chaka Pata Pon validado por la tabla nativa: familia=" + defenseMapping.Family.ToString() + ", coincidencias=" + defenseMapping.Matches + "."));
				}
			}
			else
			{
				ManualLogSource? obj2 = logger;
				if (obj2 != null)
				{
					obj2.LogWarning((object)"[Boss Rush P1] No se pudo identificar de forma inequivoca la cancion de defensa. Esta batalla conserva su dano original. Adjunta LogOutput.log.");
				}
				foreach (string item in list)
				{
					ManualLogSource? obj3 = logger;
					if (obj3 != null)
					{
						obj3.LogInfo((object)("[Boss Rush P1] Tabla de canciones: " + item));
					}
				}
			}
			return battleContext;
		}

		private static bool TryGetPlayer(GameStatus status, out Game? game, out UnitTroop? troop, out string unitName)
		{
			//IL_00d8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ee: Unknown result type (might be due to invalid IL or missing references)
			game = null;
			troop = null;
			unitName = "";
			ActorStatusObj obj = ((Il2CppObjectBase)status).TryCast<ActorStatusObj>();
			ActorObj val = ((obj != null) ? obj.pActorObj_ : null);
			if (val == null)
			{
				return false;
			}
			UnitBase val2 = ((Il2CppObjectBase)val).TryCast<UnitBase>();
			if (val2 != null)
			{
				UnitSquad pUnitSquad_ = val2.pUnitSquad_;
				troop = ((pUnitSquad_ != null) ? pUnitSquad_.pUnitTroop_ : null);
				game = ((GameActorBase)val2).pGame_;
				Info info_ = val2.info_;
				unitName = "unidad " + (((info_ != null) ? info_.uniqueId.ToString(CultureInfo.InvariantCulture) : null) ?? "?");
			}
			else
			{
				ConfigEntry<bool>? obj2 = protectHatapon;
				if (obj2 != null && obj2.Value)
				{
					FlagUnit val3 = ((Il2CppObjectBase)val).TryCast<FlagUnit>();
					if (val3 == null)
					{
						return false;
					}
					troop = val3.pUnitTroop_;
					game = val3.pGame_;
					unitName = "Hatapon";
				}
			}
			if (game != null)
			{
				UnitTroop? obj3 = troop;
				if (obj3 == null)
				{
					return false;
				}
				TroopInfo troopInfo_ = obj3.troopInfo_;
				return ((troopInfo_ != null) ? new TroopType?(troopInfo_.troopType) : ((TroopType?)null)) == (TroopType?)0;
			}
			return false;
		}

		private static void BeforeDamage(GameStatus __instance, ref HitInfo __0, out HitSnapshot? __state)
		{
			//IL_0054: Unknown result type (might be due to invalid IL or missing references)
			//IL_006f: Expected I4, but got Unknown
			//IL_010c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0113: Expected I4, but got Unknown
			//IL_0115: Unknown result type (might be due to invalid IL or missing references)
			//IL_011c: Expected I4, but got Unknown
			//IL_01ab: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b0: Unknown result type (might be due to invalid IL or missing references)
			__state = null;
			ConfigEntry<bool>? obj = enabled;
			if (obj != null && obj.Value && !damageEntryObserved)
			{
				damageEntryObserved = true;
				ManualLogSource? obj2 = logger;
				if (obj2 != null)
				{
					obj2.LogInfo((object)"[Boss Rush P1] Entrada al calculo de dano de P1 observada; se comprobaran el receptor y la cancion.");
				}
			}
			ConfigEntry<bool>? obj3 = enabled;
			if (obj3 == null || !obj3.Value || __0 == null || !DefensePolicy.IsDamageImpact((int)__0.hitType, __0.damageParam != null, __0.hitPower))
			{
				return;
			}
			try
			{
				if (!TryGetPlayer(__instance, out Game game, out UnitTroop troop, out string unitName) || game == null || troop == null)
				{
					return;
				}
				BattleContext battle = GetBattle(game, fromImpact: true);
				if (battle == null || !battle.Mapping.IsValid)
				{
					return;
				}
				if (!battle.HookObserved)
				{
					battle.HookObserved = true;
					ManualLogSource? obj4 = logger;
					if (obj4 != null)
					{
						obj4.LogInfo((object)"[Boss Rush P1] Calculo de dano de P1 observado para el ejercito del jugador.");
					}
				}
				InstructionParam instructionParam_ = troop.instructionParam_;
				CommandParam val = ((instructionParam_ != null) ? instructionParam_.commandParam_ : null);
				Director soundDirector_ = game.soundDirector_;
				BeatCommander val2 = ((soundDirector_ != null) ? soundDirector_.beatCommander_ : null);
				if (instructionParam_ == null || val == null || val2 == null)
				{
					return;
				}
				int command = (int)val.command;
				int lastAction = (int)instructionParam_.lastActionCmd_;
				bool failedRhythmMode_ = val2.failedRhythmMode_;
				DefenseMode defenseMode = DefensePolicy.Classify(command, lastAction, failedRhythmMode_, battle.Mapping.Family);
				float hitPower = __0.hitPower;
				float multiplier = DefensePolicy.Multiplier(defenseMode, normalMultiplier.Value, chargedMultiplier.Value);
				float scaled = hitPower;
				bool flag = DefensePolicy.TryScalePower(hitPower, multiplier, out scaled);
				bool flag2 = battle.LoggedHits[(int)defenseMode] < diagnosticHits.Value;
				object obj5;
				if (!(flag || flag2))
				{
					obj5 = null;
				}
				else
				{
					obj5 = new HitSnapshot
					{
						Battle = battle,
						Unit = unitName,
						HitType = __0.hitType,
						Command = command,
						LastAction = lastAction,
						Mode = defenseMode,
						OriginalPower = hitPower,
						AppliedPower = (flag ? scaled : hitPower)
					};
					object obj6 = obj5;
					Info info_ = __instance.info_;
					((HitSnapshot)obj6).HpBefore = ((info_ != null) ? info_.hitPoint : (-1));
					((HitSnapshot)obj5).ShouldLog = flag2;
					((HitSnapshot)obj5).RhythmFailed = failedRhythmMode_;
				}
				HitSnapshot hitSnapshot = (HitSnapshot)obj5;
				if (flag)
				{
					HitInfo val3 = CopyHit(__0, scaled);
					if (hitSnapshot != null)
					{
						hitSnapshot.Copy = val3;
					}
					__0 = val3;
				}
				__state = hitSnapshot;
			}
			catch (Exception ex)
			{
				Report("No se pudo preparar un impacto defensivo", ex);
			}
		}

		private static byte CalculateNative(IntPtr hitInfo, IntPtr hitResultRef, IntPtr damageParam, IntPtr gameStatus, IntPtr nbVecRef, float accuracy, byte isEnemy, byte isGimmick, IntPtr methodInfo)
		{
			//IL_0069: Unknown result type (might be due to invalid IL or missing references)
			//IL_006f: Expected O, but got Unknown
			//IL_0070: Unknown result type (might be due to invalid IL or missing references)
			//IL_0077: Expected O, but got Unknown
			//IL_0109: Unknown result type (might be due to invalid IL or missing references)
			//IL_0118: Expected O, but got Unknown
			NativeDamageCall call = new NativeDamageCall(hitInfo, hitResultRef, damageParam, gameStatus, nbVecRef, accuracy, isEnemy, isGimmick, methodInfo);
			GameStatus val = null;
			HitSnapshot __state = null;
			try
			{
				if (!nativeEntryObserved)
				{
					nativeEntryObserved = true;
					ManualLogSource? obj = logger;
					if (obj != null)
					{
						obj.LogInfo((object)"[Boss Rush P1] Calculador nativo P1S alcanzado.");
					}
				}
				ConfigEntry<bool>? obj2 = enabled;
				if (obj2 != null && obj2.Value && hitInfo != IntPtr.Zero && gameStatus != IntPtr.Zero)
				{
					val = new GameStatus(gameStatus);
					HitInfo __ = new HitInfo(hitInfo);
					BeforeDamage(val, ref __, out __state);
					call = call.WithHitInfo(((Il2CppObjectBase)__).Pointer);
				}
			}
			catch (Exception ex)
			{
				Report("No se pudo preparar el impacto nativo", ex);
			}
			byte b;
			try
			{
				b = calculatorHook.InvokeOriginal(call);
			}
			catch (Exception ex2)
			{
				Report("El calculo nativo lanzo una excepcion; no se repetira el impacto", ex2);
				GC.KeepAlive(__state?.Copy);
				return 0;
			}
			try
			{
				if (val != null && __state != null)
				{
					IntPtr intPtr = ((hitResultRef == IntPtr.Zero) ? IntPtr.Zero : Marshal.ReadIntPtr(hitResultRef));
					if (intPtr != IntPtr.Zero)
					{
						AfterDamage(val, new HitResult(intPtr), b != 0, __state);
					}
				}
			}
			catch (Exception ex3)
			{
				Report("No se pudo observar el resultado nativo", ex3);
			}
			finally
			{
				GC.KeepAlive(__state?.Copy);
			}
			return b;
		}

		private static HitInfo CopyHit(HitInfo source, float power)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0005: 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)
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			//IL_001d: 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_0030: Unknown result type (might be due to invalid IL or missing references)
			//IL_003c: Unknown result type (might be due to invalid IL or missing references)
			//IL_003e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0048: 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_0054: 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_0062: 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_006e: 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_0091: Expected O, but got Unknown
			return new HitInfo
			{
				isHit = source.isHit,
				hitType = source.hitType,
				hitPower = power,
				hitAttribute = source.hitAttribute,
				hitUniqueId = source.hitUniqueId,
				hitCategory = source.hitCategory,
				hitPos = source.hitPos,
				pParent = source.pParent,
				pPos = source.pPos,
				pVec = source.pVec,
				damageParam = source.damageParam,
				accuracyRatio = source.accuracyRatio
			};
		}

		private static void AfterDamage(GameStatus __instance, HitResult __1, bool __result, HitSnapshot? __state)
		{
			if (__state == null)
			{
				return;
			}
			try
			{
				if (__state.ShouldLog)
				{
					__state.Battle.LoggedHits[(int)__state.Mode]++;
					ManualLogSource? obj = logger;
					if (obj != null)
					{
						string[] obj2 = new string[27]
						{
							"[Boss Rush P1] Impacto: ",
							__state.Unit,
							", tipo=",
							((object)Unsafe.As<HitType, HitType>(ref __state.HitType)/*cast due to .constrained prefix*/).ToString(),
							", defensa=",
							__state.Mode.ToString(),
							", cmd=",
							__state.Command.ToString(),
							", ultima=",
							__state.LastAction.ToString(),
							", ritmoFallado=",
							__state.RhythmFailed.ToString(),
							", potencia=",
							F(__state.OriginalPower),
							"->",
							F(__state.AppliedPower),
							", potenciaTrasCalculo=",
							(__state.Copy == null) ? "sin copia" : F(__state.Copy.hitPower),
							", dano=",
							(__1 == null) ? "?" : __1.damage.ToString(CultureInfo.InvariantCulture),
							", HP=",
							__state.HpBefore.ToString(),
							"->",
							null,
							null,
							null,
							null
						};
						Info info_ = __instance.info_;
						obj2[23] = ((info_ != null) ? new int?(info_.hitPoint) : ((int?)null)).ToString();
						obj2[24] = ", resultado=";
						obj2[25] = __result.ToString();
						obj2[26] = ".";
						obj.LogInfo((object)string.Concat(obj2));
					}
				}
			}
			catch (Exception ex)
			{
				Report("No se pudo registrar un impacto", ex);
			}
			finally
			{
				GC.KeepAlive(__state.Copy);
			}
		}

		private static void Report(string message, Exception ex)
		{
			string text = message + ": " + ex.GetType().Name + ": " + ex.Message;
			if (Errors.Count < 16 && Errors.Add(text))
			{
				ManualLogSource? obj = logger;
				if (obj != null)
				{
					obj.LogWarning((object)("[Boss Rush P1] " + text));
				}
			}
		}

		internal static void Stop()
		{
			calculatorHook?.Dispose();
			calculatorHook = null;
			Harmony? obj = harmony;
			if (obj != null)
			{
				obj.UnpatchSelf();
			}
			harmony = null;
			Battles.Clear();
			Errors.Clear();
			damageEntryObserved = false;
			nativeEntryObserved = false;
		}
	}
	internal enum DefenseFamily
	{
		Unknown,
		ShortRange,
		LongRange
	}
	internal enum DefenseMode
	{
		None,
		Normal,
		Charged
	}
	internal static class DefensePolicy
	{
		internal static bool IsDamageImpact(int hitType, bool hasAttackDamageParam, float power)
		{
			if (hitType != 2)
			{
				if (hitType == 0 && hasAttackDamageParam && float.IsFinite(power))
				{
					return power > 0f;
				}
				return false;
			}
			return true;
		}

		internal static bool IsDefenseSong(ReadOnlySpan<short> keys)
		{
			ReadOnlySpan<short> readOnlySpan = stackalloc short[4] { 4, 4, 3, 1 };
			int num = 0;
			bool flag = false;
			ReadOnlySpan<short> readOnlySpan2 = keys;
			for (int i = 0; i < readOnlySpan2.Length; i++)
			{
				short num2 = readOnlySpan2[i];
				switch (num2)
				{
				case -1:
					if (num != readOnlySpan.Length)
					{
						return false;
					}
					flag = true;
					continue;
				case 0:
					continue;
				}
				if (flag)
				{
					return false;
				}
				if (num >= readOnlySpan.Length || num2 != readOnlySpan[num++])
				{
					return false;
				}
			}
			return num == readOnlySpan.Length;
		}

		internal static DefenseFamily FamilyForBeatCommand(uint command)
		{
			return command switch
			{
				3u => DefenseFamily.LongRange, 
				2u => DefenseFamily.ShortRange, 
				_ => DefenseFamily.Unknown, 
			};
		}

		internal static DefenseMode Classify(int command, int lastAction, bool rhythmFailed, DefenseFamily family)
		{
			if (rhythmFailed || family == DefenseFamily.Unknown)
			{
				return DefenseMode.None;
			}
			if (command == -1 || command == 0)
			{
				command = lastAction;
			}
			int num = ((family == DefenseFamily.ShortRange) ? 9 : 10);
			if (command == num || command == num + 5)
			{
				return DefenseMode.Normal;
			}
			if (command == num + 10 || command == num + 15)
			{
				return DefenseMode.Charged;
			}
			return DefenseMode.None;
		}

		internal static float Multiplier(DefenseMode mode, float normal, float charged)
		{
			float num = mode switch
			{
				DefenseMode.Charged => charged, 
				DefenseMode.Normal => normal, 
				_ => 1f, 
			};
			if (!float.IsFinite(num) || !(num >= 0.05f) || !(num <= 1f))
			{
				return 1f;
			}
			return num;
		}

		internal static bool TryScalePower(float power, float multiplier, out float scaled)
		{
			scaled = power;
			if (!float.IsFinite(power) || power <= 0f || !float.IsFinite(multiplier) || multiplier < 0.05f || multiplier >= 1f)
			{
				return false;
			}
			float num = power * multiplier;
			if (!float.IsFinite(num) || num <= 0f)
			{
				return false;
			}
			scaled = num;
			return true;
		}
	}
	internal sealed class DefenseMapping
	{
		internal DefenseFamily Family { get; private set; }

		internal bool HasConflict { get; private set; }

		internal int Matches { get; private set; }

		internal bool IsValid
		{
			get
			{
				if (Matches > 0 && !HasConflict)
				{
					return Family != DefenseFamily.Unknown;
				}
				return false;
			}
		}

		internal void Observe(uint nativeBeatCommand, ReadOnlySpan<short> keys)
		{
			if (DefensePolicy.IsDefenseSong(keys))
			{
				Matches++;
				DefenseFamily defenseFamily = DefensePolicy.FamilyForBeatCommand(nativeBeatCommand);
				if (defenseFamily == DefenseFamily.Unknown || (Family != DefenseFamily.Unknown && defenseFamily != Family))
				{
					HasConflict = true;
				}
				if (!HasConflict)
				{
					Family = defenseFamily;
				}
			}
		}
	}
	internal sealed class NativeCalculatorHook : IDisposable
	{
		private INativeDetour? detour;

		private NativeDamageCalculator? original;

		private NativeDamageCalculator? callback;

		internal void Install(NativeDamageCalculator handler)
		{
			InstallFor(typeof(DamageCalculation), typeof(HitInfo), typeof(HitResult), typeof(DamageParam), typeof(GameStatus), handler);
		}

		internal void InstallBossRush(NativeDamageCalculator handler)
		{
			InstallFor(typeof(DamageCalculation), typeof(HitInfo), typeof(HitResult), typeof(DamageParam), typeof(GameStatus), handler);
		}

		private unsafe void InstallFor(Type type, Type hitInfo, Type hitResult, Type damageParam, Type gameStatus, NativeDamageCalculator handler)
		{
			if (RuntimeInformation.ProcessArchitecture != Architecture.X64)
			{
				throw new PlatformNotSupportedException("Este paquete requiere el juego x64.");
			}
			MethodInfo methodInfo = type.GetMethod("calcDamage", BindingFlags.Static | BindingFlags.Public) ?? throw new MissingMethodException(type.FullName, "calcDamage");
			ParameterInfo[] parameters = methodInfo.GetParameters();
			if (parameters.Length != 8 || parameters[0].ParameterType != hitInfo || parameters[1].ParameterType != hitResult.MakeByRefType() || parameters[2].ParameterType != damageParam || parameters[3].ParameterType != gameStatus || !parameters[4].ParameterType.IsByRef || parameters[4].ParameterType.GetElementType() != typeof(Nullable<Vector4>) || parameters[5].ParameterType != typeof(float) || parameters[6].ParameterType != typeof(bool) || parameters[7].ParameterType != typeof(bool) || methodInfo.ReturnType != typeof(bool))
			{
				throw new InvalidOperationException("La firma del calculador nativo no coincide con la compatible.");
			}
			RuntimeHelpers.RunClassConstructor(type.TypeHandle);
			IntPtr intPtr = (IntPtr)(type.GetFields(BindingFlags.Static | BindingFlags.NonPublic).Single((FieldInfo f) => f.Name.StartsWith("NativeMethodInfoPtr_calcDamage_", StringComparison.Ordinal) && f.FieldType == typeof(IntPtr)).GetValue(null) ?? ((object)IntPtr.Zero));
			if (intPtr == IntPtr.Zero)
			{
				throw new InvalidOperationException("Falta MethodInfo del calculador.");
			}
			INativeMethodInfoStruct val = UnityVersionHandler.Wrap((Il2CppMethodInfo*)(void*)intPtr);
			if (val == null || val.ParametersCount != 8 || val.MethodPointer == IntPtr.Zero)
			{
				throw new InvalidOperationException("El calculador nativo no tiene una entrada valida.");
			}
			callback = handler;
			detour = INativeDetour.CreateAndApply<NativeDamageCalculator>(val.MethodPointer, callback, ref original);
		}

		internal byte InvokeOriginal(NativeDamageCall call)
		{
			return call.Invoke(original ?? throw new InvalidOperationException("El trampolin de dano no esta preparado."));
		}

		public void Dispose()
		{
			((IDisposable)detour)?.Dispose();
			detour = null;
			original = null;
			callback = null;
		}
	}
	[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
	internal delegate byte NativeDamageCalculator(IntPtr hitInfo, IntPtr hitResultRef, IntPtr damageParam, IntPtr gameStatus, IntPtr nbVecRef, float accuracy, byte isEnemy, byte isGimmick, IntPtr methodInfo);
	internal readonly record struct NativeDamageCall(IntPtr HitInfo, IntPtr HitResultRef, IntPtr DamageParam, IntPtr GameStatus, IntPtr NbVecRef, float Accuracy, byte IsEnemy, byte IsGimmick, IntPtr MethodInfo)
	{
		internal NativeDamageCall WithHitInfo(IntPtr replacement)
		{
			return this with
			{
				HitInfo = replacement
			};
		}

		internal byte Invoke(NativeDamageCalculator original)
		{
			return original(HitInfo, HitResultRef, DamageParam, GameStatus, NbVecRef, Accuracy, IsEnemy, IsGimmick, MethodInfo);
		}
	}
	[BepInPlugin("com.cpuffles.patapon1.defenseplus", "Patapon 1 Defense Plus", "0.1.4")]
	public sealed class Plugin : BasePlugin
	{
		private sealed class BattleContext
		{
			internal readonly Game Game;

			internal readonly DefenseMapping Mapping;

			internal readonly int[] LoggedHits = new int[3];

			internal bool HookObserved;

			internal readonly bool ReadAtImpact;

			internal BattleContext(Game game, DefenseMapping mapping, bool readAtImpact)
			{
				Game = game;
				Mapping = mapping;
				ReadAtImpact = readAtImpact;
			}
		}

		private sealed class HitSnapshot
		{
			internal BattleContext Battle;

			internal HitInfo? Copy;

			internal bool ShouldLog;

			internal string Unit = "";

			internal HitType HitType;

			internal int Command;

			internal int LastAction;

			internal DefenseMode Mode;

			internal bool RhythmFailed;

			internal float OriginalPower;

			internal float AppliedPower;

			internal int HpBefore;
		}

		public const string Id = "com.cpuffles.patapon1.defenseplus";

		public const string Version = "0.1.4";

		private static ManualLogSource? logger;

		private static ConfigEntry<bool>? enabled;

		private static ConfigEntry<float>? normalMultiplier;

		private static ConfigEntry<float>? chargedMultiplier;

		private static ConfigEntry<bool>? protectHatapon;

		private static ConfigEntry<int>? diagnosticHits;

		private static Harmony? harmony;

		private static NativeCalculatorHook? calculatorHook;

		private static bool damageEntryObserved;

		private static bool nativeEntryObserved;

		private static readonly Dictionary<IntPtr, BattleContext> Battles = new Dictionary<IntPtr, BattleContext>();

		private static readonly HashSet<string> Errors = new HashSet<string>();

		public override void Load()
		{
			//IL_0059: Unknown result type (might be due to invalid IL or missing references)
			//IL_0063: Expected O, but got Unknown
			//IL_0096: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a0: Expected O, but got Unknown
			//IL_00e8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f2: Expected O, but got Unknown
			//IL_00fc: Unknown result type (might be due to invalid IL or missing references)
			//IL_0106: Expected O, but got Unknown
			logger = ((BasePlugin)this).Log;
			enabled = ((BasePlugin)this).Config.Bind<bool>("General", "Enabled", true, "Mejora la defensa de Patapon 1 durante Chaka Chaka Pata Pon.");
			normalMultiplier = ((BasePlugin)this).Config.Bind<float>("Balance", "NormalIncomingPowerMultiplier", 0.5f, new ConfigDescription("Multiplicador adicional de la potencia del golpe entrante al defender. 0.50 = mitad; 1 = sin refuerzo. Valor propio del mod, no una cifra verificada de PSP.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.05f, 1f), Array.Empty<object>()));
			chargedMultiplier = ((BasePlugin)this).Config.Bind<float>("Balance", "ChargedIncomingPowerMultiplier", 0.2f, new ConfigDescription("Multiplicador al defender con la carga de Pon Chaka reconocida por el juego. 0.20 = una quinta parte. No protege durante la cancion de carga por si sola.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.05f, 1f), Array.Empty<object>()));
			protectHatapon = ((BasePlugin)this).Config.Bind<bool>("Balance", "ProtectHatapon", true, "Aplica el refuerzo a Hatapon cuando su ejercito defiende.");
			diagnosticHits = ((BasePlugin)this).Config.Bind<int>("Diagnostics", "LoggedHitsPerState", 8, new ConfigDescription("Primeros impactos por estado (normal, defensa y defensa cargada) en cada batalla. 8 = hasta 24 lineas en total; 0 desactiva estos mensajes.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 50), Array.Empty<object>()));
			harmony = new Harmony("com.cpuffles.patapon1.defenseplus");
			damageEntryObserved = false;
			nativeEntryObserved = false;
			try
			{
				Patch(typeof(Game), "terminate", "BattleEnded", null);
				calculatorHook = new NativeCalculatorHook();
				calculatorHook.Install(CalculateNative);
				((BasePlugin)this).Log.LogInfo((object)("Defense Plus 0.1.4 cargado. Defensa normal x" + F(normalMultiplier.Value) + "; cargada x" + F(chargedMultiplier.Value) + ". Beta: mejora configurable, no replica exacta certificada de PSP."));
			}
			catch (Exception ex)
			{
				calculatorHook?.Dispose();
				calculatorHook = null;
				harmony.UnpatchSelf();
				Battles.Clear();
				((BasePlugin)this).Log.LogError((object)("Defense Plus se desactivo al no poder conectar con esta version: " + ex));
				return;
			}
			try
			{
				BossRushDefense.Start(((BasePlugin)this).Log, enabled, normalMultiplier, chargedMultiplier, protectHatapon, diagnosticHits);
			}
			catch (Exception ex2)
			{
				BossRushDefense.Stop();
				((BasePlugin)this).Log.LogError((object)("No se pudo activar Defense Plus en Boss Rush P1; la campana sigue activa: " + ex2));
			}
		}

		private static void Patch(Type type, string name, string? before, string? after)
		{
			//IL_0030: 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)
			MethodInfo methodInfo = AccessTools.DeclaredMethod(type, name, (Type[])null, (Type[])null) ?? throw new MissingMethodException(type.FullName, name);
			harmony.Patch((MethodBase)methodInfo, (before == null) ? ((HarmonyMethod)null) : new HarmonyMethod(typeof(Plugin), before, (Type[])null), (after == null) ? ((HarmonyMethod)null) : new HarmonyMethod(typeof(Plugin), after, (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
		}

		private static string F(float value)
		{
			return value.ToString("0.###", CultureInfo.InvariantCulture);
		}

		private static void BattleEnded(Game __instance)
		{
			Battles.Remove(((Il2CppObjectBase)__instance).Pointer);
		}

		private static BattleContext? GetBattle(Game game, bool fromImpact = false)
		{
			if (Battles.TryGetValue(((Il2CppObjectBase)game).Pointer, out BattleContext value))
			{
				if (value.Mapping.IsValid || !fromImpact || value.ReadAtImpact)
				{
					return value;
				}
				Battles.Remove(((Il2CppObjectBase)game).Pointer);
			}
			Director soundDirector_ = game.soundDirector_;
			ParamFileHolder val = ((soundDirector_ != null) ? soundDirector_.paramHolder_ : null);
			if (val == null)
			{
				return null;
			}
			uint cPECommandParamNum = val.getCPECommandParamNum();
			if (cPECommandParamNum == 0)
			{
				return null;
			}
			if (cPECommandParamNum > 256)
			{
				throw new InvalidOperationException("La tabla de canciones tiene un tamano inesperado.");
			}
			DefenseMapping defenseMapping = new DefenseMapping();
			List<string> list = new List<string>();
			for (uint num = 0u; num < cPECommandParamNum; num++)
			{
				CommandParam cPECommandParam = val.getCPECommandParam(num);
				Il2CppStructArray<short> val2 = ((cPECommandParam != null) ? cPECommandParam.key : null);
				if (cPECommandParam != null && val2 != null && ((Il2CppArrayBase<short>)(object)val2).Length <= 64)
				{
					short[] array = new short[((Il2CppArrayBase<short>)(object)val2).Length];
					for (int i = 0; i < array.Length; i++)
					{
						array[i] = ((Il2CppArrayBase<short>)(object)val2)[i];
					}
					defenseMapping.Observe(cPECommandParam.command, array);
					list.Add("id=" + cPECommandParam.id + ", cmd=" + cPECommandParam.command + ", keys=[" + string.Join(",", array) + "]");
				}
			}
			BattleContext battleContext = new BattleContext(game, defenseMapping, fromImpact);
			Battles[((Il2CppObjectBase)game).Pointer] = battleContext;
			if (defenseMapping.IsValid)
			{
				ManualLogSource? obj = logger;
				if (obj != null)
				{
					obj.LogInfo((object)("Chaka Chaka Pata Pon validado por la tabla nativa: familia=" + defenseMapping.Family.ToString() + ", coincidencias=" + defenseMapping.Matches + "."));
				}
			}
			else
			{
				ManualLogSource? obj2 = logger;
				if (obj2 != null)
				{
					obj2.LogWarning((object)"No se pudo identificar de forma inequivoca la cancion de defensa. Esta batalla conserva su dano original. Adjunta LogOutput.log.");
				}
				foreach (string item in list)
				{
					ManualLogSource? obj3 = logger;
					if (obj3 != null)
					{
						obj3.LogInfo((object)("Tabla de canciones: " + item));
					}
				}
			}
			return battleContext;
		}

		private static bool TryGetPlayer(GameStatus status, out Game? game, out UnitTroop? troop, out string unitName)
		{
			//IL_00d8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ee: Unknown result type (might be due to invalid IL or missing references)
			game = null;
			troop = null;
			unitName = "";
			ActorStatusObj obj = ((Il2CppObjectBase)status).TryCast<ActorStatusObj>();
			ActorObj val = ((obj != null) ? obj.pActorObj_ : null);
			if (val == null)
			{
				return false;
			}
			UnitBase val2 = ((Il2CppObjectBase)val).TryCast<UnitBase>();
			if (val2 != null)
			{
				UnitSquad pUnitSquad_ = val2.pUnitSquad_;
				troop = ((pUnitSquad_ != null) ? pUnitSquad_.pUnitTroop_ : null);
				game = ((GameActorBase)val2).pGame_;
				Info info_ = val2.info_;
				unitName = "unidad " + (((info_ != null) ? info_.uniqueId.ToString(CultureInfo.InvariantCulture) : null) ?? "?");
			}
			else
			{
				ConfigEntry<bool>? obj2 = protectHatapon;
				if (obj2 != null && obj2.Value)
				{
					FlagUnit val3 = ((Il2CppObjectBase)val).TryCast<FlagUnit>();
					if (val3 == null)
					{
						return false;
					}
					troop = val3.pUnitTroop_;
					game = val3.pGame_;
					unitName = "Hatapon";
				}
			}
			if (game != null)
			{
				UnitTroop? obj3 = troop;
				if (obj3 == null)
				{
					return false;
				}
				TroopInfo troopInfo_ = obj3.troopInfo_;
				return ((troopInfo_ != null) ? new TroopType?(troopInfo_.troopType) : ((TroopType?)null)) == (TroopType?)0;
			}
			return false;
		}

		private static void BeforeDamage(GameStatus __instance, ref HitInfo __0, out HitSnapshot? __state)
		{
			//IL_0054: Unknown result type (might be due to invalid IL or missing references)
			//IL_006f: Expected I4, but got Unknown
			//IL_010c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0113: Expected I4, but got Unknown
			//IL_0115: Unknown result type (might be due to invalid IL or missing references)
			//IL_011c: Expected I4, but got Unknown
			//IL_01ab: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b0: Unknown result type (might be due to invalid IL or missing references)
			__state = null;
			ConfigEntry<bool>? obj = enabled;
			if (obj != null && obj.Value && !damageEntryObserved)
			{
				damageEntryObserved = true;
				ManualLogSource? obj2 = logger;
				if (obj2 != null)
				{
					obj2.LogInfo((object)"Entrada al calculo de dano de P1 observada; se comprobaran el receptor y la cancion.");
				}
			}
			ConfigEntry<bool>? obj3 = enabled;
			if (obj3 == null || !obj3.Value || __0 == null || !DefensePolicy.IsDamageImpact((int)__0.hitType, __0.damageParam != null, __0.hitPower))
			{
				return;
			}
			try
			{
				if (!TryGetPlayer(__instance, out Game game, out UnitTroop troop, out string unitName) || game == null || troop == null)
				{
					return;
				}
				BattleContext battle = GetBattle(game, fromImpact: true);
				if (battle == null || !battle.Mapping.IsValid)
				{
					return;
				}
				if (!battle.HookObserved)
				{
					battle.HookObserved = true;
					ManualLogSource? obj4 = logger;
					if (obj4 != null)
					{
						obj4.LogInfo((object)"Calculo de dano de P1 observado para el ejercito del jugador.");
					}
				}
				InstructionParam instructionParam_ = troop.instructionParam_;
				CommandParam val = ((instructionParam_ != null) ? instructionParam_.commandParam_ : null);
				Director soundDirector_ = game.soundDirector_;
				BeatCommander val2 = ((soundDirector_ != null) ? soundDirector_.beatCommander_ : null);
				if (instructionParam_ == null || val == null || val2 == null)
				{
					return;
				}
				int command = (int)val.command;
				int lastAction = (int)instructionParam_.lastActionCmd_;
				bool failedRhythmMode_ = val2.failedRhythmMode_;
				DefenseMode defenseMode = DefensePolicy.Classify(command, lastAction, failedRhythmMode_, battle.Mapping.Family);
				float hitPower = __0.hitPower;
				float multiplier = DefensePolicy.Multiplier(defenseMode, normalMultiplier.Value, chargedMultiplier.Value);
				float scaled = hitPower;
				bool flag = DefensePolicy.TryScalePower(hitPower, multiplier, out scaled);
				bool flag2 = battle.LoggedHits[(int)defenseMode] < diagnosticHits.Value;
				object obj5;
				if (!(flag || flag2))
				{
					obj5 = null;
				}
				else
				{
					obj5 = new HitSnapshot
					{
						Battle = battle,
						Unit = unitName,
						HitType = __0.hitType,
						Command = command,
						LastAction = lastAction,
						Mode = defenseMode,
						OriginalPower = hitPower,
						AppliedPower = (flag ? scaled : hitPower)
					};
					object obj6 = obj5;
					Info info_ = __instance.info_;
					((HitSnapshot)obj6).HpBefore = ((info_ != null) ? info_.hitPoint : (-1));
					((HitSnapshot)obj5).ShouldLog = flag2;
					((HitSnapshot)obj5).RhythmFailed = failedRhythmMode_;
				}
				HitSnapshot hitSnapshot = (HitSnapshot)obj5;
				if (flag)
				{
					HitInfo val3 = CopyHit(__0, scaled);
					if (hitSnapshot != null)
					{
						hitSnapshot.Copy = val3;
					}
					__0 = val3;
				}
				__state = hitSnapshot;
			}
			catch (Exception ex)
			{
				Report("No se pudo preparar un impacto defensivo", ex);
			}
		}

		private static byte CalculateNative(IntPtr hitInfo, IntPtr hitResultRef, IntPtr damageParam, IntPtr gameStatus, IntPtr nbVecRef, float accuracy, byte isEnemy, byte isGimmick, IntPtr methodInfo)
		{
			//IL_0069: Unknown result type (might be due to invalid IL or missing references)
			//IL_006f: Expected O, but got Unknown
			//IL_0070: Unknown result type (might be due to invalid IL or missing references)
			//IL_0077: Expected O, but got Unknown
			//IL_0109: Unknown result type (might be due to invalid IL or missing references)
			//IL_0118: Expected O, but got Unknown
			NativeDamageCall call = new NativeDamageCall(hitInfo, hitResultRef, damageParam, gameStatus, nbVecRef, accuracy, isEnemy, isGimmick, methodInfo);
			GameStatus val = null;
			HitSnapshot __state = null;
			try
			{
				if (!nativeEntryObserved)
				{
					nativeEntryObserved = true;
					ManualLogSource? obj = logger;
					if (obj != null)
					{
						obj.LogInfo((object)"Calculador nativo de dano de P1 alcanzado.");
					}
				}
				ConfigEntry<bool>? obj2 = enabled;
				if (obj2 != null && obj2.Value && hitInfo != IntPtr.Zero && gameStatus != IntPtr.Zero)
				{
					val = new GameStatus(gameStatus);
					HitInfo __ = new HitInfo(hitInfo);
					BeforeDamage(val, ref __, out __state);
					call = call.WithHitInfo(((Il2CppObjectBase)__).Pointer);
				}
			}
			catch (Exception ex)
			{
				Report("No se pudo preparar el impacto nativo", ex);
			}
			byte b;
			try
			{
				b = calculatorHook.InvokeOriginal(call);
			}
			catch (Exception ex2)
			{
				Report("El calculo nativo lanzo una excepcion; no se repetira el impacto", ex2);
				GC.KeepAlive(__state?.Copy);
				return 0;
			}
			try
			{
				if (val != null && __state != null)
				{
					IntPtr intPtr = ((hitResultRef == IntPtr.Zero) ? IntPtr.Zero : Marshal.ReadIntPtr(hitResultRef));
					if (intPtr != IntPtr.Zero)
					{
						AfterDamage(val, new HitResult(intPtr), b != 0, __state);
					}
				}
			}
			catch (Exception ex3)
			{
				Report("No se pudo observar el resultado nativo", ex3);
			}
			finally
			{
				GC.KeepAlive(__state?.Copy);
			}
			return b;
		}

		private static HitInfo CopyHit(HitInfo source, float power)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0005: 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)
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			//IL_001d: 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_0030: Unknown result type (might be due to invalid IL or missing references)
			//IL_003c: Unknown result type (might be due to invalid IL or missing references)
			//IL_003e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0048: 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_0054: 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_0062: 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_006e: 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_0091: Expected O, but got Unknown
			return new HitInfo
			{
				isHit = source.isHit,
				hitType = source.hitType,
				hitPower = power,
				hitAttribute = source.hitAttribute,
				hitUniqueId = source.hitUniqueId,
				hitCategory = source.hitCategory,
				hitPos = source.hitPos,
				pParent = source.pParent,
				pPos = source.pPos,
				pVec = source.pVec,
				damageParam = source.damageParam,
				accuracyRatio = source.accuracyRatio
			};
		}

		private static void AfterDamage(GameStatus __instance, HitResult __1, bool __result, HitSnapshot? __state)
		{
			if (__state == null)
			{
				return;
			}
			try
			{
				if (__state.ShouldLog)
				{
					__state.Battle.LoggedHits[(int)__state.Mode]++;
					ManualLogSource? obj = logger;
					if (obj != null)
					{
						string[] obj2 = new string[27]
						{
							"Impacto: ",
							__state.Unit,
							", tipo=",
							((object)Unsafe.As<HitType, HitType>(ref __state.HitType)/*cast due to .constrained prefix*/).ToString(),
							", defensa=",
							__state.Mode.ToString(),
							", cmd=",
							__state.Command.ToString(),
							", ultima=",
							__state.LastAction.ToString(),
							", ritmoFallado=",
							__state.RhythmFailed.ToString(),
							", potencia=",
							F(__state.OriginalPower),
							"->",
							F(__state.AppliedPower),
							", potenciaTrasCalculo=",
							(__state.Copy == null) ? "sin copia" : F(__state.Copy.hitPower),
							", dano=",
							(__1 == null) ? "?" : __1.damage.ToString(CultureInfo.InvariantCulture),
							", HP=",
							__state.HpBefore.ToString(),
							"->",
							null,
							null,
							null,
							null
						};
						Info info_ = __instance.info_;
						obj2[23] = ((info_ != null) ? new int?(info_.hitPoint) : ((int?)null)).ToString();
						obj2[24] = ", resultado=";
						obj2[25] = __result.ToString();
						obj2[26] = ".";
						obj.LogInfo((object)string.Concat(obj2));
					}
				}
			}
			catch (Exception ex)
			{
				Report("No se pudo registrar un impacto", ex);
			}
			finally
			{
				GC.KeepAlive(__state.Copy);
			}
		}

		private static void Report(string message, Exception ex)
		{
			string text = message + ": " + ex.GetType().Name + ": " + ex.Message;
			if (Errors.Count < 16 && Errors.Add(text))
			{
				ManualLogSource? obj = logger;
				if (obj != null)
				{
					obj.LogWarning((object)text);
				}
			}
		}

		public override bool Unload()
		{
			BossRushDefense.Stop();
			calculatorHook?.Dispose();
			calculatorHook = null;
			Harmony? obj = harmony;
			if (obj != null)
			{
				obj.UnpatchSelf();
			}
			Battles.Clear();
			Errors.Clear();
			return true;
		}
	}
}