Decompiled source of MonsterFallDamage v1.1.1

plugins/MonsterFallDamagePlugin/MonsterFallDamagePlugin.dll

Decompiled 2 months ago
using System;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: TargetFramework(".NETFramework,Version=v4.7.2", FrameworkDisplayName = ".NET Framework 4.7.2")]
[assembly: AssemblyCompany("MonsterFallDamagePlugin")]
[assembly: AssemblyConfiguration("Debug")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0")]
[assembly: AssemblyProduct("MonsterFallDamagePlugin")]
[assembly: AssemblyTitle("MonsterFallDamagePlugin")]
[assembly: AssemblyVersion("1.0.0.0")]
namespace MonsterFallDamagePlugin;

[BepInPlugin("com.mods.monsterfallDamage", "MonsterFallDamage", "1.1.1")]
[BepInProcess("valheim.exe")]
public class Plugin : BaseUnityPlugin
{
	public const string GUID = "com.mods.monsterfallDamage";

	public const string NAME = "MonsterFallDamage";

	public const string VERSION = "1.1.1";

	internal static ManualLogSource Log;

	private readonly Harmony _harmony = new Harmony("com.mods.monsterfallDamage");

	internal static ConfigEntry<bool> ApplyToPlayer;

	internal static ConfigEntry<float> MinFallHeight;

	internal static ConfigEntry<float> DamageDistance;

	internal static ConfigEntry<float> DamagePerUnit;

	internal static ConfigEntry<float> MaxDamage;

	internal static ConfigEntry<bool> IgnoreJumpAscent;

	internal static ConfigEntry<bool> IgnoreFlyingLandings;

	internal static ConfigEntry<float> FlyingLandingGraceSeconds;

	internal static ConfigEntry<bool> EnableDebugLog;

	internal static ConfigEntry<KeyboardShortcut> DebugLogToggleKey;

	internal static ConfigEntry<string> ExemptPrefabPrefixes;

	private void Awake()
	{
		//IL_005a: Unknown result type (might be due to invalid IL or missing references)
		//IL_0064: Expected O, but got Unknown
		//IL_0097: Unknown result type (might be due to invalid IL or missing references)
		//IL_00a1: Expected O, but got Unknown
		//IL_00d4: Unknown result type (might be due to invalid IL or missing references)
		//IL_00de: Expected O, but got Unknown
		//IL_0111: Unknown result type (might be due to invalid IL or missing references)
		//IL_011b: Expected O, but got Unknown
		//IL_018e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0198: Expected O, but got Unknown
		//IL_01e0: Unknown result type (might be due to invalid IL or missing references)
		Log = ((BaseUnityPlugin)this).Logger;
		ApplyToPlayer = ((BaseUnityPlugin)this).Config.Bind<bool>("Fall Damage", "Apply To Player", true, "If true, the same fall damage formula is applied to the player (overrides Valheim default).");
		MinFallHeight = ((BaseUnityPlugin)this).Config.Bind<float>("Fall Damage", "Min Fall Height (m)", 4f, new ConfigDescription("Falls below this height deal no damage. (Player default: 4)", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 20f), Array.Empty<object>()));
		DamageDistance = ((BaseUnityPlugin)this).Config.Bind<float>("Fall Damage", "Damage Interval (m)", 16f, new ConfigDescription("Damage is added for every X meters fallen above the minimum height. (Player default: 16)", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.5f, 100f), Array.Empty<object>()));
		DamagePerUnit = ((BaseUnityPlugin)this).Config.Bind<float>("Fall Damage", "Damage Per Interval", 100f, new ConfigDescription("Damage dealt per interval distance. (Player default: 100)", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 100f), Array.Empty<object>()));
		MaxDamage = ((BaseUnityPlugin)this).Config.Bind<float>("Fall Damage", "Max Damage (0 for unlimited)", 100f, new ConfigDescription("Maximum fall damage cap. Set to 0 for no limit. (Player default: 100)", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 99999f), Array.Empty<object>()));
		IgnoreJumpAscent = ((BaseUnityPlugin)this).Config.Bind<bool>("Fall Exemption", "IgnoreJumpAscent", true, "Height gained by a creature's own jump is not counted toward fall damage (hopping on flat ground deals no damage; jumping off a cliff only counts the drop below the take-off point).");
		IgnoreFlyingLandings = ((BaseUnityPlugin)this).Config.Bind<bool>("Fall Exemption", "IgnoreFlyingLandings", true, "While flying, the altitude baseline is reset every frame, and no fall damage is applied for a short grace period after landing.");
		FlyingLandingGraceSeconds = ((BaseUnityPlugin)this).Config.Bind<float>("Fall Exemption", "FlyingLandingGraceSeconds", 3f, new ConfigDescription("Grace period (seconds) after a flying creature lands during which fall damage is not applied.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 30f), Array.Empty<object>()));
		EnableDebugLog = ((BaseUnityPlugin)this).Config.Bind<bool>("Debug", "EnableDebugLog", false, "Logs verification details on each landing (prefab name, heights, exemption reason, etc). Can be left off once verified.");
		DebugLogToggleKey = ((BaseUnityPlugin)this).Config.Bind<KeyboardShortcut>("Debug", "Debug Log Toggle Key", new KeyboardShortcut((KeyCode)289, (KeyCode[])(object)new KeyCode[1] { (KeyCode)308 }), "In-game shortcut that turns EnableDebugLog on/off without restarting the game.");
		ExemptPrefabPrefixes = ((BaseUnityPlugin)this).Config.Bind<string>("Fall Exemption", "ExemptPrefabPrefixes", "Blob", "Creatures whose prefab name (after stripping \"(Clone)\", case-insensitive) starts with one of these comma-separated prefixes are fully immune to fall damage (other damage is unaffected). The default \"Blob\" covers all slime variants (Blob/BlobElite/BlobAspect/BlobLava/BlobTar/ BlobMork/BlobMorkMini/BlobFrost, etc).");
		_harmony.PatchAll();
		((BaseUnityPlugin)this).Logger.LogInfo((object)"MonsterFallDamage 1.1.1 loaded.");
	}

	private void OnDestroy()
	{
		_harmony.UnpatchSelf();
	}

	private void Update()
	{
		//IL_0006: 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)
		KeyboardShortcut value = DebugLogToggleKey.Value;
		if (((KeyboardShortcut)(ref value)).IsDown() && !IsBlockingInputActive())
		{
			bool flag = !EnableDebugLog.Value;
			EnableDebugLog.Value = flag;
			string text = (flag ? "ON" : "OFF");
			((BaseUnityPlugin)this).Logger.LogInfo((object)("===== MonsterFallDamage debug log " + text + " (v1.1.1) ====="));
			if (flag)
			{
				LogAllConfigValues();
			}
			DebugMessageHelper.ShowScreenMessage("MonsterFallDamage log: " + text);
		}
	}

	private static bool IsBlockingInputActive()
	{
		try
		{
			if (Console.IsVisible())
			{
				return true;
			}
			if ((Object)(object)Chat.instance != (Object)null && Chat.instance.HasFocus())
			{
				return true;
			}
			if (Menu.IsVisible())
			{
				return true;
			}
		}
		catch (Exception ex)
		{
			Log.LogWarning((object)("[MonsterFallDamage] 입력 차단 상태 확인 실패(토글은 계속 동작): " + ex.Message));
		}
		return false;
	}

	private void LogAllConfigValues()
	{
		//IL_00f0: Unknown result type (might be due to invalid IL or missing references)
		((BaseUnityPlugin)this).Logger.LogInfo((object)($"[MonsterFallDamage:설정값] ApplyToPlayer={ApplyToPlayer.Value}, " + $"MinFallHeight={MinFallHeight.Value}, DamageDistance={DamageDistance.Value}, " + $"DamagePerUnit={DamagePerUnit.Value}, MaxDamage={MaxDamage.Value}, " + $"IgnoreJumpAscent={IgnoreJumpAscent.Value}, IgnoreFlyingLandings={IgnoreFlyingLandings.Value}, " + $"FlyingLandingGraceSeconds={FlyingLandingGraceSeconds.Value}, " + "ExemptPrefabPrefixes=" + ExemptPrefabPrefixes.Value + ", " + $"DebugLogToggleKey={DebugLogToggleKey.Value}"));
	}
}
internal static class DebugMessageHelper
{
	private static MethodInfo s_messageMethod;

	private static object s_messageTypeValue;

	private static bool s_setupAttempted;

	internal static void ShowScreenMessage(string text)
	{
		EnsureSetup();
		if (s_messageMethod == null)
		{
			return;
		}
		Player localPlayer = Player.m_localPlayer;
		if ((Object)(object)localPlayer == (Object)null)
		{
			return;
		}
		try
		{
			s_messageMethod.Invoke(localPlayer, new object[4] { s_messageTypeValue, text, 0, null });
		}
		catch (Exception ex)
		{
			Plugin.Log.LogWarning((object)("[MonsterFallDamage] 화면 메시지 표시 실패(기능에는 영향 없음): " + ex.Message));
		}
	}

	private static void EnsureSetup()
	{
		if (s_setupAttempted)
		{
			return;
		}
		s_setupAttempted = true;
		try
		{
			MethodInfo methodInfo = AccessTools.Method(typeof(Player), "Message", (Type[])null, (Type[])null);
			if (methodInfo == null)
			{
				Plugin.Log.LogWarning((object)"[MonsterFallDamage] Player.Message 메서드를 찾지 못해 화면 메시지를 표시할 수 없습니다 (로그 기록 자체는 정상 동작).");
				return;
			}
			ParameterInfo[] parameters = methodInfo.GetParameters();
			if (parameters.Length == 0)
			{
				Plugin.Log.LogWarning((object)"[MonsterFallDamage] Player.Message 시그니처가 예상과 달라 화면 메시지를 표시할 수 없습니다.");
				return;
			}
			s_messageTypeValue = Enum.Parse(parameters[0].ParameterType, "TopLeft");
			s_messageMethod = methodInfo;
		}
		catch (Exception ex)
		{
			Plugin.Log.LogWarning((object)("[MonsterFallDamage] 화면 메시지 설정 실패(기능에는 영향 없음): " + ex.Message));
		}
	}
}
internal static class FallExemptionState
{
	internal sealed class State
	{
		public float? JumpStartY;

		public float JumpRecordedAt = -1f;

		public float FlyingGraceUntil = -1f;

		public bool WasAirborne;

		public bool? IsFallDamageExempt;
	}

	private static readonly ConditionalWeakTable<Character, State> _table = new ConditionalWeakTable<Character, State>();

	public static State Get(Character c)
	{
		return _table.GetOrCreateValue(c);
	}
}
internal static class DebugLogger
{
	internal static void Log(string msg)
	{
		if (Plugin.EnableDebugLog.Value)
		{
			Plugin.Log.LogInfo((object)msg);
		}
	}
}
[HarmonyPatch(typeof(Character), "Jump")]
public static class Patch_RecordJumpStart
{
	public static void Postfix(Character __instance)
	{
		//IL_0021: Unknown result type (might be due to invalid IL or missing references)
		//IL_0049: Unknown result type (might be due to invalid IL or missing references)
		if (Plugin.IgnoreJumpAscent.Value)
		{
			FallExemptionState.State state = FallExemptionState.Get(__instance);
			float y = ((Component)__instance).transform.position.y;
			state.JumpStartY = y;
			state.JumpRecordedAt = Time.time;
			DebugLogger.Log($"[MonsterFallDamage:점프기록] id={__instance.GetZDOID()} {((Object)((Component)__instance).gameObject).name} | " + $"시작높이={y:F2}");
		}
	}
}
[HarmonyPatch(typeof(Character), "UpdateFlying")]
public static class Patch_FlyingBaselineReset
{
	private static readonly FieldInfo f_maxAirAltitude = AccessTools.Field(typeof(Character), "m_maxAirAltitude");

	public static void Postfix(Character __instance)
	{
		//IL_0020: Unknown result type (might be due to invalid IL or missing references)
		if (Plugin.IgnoreFlyingLandings.Value)
		{
			f_maxAirAltitude.SetValue(__instance, ((Component)__instance).transform.position.y);
		}
	}
}
[HarmonyPatch(typeof(Character), "Land")]
public static class Patch_FlyingLandGrace
{
	public static void Postfix(Character __instance)
	{
		if (Plugin.IgnoreFlyingLandings.Value)
		{
			FallExemptionState.State state = FallExemptionState.Get(__instance);
			state.FlyingGraceUntil = Time.time + Plugin.FlyingLandingGraceSeconds.Value;
		}
	}
}
[HarmonyPatch(typeof(Character), "UpdateGroundContact")]
public static class Patch_MonsterFallDamage
{
	private const float JumpRecordExpirySeconds = 0.5f;

	private static readonly FieldInfo f_groundContact = AccessTools.Field(typeof(Character), "m_groundContact");

	private static readonly FieldInfo f_maxAirAltitude = AccessTools.Field(typeof(Character), "m_maxAirAltitude");

	private static readonly FieldInfo f_groundContactPoint = AccessTools.Field(typeof(Character), "m_groundContactPoint");

	private static readonly FieldInfo f_groundContactNormal = AccessTools.Field(typeof(Character), "m_groundContactNormal");

	public static void Prefix(Character __instance)
	{
		//IL_0109: Unknown result type (might be due to invalid IL or missing references)
		//IL_0116: Unknown result type (might be due to invalid IL or missing references)
		//IL_011b: Unknown result type (might be due to invalid IL or missing references)
		//IL_00b2: Unknown result type (might be due to invalid IL or missing references)
		//IL_0420: Unknown result type (might be due to invalid IL or missing references)
		//IL_0425: Unknown result type (might be due to invalid IL or missing references)
		//IL_0432: Unknown result type (might be due to invalid IL or missing references)
		//IL_0437: Unknown result type (might be due to invalid IL or missing references)
		//IL_0439: Unknown result type (might be due to invalid IL or missing references)
		//IL_0440: Expected O, but got Unknown
		//IL_0450: Unknown result type (might be due to invalid IL or missing references)
		//IL_0452: Unknown result type (might be due to invalid IL or missing references)
		//IL_0459: Unknown result type (might be due to invalid IL or missing references)
		//IL_045b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0463: Unknown result type (might be due to invalid IL or missing references)
		if (__instance.IsDead())
		{
			return;
		}
		bool flag = __instance.IsPlayer();
		if (flag && !Plugin.ApplyToPlayer.Value)
		{
			return;
		}
		FallExemptionState.State state = FallExemptionState.Get(__instance);
		if (!(bool)f_groundContact.GetValue(__instance))
		{
			state.WasAirborne = true;
			return;
		}
		bool wasAirborne = state.WasAirborne;
		state.WasAirborne = false;
		if (!wasAirborne)
		{
			if (state.JumpStartY.HasValue && Time.time - state.JumpRecordedAt > 0.5f)
			{
				DebugLogger.Log($"[MonsterFallDamage:점프기록만료] id={__instance.GetZDOID()} {((Object)((Component)__instance).gameObject).name} | " + $"시작높이={state.JumpStartY.Value:F2}");
				state.JumpStartY = null;
			}
			return;
		}
		float y = ((Component)__instance).transform.position.y;
		string arg = ((object)__instance.GetZDOID()/*cast due to .constrained prefix*/).ToString();
		string name = ((Object)((Component)__instance).gameObject).name;
		bool flag2 = __instance.IsFlying();
		float num = (float)f_maxAirAltitude.GetValue(__instance);
		float num2 = num;
		if (Plugin.IgnoreJumpAscent.Value && state.JumpStartY.HasValue)
		{
			num2 = Mathf.Min(num2, state.JumpStartY.Value);
		}
		float num3 = Mathf.Max(0f, num2 - y);
		if (!state.IsFallDamageExempt.HasValue)
		{
			state.IsFallDamageExempt = IsExemptPrefab(name);
		}
		if (state.IsFallDamageExempt.Value)
		{
			DebugLogger.Log($"[MonsterFallDamage:착지] id={arg} {name} | 최고높이={num:F2} " + $"기준점(점프반영)={num2:F2} 착지높이={y:F2} 낙하높이={num3:F2} " + $"비행={flag2} 적용데미지=0 제외사유=슬라임류면제");
			state.JumpStartY = null;
			return;
		}
		if (Plugin.IgnoreFlyingLandings.Value && Time.time < state.FlyingGraceUntil)
		{
			if (flag)
			{
				f_maxAirAltitude.SetValue(__instance, y);
			}
			DebugLogger.Log($"[MonsterFallDamage:착지] id={arg} {name} | 최고높이={num:F2} " + $"기준점(점프반영)={num2:F2} 착지높이={y:F2} 낙하높이={num3:F2} " + $"비행={flag2} 적용데미지=0 제외사유=비행착지유예");
			state.JumpStartY = null;
			return;
		}
		state.JumpStartY = null;
		float value = Plugin.MinFallHeight.Value;
		if (num3 <= value)
		{
			DebugLogger.Log($"[MonsterFallDamage:착지] id={arg} {name} | 최고높이={num:F2} " + $"기준점(점프반영)={num2:F2} 착지높이={y:F2} 낙하높이={num3:F2} " + $"비행={flag2} 적용데미지=0 제외사유=최소높이미만");
			return;
		}
		float num4 = (num3 - value) / Plugin.DamageDistance.Value * Plugin.DamagePerUnit.Value;
		float value2 = Plugin.MaxDamage.Value;
		if (value2 > 0f)
		{
			num4 = Mathf.Min(num4, value2);
		}
		if (num4 <= 0f)
		{
			DebugLogger.Log($"[MonsterFallDamage:착지] id={arg} {name} | 최고높이={num:F2} " + $"기준점(점프반영)={num2:F2} 착지높이={y:F2} 낙하높이={num3:F2} " + $"비행={flag2} 적용데미지=0 제외사유=데미지설정값0");
			return;
		}
		if (flag)
		{
			f_maxAirAltitude.SetValue(__instance, y);
		}
		Vector3 point = (Vector3)f_groundContactPoint.GetValue(__instance);
		Vector3 dir = (Vector3)f_groundContactNormal.GetValue(__instance);
		HitData val = new HitData();
		val.m_damage.m_damage = num4;
		val.m_point = point;
		val.m_dir = dir;
		val.m_hitType = (HitType)3;
		__instance.Damage(val);
		DebugLogger.Log($"[MonsterFallDamage:착지] id={arg} {name} | 최고높이={num:F2} " + $"기준점(점프반영)={num2:F2} 착지높이={y:F2} 낙하높이={num3:F2} " + $"비행={flag2} 적용데미지={num4:F1} 제외사유=없음");
	}

	private static bool IsExemptPrefab(string gameObjectName)
	{
		string text = (gameObjectName.EndsWith("(Clone)") ? gameObjectName.Substring(0, gameObjectName.Length - "(Clone)".Length) : gameObjectName);
		string[] array = Plugin.ExemptPrefabPrefixes.Value.Split(new char[1] { ',' });
		string[] array2 = array;
		foreach (string text2 in array2)
		{
			string text3 = text2.Trim();
			if (text3.Length != 0 && text.StartsWith(text3, StringComparison.OrdinalIgnoreCase))
			{
				return true;
			}
		}
		return false;
	}
}