Decompiled source of GrudgeLog v0.2.0

GrudgeLog.dll

Decompiled an hour ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Text;
using System.Text.RegularExpressions;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using UnityEngine;
using UnityEngine.SceneManagement;

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

[Serializable]
public class DeathEntry
{
	public string cause;

	public float height;

	public float runSeconds;

	public string perk;

	public string timestamp;
}
[Serializable]
public class DeathLog
{
	public List<DeathEntry> entries = new List<DeathEntry>();
}
[BepInPlugin("local.grudgelog", "Grudge Log", "0.3.0")]
public class GrudgeLogMod : BaseUnityPlugin
{
	internal static ManualLogSource Log;

	private static ConfigEntry<string> PlayerTypeName;

	private static ConfigEntry<string> DeathMethodNames;

	private static ConfigEntry<string> PerkFieldName;

	private static ConfigEntry<string> HeightMemberName;

	private static ConfigEntry<KeyCode> ToggleKey;

	private bool showMenu;

	private string statsText = "";

	private Rect windowRect = new Rect(20f, 20f, 460f, 10f);

	private static bool statsDirty;

	private static DeathLog deathLog = new DeathLog();

	private static string logPath;

	private static float runStart;

	private static float lastDeathTime = -100f;

	private const BindingFlags All = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;

	private const BindingFlags AnyMember = BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic;

	private static MemberInfo heightMember;

	private static bool heightResolved;

	private void Awake()
	{
		Init();
	}

	private void Init()
	{
		Log = ((BaseUnityPlugin)this).Logger;
		PlayerTypeName = ((BaseUnityPlugin)this).Config.Bind<string>("Target", "PlayerTypeName", "ENT_Player", "Имя класса игрока (из лога/dnSpy). Это ПРЕДПОЛОЖЕНИЕ, проверьте.");
		DeathMethodNames = ((BaseUnityPlugin)this).Config.Bind<string>("Target", "DeathMethodNames", "Kill,Die,OnDeath", "Методы, вызываемые при смерти (через запятую). Патчатся только существующие.");
		PerkFieldName = ((BaseUnityPlugin)this).Config.Bind<string>("Target", "PerkFieldName", "", "Поле игрока со списком перков. Пусто = перк будет 'unknown'.");
		HeightMemberName = ((BaseUnityPlugin)this).Config.Bind<string>("Target", "HeightMember", "", "Откуда брать высоту, формат Тип.Член (например CL_GameManager.GetPlayerCorrectedHeight). Пусто = автопоиск, а если не нашли - координата Y.");
		ToggleKey = ((BaseUnityPlugin)this).Config.Bind<KeyCode>("Menu", "ToggleKey", (KeyCode)289, "Кнопка открытия/закрытия меню статистики");
		string text = Path.Combine(Paths.ConfigPath, "GrudgeLog");
		Directory.CreateDirectory(text);
		logPath = Path.Combine(text, "deaths.json");
		LoadLog();
		runStart = Time.realtimeSinceStartup;
		SceneManager.sceneLoaded += delegate
		{
			runStart = Time.realtimeSinceStartup;
		};
		PatchDeathMethods();
	}

	private void PatchDeathMethods()
	{
		//IL_00b2: Unknown result type (might be due to invalid IL or missing references)
		//IL_00b8: Expected O, but got Unknown
		//IL_015e: Unknown result type (might be due to invalid IL or missing references)
		//IL_016c: Expected O, but got Unknown
		Type type = FindType(PlayerTypeName.Value);
		if (type == null)
		{
			Log.LogWarning((object)("Класс '" + PlayerTypeName.Value + "' не найден. Похожие типы:"));
			{
				foreach (Type item in from t in AllTypes()
					where Regex.IsMatch(t.Name, "player", RegexOptions.IgnoreCase)
					select t)
				{
					Log.LogWarning((object)("   " + item.FullName));
				}
				return;
			}
		}
		Harmony val = new Harmony("local.grudgelog");
		string[] source = (from s in DeathMethodNames.Value.Split(new char[1] { ',' })
			select s.Trim() into s
			where s.Length > 0
			select s).ToArray();
		int num = 0;
		MethodInfo[] methods = type.GetMethods(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
		foreach (MethodInfo methodInfo in methods)
		{
			if (source.Contains(methodInfo.Name))
			{
				try
				{
					val.Patch((MethodBase)methodInfo, new HarmonyMethod(typeof(GrudgeLogMod), "DeathPrefix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
					num++;
					Log.LogInfo((object)("Перехват: " + type.Name + "." + methodInfo.Name));
				}
				catch (Exception ex)
				{
					Log.LogWarning((object)("Не удалось пропатчить " + methodInfo.Name + ": " + ex.Message));
				}
			}
		}
		if (num != 0)
		{
			return;
		}
		Log.LogWarning((object)("В " + type.Name + " нет методов " + DeathMethodNames.Value + ". Кандидаты:"));
		foreach (MethodInfo item2 in from m in type.GetMethods(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)
			where Regex.IsMatch(m.Name, "kill|die|death|dead", RegexOptions.IgnoreCase)
			select m)
		{
			Log.LogWarning((object)("   " + item2.Name));
		}
	}

	private static void DeathPrefix(object __instance, object[] __args, MethodBase __originalMethod)
	{
		try
		{
			OnDeath(__instance, __args, __originalMethod.Name);
		}
		catch (Exception ex)
		{
			Log.LogWarning((object)("OnDeath: " + ex.Message));
		}
	}

	private static void OnDeath(object player, object[] args, string methodName)
	{
		if (!(Time.realtimeSinceStartup - lastDeathTime < 2f))
		{
			lastDeathTime = Time.realtimeSinceStartup;
			DeathEntry deathEntry = new DeathEntry
			{
				cause = GetCause(args, methodName),
				height = GetHeight(player),
				runSeconds = Time.realtimeSinceStartup - runStart,
				perk = GetPerk(player),
				timestamp = DateTime.Now.ToString("s")
			};
			deathLog.entries.Add(deathEntry);
			SaveLog();
			statsDirty = true;
			Log.LogInfo((object)GenerateSummary(deathEntry));
		}
	}

	private static void SaveLog()
	{
		try
		{
			File.WriteAllText(logPath, JsonUtility.ToJson((object)deathLog, true));
		}
		catch (Exception ex)
		{
			Log.LogWarning((object)("SaveLog: " + ex.Message));
		}
	}

	private static void LoadLog()
	{
		try
		{
			if (File.Exists(logPath))
			{
				deathLog = JsonUtility.FromJson<DeathLog>(File.ReadAllText(logPath)) ?? new DeathLog();
			}
		}
		catch (Exception ex)
		{
			Log.LogWarning((object)("LoadLog: " + ex.Message));
			deathLog = new DeathLog();
		}
	}

	private static string GenerateSummary(DeathEntry e)
	{
		string today = DateTime.Now.ToString("yyyy-MM-dd");
		int num = deathLog.entries.Count((DeathEntry x) => x.cause == e.cause && x.timestamp.StartsWith(today));
		return string.Format(CultureInfo.InvariantCulture, "You died from {0} at height {1:0.#}. This is death #{2} from this cause today.", e.cause, e.height, num);
	}

	private void OnGUI()
	{
		//IL_000a: Unknown result type (might be due to invalid IL or missing references)
		//IL_0010: Invalid comparison between Unknown and I4
		//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_006f: Unknown result type (might be due to invalid IL or missing references)
		//IL_007b: Unknown result type (might be due to invalid IL or missing references)
		//IL_008a: Unknown result type (might be due to invalid IL or missing references)
		//IL_008f: Unknown result type (might be due to invalid IL or missing references)
		//IL_00bf: Expected O, but got Unknown
		//IL_00ba: Unknown result type (might be due to invalid IL or missing references)
		//IL_00bf: Unknown result type (might be due to invalid IL or missing references)
		Event current = Event.current;
		if (current != null && (int)current.type == 4 && current.keyCode == ToggleKey.Value)
		{
			showMenu = !showMenu;
			if (showMenu)
			{
				statsDirty = true;
			}
			current.Use();
		}
		if (showMenu)
		{
			if (statsDirty)
			{
				statsText = BuildStats();
				statsDirty = false;
			}
			windowRect = GUILayout.Window(1728, windowRect, new WindowFunction(DrawWindow), "Grudge Log  (" + ((object)ToggleKey.Value/*cast due to .constrained prefix*/).ToString() + " - close)", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(460f) });
		}
	}

	private void DrawWindow(int id)
	{
		GUILayout.Label(statsText, Array.Empty<GUILayoutOption>());
		if (GUILayout.Button("Refresh", Array.Empty<GUILayoutOption>()))
		{
			statsDirty = true;
		}
		GUI.DragWindow();
	}

	private static string BuildStats()
	{
		List<DeathEntry> entries = deathLog.entries;
		if (entries.Count == 0)
		{
			return "No deaths yet. Go get that first one!";
		}
		string today = DateTime.Now.ToString("yyyy-MM-dd");
		List<DeathEntry> list = entries.Where((DeathEntry x) => x.timestamp != null && x.timestamp.StartsWith(today)).ToList();
		List<float> list2 = (from x in entries
			where !float.IsNaN(x.height)
			select x.height).ToList();
		StringBuilder stringBuilder = new StringBuilder();
		stringBuilder.AppendLine("Total deaths: " + entries.Count + "     Today: " + list.Count);
		if (list2.Count > 0)
		{
			stringBuilder.AppendLine("Best height: " + list2.Max().ToString("0.#") + "     Average: " + list2.Average().ToString("0.#"));
		}
		stringBuilder.AppendLine();
		stringBuilder.AppendLine("Today's causes:");
		foreach (IGrouping<string, DeathEntry> item in (from x in list
			group x by x.cause into g
			orderby g.Count() descending
			select g).Take(5))
		{
			stringBuilder.AppendLine("   " + item.Key + " - " + item.Count());
		}
		stringBuilder.AppendLine();
		stringBuilder.AppendLine("Latest deaths (time, cause, height, run time, perk):");
		foreach (DeathEntry item2 in entries.Skip(Math.Max(0, entries.Count - 5)).Reverse())
		{
			TimeSpan timeSpan = TimeSpan.FromSeconds(item2.runSeconds);
			string text = ((item2.timestamp != null && item2.timestamp.Length >= 16) ? item2.timestamp.Substring(11, 5) : "--:--");
			stringBuilder.AppendLine("   " + text + "  " + item2.cause + "  " + item2.height.ToString("0.#") + "  " + (int)timeSpan.TotalMinutes + ":" + timeSpan.Seconds.ToString("00") + ((string.IsNullOrEmpty(item2.perk) || item2.perk == "unknown") ? "" : ("  [" + item2.perk + "]")));
		}
		return stringBuilder.ToString();
	}

	private static string GetCause(object[] args, string methodName)
	{
		if (args != null)
		{
			foreach (object obj in args)
			{
				if (obj is string { Length: >0 } text)
				{
					return text;
				}
				if (obj != null && obj.GetType().IsEnum)
				{
					return obj.ToString();
				}
			}
		}
		return methodName;
	}

	private static float GetHeight(object player)
	{
		//IL_0047: Unknown result type (might be due to invalid IL or missing references)
		if (!heightResolved)
		{
			ResolveHeight(player);
		}
		if (heightMember != null && TryRead(heightMember, player, out var v))
		{
			return v;
		}
		Component val = (Component)((player is Component) ? player : null);
		if (!((Object)(object)val != (Object)null))
		{
			return float.NaN;
		}
		return val.transform.position.y;
	}

	private static void ResolveHeight(object player)
	{
		heightResolved = true;
		try
		{
			List<Type> list = new Type[2]
			{
				FindType("CL_GameManager"),
				player?.GetType()
			}.Where((Type t) => t != null).Distinct().ToList();
			string value = HeightMemberName.Value;
			if (!string.IsNullOrEmpty(value) && value.Contains("."))
			{
				string name = value.Substring(0, value.LastIndexOf('.'));
				string mn = value.Substring(value.LastIndexOf('.') + 1);
				Type type = FindType(name);
				if (type != null)
				{
					heightMember = type.GetMembers(BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic).FirstOrDefault((MemberInfo m) => m.Name == mn);
				}
				Log.LogInfo((object)((heightMember != null) ? ("Источник высоты (из конфига): " + value) : ("Член из конфига не найден: " + value)));
			}
			foreach (Type item in list)
			{
				MemberInfo[] members = item.GetMembers(BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
				foreach (MemberInfo memberInfo in members)
				{
					if ((memberInfo.MemberType == MemberTypes.Method || memberInfo.MemberType == MemberTypes.Property || memberInfo.MemberType == MemberTypes.Field) && Regex.IsMatch(memberInfo.Name, "height|altitude", RegexOptions.IgnoreCase))
					{
						float v;
						bool flag = TryRead(memberInfo, player, out v);
						Log.LogInfo((object)("[height] " + item.Name + "." + memberInfo.Name + " (" + memberInfo.MemberType.ToString() + ") = " + (flag ? v.ToString() : "n/a")));
						if (heightMember == null && flag && Regex.IsMatch(memberInfo.Name, "player|correct", RegexOptions.IgnoreCase))
						{
							heightMember = memberInfo;
						}
					}
				}
			}
			Log.LogInfo((object)((heightMember != null) ? ("Источник высоты: " + heightMember.ReflectedType.Name + "." + heightMember.Name) : "Источник высоты не найден, используем координату Y"));
		}
		catch (Exception ex)
		{
			Log.LogWarning((object)("ResolveHeight: " + ex.Message));
		}
	}

	private static bool TryRead(MemberInfo m, object player, out float v)
	{
		v = 0f;
		try
		{
			FieldInfo fieldInfo = m as FieldInfo;
			PropertyInfo propertyInfo = m as PropertyInfo;
			MethodInfo methodInfo = m as MethodInfo;
			object obj;
			if (fieldInfo != null)
			{
				if (fieldInfo.FieldType != typeof(float))
				{
					return false;
				}
				object target = GetTarget(fieldInfo.ReflectedType, player, fieldInfo.IsStatic);
				if (target == null && !fieldInfo.IsStatic)
				{
					return false;
				}
				obj = fieldInfo.GetValue(target);
			}
			else if (propertyInfo != null)
			{
				MethodInfo getMethod = propertyInfo.GetGetMethod(nonPublic: true);
				if (getMethod == null || propertyInfo.PropertyType != typeof(float) || propertyInfo.GetIndexParameters().Length != 0)
				{
					return false;
				}
				object target2 = GetTarget(propertyInfo.ReflectedType, player, getMethod.IsStatic);
				if (target2 == null && !getMethod.IsStatic)
				{
					return false;
				}
				obj = getMethod.Invoke(target2, null);
			}
			else
			{
				if (!(methodInfo != null))
				{
					return false;
				}
				if (methodInfo.IsSpecialName || methodInfo.ReturnType != typeof(float) || methodInfo.GetParameters().Length != 0 || methodInfo.ContainsGenericParameters)
				{
					return false;
				}
				object target3 = GetTarget(methodInfo.ReflectedType, player, methodInfo.IsStatic);
				if (target3 == null && !methodInfo.IsStatic)
				{
					return false;
				}
				obj = methodInfo.Invoke(target3, null);
			}
			v = (float)obj;
			return true;
		}
		catch
		{
			return false;
		}
	}

	private static object GetTarget(Type owner, object player, bool isStatic)
	{
		if (isStatic)
		{
			return null;
		}
		if (player != null && owner.IsInstanceOfType(player))
		{
			return player;
		}
		FieldInfo fieldInfo = owner.GetFields(BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic).FirstOrDefault((FieldInfo x) => x.FieldType == owner);
		if (fieldInfo != null)
		{
			return fieldInfo.GetValue(null);
		}
		PropertyInfo propertyInfo = owner.GetProperties(BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic).FirstOrDefault((PropertyInfo x) => x.PropertyType == owner && x.CanRead && x.GetIndexParameters().Length == 0);
		if (!(propertyInfo != null))
		{
			return null;
		}
		return propertyInfo.GetValue(null, null);
	}

	private static string GetPerk(object player)
	{
		if (string.IsNullOrEmpty(PerkFieldName.Value) || player == null)
		{
			return "unknown";
		}
		object obj = player.GetType().GetField(PerkFieldName.Value, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)?.GetValue(player);
		if (obj == null)
		{
			return "unknown";
		}
		if (!(obj is string) && obj is IEnumerable source)
		{
			return string.Join(", ", (from object x in source
				select x?.ToString() ?? "?").ToArray());
		}
		return obj.ToString();
	}

	private static IEnumerable<Type> AllTypes()
	{
		return AppDomain.CurrentDomain.GetAssemblies().SelectMany(delegate(Assembly a)
		{
			try
			{
				return a.GetTypes();
			}
			catch
			{
				return new Type[0];
			}
		});
	}

	private static Type FindType(string name)
	{
		return AllTypes().FirstOrDefault((Type t) => t.Name == name);
	}
}