Decompiled source of PeakRecord v0.3.2

plugins/com.github.wwshare.peakrecord.dll

Decompiled 2 hours ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.IO.Compression;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Cryptography;
using System.Security.Permissions;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Logging;
using ExitGames.Client.Photon;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Peak;
using Peak.Afflictions;
using Photon.Pun;
using Photon.Realtime;
using Photon.Voice.Unity;
using Photon.Voice.Windows;
using Steamworks;
using TMPro;
using Unity.Mathematics;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.Events;
using UnityEngine.InputSystem;
using UnityEngine.InputSystem.Controls;
using UnityEngine.Rendering;
using UnityEngine.SceneManagement;
using UnityEngine.TextCore.LowLevel;
using UnityEngine.UI;
using Zorro.Core;
using Zorro.Settings;
using Zorro.UI.Modal;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: IgnoresAccessChecksTo("Assembly-CSharp")]
[assembly: AssemblyCompany("com.github.wwshare.peakrecord")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("0.3.2.0")]
[assembly: AssemblyInformationalVersion("0.3.2")]
[assembly: AssemblyProduct("com.github.wwshare.peakrecord")]
[assembly: AssemblyTitle("PeakRecord")]
[assembly: AssemblyMetadata("AI_Assisted_Creation", "This assembly was partially or fully created with the assistance of Generative AI (e.g., Code Suggestions, Refactoring, Documentation Generation).")]
[assembly: AssemblyMetadata("AI_Model_Vendor", "GitHub Copilot (Microsoft)")]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("0.3.2.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
	[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)]
	internal sealed class IgnoresAccessChecksToAttribute : Attribute
	{
		public string AssemblyName { get; }

		public IgnoresAccessChecksToAttribute(string assemblyName)
		{
			AssemblyName = assemblyName;
		}
	}
}
namespace PeakRecord
{
	internal sealed class BuildIdentity
	{
		internal string BuildId = "";

		internal string GameVersion = "";

		internal string AssemblyMvid = "";

		internal string UnityDataStamp = "";

		internal string BepInExVersion = "";
	}
	internal static class BuildFingerprint
	{
		private const int HashSampleBytes = 65536;

		private static readonly Lazy<BuildIdentity> Cached = new Lazy<BuildIdentity>(Capture, LazyThreadSafetyMode.ExecutionAndPublication);

		internal static BuildIdentity Current
		{
			get
			{
				try
				{
					return Cached.Value;
				}
				catch
				{
					return new BuildIdentity();
				}
			}
		}

		internal static string Describe()
		{
			BuildIdentity current = Current;
			return "build=" + Show(current.BuildId) + " game=" + Show(current.GameVersion) + " mvid=" + Show(current.AssemblyMvid) + " data=" + Show(current.UnityDataStamp) + " bepinex=" + Show(current.BepInExVersion);
		}

		private static BuildIdentity Capture()
		{
			BuildIdentity buildIdentity = new BuildIdentity();
			try
			{
				buildIdentity.GameVersion = Application.version ?? "";
			}
			catch
			{
				buildIdentity.GameVersion = "";
			}
			try
			{
				string text = typeof(MapBaker).Assembly.ManifestModule.ModuleVersionId.ToString("N");
				buildIdentity.AssemblyMvid = ((text.Length > 8) ? text.Substring(0, 8) : text).ToLowerInvariant();
			}
			catch
			{
				buildIdentity.AssemblyMvid = "";
			}
			buildIdentity.UnityDataStamp = ReadUnityDataStamp();
			try
			{
				Version version = typeof(Chainloader).Assembly.GetName().Version;
				buildIdentity.BepInExVersion = ((version == null) ? "" : version.ToString());
			}
			catch
			{
				buildIdentity.BepInExVersion = "";
			}
			buildIdentity.BuildId = Append(Append(Append("", buildIdentity.GameVersion), buildIdentity.AssemblyMvid), buildIdentity.UnityDataStamp);
			return buildIdentity;
		}

		private static string Append(string current, string part)
		{
			if (string.IsNullOrEmpty(part))
			{
				return current;
			}
			if (current.Length != 0)
			{
				return current + "+" + part;
			}
			return part;
		}

		private static string ReadUnityDataStamp()
		{
			string path;
			try
			{
				path = Path.Combine(Application.dataPath, "data.unity3d");
			}
			catch
			{
				return "unreadable";
			}
			string text = TryHashFile(path, null);
			if (!string.IsNullOrEmpty(text))
			{
				return text;
			}
			try
			{
				text = TryHashFile(Path.Combine(Application.streamingAssetsPath, "maps", "maps.manifest"), "maps-");
				if (!string.IsNullOrEmpty(text))
				{
					return text;
				}
			}
			catch
			{
			}
			return "missing";
		}

		private static string TryHashFile(string path, string prefix)
		{
			try
			{
				FileInfo fileInfo = new FileInfo(path);
				if (!fileInfo.Exists)
				{
					return null;
				}
				long length = fileInfo.Length;
				byte[] array = new byte[65536];
				int i = 0;
				using (FileStream fileStream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
				{
					int num;
					for (; i < array.Length; i += num)
					{
						num = fileStream.Read(array, i, array.Length - i);
						if (num <= 0)
						{
							break;
						}
					}
				}
				using SHA1 sHA = SHA1.Create();
				string text = ToHex(sHA.ComputeHash(array, 0, i));
				return prefix + length.ToString("x", CultureInfo.InvariantCulture) + "-" + ((text.Length > 8) ? text.Substring(0, 8) : text);
			}
			catch
			{
				return null;
			}
		}

		private static string ToHex(byte[] bytes)
		{
			char[] array = new char[bytes.Length * 2];
			for (int i = 0; i < bytes.Length; i++)
			{
				array[i * 2] = "0123456789abcdef"[bytes[i] >> 4];
				array[i * 2 + 1] = "0123456789abcdef"[bytes[i] & 0xF];
			}
			return new string(array);
		}

		private static string Show(string value)
		{
			if (!string.IsNullOrEmpty(value))
			{
				return value;
			}
			return "-";
		}
	}
	public static class CharacterVisualState
	{
		public const int PartCount = 20;

		private static GameObject[] Parts(CustomizationRefs refs)
		{
			GameObject[] array = (GameObject[])(object)new GameObject[20];
			if ((Object)(object)refs == (Object)null)
			{
				return array;
			}
			array[0] = (((Object)(object)refs.skirt != (Object)null) ? ((Component)refs.skirt).gameObject : null);
			array[1] = (((Object)(object)refs.shorts != (Object)null) ? ((Component)refs.shorts).gameObject : null);
			array[2] = (((Object)(object)refs.skirtShadow != (Object)null) ? ((Component)refs.skirtShadow).gameObject : null);
			array[3] = (((Object)(object)refs.shortsShadow != (Object)null) ? ((Component)refs.shortsShadow).gameObject : null);
			array[4] = (((Object)(object)refs.accessoryRenderer != (Object)null) ? ((Component)refs.accessoryRenderer).gameObject : null);
			array[5] = (((Object)(object)refs.thirdEye != (Object)null) ? refs.thirdEye.gameObject : null);
			array[6] = (((Object)(object)refs.sashRenderer != (Object)null) ? ((Component)refs.sashRenderer).gameObject : null);
			array[7] = (((Object)(object)refs.medalRenderer != (Object)null) ? ((Component)refs.medalRenderer).gameObject : null);
			array[8] = (((Object)(object)refs.blindRenderer != (Object)null) ? ((Component)refs.blindRenderer).gameObject : null);
			array[9] = (((Object)(object)refs.chickenRenderer != (Object)null) ? ((Component)refs.chickenRenderer).gameObject : null);
			array[10] = (((Object)(object)refs.headShadow != (Object)null) ? ((Component)refs.headShadow).gameObject : null);
			array[11] = (((Object)(object)refs.skeletonRenderer != (Object)null) ? ((Component)refs.skeletonRenderer).gameObject : null);
			array[12] = (((Object)(object)refs.mouthRenderer != (Object)null) ? ((Component)refs.mouthRenderer).gameObject : null);
			array[13] = (((Object)(object)refs.mainRenderer != (Object)null) ? ((Component)refs.mainRenderer).gameObject : null);
			array[14] = (((Object)(object)refs.mainRendererShadow != (Object)null) ? ((Component)refs.mainRendererShadow).gameObject : null);
			if (refs.playerHats != null)
			{
				for (int i = 0; i < refs.playerHats.Length && 15 + i < 20; i++)
				{
					array[15 + i] = (((Object)(object)refs.playerHats[i] != (Object)null) ? ((Component)refs.playerHats[i]).gameObject : null);
				}
			}
			return array;
		}

		public static ushort Capture(CustomizationRefs refs)
		{
			ushort num = 0;
			GameObject[] array = Parts(refs);
			for (int i = 0; i < array.Length && i < 16; i++)
			{
				if ((Object)(object)array[i] != (Object)null && array[i].activeSelf)
				{
					num |= (ushort)(1 << i);
				}
			}
			return num;
		}

		public static void Apply(CustomizationRefs refs, ushort mask)
		{
			if ((Object)(object)refs == (Object)null)
			{
				return;
			}
			GameObject[] array = Parts(refs);
			for (int i = 0; i < array.Length && i < 16; i++)
			{
				if (!((Object)(object)array[i] == (Object)null))
				{
					bool flag = (mask & (1 << i)) != 0;
					if (array[i].activeSelf != flag)
					{
						array[i].SetActive(flag);
					}
				}
			}
		}

		public static string CaptureMeshName(CustomizationRefs refs)
		{
			try
			{
				if ((Object)(object)refs != (Object)null && (Object)(object)refs.mainRenderer != (Object)null && (Object)(object)refs.mainRenderer.sharedMesh != (Object)null)
				{
					return ((Object)refs.mainRenderer.sharedMesh).name;
				}
			}
			catch
			{
			}
			return "";
		}

		public static bool ApplyMeshByName(CustomizationRefs refs, string meshName)
		{
			if (string.IsNullOrEmpty(meshName))
			{
				return false;
			}
			try
			{
				Customization instance = Singleton<Customization>.Instance;
				if ((Object)(object)instance == (Object)null || instance.fits == null)
				{
					return false;
				}
				for (int i = 0; i < instance.fits.Length; i++)
				{
					CustomizationOption val = instance.fits[i];
					if (!((Object)(object)val == (Object)null) && !((Object)(object)val.fitMesh == (Object)null) && !(((Object)val.fitMesh).name != meshName))
					{
						if ((Object)(object)refs.mainRenderer != (Object)null)
						{
							refs.mainRenderer.sharedMesh = val.fitMesh;
						}
						if ((Object)(object)refs.mainRendererShadow != (Object)null)
						{
							refs.mainRendererShadow.sharedMesh = val.fitMesh;
						}
						return true;
					}
				}
			}
			catch
			{
			}
			return false;
		}
	}
	internal static class CompatibilityHooks
	{
		private const string TerrainPluginTypeName = "TerrainRandomiser.Plugin";

		private const string TerrainStateKey = "terrainRandomiser";

		private static Type _terrainPluginType;

		internal static void Capture(RecordManifest manifest)
		{
			if (manifest == null)
			{
				return;
			}
			int num = 0;
			try
			{
				List<string> list = new List<string>();
				foreach (KeyValuePair<string, PluginInfo> pluginInfo in Chainloader.PluginInfos)
				{
					PluginInfo value = pluginInfo.Value;
					if (value != null && value.Metadata != null)
					{
						string text = value.Metadata.GUID ?? pluginInfo.Key ?? "";
						if (text.IndexOf("peakrecord", StringComparison.OrdinalIgnoreCase) < 0)
						{
							string text2 = value.Metadata.Name ?? text;
							string text3 = ((value.Metadata.Version == null) ? "" : value.Metadata.Version.ToString());
							list.Add(text2 + "|" + text + "|" + text3);
						}
					}
				}
				list.Sort(StringComparer.Ordinal);
				manifest.mods = list.ToArray();
				num = list.Count;
			}
			catch (Exception ex)
			{
				Plugin.Log?.LogWarning("[兼容性] 记录 mod 列表失败: " + ex.Message);
			}
			try
			{
				manifest.mapSetHash = GameMapCatalog.MapSetHash;
			}
			catch (Exception ex2)
			{
				Plugin.Log?.LogWarning("[兼容性] 记录地图集指纹失败: " + ex2.Message);
			}
			try
			{
				BuildIdentity current2 = BuildFingerprint.Current;
				manifest.buildId = current2.BuildId ?? "";
				manifest.assemblyMvid = current2.AssemblyMvid ?? "";
				manifest.unityDataStamp = current2.UnityDataStamp ?? "";
				manifest.bepinexVersion = current2.BepInExVersion ?? "";
				Plugin.Log?.LogInfo("[Build] 当前 build: " + BuildFingerprint.Describe());
			}
			catch (Exception ex3)
			{
				Plugin.Log?.LogWarning("[Build] 记录游戏 build 指纹失败: " + ex3.Message);
			}
			string arg = "未安装";
			try
			{
				Type type = FindTerrainPluginType();
				object obj = ((type == null) ? null : GetStaticMember(type, "Instance"));
				object obj2 = ((obj == null) ? null : GetMember(obj, "roomMapSettings"));
				if (obj2 != null)
				{
					string text4 = JsonConvert.SerializeObject(obj2);
					manifest.modStateJson = "{\"terrainRandomiser\":" + text4 + "}";
					arg = "已捕获";
					string text5 = DescribeTerrainSettings(obj2);
					Plugin.Log?.LogInfo("[兼容性] 已捕获 TerrainRandomiser 状态" + (string.IsNullOrEmpty(text5) ? "" : (" (" + text5 + ")")));
				}
				else if (type != null)
				{
					arg = "失败";
					Plugin.Log?.LogWarning((obj == null) ? "[兼容性] TerrainRandomiser 已安装但 Instance 为空, 跳过状态记录。" : "[兼容性] TerrainRandomiser 已加载但没有 roomMapSettings, 跳过状态记录。");
				}
			}
			catch (Exception ex4)
			{
				arg = "失败";
				Plugin.Log?.LogWarning("[兼容性] 捕获 TerrainRandomiser 状态失败: " + ex4.Message);
			}
			Plugin.Log?.LogInfo($"[兼容性] 已记录其它 mod {num} 个; TerrainRandomiser 状态={arg}");
		}

		internal static void ApplyBeforeMapLoad(RecordManifest manifest)
		{
			if (manifest == null)
			{
				return;
			}
			try
			{
				CompareMods(manifest);
			}
			catch (Exception ex)
			{
				Plugin.Log?.LogWarning("[兼容性] 对比 mod 列表失败: " + ex.Message);
			}
			try
			{
				RestoreTerrainState(manifest);
			}
			catch (Exception ex2)
			{
				Plugin.Log?.LogWarning("[兼容性] 恢复 TerrainRandomiser 状态失败: " + ex2.Message);
			}
		}

		internal static string Describe()
		{
			try
			{
				List<string> list = new List<string>();
				foreach (KeyValuePair<string, PluginInfo> pluginInfo in Chainloader.PluginInfos)
				{
					PluginInfo value = pluginInfo.Value;
					if (value != null && value.Metadata != null)
					{
						string text = value.Metadata.GUID ?? pluginInfo.Key ?? "";
						if (text.IndexOf("peakrecord", StringComparison.OrdinalIgnoreCase) < 0)
						{
							list.Add((value.Metadata.Name ?? text) + "(" + text + ")");
						}
					}
				}
				list.Sort(StringComparer.Ordinal);
				if (list.Count == 0)
				{
					return "其它 mod 0 个";
				}
				return string.Format("其它 mod {0} 个: {1}", list.Count, string.Join(", ", list));
			}
			catch (Exception ex)
			{
				return "其它 mod 列表不可用: " + ex.Message;
			}
		}

		private static void CompareMods(RecordManifest manifest)
		{
			string[] mods = manifest.mods;
			if (mods == null || mods.Length == 0)
			{
				return;
			}
			Dictionary<string, string> dictionary = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
			foreach (KeyValuePair<string, PluginInfo> pluginInfo in Chainloader.PluginInfos)
			{
				PluginInfo value = pluginInfo.Value;
				if (value != null && value.Metadata != null)
				{
					string text = value.Metadata.GUID ?? pluginInfo.Key ?? "";
					if (text.IndexOf("peakrecord", StringComparison.OrdinalIgnoreCase) < 0)
					{
						dictionary[text] = value.Metadata.Name ?? text;
					}
				}
			}
			HashSet<string> hashSet = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
			for (int i = 0; i < mods.Length; i++)
			{
				SplitModEntry(mods[i], out var name, out var guid);
				if (!string.IsNullOrEmpty(guid))
				{
					hashSet.Add(guid);
					if (!dictionary.ContainsKey(guid))
					{
						Plugin.Log?.LogWarning("[兼容性] 记录使用了 mod " + name + ",但当前未安装/未启用;相关物品/地形可能缺失");
					}
				}
			}
			List<string> list = new List<string>();
			foreach (KeyValuePair<string, string> item in dictionary)
			{
				if (!hashSet.Contains(item.Key))
				{
					list.Add(item.Value);
				}
			}
			if (list.Count > 0)
			{
				list.Sort(StringComparer.Ordinal);
				Plugin.Log?.LogInfo(string.Format("[兼容性] 当前额外启用了 {0} 个录制时没有的 mod: {1}", list.Count, string.Join(", ", list)));
			}
		}

		private static void RestoreTerrainState(RecordManifest manifest)
		{
			//IL_0055: Unknown result type (might be due to invalid IL or missing references)
			//IL_005c: Invalid comparison between Unknown and I4
			if (string.IsNullOrEmpty(manifest.modStateJson))
			{
				return;
			}
			JObject val;
			try
			{
				val = JObject.Parse(manifest.modStateJson);
			}
			catch (Exception ex)
			{
				Plugin.Log?.LogWarning("[兼容性] 解析记录中的 mod 状态 JSON 失败: " + ex.Message);
				return;
			}
			JToken val2 = val["terrainRandomiser"];
			if (val2 == null || (int)val2.Type == 10)
			{
				return;
			}
			Type type = FindTerrainPluginType();
			if (type == null)
			{
				Plugin.Log?.LogWarning("[兼容性] 记录包含 TerrainRandomiser 地形设置,但当前未安装/未启用该 mod;地形可能与录制时不同。");
				return;
			}
			object staticMember = GetStaticMember(type, "Instance");
			if (staticMember == null)
			{
				Plugin.Log?.LogWarning("[兼容性] TerrainRandomiser 已安装但未初始化,跳过地形状态恢复。");
				return;
			}
			Type memberType = GetMemberType(staticMember, "roomMapSettings");
			if (memberType == null)
			{
				Plugin.Log?.LogWarning("[兼容性] TerrainRandomiser 找不到 roomMapSettings 字段/属性,跳过地形状态恢复。");
				return;
			}
			object obj;
			try
			{
				obj = JsonConvert.DeserializeObject(val2.ToString((Formatting)0, Array.Empty<JsonConverter>()), memberType);
			}
			catch (Exception ex2)
			{
				Plugin.Log?.LogWarning("[兼容性] 反序列化 TerrainRandomiser 状态失败: " + ex2.Message);
				return;
			}
			if (obj == null)
			{
				Plugin.Log?.LogWarning("[兼容性] TerrainRandomiser 状态反序列化为空,跳过地形状态恢复。");
				return;
			}
			if (!SetMember(staticMember, "roomMapSettings", obj))
			{
				Plugin.Log?.LogWarning("[兼容性] 写入 TerrainRandomiser.roomMapSettings 失败,跳过地形状态恢复。");
				return;
			}
			if (GetMemberType(staticMember, "mapSettings") != null)
			{
				try
				{
					SetMember(staticMember, "mapSettings", obj);
				}
				catch (Exception ex3)
				{
					Plugin.Log?.LogWarning("[兼容性] 同步 TerrainRandomiser.mapSettings 失败: " + ex3.Message);
				}
			}
			try
			{
				SetMember(obj, "enableRandomiser", true);
			}
			catch (Exception ex4)
			{
				Plugin.Log?.LogWarning("[兼容性] 设置 TerrainRandomiser.enableRandomiser 失败: " + ex4.Message);
			}
			object member = GetMember(obj, "seed");
			Plugin.Log?.LogInfo("[兼容性] 已恢复 TerrainRandomiser 种子=" + ((member == null) ? "未知" : member.ToString()));
		}

		private static void SplitModEntry(string entry, out string name, out string guid)
		{
			name = entry ?? "";
			guid = "";
			if (string.IsNullOrEmpty(entry))
			{
				return;
			}
			int num = entry.IndexOf('|');
			if (num <= 0)
			{
				guid = entry;
				return;
			}
			name = entry.Substring(0, num);
			int num2 = entry.IndexOf('|', num + 1);
			guid = ((num2 < 0) ? entry.Substring(num + 1) : entry.Substring(num + 1, num2 - num - 1));
			if (string.IsNullOrEmpty(name))
			{
				name = guid;
			}
		}

		private static Type FindTerrainPluginType()
		{
			if (_terrainPluginType != null)
			{
				return _terrainPluginType;
			}
			Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();
			for (int i = 0; i < assemblies.Length; i++)
			{
				try
				{
					Type type = assemblies[i].GetType("TerrainRandomiser.Plugin", throwOnError: false);
					if (type != null)
					{
						_terrainPluginType = type;
						return type;
					}
				}
				catch
				{
				}
			}
			return null;
		}

		private static string DescribeTerrainSettings(object settings)
		{
			try
			{
				object member = GetMember(settings, "enableRandomiser");
				object member2 = GetMember(settings, "seed");
				if (member == null && member2 == null)
				{
					return "";
				}
				List<string> list = new List<string>();
				if (member != null)
				{
					list.Add("enableRandomiser=" + member);
				}
				if (member2 != null)
				{
					list.Add("seed=" + member2);
				}
				return string.Join(", ", list);
			}
			catch
			{
				return "";
			}
		}

		private static object GetStaticMember(Type type, string name)
		{
			FieldInfo field = type.GetField(name, BindingFlags.Static | BindingFlags.Public | BindingFlags.FlattenHierarchy);
			if (field != null)
			{
				return field.GetValue(null);
			}
			PropertyInfo property = type.GetProperty(name, BindingFlags.Static | BindingFlags.Public | BindingFlags.FlattenHierarchy);
			if (property != null && property.CanRead && property.GetIndexParameters().Length == 0)
			{
				return property.GetValue(null, null);
			}
			return null;
		}

		private static object GetMember(object target, string name)
		{
			if (target == null)
			{
				return null;
			}
			Type type = target.GetType();
			FieldInfo field = type.GetField(name, BindingFlags.Instance | BindingFlags.Public | BindingFlags.FlattenHierarchy);
			if (field != null)
			{
				return field.GetValue(target);
			}
			PropertyInfo property = type.GetProperty(name, BindingFlags.Instance | BindingFlags.Public | BindingFlags.FlattenHierarchy);
			if (property != null && property.CanRead && property.GetIndexParameters().Length == 0)
			{
				return property.GetValue(target, null);
			}
			return null;
		}

		private static Type GetMemberType(object target, string name)
		{
			if (target == null)
			{
				return null;
			}
			Type type = target.GetType();
			FieldInfo field = type.GetField(name, BindingFlags.Instance | BindingFlags.Public | BindingFlags.FlattenHierarchy);
			if (field != null)
			{
				return field.FieldType;
			}
			PropertyInfo property = type.GetProperty(name, BindingFlags.Instance | BindingFlags.Public | BindingFlags.FlattenHierarchy);
			if (property != null && property.GetIndexParameters().Length == 0)
			{
				return property.PropertyType;
			}
			return null;
		}

		private static bool SetMember(object target, string name, object value)
		{
			if (target == null)
			{
				return false;
			}
			Type type = target.GetType();
			FieldInfo field = type.GetField(name, BindingFlags.Instance | BindingFlags.Public);
			if (field != null)
			{
				field.SetValue(target, value);
				return true;
			}
			PropertyInfo property = type.GetProperty(name, BindingFlags.Instance | BindingFlags.Public);
			if (property != null && property.CanWrite && property.GetIndexParameters().Length == 0)
			{
				property.SetValue(target, value, null);
				return true;
			}
			return false;
		}
	}
	public sealed class CursorKeeper : MonoBehaviour
	{
		private void LateUpdate()
		{
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			if (!RecordUI.WindowOpen && !ReplayView.IsNativePauseOpen && !ReplayHud.IsAdjustModeActive)
			{
				return;
			}
			try
			{
				if ((int)Cursor.lockState != 0)
				{
					Cursor.lockState = (CursorLockMode)0;
				}
				if (!Cursor.visible)
				{
					Cursor.visible = true;
				}
			}
			catch
			{
			}
		}
	}
	public static class Diagnostics
	{
		public const bool Verbose = false;

		public const float SlowWindowMs = 33f;

		public const float SlowSingleFrameMs = 50f;

		public const bool StatusLine = true;

		public const float StatusIntervalSec = 15f;

		public static bool PerfSweep => RecordSettings.PerfSweep;
	}
	[DefaultExecutionOrder(-10000)]
	public sealed class ReplayFrameProbeEarly : MonoBehaviour
	{
		private void Update()
		{
			ReplayEngine.ProbeUpdatePhaseStart();
		}
	}
	[DefaultExecutionOrder(10000)]
	public sealed class ReplayFrameProbeLate : MonoBehaviour
	{
		private void LateUpdate()
		{
			ReplayEngine.ProbeLatePhaseEnd();
		}
	}
	internal static class FrameProbeClock
	{
		public static long Now()
		{
			return Stopwatch.GetTimestamp();
		}

		public static double MsSince(long from)
		{
			return (double)(Now() - from) * 1000.0 / (double)Stopwatch.Frequency;
		}
	}
	internal static class GameMapCatalog
	{
		private static bool _tried;

		private static string[] _scenes;

		private static string[] _biomes;

		private static string _hash;

		internal static string GameVersion
		{
			get
			{
				try
				{
					return Application.version ?? "";
				}
				catch
				{
					return "";
				}
			}
		}

		internal static int SlotCount
		{
			get
			{
				Ensure();
				if (_scenes != null)
				{
					return _scenes.Length;
				}
				return 0;
			}
		}

		internal static string MapSetHash
		{
			get
			{
				Ensure();
				return _hash ?? "";
			}
		}

		internal static void Ensure()
		{
			if (_tried)
			{
				return;
			}
			_tried = true;
			try
			{
				MapBaker instance = SingletonAsset<MapBaker>.Instance;
				if (!((Object)(object)instance == (Object)null) && instance.ScenePaths != null && instance.ScenePaths.Length != 0)
				{
					int num = instance.ScenePaths.Length;
					_scenes = new string[num];
					_biomes = new string[num];
					for (int i = 0; i < num; i++)
					{
						_scenes[i] = instance.GetLevel(i) ?? "";
						_biomes[i] = instance.GetBiomeID(i) ?? "";
					}
					_hash = ComputeHash(_scenes, _biomes);
				}
			}
			catch (Exception ex)
			{
				Plugin.Log?.LogWarning("[地图还原] 读取游戏地图目录(MapBaker)失败: " + ex.Message);
			}
		}

		internal static string Describe()
		{
			Ensure();
			if (_scenes == null || _scenes.Length == 0)
			{
				return "地图目录不可用(读不到 MapBaker); 游戏版本=" + GameVersion;
			}
			return string.Format(CultureInfo.InvariantCulture, "游戏版本={0} 地图张数={1} 地图集指纹={2}", GameVersion, _scenes.Length, MapSetHash);
		}

		internal static string BackupAdvice()
		{
			return "地图说明: 2026-10 之后的版本把关卡拆到 StreamingAssets/maps/levels<min>-<max>.assetBundle(单个 1.4~2.2GB), 太大不再随记录封装; 同一 build 回放会直接加载本机对应关卡包。";
		}

		private static int IndexOf(string sceneName, string biomeId)
		{
			if (_scenes == null)
			{
				return -1;
			}
			for (int i = 0; i < _scenes.Length; i++)
			{
				if (string.Equals(_scenes[i], sceneName, StringComparison.OrdinalIgnoreCase) && (string.IsNullOrEmpty(biomeId) || string.Equals(_biomes[i], biomeId, StringComparison.OrdinalIgnoreCase)))
				{
					return i;
				}
			}
			return -1;
		}

		private static int IndexOfBiome(string biomeId)
		{
			if (_biomes == null || string.IsNullOrEmpty(biomeId))
			{
				return -1;
			}
			for (int i = 0; i < _biomes.Length; i++)
			{
				if (string.Equals(_biomes[i], biomeId, StringComparison.OrdinalIgnoreCase))
				{
					return i;
				}
			}
			return -1;
		}

		internal static string DefaultScene()
		{
			Ensure();
			if (_scenes != null)
			{
				for (int i = 0; i < _scenes.Length; i++)
				{
					if (!string.IsNullOrEmpty(_scenes[i]))
					{
						return _scenes[i];
					}
				}
			}
			return "Level_0";
		}

		private static int IndexOfScene(string sceneName)
		{
			if (_scenes == null || string.IsNullOrEmpty(sceneName))
			{
				return -1;
			}
			for (int i = 0; i < _scenes.Length; i++)
			{
				if (string.Equals(_scenes[i], sceneName, StringComparison.OrdinalIgnoreCase))
				{
					return i;
				}
			}
			return -1;
		}

		internal static string Resolve(string recordedScene, string recordedBiome, string recordedVersion, string recordedMapSetHash, int recordedLevelIndex, out string note)
		{
			note = "";
			Ensure();
			bool flag = !string.IsNullOrEmpty(recordedVersion) && !string.IsNullOrEmpty(GameVersion) && !string.Equals(recordedVersion, GameVersion, StringComparison.OrdinalIgnoreCase);
			bool flag2 = !string.IsNullOrEmpty(recordedMapSetHash) && !string.IsNullOrEmpty(MapSetHash) && !string.Equals(recordedMapSetHash, MapSetHash, StringComparison.OrdinalIgnoreCase);
			string text = (flag ? ("; ⚠\ufe0f 记录来自游戏版本 " + recordedVersion + ", 当前是 " + GameVersion) : "");
			string text2 = (flag2 ? ("; ⚠\ufe0f 地图集指纹不同(记录 " + Short(recordedMapSetHash) + " / 当前 " + Short(MapSetHash) + ")") : "");
			string text3 = ((!string.IsNullOrEmpty(recordedScene)) ? recordedScene : ((recordedLevelIndex >= 0 && _scenes != null && _scenes.Length != 0) ? ("Level_" + recordedLevelIndex % _scenes.Length) : DefaultScene()));
			if (flag2)
			{
				note = "地图集已变化" + text2 + text + "; 新版本的 " + text3 + " 与录制时不是同一张图, 本次按同名关卡尽力加载(外观/地形可能不同)。";
				return text3;
			}
			if (_scenes == null || _scenes.Length == 0)
			{
				note = "地图目录不可用(读不到 MapBaker), 按记录的场景名 " + text3 + " 直接加载" + text + "。";
				return text3;
			}
			int num = IndexOf(recordedScene, recordedBiome);
			if (num >= 0)
			{
				note = string.Format("地图身份匹配: {0}(生态 {1}) 仍在槽位 {2}{3}。", recordedScene, string.IsNullOrEmpty(recordedBiome) ? "未记录" : recordedBiome, num, text);
				return recordedScene;
			}
			int num2 = IndexOfScene(recordedScene);
			if (num2 >= 0)
			{
				note = string.Format("地图身份匹配: {0} 仍在槽位 {1}(生态记录为 {2}, 当前为 {3}){4}。", recordedScene, num2, string.IsNullOrEmpty(recordedBiome) ? "未记录" : recordedBiome, _biomes[num2], text);
				return _scenes[num2];
			}
			int num3 = IndexOfBiome(recordedBiome);
			if (num3 >= 0 && !string.IsNullOrEmpty(_scenes[num3]))
			{
				string text4 = _scenes[num3];
				note = $"记录里的 {recordedScene} 已不在当前地图目录中; 按生态 {recordedBiome} 在新版本里定位到槽位 {num3} = {text4}, 改加载它(外观可能与录制时不同){text}。";
				return text4;
			}
			note = "⚠\ufe0f 记录的地图 " + recordedScene + "(生态 " + (string.IsNullOrEmpty(recordedBiome) ? "未记录" : recordedBiome) + ") 在当前游戏版本的地图集里找不到对应项 —— 本次回放的世界与录制时**不同**, 无法还原" + text + "。当前目录: " + MapSetHash + "。" + BackupAdvice();
			return text3;
		}

		private static string Short(string hash)
		{
			if (string.IsNullOrEmpty(hash))
			{
				return "-";
			}
			if (hash.Length <= 12)
			{
				return hash;
			}
			return hash.Substring(0, 12);
		}

		private static string ComputeHash(string[] scenes, string[] biomes)
		{
			ulong num = 14695981039346656037uL;
			StringBuilder stringBuilder = new StringBuilder();
			for (int i = 0; i < scenes.Length; i++)
			{
				stringBuilder.Append(scenes[i]).Append('|').Append((biomes != null && i < biomes.Length) ? biomes[i] : "")
					.Append(';');
			}
			string text = stringBuilder.ToString();
			for (int j = 0; j < text.Length; j++)
			{
				num ^= text[j];
				num *= 1099511628211L;
			}
			return num.ToString("x16", CultureInfo.InvariantCulture);
		}
	}
	[HarmonyPatch(typeof(PlayerShaderParams), "Update")]
	internal static class Patch_PlayerShaderParamsUpdate
	{
		private static bool _warned;

		[HarmonyPrefix]
		private static bool Prefix()
		{
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			//IL_002c: Unknown result type (might be due to invalid IL or missing references)
			//IL_002d: Unknown result type (might be due to invalid IL or missing references)
			//IL_003a: 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_00a6: 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_0061: Unknown result type (might be due to invalid IL or missing references)
			//IL_006e: Unknown result type (might be due to invalid IL or missing references)
			long startTs = PerfProbe.Enter();
			try
			{
				ModIsolation.Tick();
				ReplayCameraController.UpdateHideTheBody();
				Character localCharacter = Character.localCharacter;
				if ((Object)(object)localCharacter == (Object)null)
				{
					return true;
				}
				Vector3 center = localCharacter.Center;
				if (float.IsNaN(center.x) || float.IsNaN(center.y) || float.IsNaN(center.z) || float.IsInfinity(center.x) || float.IsInfinity(center.y) || float.IsInfinity(center.z) || ((Vector3)(ref center)).sqrMagnitude > 1E+10f)
				{
					if (!_warned)
					{
						_warned = true;
						Plugin.Log?.LogWarning($"黑屏保险: 本机角色坐标非有限({center:F1}), 已跳过写入全局 PlayerPos —— 避免整屏黑。");
					}
					return false;
				}
			}
			catch
			{
			}
			finally
			{
				PerfProbe.Leave(1, startTs);
			}
			return true;
		}
	}
	[HarmonyPatch(typeof(RunManager), "StartRun")]
	internal static class Patch_RunManagerStartRun
	{
		[HarmonyPostfix]
		private static void Postfix()
		{
			try
			{
				if (!RecordSettings.RecordingEnabled)
				{
					return;
				}
				if (PeakRecorder.ReplayActive)
				{
					Plugin.Log?.LogInfo("回放中: 忽略 RunManager.StartRun 的开录请求。");
					return;
				}
				PeakRecorder instance = PeakRecorder.Instance;
				if (!((Object)(object)instance == (Object)null))
				{
					if (instance.IsRecording)
					{
						Plugin.Log?.LogInfo("RunManager.StartRun: 录制已在运行(关卡初始化时已开录)。");
					}
					else
					{
						instance.StartRecording();
					}
				}
			}
			catch (Exception ex)
			{
				Plugin.Log?.LogWarning("StartRun 补丁异常: " + ex.Message);
			}
		}
	}
	[HarmonyPatch(typeof(MapHandler), "InitializeMap")]
	internal static class Patch_MapHandlerInitializeMap
	{
		[HarmonyPostfix]
		private static void Postfix()
		{
			try
			{
				if (PeakRecorder.ReplayActive && RecordSettings.ReplayAsHost)
				{
					ReplayGuards.MarkInitialSpawnersDone();
				}
				ReplayGuards.LogMapSeed(PeakRecorder.ReplayActive ? "回放" : "录制");
				PeakRecorder.Instance?.StartRecordingAtLevelInit();
			}
			catch (Exception ex)
			{
				Plugin.Log?.LogWarning("InitializeMap 补丁异常: " + ex.Message);
			}
		}
	}
	[HarmonyPatch(typeof(Quicksave), "SaveNow")]
	internal static class Patch_ReplaySkipQuicksaveSave
	{
		[HarmonyPrefix]
		private static bool Prefix()
		{
			try
			{
				return !PeakRecorder.ReplayActive;
			}
			catch
			{
				return true;
			}
		}
	}
	[HarmonyPatch(typeof(Quicksave), "DestroySaveData")]
	internal static class Patch_ReplaySkipQuicksaveDestroy
	{
		[HarmonyPrefix]
		private static bool Prefix()
		{
			try
			{
				return !PeakRecorder.ReplayActive;
			}
			catch
			{
				return true;
			}
		}
	}
	[HarmonyPatch(typeof(GUIManager), "Quicksave")]
	internal static class Patch_ReplaySkipQuicksaveToast
	{
		[HarmonyPrefix]
		private static bool Prefix()
		{
			try
			{
				return !PeakRecorder.ReplayActive;
			}
			catch
			{
				return true;
			}
		}
	}
	[HarmonyPatch(typeof(Character), "RPCEndGame")]
	internal static class Patch_ReplaySkipCharacterEndGame
	{
		[HarmonyPrefix]
		private static bool Prefix()
		{
			try
			{
				if (!PeakRecorder.ReplayActive)
				{
					return true;
				}
				ReplayEngine.NotifyRecordedRunEnded();
				Plugin.Log?.LogInfo("[回放] 拦截录制中的 RPCEndGame(不打开游戏结束界面/不加载结束场景)。");
				return false;
			}
			catch
			{
				return true;
			}
		}
	}
	[HarmonyPatch(typeof(RunManager), "EndGame")]
	internal static class Patch_RunManagerEndGame
	{
		[HarmonyPostfix]
		private static void Postfix()
		{
			try
			{
				PeakRecorder instance = PeakRecorder.Instance;
				if (!((Object)(object)instance == (Object)null) && instance.IsRecording)
				{
					long timestamp = Stopwatch.GetTimestamp();
					Plugin.Log?.LogInfo("[结束体检] 1/3 EndGame 进入。");
					instance.AddSimpleEvent(RecordEventType.RunEnded, "本局结束");
					instance.StopRecording();
					Plugin.Log?.LogInfo($"[结束体检] 2/3 停止录制 + 实时落盘收尾完成, 耗时 {ElapsedMs(timestamp)}ms。");
					RecordUI.QueueExport(instance.Data);
					Plugin.Log?.LogInfo("[结束体检] 3/3 自动封包已排到后续帧执行(不阻塞结束演出)。");
				}
			}
			catch (Exception ex)
			{
				Plugin.Log?.LogWarning("EndGame 补丁异常: " + ex.Message);
			}
		}

		internal static long ElapsedMs(long sinceTimestamp)
		{
			return (long)((double)(Stopwatch.GetTimestamp() - sinceTimestamp) * 1000.0 / (double)Stopwatch.Frequency);
		}
	}
	internal static class PauseMenuPatchUtil
	{
		internal static void ClearPauseKey()
		{
			try
			{
				Character localCharacter = Character.localCharacter;
				if ((Object)(object)localCharacter != (Object)null && (Object)(object)localCharacter.input != (Object)null)
				{
					localCharacter.input.pauseWasPressed = false;
				}
			}
			catch
			{
			}
		}
	}
	[HarmonyPatch(typeof(GUIManager), "UpdatePaused")]
	internal static class Patch_GuiManagerUpdatePaused
	{
		[HarmonyPrefix]
		private static bool Prefix()
		{
			if (PeakRecorder.ReplayActive)
			{
				try
				{
					PauseMenuPatchUtil.ClearPauseKey();
				}
				catch
				{
				}
				return false;
			}
			try
			{
				if (!RecordUI.WindowOpen || ReplayView.IsNativePauseOpen)
				{
					return true;
				}
				PauseMenuPatchUtil.ClearPauseKey();
				return false;
			}
			catch
			{
				return true;
			}
		}
	}
	[HarmonyPatch(typeof(PauseMenuHandler), "OnEnable")]
	internal static class Patch_PauseMenuHandlerOnEnable
	{
		private static bool _logged;

		[HarmonyPrefix]
		private static bool Prefix(PauseMenuHandler __instance)
		{
			if ((Object)(object)__instance == (Object)null || !PeakRecorder.ReplayActive)
			{
				return true;
			}
			try
			{
				if (((Component)__instance).gameObject.activeSelf)
				{
					((Component)__instance).gameObject.SetActive(false);
				}
				if (!_logged)
				{
					_logged = true;
					Plugin.Log?.LogInfo("[ESC] 回放中已阻止原生暂停菜单激活(ESC 只用于两次退出回放)。");
				}
			}
			catch
			{
			}
			return false;
		}
	}
	[HarmonyPatch(typeof(PauseMenuMainPage), "Quit")]
	internal static class Patch_PauseMenuQuit
	{
		[HarmonyPrefix]
		private static bool Prefix()
		{
			try
			{
				if (PeakRecorder.ReplayActive)
				{
					Plugin.Log?.LogInfo("回放中通过原生暂停菜单退出: 返回主菜单。");
					ReplayView.ExitToTitle();
					return false;
				}
				PeakRecorder instance = PeakRecorder.Instance;
				if ((Object)(object)instance != (Object)null && instance.IsRecording)
				{
					Plugin.Log?.LogInfo("检测到录制中退出: 先自动封包, 再继续原生 Quit。");
					PeakRecorder.FinalizeAndExport();
				}
			}
			catch (Exception ex)
			{
				Plugin.Log?.LogWarning("暂停菜单 Quit 补丁异常: " + ex.Message);
			}
			return true;
		}
	}
	[HarmonyPatch(typeof(CharacterSpawner), "RPC_NewPlayerSpawn")]
	internal static class Patch_ReplayBlockNewPlayerSpawn
	{
		private static bool _logged;

		[HarmonyPrefix]
		private static bool Prefix()
		{
			if (!PeakRecorder.ReplayActive)
			{
				return true;
			}
			if (!_logged)
			{
				_logged = true;
				Plugin.Log?.LogInfo("[回放] 已忽略录制里的 CharacterSpawner.RPC_NewPlayerSpawn —— 不为观察者生成本机角色。");
			}
			return false;
		}
	}
	[HarmonyPatch(typeof(CharacterSpawner), "RPC_MiniRunPlayerSpawn")]
	internal static class Patch_ReplayBlockMiniRunSpawn
	{
		[HarmonyPrefix]
		private static bool Prefix()
		{
			return !PeakRecorder.ReplayActive;
		}
	}
	[HarmonyPatch(typeof(CharacterSpawner), "RPC_ReconnectingPlayerSpawn")]
	internal static class Patch_ReplayBlockReconnectSpawn
	{
		[HarmonyPrefix]
		private static bool Prefix()
		{
			return !PeakRecorder.ReplayActive;
		}
	}
	[HarmonyPatch(typeof(CharacterSpawner), "SpawnMyPlayerCharacter")]
	internal static class Patch_ReplayBlockSpawnMyPlayerCharacter
	{
		private static bool _logged;

		[HarmonyPrefix]
		private static bool Prefix(ref Character __result)
		{
			if (!PeakRecorder.ReplayActive)
			{
				return true;
			}
			__result = null;
			if (!_logged)
			{
				_logged = true;
				Plugin.Log?.LogInfo("[回放] 已拦截 CharacterSpawner.SpawnMyPlayerCharacter —— 回放期间不生成任何本机角色。");
			}
			return false;
		}
	}
	[HarmonyPatch(typeof(GUIManager), "UpdateWindowStatus")]
	internal static class Patch_GuiManagerUpdateWindowStatus
	{
		[HarmonyPostfix]
		private static void Postfix(GUIManager __instance)
		{
			try
			{
				if ((Object)(object)__instance != (Object)null && RecordUI.WindowOpen)
				{
					__instance.windowBlockingInput = true;
					__instance.windowShowingCursor = true;
				}
			}
			catch
			{
			}
		}
	}
	[HarmonyPatch(typeof(GUIManager), "UpdateReticle")]
	internal static class Patch_GuiManagerUpdateReticle
	{
		private struct ReticleState
		{
			public bool Swapped;

			public Character Local;

			public Character Gui;
		}

		[HarmonyPrefix]
		private static void Prefix(GUIManager __instance, out ReticleState __state)
		{
			__state = default(ReticleState);
			try
			{
				if ((Object)(object)__instance == (Object)null || !PeakRecorder.ReplayActive)
				{
					return;
				}
				Character watched = ReplayView.Watched;
				if (ReplayView.Mode == ReplayCameraController.ViewMode.FreeCam || (Object)(object)watched == (Object)null)
				{
					if ((Object)(object)Character.localCharacter != (Object)null && (Object)(object)__instance.character != (Object)(object)Character.localCharacter)
					{
						__instance.character = Character.localCharacter;
					}
				}
				else
				{
					__state.Local = Character.localCharacter;
					__state.Gui = __instance.character;
					__state.Swapped = true;
					Character.localCharacter = watched;
					__instance.character = watched;
				}
			}
			catch (Exception ex)
			{
				Restore(__instance, __state);
				Plugin.Log?.LogWarning("准星观察目标切换失败: " + ex.Message);
			}
		}

		[HarmonyPostfix]
		private static void Postfix(GUIManager __instance, ReticleState __state)
		{
			Restore(__instance, __state);
		}

		[HarmonyFinalizer]
		private static Exception Finalizer(GUIManager __instance, ReticleState __state, Exception __exception)
		{
			Restore(__instance, __state);
			return __exception;
		}

		private static void Restore(GUIManager instance, ReticleState state)
		{
			if (!state.Swapped)
			{
				return;
			}
			state.Swapped = false;
			try
			{
				Character.localCharacter = state.Local;
				if ((Object)(object)instance != (Object)null)
				{
					instance.character = state.Gui;
				}
			}
			catch
			{
			}
		}
	}
	[HarmonyPatch(typeof(Interaction), "LateUpdate")]
	internal static class Patch_InteractionLateUpdate
	{
		[HarmonyPrefix]
		private static bool Prefix(Interaction __instance)
		{
			try
			{
				if (!PeakRecorder.ReplayActive || (Object)(object)__instance == (Object)null)
				{
					return true;
				}
				__instance.currentHovered = null;
				__instance.bestInteractable = null;
				__instance.bestCharacter = null;
				return false;
			}
			catch (Exception ex)
			{
				Plugin.Log?.LogWarning("回放交互拦截失败: " + ex.Message);
				return true;
			}
		}
	}
	[HarmonyPatch(typeof(Modal), "OpenModal")]
	internal static class Patch_ModalOpen
	{
		[HarmonyPrefix]
		private static bool Prefix()
		{
			if (!PeakRecorder.ReplayActive)
			{
				return true;
			}
			Plugin.Log?.LogInfo("回放中: 已拦截一个游戏弹窗(离线提示等)。");
			return false;
		}
	}
	[HarmonyPatch(typeof(CharacterVoiceHandler), "OnAudioFilterRead")]
	internal static class Patch_VoiceOnAudioFilterRead
	{
		[HarmonyPostfix]
		private static void Postfix(CharacterVoiceHandler __instance, float[] data, int channels)
		{
			try
			{
				if (VoiceCapture.Enabled && RecordSettings.VoiceMode != VoiceRecordMode.Off && data != null)
				{
					Character character = __instance.m_character;
					if (!((Object)(object)character == (Object)null) && !character.IsLocal)
					{
						VoiceCapture.Feed(((MonoBehaviourPun)character).photonView.Owner.ActorNumber, data, channels, AudioSettings.outputSampleRate);
					}
				}
			}
			catch
			{
			}
		}
	}
	[HarmonyPatch(typeof(MicWrapper), "Read")]
	internal static class Patch_LocalMicWrapperRead
	{
		[HarmonyPostfix]
		private static void Postfix(MicWrapper __instance, float[] buffer, bool __result)
		{
			if (!__result || __instance == null || buffer == null)
			{
				return;
			}
			try
			{
				VoiceCapture.FeedLocal(buffer, __instance.Channels, __instance.SamplingRate);
			}
			catch
			{
			}
		}
	}
	[HarmonyPatch(typeof(WindowsAudioInPusher), "push")]
	internal static class Patch_LocalMicPusherPush
	{
		[HarmonyPostfix]
		private static void Postfix(IntPtr buf, int lenBytes)
		{
			if (buf == IntPtr.Zero || lenBytes <= 0)
			{
				return;
			}
			try
			{
				int num = lenBytes / 2;
				short[] array = new short[num];
				Marshal.Copy(buf, array, 0, num);
				VoiceCapture.FeedLocalShort(array, 16000);
			}
			catch
			{
			}
		}
	}
	[HarmonyPatch("Photon.Voice.Unity.MicWrapperPusherOnAudioFilterRead, PhotonVoice.API", "OnAudioFilterRead")]
	internal static class Patch_LocalMicWrapperPusherFilterRead
	{
		[HarmonyPrefix]
		private static void Prefix(float[] frame, int channels)
		{
			if (frame == null || frame.Length == 0)
			{
				return;
			}
			try
			{
				VoiceCapture.FeedLocal(frame, channels, AudioSettings.outputSampleRate);
			}
			catch
			{
			}
		}
	}
	[HarmonyPatch(typeof(LandImpactAudio), "Update")]
	internal static class Patch_ReplayMuteLandImpactAudio
	{
		private static bool _logged;

		[HarmonyPrefix]
		private static bool Prefix(LandImpactAudio __instance)
		{
			if (!PeakRecorder.ReplayActive)
			{
				return true;
			}
			try
			{
				if ((Object)(object)__instance.impactHeavy != (Object)null)
				{
					__instance.impactHeavy.SetActive(false);
				}
				if ((Object)(object)__instance.impactMedium != (Object)null)
				{
					__instance.impactMedium.SetActive(false);
				}
				if ((Object)(object)__instance.impactSmall != (Object)null)
				{
					__instance.impactSmall.SetActive(false);
				}
			}
			catch
			{
			}
			if (!_logged)
			{
				_logged = true;
				Plugin.Log?.LogInfo("[回放] 已停用程序化落地/坠落音效(低帧率会放大每帧位移,导致落地音量失真)。");
			}
			return false;
		}
	}
	[HarmonyPatch(typeof(FallAudio), "Update")]
	internal static class Patch_ReplayMuteFallAudio
	{
		[HarmonyPrefix]
		private static bool Prefix(FallAudio __instance)
		{
			if (!PeakRecorder.ReplayActive)
			{
				return true;
			}
			try
			{
				if ((Object)(object)__instance.au != (Object)null)
				{
					__instance.au.volume = 0f;
				}
			}
			catch
			{
			}
			return false;
		}
	}
	[HarmonyPatch(typeof(Action_ApplyMassAffliction), "TryAddAfflictionToLocalCharacter")]
	internal static class Patch_ReplayMassAfflictionTarget
	{
		[HarmonyPrefix]
		private static void Prefix(out Character __state)
		{
			__state = null;
			if (!PeakRecorder.ReplayActive)
			{
				return;
			}
			try
			{
				Character val = ReplayEngine.Instance?.GetRecordedLocalCharacter();
				if ((Object)(object)val != (Object)null && (Object)(object)Character.localCharacter != (Object)(object)val)
				{
					__state = Character.localCharacter;
					Character.localCharacter = val;
				}
			}
			catch
			{
			}
		}

		[HarmonyFinalizer]
		private static void Finalizer(Character __state)
		{
			if ((Object)(object)__state != (Object)null)
			{
				try
				{
					Character.localCharacter = __state;
				}
				catch
				{
				}
			}
		}
	}
	[HarmonyPatch(typeof(CharacterAfflictions), "Update")]
	internal static class Patch_ReplayAfflictionLifetime
	{
		[HarmonyPostfix]
		private static void Postfix(CharacterAfflictions __instance)
		{
			if (!PeakRecorder.ReplayActive || (Object)(object)__instance == (Object)null)
			{
				return;
			}
			Character character = __instance.character;
			if ((Object)(object)character == (Object)null || character.IsLocal)
			{
				return;
			}
			try
			{
				if ((Object)(object)((MonoBehaviourPun)character).photonView != (Object)null && ((MonoBehaviourPun)character).photonView.IsMine)
				{
					return;
				}
			}
			catch
			{
				return;
			}
			ReplayEngine instance = ReplayEngine.Instance;
			if ((Object)(object)instance == (Object)null || !instance.Active || !instance.Playing)
			{
				return;
			}
			List<Affliction> afflictionList = __instance.afflictionList;
			if (afflictionList == null)
			{
				return;
			}
			if (!instance.IsActorVisible(character))
			{
				try
				{
					for (int num = afflictionList.Count - 1; num >= 0; num--)
					{
						Affliction val = afflictionList[num];
						if (val != null)
						{
							__instance.RemoveAffliction(val, true, false);
						}
					}
				}
				catch
				{
				}
			}
			float playheadDeltaSeconds = instance.PlayheadDeltaSeconds;
			if (playheadDeltaSeconds <= 0f)
			{
				return;
			}
			for (int num2 = afflictionList.Count - 1; num2 >= 0; num2--)
			{
				Affliction val2 = afflictionList[num2];
				if (val2 != null)
				{
					if (val2.bonusTime > 0f)
					{
						val2.bonusTime -= playheadDeltaSeconds;
					}
					else
					{
						val2.timeElapsed += playheadDeltaSeconds;
					}
					if (val2.timeElapsed >= val2.totalTime)
					{
						__instance.RemoveAffliction(val2, true, false);
					}
					else
					{
						try
						{
							val2.UpdateEffect();
						}
						catch
						{
						}
					}
				}
			}
		}
	}
	[HarmonyPatch(typeof(Item), "Consume")]
	internal static class Patch_ItemConsume
	{
		[HarmonyPostfix]
		private static void Postfix(Item __instance)
		{
			//IL_00ae: 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)
			try
			{
				PeakRecorder instance = PeakRecorder.Instance;
				if (!((Object)(object)instance == (Object)null) && instance.IsRecording && !((Object)(object)__instance == (Object)null))
				{
					RecordEvent recordEvent = new RecordEvent();
					recordEvent.Type = RecordEventType.ItemConsumed;
					recordEvent.TimeMs = Mathf.Max(0, PeakRecorder.NetworkTimeMs() + instance.TimeOffsetMs - instance.SessionStartServerMs);
					recordEvent.ItemId = __instance.itemID;
					recordEvent.Actor = PeakRecorder.ActorToSbyte(__instance.trueHolderCharacter);
					recordEvent.ItemGuid = ((__instance.data != null) ? __instance.data.guid : Guid.Empty);
					recordEvent.Value = (ushort)Mathf.Clamp(PeakRecorder.GetItemUses(__instance), 0, 65535);
					recordEvent.Position = __instance.transform.position;
					instance.QueueCooldown(recordEvent.Actor, RecordEventType.ItemConsumed, 0.2f, recordEvent);
				}
			}
			catch
			{
			}
		}
	}
	[HarmonyPatch(typeof(Campfire), "Light_Rpc")]
	internal static class Patch_CampfireLight
	{
		[HarmonyPostfix]
		private static void Postfix(Campfire __instance)
		{
			try
			{
				PeakRecorder instance = PeakRecorder.Instance;
				if (((Object)(object)instance != (Object)null && instance.OnCampfireState(__instance, lit: true)) || (Object)(object)instance == (Object)null || !instance.IsRecording)
				{
					ReplayEngine.Instance?.OnCampfireLit();
				}
			}
			catch
			{
			}
		}
	}
	[HarmonyPatch(typeof(Campfire), "Extinguish_Rpc")]
	internal static class Patch_CampfireExtinguish
	{
		[HarmonyPostfix]
		private static void Postfix(Campfire __instance)
		{
			try
			{
				PeakRecorder.Instance?.OnCampfireState(__instance, lit: false);
			}
			catch
			{
			}
		}
	}
	[HarmonyPatch(typeof(CharacterCarrying), "RPCA_StartCarry")]
	internal static class Patch_CarryStart
	{
		[HarmonyPostfix]
		private static void Postfix(CharacterCarrying __instance)
		{
			try
			{
				PeakRecorder instance = PeakRecorder.Instance;
				if (!((Object)(object)instance == (Object)null) && instance.IsRecording && !((Object)(object)__instance == (Object)null))
				{
					Character component = ((Component)__instance).GetComponent<Character>();
					if (!((Object)(object)component == (Object)null) && !((Object)(object)component.data == (Object)null))
					{
						RecordEvent recordEvent = new RecordEvent();
						recordEvent.Type = RecordEventType.CarryStart;
						recordEvent.TimeMs = Mathf.Max(0, PeakRecorder.NetworkTimeMs() + instance.TimeOffsetMs - instance.SessionStartServerMs);
						recordEvent.Actor = PeakRecorder.ActorToSbyte(component);
						recordEvent.TargetActor = PeakRecorder.ActorToSbyte(component.data.carriedPlayer);
						instance.QueueCooldown(recordEvent.Actor, RecordEventType.CarryStart, 0.5f, recordEvent);
					}
				}
			}
			catch
			{
			}
		}
	}
	[HarmonyPatch(typeof(CharacterItems), "OnPickupAccepted")]
	internal static class Patch_ItemPickup
	{
		[HarmonyPostfix]
		private static void Postfix(CharacterItems __instance, byte slotID)
		{
			//IL_00f6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fb: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				PeakRecorder instance = PeakRecorder.Instance;
				if ((Object)(object)instance == (Object)null || !instance.IsRecording || (Object)(object)__instance == (Object)null)
				{
					return;
				}
				Character character = __instance.character;
				if ((Object)(object)character == (Object)null)
				{
					return;
				}
				Item val = null;
				try
				{
					ItemSlot itemSlot = character.player.GetItemSlot(slotID);
					if (itemSlot != null)
					{
						val = itemSlot.prefab;
					}
				}
				catch
				{
				}
				RecordEvent recordEvent = new RecordEvent();
				recordEvent.Type = RecordEventType.ItemPickedUp;
				recordEvent.TimeMs = Mathf.Max(0, PeakRecorder.NetworkTimeMs() + instance.TimeOffsetMs - instance.SessionStartServerMs);
				recordEvent.Actor = PeakRecorder.ActorToSbyte(character);
				recordEvent.Slot = slotID;
				if ((Object)(object)val != (Object)null)
				{
					recordEvent.ItemId = val.itemID;
					recordEvent.ItemGuid = ((val.data != null) ? val.data.guid : Guid.Empty);
					recordEvent.Text = ((val.UIData != null) ? val.UIData.itemName : "");
					recordEvent.Position = val.transform.position;
				}
				instance.QueueCooldown(recordEvent.Actor, RecordEventType.ItemPickedUp, 0.2f, recordEvent);
			}
			catch
			{
			}
		}
	}
	[HarmonyPatch(typeof(Backpack), "RPCAddItemToBackpack")]
	internal static class Patch_BackpackStore
	{
		[HarmonyPostfix]
		private static void Postfix(PhotonView playerView, byte slotID, byte backpackSlotID)
		{
			BackpackStoreRecorder.Record(playerView, slotID, backpackSlotID);
		}
	}
	[HarmonyPatch(typeof(CharacterBackpackHandler), "RPCAddItemToCharacterBackpack")]
	internal static class Patch_BackpackStoreHandler
	{
		[HarmonyPostfix]
		private static void Postfix(PhotonView playerView, byte inventorySlotID, byte backpackSlotID)
		{
			BackpackStoreRecorder.Record(playerView, inventorySlotID, backpackSlotID);
		}
	}
	internal static class BackpackStoreRecorder
	{
		internal static void Record(PhotonView playerView, byte slotID, byte backpackSlotID)
		{
			try
			{
				PeakRecorder instance = PeakRecorder.Instance;
				if ((Object)(object)instance == (Object)null || !instance.IsRecording || PeakRecorder.ReplayActive || (Object)(object)playerView == (Object)null)
				{
					return;
				}
				Player component = ((Component)playerView).GetComponent<Player>();
				if (!((Object)(object)component == (Object)null))
				{
					ItemSlot itemSlot = component.GetItemSlot(slotID);
					if (itemSlot != null && !itemSlot.IsEmpty() && !((Object)(object)itemSlot.prefab == (Object)null))
					{
						RecordEvent recordEvent = new RecordEvent();
						recordEvent.Type = RecordEventType.BackpackStored;
						recordEvent.TimeMs = Mathf.Max(0, PeakRecorder.NetworkTimeMs() + instance.TimeOffsetMs - instance.SessionStartServerMs);
						recordEvent.Actor = (sbyte)(((Object)(object)component.character != (Object)null) ? PeakRecorder.ActorToSbyte(component.character) : (-1));
						recordEvent.Slot = slotID;
						recordEvent.Slot2 = backpackSlotID;
						recordEvent.ItemId = itemSlot.prefab.itemID;
						recordEvent.ItemGuid = ((itemSlot.data != null) ? itemSlot.data.guid : Guid.Empty);
						recordEvent.Text = ((itemSlot.prefab.UIData != null) ? itemSlot.prefab.UIData.itemName : "");
						instance.QueueCooldown(recordEvent.Actor, RecordEventType.BackpackStored, 0.2f, recordEvent);
					}
				}
			}
			catch
			{
			}
		}
	}
	[HarmonyPatch(typeof(PointPinger), "ReceivePoint_Rpc")]
	internal static class Patch_PlayerPing
	{
		[HarmonyPostfix]
		private static void Postfix(PointPinger __instance, Vector3 point, Vector3 hitNormal)
		{
			//IL_0076: Unknown result type (might be due to invalid IL or missing references)
			//IL_0077: 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_007e: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				PeakRecorder instance = PeakRecorder.Instance;
				if (!((Object)(object)instance == (Object)null) && instance.IsRecording && !PeakRecorder.ReplayActive && !((Object)(object)__instance == (Object)null))
				{
					RecordEvent recordEvent = new RecordEvent();
					recordEvent.Type = RecordEventType.Ping;
					recordEvent.TimeMs = Mathf.Max(0, PeakRecorder.NetworkTimeMs() + instance.TimeOffsetMs - instance.SessionStartServerMs);
					Character character = __instance.character;
					recordEvent.Actor = (sbyte)(((Object)(object)character != (Object)null) ? PeakRecorder.ActorToSbyte(character) : (-1));
					recordEvent.Position = point;
					recordEvent.Velocity = hitNormal;
					instance.QueueCooldown(recordEvent.Actor, RecordEventType.Ping, 0.2f, recordEvent);
				}
			}
			catch
			{
			}
		}
	}
	[HarmonyPatch(typeof(Item), "RPC_SetThrownData")]
	internal static class Patch_ItemThrown
	{
		[HarmonyPostfix]
		private static void Postfix(Item __instance, float thrownAmount)
		{
			//IL_00b4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b9: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				PeakRecorder instance = PeakRecorder.Instance;
				if (!((Object)(object)instance == (Object)null) && instance.IsRecording && !((Object)(object)__instance == (Object)null))
				{
					RecordEvent recordEvent = new RecordEvent();
					recordEvent.Type = RecordEventType.ItemThrown;
					recordEvent.TimeMs = Mathf.Max(0, PeakRecorder.NetworkTimeMs() + instance.TimeOffsetMs - instance.SessionStartServerMs);
					recordEvent.Actor = PeakRecorder.ActorToSbyte(__instance.trueHolderCharacter);
					recordEvent.ItemId = __instance.itemID;
					recordEvent.ItemGuid = ((__instance.data != null) ? __instance.data.guid : Guid.Empty);
					recordEvent.Value = (ushort)Mathf.Clamp(Mathf.RoundToInt(thrownAmount * 100f), 0, 65535);
					recordEvent.Position = __instance.transform.position;
					instance.QueueCooldown(recordEvent.Actor, RecordEventType.ItemThrown, 0.15f, recordEvent);
					instance.RequestSceneCensus();
				}
			}
			catch
			{
			}
		}
	}
	[HarmonyPatch(typeof(Luggage), "OpenLuggageRPC")]
	internal static class Patch_LuggageOpened
	{
		private static int _replayOpenLogged;

		private const int ReplayOpenLogLimit = 40;

		[HarmonyPrefix]
		private static void Prefix(Luggage __instance, bool spawnItems)
		{
			try
			{
			}
			catch
			{
			}
		}

		private static string DescribeReplayLuggageCaller()
		{
			try
			{
				StackTrace stackTrace = new StackTrace(1, fNeedFileInfo: false);
				string text = "";
				int num = 0;
				for (int i = 0; i < stackTrace.FrameCount; i++)
				{
					if (num >= 2)
					{
						break;
					}
					MethodBase methodBase = stackTrace.GetFrame(i)?.GetMethod();
					if (!(methodBase == null))
					{
						string text2 = ((methodBase.DeclaringType != null) ? methodBase.DeclaringType.Name : "?");
						if (!(text2 == "Patch_LuggageOpened") && !(text2 == "Luggage"))
						{
							text = text + ((text.Length > 0) ? " <- " : "") + text2 + "." + methodBase.Name;
							num++;
						}
					}
				}
				return (text.Length > 0) ? text : "?";
			}
			catch
			{
				return "?";
			}
		}

		[HarmonyPostfix]
		private static void Postfix(Luggage __instance, bool spawnItems)
		{
			//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)
			try
			{
				PeakRecorder instance = PeakRecorder.Instance;
				if (!((Object)(object)instance == (Object)null) && instance.IsRecording && !((Object)(object)__instance == (Object)null))
				{
					RecordEvent recordEvent = new RecordEvent();
					recordEvent.Type = RecordEventType.LuggageOpened;
					recordEvent.TimeMs = Mathf.Max(0, PeakRecorder.NetworkTimeMs() + instance.TimeOffsetMs - instance.SessionStartServerMs);
					recordEvent.Actor = -1;
					recordEvent.Slot = (spawnItems ? ((byte)1) : ((byte)0));
					recordEvent.Text = ((Object)((Component)__instance).gameObject).name;
					recordEvent.Position = ((Component)__instance).transform.position;
					instance.QueueCooldown(-1, RecordEventType.LuggageOpened, 0.2f, recordEvent);
				}
			}
			catch
			{
			}
		}
	}
	[HarmonyPatch(typeof(CharacterItems), "DropItemRpc")]
	internal static class Patch_ItemDropRpc
	{
		[HarmonyPostfix]
		private static void Postfix(CharacterItems __instance, float throwCharge, byte slotID)
		{
			//IL_00f7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fc: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				PeakRecorder instance = PeakRecorder.Instance;
				if ((Object)(object)instance == (Object)null || !instance.IsRecording || (Object)(object)__instance == (Object)null)
				{
					return;
				}
				Character character = __instance.character;
				RecordEvent recordEvent = new RecordEvent();
				recordEvent.Type = ((throwCharge > 0.05f) ? RecordEventType.ItemThrown : RecordEventType.ItemDropped);
				recordEvent.TimeMs = Mathf.Max(0, PeakRecorder.NetworkTimeMs() + instance.TimeOffsetMs - instance.SessionStartServerMs);
				recordEvent.Actor = PeakRecorder.ActorToSbyte(character);
				recordEvent.Slot = slotID;
				recordEvent.Value = (ushort)Mathf.Clamp(Mathf.RoundToInt(throwCharge * 100f), 0, 65535);
				if ((Object)(object)character != (Object)null && (Object)(object)character.data != (Object)null)
				{
					Item currentItem = character.data.currentItem;
					if ((Object)(object)currentItem != (Object)null)
					{
						recordEvent.ItemId = currentItem.itemID;
						recordEvent.ItemGuid = ((currentItem.data != null) ? currentItem.data.guid : Guid.Empty);
						recordEvent.Position = currentItem.transform.position;
						try
						{
							recordEvent.Text = ((currentItem.UIData != null) ? currentItem.UIData.itemName : "");
						}
						catch
						{
						}
					}
				}
				instance.QueueCooldown(recordEvent.Actor, recordEvent.Type, 0.15f, recordEvent);
				instance.RequestSceneCensus();
			}
			catch
			{
			}
		}
	}
	[HarmonyPatch(typeof(ItemCooking), "SyncCookingStateRPC")]
	internal static class Patch_ItemCooking
	{
		[HarmonyPostfix]
		private static void Postfix(ItemCooking __instance)
		{
			//IL_00ca: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cf: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				PeakRecorder instance = PeakRecorder.Instance;
				if ((Object)(object)instance == (Object)null || !instance.IsRecording || (Object)(object)__instance == (Object)null)
				{
					return;
				}
				Item item = ((ItemComponent)__instance).item;
				RecordEvent recordEvent = new RecordEvent();
				recordEvent.Type = RecordEventType.ItemCooked;
				recordEvent.TimeMs = Mathf.Max(0, PeakRecorder.NetworkTimeMs() + instance.TimeOffsetMs - instance.SessionStartServerMs);
				recordEvent.Actor = PeakRecorder.ActorToSbyte(((Object)(object)item != (Object)null) ? item.trueHolderCharacter : null);
				recordEvent.Value = (ushort)Mathf.Clamp(__instance.timesCookedLocal, 0, 65535);
				if ((Object)(object)item != (Object)null)
				{
					recordEvent.ItemId = item.itemID;
					recordEvent.ItemGuid = ((item.data != null) ? item.data.guid : Guid.Empty);
					recordEvent.Position = item.transform.position;
					try
					{
						recordEvent.Text = ((item.UIData != null) ? item.UIData.itemName : "");
					}
					catch
					{
					}
				}
				instance.QueueCooldown(recordEvent.Actor, RecordEventType.ItemCooked, 0.3f, recordEvent);
			}
			catch
			{
			}
		}
	}
	[HarmonyPatch(typeof(PhotonNetwork), "Instantiate", new Type[]
	{
		typeof(string),
		typeof(Vector3),
		typeof(Quaternion),
		typeof(byte),
		typeof(object[])
	})]
	internal static class Patch_PhotonInstantiate
	{
		[HarmonyPostfix]
		private static void Postfix(string __0, Vector3 __1, Quaternion __2, object[] __4, GameObject __result)
		{
			//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)
			try
			{
				PeakRecorder instance = PeakRecorder.Instance;
				if (!((Object)(object)instance == (Object)null) && instance.IsRecording)
				{
					instance.AddPrefabSpawn(__0, __1, __2, __result, __4);
				}
			}
			catch
			{
			}
		}
	}
	[HarmonyPatch(typeof(Object), "Instantiate", new Type[]
	{
		typeof(Object),
		typeof(Vector3),
		typeof(Quaternion)
	})]
	internal static class Patch_ObjectInstantiatePositional
	{
		[HarmonyPostfix]
		private static void Postfix(Object __result)
		{
			try
			{
				PeakRecorder instance = PeakRecorder.Instance;
				if (!((Object)(object)instance == (Object)null) && instance.IsRecording)
				{
					instance.AddInstantiatedObject((GameObject)(object)((__result is GameObject) ? __result : null));
				}
			}
			catch
			{
			}
		}
	}
	[HarmonyPatch(typeof(PhotonView), "RPC", new Type[]
	{
		typeof(string),
		typeof(RpcTarget),
		typeof(object[])
	})]
	internal static class Patch_PhotonViewRpc
	{
		[ThreadStatic]
		internal static bool LocalSendInProgress;

		internal static byte PendingTarget = 8;

		[HarmonyPrefix]
		private static void Prefix(PhotonView __instance, string __0, RpcTarget __1, object[] __2)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			LocalSendInProgress = true;
			PendingTarget = (byte)__1;
		}

		[HarmonyFinalizer]
		private static void Finalizer()
		{
			LocalSendInProgress = false;
		}

		[HarmonyPostfix]
		private static void Postfix(PhotonView __instance, string __0, RpcTarget __1, object[] __2)
		{
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			//IL_0052: 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_001e: Invalid comparison between Unknown and I4
			//IL_002c: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Invalid comparison between Unknown and I4
			//IL_0020: Unknown result type (might be due to invalid IL or missing references)
			//IL_0022: Invalid comparison between Unknown and I4
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_0026: Invalid comparison between Unknown and I4
			try
			{
				PeakRecorder instance = PeakRecorder.Instance;
				if ((Object)(object)instance == (Object)null || !instance.IsRecording)
				{
					return;
				}
				bool flag = (int)__1 == 0 || (int)__1 == 3 || (int)__1 == 5 || (int)__1 == 6;
				if ((int)__1 == 2)
				{
					try
					{
						flag = PhotonNetwork.IsMasterClient;
					}
					catch
					{
						flag = false;
					}
				}
				if (!flag)
				{
					instance.AddRpcCall(__instance, __0, __2, PeakRecorder.LocalActorNumber(), -1, null, PhotonNetwork.ServerTimestamp, (byte)__1);
				}
			}
			catch
			{
			}
		}
	}
	[HarmonyPatch(typeof(PhotonView), "RPC", new Type[]
	{
		typeof(string),
		typeof(Player),
		typeof(object[])
	})]
	internal static class Patch_PhotonViewRpcTargeted
	{
		[HarmonyPrefix]
		private static void Prefix(Player __1)
		{
			try
			{
				Player localPlayer = PhotonNetwork.LocalPlayer;
				Patch_PhotonViewRpc.LocalSendInProgress = __1 != null && localPlayer != null && __1.ActorNumber == localPlayer.ActorNumber;
			}
			catch
			{
				Patch_PhotonViewRpc.LocalSendInProgress = false;
			}
		}

		[HarmonyFinalizer]
		private static void Finalizer()
		{
			Patch_PhotonViewRpc.LocalSendInProgress = false;
		}

		[HarmonyPostfix]
		private static void Postfix(PhotonView __instance, string __0, Player __1, object[] __2)
		{
			try
			{
				PeakRecorder instance = PeakRecorder.Instance;
				if (!((Object)(object)instance == (Object)null) && instance.IsRecording)
				{
					int num = ((__1 == null) ? (-1) : __1.ActorNumber);
					int num2 = PeakRecorder.LocalActorNumber();
					if (num != num2)
					{
						instance.AddRpcCall(__instance, __0, __2, num2, num, null, PhotonNetwork.ServerTimestamp, 7);
					}
				}
			}
			catch
			{
			}
		}
	}
	[HarmonyPatch(typeof(PhotonNetwork), "ExecuteRpc", new Type[]
	{
		typeof(Hashtable),
		typeof(Player)
	})]
	internal static class Patch_PhotonNetworkExecuteRpc
	{
		[HarmonyPrefix]
		private static void Prefix(Hashtable rpcData, Player sender)
		{
			try
			{
				PeakRecorder instance = PeakRecorder.Instance;
				if ((Object)(object)instance == (Object)null || !instance.IsRecording || rpcData == null)
				{
					return;
				}
				if (Patch_PhotonViewRpc.LocalSendInProgress && !instance.WasRaisedJustNow(rpcData))
				{
					int senderActor = PeakRecorder.LocalActorNumber();
					try
					{
						if (sender != null)
						{
							senderActor = sender.ActorNumber;
						}
					}
					catch
					{
					}
					instance.NoteNetEventLocalRpc(rpcData, senderActor);
				}
				instance.NoteRpcExecuted(rpcData, sender, Patch_PhotonViewRpc.LocalSendInProgress);
			}
			catch
			{
			}
			finally
			{
				Patch_PhotonViewRpc.LocalSendInProgress = false;
			}
		}
	}
	[HarmonyPatch(typeof(PhotonView), "SerializeView")]
	internal static class Patch_PhotonViewSerializeView
	{
		[HarmonyPostfix]
		private static void Postfix(PhotonView __instance, PhotonStream stream)
		{
			long startTs = PerfProbe.Enter();
			try
			{
				PeakRecorder instance = PeakRecorder.Instance;
				if (!((Object)(object)instance == (Object)null) && instance.IsRecording && stream != null && stream.IsWriting)
				{
					instance.NoteSyncSent(__instance, stream);
				}
			}
			catch
			{
			}
			finally
			{
				PerfProbe.Leave(3, startTs);
			}
		}
	}
	[HarmonyPatch(typeof(PhotonView), "DeserializeView")]
	internal static class Patch_PhotonViewDeserializeView
	{
		[HarmonyPrefix]
		private static void Prefix(PhotonView __instance, PhotonStream stream, PhotonMessageInfo info)
		{
			//IL_002c: 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)
			long startTs = PerfProbe.Enter();
			try
			{
				PeakRecorder instance = PeakRecorder.Instance;
				if ((Object)(object)instance == (Object)null || !instance.IsRecording || stream == null || stream.IsWriting)
				{
					return;
				}
				int senderActor = -1;
				try
				{
					if (info.Sender != null)
					{
						senderActor = info.Sender.ActorNumber;
					}
				}
				catch
				{
				}
				instance.NoteSyncPayload(__instance.ViewID, stream.ToArray(), senderActor);
			}
			catch
			{
			}
			finally
			{
				PerfProbe.Leave(4, startTs);
			}
		}
	}
	[HarmonyPatch(typeof(PhotonNetwork), "RaiseEventInternal", new Type[]
	{
		typeof(byte),
		typeof(object),
		typeof(RaiseEventOptions),
		typeof(SendOptions)
	})]
	internal static class Patch_PhotonNetworkRaiseEventInternal
	{
		[HarmonyPrefix]
		private static void Prefix(byte __0, object __1)
		{
			long startTs = PerfProbe.Enter();
			try
			{
				PeakRecorder instance = PeakRecorder.Instance;
				if (!((Object)(object)instance == (Object)null) && instance.IsRecording && !PeakRecorder.ReplayActive)
				{
					instance.NoteNetEventRaised(__0, __1);
				}
			}
			catch
			{
			}
			finally
			{
				PerfProbe.Leave(5, startTs);
			}
		}
	}
	[HarmonyPatch(typeof(LoadBalancingClient), "OnEvent")]
	internal static class Patch_LoadBalancingClientOnEvent
	{
		[HarmonyPrefix]
		private static void Prefix(EventData photonEvent)
		{
			long startTs = PerfProbe.Enter();
			try
			{
				if (photonEvent == null)
				{
					return;
				}
				if (photonEvent.Code == 220)
				{
					Identify.HandleIncoming(photonEvent.Sender, photonEvent[photonEvent.CustomDataKey]);
					return;
				}
				PeakRecorder instance = PeakRecorder.Instance;
				if (!((Object)(object)instance == (Object)null) && instance.IsRecording && !PeakRecorder.ReplayActive)
				{
					object content = photonEvent[photonEvent.CustomDataKey];
					instance.NoteNetEventReceived(photonEvent.Code, content, photonEvent.Sender);
				}
			}
			catch
			{
			}
			finally
			{
				PerfProbe.Leave(6, startTs);
			}
		}
	}
	[HarmonyPatch(typeof(PhotonNetwork), "get_IsMasterClient")]
	internal static class Patch_PhotonNetworkIsMasterClient
	{
		[HarmonyPrefix]
		private static bool Prefix(ref bool __result)
		{
			long startTs = PerfProbe.Enter();
			if (!PeakRecorder.ReplayActive)
			{
				PerfProbe.Leave(2, startTs);
				return true;
			}
			if (RecordSettings.ReplayAsHost)
			{
				PerfProbe.Leave(2, startTs);
				return true;
			}
			__result = false;
			PerfProbe.Leave(2, startTs);
			return false;
		}
	}
	[HarmonyPatch(typeof(Player), "SyncInventoryRPC")]
	internal static class Patch_PlayerSyncInventoryRpcForce
	{
		[HarmonyPrefix]
		private static void Prefix(ref bool __1)
		{
			if (PeakRecorder.ReplayActive)
			{
				__1 = true;
			}
		}
	}
	[HarmonyPatch(typeof(GUIManager), "UpdateSpectate")]
	internal static class Patch_GuiManagerUpdateSpectate
	{
		[HarmonyPrefix]
		private static bool Prefix()
		{
			if (!PeakRecorder.ReplayActive)
			{
				return true;
			}
			return (Object)(object)Character.localCharacter != (Object)null;
		}
	}
	[HarmonyPatch(typeof(AchievementManager), "AddToRunBasedInt")]
	internal static class Patch_AchievementAddToRunBasedInt
	{
		[HarmonyPrefix]
		private static bool Prefix(AchievementManager __instance)
		{
			if (!PeakRecorder.ReplayActive)
			{
				return true;
			}
			return ReplayGuards.AchievementDataReady(__instance);
		}
	}
	[HarmonyPatch(typeof(AchievementManager), "GetRunBasedInt")]
	internal static class Patch_AchievementGetRunBasedInt
	{
		[HarmonyPrefix]
		private static bool Prefix(AchievementManager __instance, ref int __result)
		{
			if (!PeakRecorder.ReplayActive)
			{
				return true;
			}
			if (ReplayGuards.AchievementDataReady(__instance))
			{
				return true;
			}
			__result = 0;
			return false;
		}
	}
	[HarmonyPatch(typeof(PointPinger), "ReceivePoint_Rpc")]
	internal static class Patch_PointPingerReceivePoint
	{
		[HarmonyPrefix]
		private static bool Prefix()
		{
			if (!PeakRecorder.ReplayActive)
			{
				return true;
			}
			return (Object)(object)Character.localCharacter != (Object)null;
		}
	}
	internal static class ReplayGuards
	{
		public static bool AchievementDataReady(AchievementManager manager)
		{
			//IL_000a: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				return (Object)(object)manager != (Object)null && manager.runBasedValueData.runBasedInts != null;
			}
			catch
			{
				return false;
			}
		}

		public static void LogMapSeed(string phase)
		{
			try
			{
				int num = int.MinValue;
				LevelGeneration val = Object.FindObjectOfType<LevelGeneration>();
				if ((Object)(object)val != (Object)null)
				{
					num = val.seed;
				}
				int num2 = ReadExternalMapSeed();
				Plugin.Log?.LogInfo("地图 seed [" + phase + "]: LevelGeneration.seed=" + ((num == int.MinValue) ? "无实例" : num.ToString()) + ((num2 == int.MinValue) ? "" : $", 第三方地图 mod seed={num2}") + (((Object)(object)val == (Object)null) ? "" : $", 网格={val.updateLightmap}"));
			}
			catch (Exception ex)
			{
				Plugin.Log?.LogWarning("读取地图 seed 失败: " + ex.Message);
			}
		}

		private static int ReadExternalMapSeed()
		{
			try
			{
				Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();
				for (int i = 0; i < assemblies.Length; i++)
				{
					Type type = assemblies[i].GetType("TerrainRandomiser.Plugin", throwOnError: false);
					if (type == null)
					{
						continue;
					}
					object obj = type.GetProperty("Instance", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic)?.GetValue(null, null);
					if (obj == null)
					{
						continue;
					}
					object obj2 = obj.GetType().GetField("mapSettings", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)?.GetValue(obj);
					if (obj2 != null)
					{
						object obj3 = obj2.GetType().GetField("seed", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)?.GetValue(obj2);
						if (obj3 is int)
						{
							return (int)obj3;
						}
					}
				}
			}
			catch
			{
			}
			return int.MinValue;
		}

		public static void MarkInitialSpawnersDone()
		{
			try
			{
				MapHandler val = Object.FindObjectOfType<MapHandler>();
				if (!((Object)(object)val == (Object)null))
				{
					FieldInfo field = typeof(MapHandler).GetField("hasSpawnedInitialSpawners", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
					if (field == null)
					{
						Plugin.Log?.LogWarning("回放(主机模式): 找不到 MapHandler.hasSpawnedInitialSpawners —— 初始物品可能被重复生成。");
						return;
					}
					field.SetValue(val, true);
					Plugin.Log?.LogInfo("回放(主机模式): 已标记 MapHandler 初始物品生成完毕 —— 世界物品只由录制事件重建,不会被主机分支重复生成。");
				}
			}
			catch (Exception ex)
			{
				Plugin.Log?.LogWarning("标记初始生成完毕失败: " + ex.Message);
			}
		}
	}
	[HarmonyPatch(typeof(StaminaBar), "Update")]
	internal static class Patch_StaminaBarNumbers
	{
		private static TextMeshProUGUI _text;

		private static StaminaBar _owner;

		private static readonly Dictionary<string, TextMeshProUGUI> BarTexts = new Dictionary<string, TextMeshProUGUI>();

		[HarmonyPostfix]
		private static void Postfix(StaminaBar __instance)
		{
			//IL_0055: 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_014a: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				if (!PeakRecorder.ReplayActive)
				{
					HideAllBarTexts();
					return;
				}
				Character observedCharacter = Character.observedCharacter;
				if ((Object)(object)observedCharacter == (Object)null || (Object)(object)observedCharacter.data == (Object)null || (Object)(object)__instance == (Object)null || (Object)(object)__instance.fullBar == (Object)null)
				{
					return;
				}
				float num = Mathf.Max(1f, __instance.fullBar.sizeDelta.x);
				SetBarText(__instance.staminaBar, ((Object)__instance.staminaBar).name, Mathf.Clamp01(observedCharacter.data.currentStamina) * 100f);
				float num2 = (((Object)(object)__instance.extraBarStamina == (Object)null) ? 0f : __instance.extraBarStamina.sizeDelta.x);
				SetBarText(__instance.extraBarStamina, "ExtraStamina", Mathf.Clamp01(num2 / num) * 100f);
				if (__instance.afflictions == null)
				{
					return;
				}
				for (int i = 0; i < __instance.afflictions.Length; i++)
				{
					BarAffliction val = __instance.afflictions[i];
					if (!((Object)(object)val == (Object)null))
					{
						SetBarText(value: (val.isPetrify ? Mathf.Clamp01((float)observedCharacter.data.petrifyAmount / 100f) : ((observedCharacter.refs == null || !((Object)(object)observedCharacter.refs.afflictions != (Object)null)) ? Mathf.Clamp01(val.size / num) : Mathf.Clamp01(observedCharacter.refs.afflictions.GetCurrentStatus(val.afflictionType)))) * 100f, bar: val.rtf, key: ((Object)((Component)val).gameObject).name);
					}
				}
			}
			catch
			{
			}
		}

		private static void HideAllBarTexts()
		{
			try
			{
				foreach (KeyValuePair<string, TextMeshProUGUI> barText in BarTexts)
				{
					if ((Object)(object)barText.Value != (Object)null && ((Component)barText.Value).gameObject.activeSelf)
					{
						((Component)barText.Value).gameObject.SetActive(false);
					}
				}
			}
			catch
			{
			}
		}

		private static void SetBarText(RectTransform bar, string key, float value)
		{
			//IL_0036: Unknown result type (might be due to invalid IL or missing references)
			//IL_003b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0099: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ae: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c3: 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_00e2: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				if (!((Object)(object)bar == (Object)null) && !string.IsNullOrEmpty(key))
				{
					if (!BarTexts.TryGetValue(key, out var value2) || (Object)(object)value2 == (Object)null)
					{
						GameObject val = new GameObject("PeakRecord_BarText");
						val.transform.SetParent((Transform)(object)bar, false);
						value2 = val.AddComponent<TextMeshProUGUI>();
						((TMP_Text)value2).fontSize = 16f;
						((TMP_Text)value2).enableAutoSizing = true;
						((TMP_Text)value2).fontSizeMin = 7f;
						((TMP_Text)value2).fontSizeMax = 16f;
						((TMP_Text)value2).alignment = (TextAlignmentOptions)514;
						((Graphic)value2).raycastTarget = false;
						RectTransform rectTransform = ((TMP_Text)value2).rectTransform;
						rectTransform.anchorMin = new Vector2(0f, 0.5f);
						rectTransform.anchorMax = new Vector2(1f, 0.5f);
						rectTransform.pivot = new Vector2(0.5f, 0.5f);
						rectTransform.anchoredPosition = Vector2.zero;
						rectTransform.sizeDelta = new Vector2(0f, 16f);
						BarTexts[key] = value2;
					}
					string text = Mathf.RoundToInt(value).ToString();
					bool flag = value >= 0.5f;
					if (((Component)value2).gameObject.activeSelf != flag)
					{
						((Component)value2).gameObject.SetActive(flag);
					}
					if (flag)
					{
						((TMP_Text)value2).text = text;
					}
				}
			}
			catch
			{
			}
		}
	}
	[HarmonyPatch(typeof(GhostBallSpawner), "Update")]
	internal static class Patch_GhostBallSpawnerUpdate
	{
		[HarmonyPrefix]
		private static bool Prefix()
		{
			return !PeakRecorder.ReplayActive;
		}

		[HarmonyPrefix]
		[HarmonyPatch(typeof(GhostBallSpawner), "ForceSpawnGhost")]
		private static bool ForceSpawnGhostPrefix()
		{
			return !PeakRecorder.ReplayActive;
		}
	}
	[HarmonyPatch(typeof(HideTheBody), "Update")]
	internal static class Patch_HideTheBodyObserved
	{
		private static bool _swapped;

		[HarmonyPrefix]
		private static void Prefix(out Character __state)
		{
			__state = null;
			_swapped = false;
			if (PeakRecorder.ReplayActive && ReplayCameraController.Mode == ReplayCameraController.ViewMode.FirstPerson)
			{
				Character watched = ReplayCameraController.Watched;
				if (!((Object)(object)watched == (Object)null) && !((Object)(object)Character.localCharacter == (Object)(object)watched))
				{
					__state = Character.localCharacter;
					Character.localCharacter = watched;
					_swapped = true;
				}
			}
		}

		[HarmonyPostfix]
		private static void Postfix(Character __state)
		{
			if (_swapped)
			{
				_swapped = false;
				Character.localCharacter = __state;
			}
		}
	}
	[HarmonyPatch(typeof(StatusEmitter), "Update")]
	internal static class Patch_StatusEmitterObserved
	{
		private struct LocalSwapState
		{
			public Character Original;

			public bool Swapped;
		}

		[HarmonyPrefix]
		private static void Prefix(out LocalSwapState __state)
		{
			__state = default(LocalSwapState);
			try
			{
				if (PeakRecorder.ReplayActive)
				{
					Character observedCharacter = Character.observedCharacter;
					if (!((Object)(object)observedCharacter == (Object)null) && !((Object)(object)observedCharacter == (Object)(object)Character.localCharacter) && observedCharacter.refs != null && !((Object)(object)observedCharacter.refs.afflictions == (Object)null))
					{
						__state = new LocalSwapState
						{
							Original = Character.localCharacter,
							Swapped = true
						};
						Character.localCharacter = observedCharacter;
					}
				}
			}
			catch
			{
			}
		}

		[HarmonyPostfix]
		private static void Postfix(LocalSwapState __state)
		{
			try
			{
				if (__state.Swapped)
				{
					Character.localCharacter = __state.Original;
				}
			}
			catch
			{
			}
		}
	}
	[HarmonyPatch(typeof(CharacterBackpackHandler), "LateUpdate")]
	internal static class Patch_BackpackViewObserved
	{
		[HarmonyPostfix]
		private static void Postfix(CharacterBackpackHandler __instance)
		{
			if (!PeakRecorder.ReplayActive || (Object)(object)__instance == (Object)null || ReplayCameraController.Mode != ReplayCameraController.ViewMode.FirstPerson)
			{
				return;
			}
			Character watched = ReplayCameraController.Watched;
			if ((Object)(object)watched == (Object)null || (Object)(object)__instance.character != (Object)(object)watched)
			{
				return;
			}
			try
			{
				if ((Object)(object)__instance.backpackVisuals != (Object)null)
				{
					__instance.backpackVisuals.SetViewActive(false);
				}
				if ((Object)(object)__instance.fannypackVisuals != (Object)null)
				{
					__instance.fannypackVisuals.SetViewActive(false);
				}
				if ((Object)(object)__instance.jetpackVisuals != (Object)null)
				{
					__instance.jetpackVisuals.SetViewActive(false);
				}
				if ((Object)(object)__instance.rocketpackVisuals != (Object)null)
				{
					__instance.rocketpackVisuals.SetViewActive(false);
				}
			}
			catch
			{
			}
		}
	}
	[HarmonyPatch(typeof(NetworkConnector), "OnDisconnected")]
	internal static class Patch_ReplayDisableDisconnectedModal
	{
		[HarmonyPrefix]
		private static bool Prefix()
		{
			return !PeakRecorder.ReplayActive;
		}
	}
	[HarmonyPatch(typeof(MainMenuPageHandler), "Update")]
	internal static class Patch_ReplaySkipMainMenuDisconnected
	{
		[HarmonyPrefix]
		private static bool Prefix()
		{
			return !PeakRecorder.ReplayActive;
		}
	}
	public static class PatchRegistry
	{
		public static readonly Type[] PatchTypes = new Type[78]
		{
			typeof(Patch_RunManagerStartRun),
			typeof(Patch_RunManagerEndGame),
			typeof(Patch_ReplaySkipQuicksaveSave),
			typeof(Patch_ReplaySkipQuicksaveDestroy),
			typeof(Patch_ReplaySkipQuicksaveToast),
			typeof(Patch_ReplaySkipCharacterEndGame),
			typeof(Patch_MapHandlerInitializeMap),
			typeof(Patch_VoiceOnAudioFilterRead),
			typeof(Patch_LocalMicWrapperRead),
			typeof(Patch_LocalMicPusherPush),
			typeof(Patch_LocalMicWrapperPusherFilterRead),
			typeof(Patch_ReplayMuteLandImpactAudio),
			typeof(Patch_ReplayMuteFallAudio),
			typeof(Patch_ReplayMassAfflictionTarget),
			typeof(Patch_ReplayAfflictionLifetime),
			typeof(Patch_ItemConsume),
			typeof(Patch_CampfireLight),
			typeof(Patch_CampfireExtinguish),
			typeof(Patch_CarryStart),
			typeof(Patch_ItemPickup),
			typeof(Patch_ItemDropRpc),
			typeof(Patch_ItemThrown),
			typeof(Patch_ItemCooking),
			typeof(Patch_LuggageOpened),
			typeof(Patch_PhotonInstantiate),
			typeof(Patch_ObjectInstantiatePositional),
			typeof(Patch_PhotonViewRpc),
			typeof(Patch_PhotonViewRpcTargeted),
			typeof(Patch_PhotonNetworkExecuteRpc),
			typeof(Patch_PhotonViewSerializeView),
			typeof(Patch_PhotonViewDeserializeView),
			typeof(Patch_PhotonNetworkRaiseEventInternal),
			typeof(Patch_LoadBalancingClientOnEvent),
			typeof(Patch_PhotonNetworkIsMasterClient),
			typeof(Patch_PlayerShaderParamsUpdate),
			typeof(Patch_StaminaBarNumbers),
			typeof(Patch_GhostBallSpawnerUpdate),
			typeof(Patch_HideTheBodyObserved),
			typeof(Patch_BackpackViewObserved),
			typeof(Patch_StatusEmitterObserved),
			typeof(Patch_GuiManagerUpdatePaused),
			typeof(Patch_PauseMenuHandlerOnEnable),
			typeof(Patch_PauseMenuQuit),
			typeof(Patch_ReplayBlockNewPlayerSpawn),
			typeof(Patch_ReplayBlockMiniRunSpawn),
			typeof(Patch_ReplayBlockReconnectSpawn),
			typeof(Patch_ReplayBlockSpawnMyPlayerCharacter),
			typeof(Patch_GuiManagerUpdateWindowStatus),
			typeof(Patch_GuiManagerUpdateReticle),
			typeof(Patch_InteractionLateUpdate),
			typeof(Patch_ReplayDisableDisconnectedModal),
			typeof(Patch_ReplaySkipMainMenuDisconnected),
			typeof(Patch_PlayerSyncInventoryRpcForce),
			typeof(Patch_GuiManagerUpdateSpectate),
			typeof(Patch_AchievementAddToRunBasedInt),
			typeof(Patch_AchievementGetRunBasedInt),
			typeof(Patch_PointPingerReceivePoint),
			typeof(Patch_IsLookedAtThrottle),
			typeof(Patch_DynamicBoneDistantDisable),
			typeof(Patch_ReplayRagdollLod),
			typeof(Perf_GenericOptimizerUpdateOptimization),
			typeof(Perf_ItemOptimizationManagerUpdate),
			typeof(Perf_CharacterUpdate),
			typeof(Perf_CharacterMovementUpdate),
			typeof(Perf_CharacterAnimationsUpdate),
			typeof(Perf_CharacterAfflictionsUpdate),
			typeof(Perf_CharacterStatsUpdate),
			typeof(Perf_CharacterVoiceHandlerUpdate),
			typeof(Perf_CharacterGrabbingUpdate),
			typeof(Perf_CharacterCustomizationUpdate),
			typeof(Perf_CharacterSyncerUpdate),
			typeof(Perf_CharacterSyncerFixedUpdate),
			typeof(Perf_ItemPhysicsSyncerFixedUpdate),
			typeof(Perf_HideTheBodyUpdate),
			typeof(Perf_CharacterBackpackHandlerLateUpdate),
			typeof(Perf_StaminaBarUpdate),
			typeof(Perf_ReplayViewUpdate),
			typeof(Perf_ReplayViewLateUpdate)
		};
	}
	internal static class Identify
	{
		internal sealed class Entry
		{
			public int Actor;

			public string ModVersion = "";

			public bool Plus;

			public bool Recording;

			public int DurationMs;

			public int NetEvents;

			public int Samples;

			public string Session = "";

			public float LastSeenAt;

			public int Replies;
		}

		private static bool _sendErrorLogged;

		internal static bool Enabled => RecordSettings.IdentifyEnabled;

		internal static bool IsPlusBuild => false;

		internal static List<Entry> Detected => new List<Entry>();

		internal static void OnNewPlayerDetected(int actor)
		{
		}

		private static void QueryAll()
		{
		}

		private static void SendReply(int targetActor)
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_000d: Expected O, but got Unknown
			if (targetActor > 0)
			{
				RaiseEventOptions val = new RaiseEventOptions();
				val.TargetActors = new int[1] { targetActor };
				Send(3, withRecordInfo: true, val);
			}
		}

		private static void Send(byte sub, bool withRecordInfo, RaiseEventOptions options)
		{
			//IL_0018: Unknown result type (might be due to invalid IL or missing references)
			if (!CanSend())
			{
				return;
			}
			try
			{
				Hashtable val = BuildPayload(sub, withRecordInfo);
				PhotonNetwork.RaiseEvent((byte)220, (object)val, options, SendOptions.SendReliable);
			}
			catch (Exception ex)
			{
				if (!_sendErrorLogged)
				{
					_sendErrorLogged = true;
					Plugin.Log?.LogWarning("[识别] 发送失败: " + ex.Message);
				}
			}
		}

		private static bool CanSend()
		{
			try
			{
				if (PeakRecorder.ReplayActive)
				{
					return false;
				}
				return PhotonNetwork.InRoom && !PhotonNetwork.OfflineMode;
			}
			catch
			{
				return false;
			}
		}

		private static Hashtable BuildPayload(byte sub, bool withRecordInfo)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: Expected O, but got Unknown
			Hashtable val = new Hashtable();
			val[(byte)1] = sub;
			val[(byte)2] = Plugin.Version ?? "";
			val[(byte)3] = IsPlusBuild;
			if (!withRecordInfo)
			{
				return val;
			}
			PeakRecorder instance = PeakRecorder.Instance;
			bool flag = (Object)(object)instance != (Object)null && instance.IsRecording;
			val[(byte)4] = flag;
			if (!flag)
			{
				return val;
			}
			val[(byte)8] = ShortSession(instance.SessionId);
			val[(byte)5] = instance.DurationMs;
			val[(byte)6] = instance.NetEventCount;
			val[(byte)7] = instance.SampleCount;
			return val;
		}

		private static string ShortSession(string sessionId)
		{
			if (string.IsNullOrEmpty(sessionId))
			{
				return "";
			}
			if (sessionId.Length > 8)
			{
				return sessionId.Substring(0, 8);
			}
			return sessionId;
		}

		internal static void HandleIncoming(int sender, object content)
		{
			try
			{
				Hashtable val = (Hashtable)((content is Hashtable) ? content : null);
				if (val != null && sender > 0 && ReadByte(val, 1) == 2)
				{
					SendReply(sender);
				}
			}
			catch
			{
			}
		}

		internal static void Tick()
		{
		}

		internal static string Describe()
		{
			return "";
		}

		private static string FormatDuration(int ms)
		{
			if (ms <= 0)
			{
				return "0:00";
			}
			int num = ms / 1000;
			return num / 60 + ":" + (num % 60).ToString("00");
		}

		private static byte ReadByte(Hashtable table, byte key)
		{
			if (!((Dictionary<object, object>)(object)table).TryGetValue((object)key, out object value) || value == null)
			{
				return 0;
			}
			try
			{
				return Convert.ToByte(value);
			}
			catch
			{
				return 0;
			}
		}

		private static bool ReadBool(Hashtable table, byte key)
		{
			if (!((Dictionary<object, object>)(object)table).TryGetValue((object)key, out object value) || value == null)
			{
				return false;
			}
			try
			{
				return Convert.ToBoolean(value);
			}
			catch
			{
				return false;
			}
		}

		private static int ReadInt(Hashtable table, byte key)
		{
			if (!((Dictionary<object, object>)(object)table).TryGetValue((object)key, out object value) || value == null)
			{
				return 0;
			}
			try
			{
				return Convert.ToInt32(value);
			}
			catch
			{
				return 0;
			}
		}

		private static string ReadString(Hashtable table, byte key)
		{
			if (!((Dictionary<object, object>)(object)table).TryGetValue((object)key, out object value) || value == null)
			{
				return "";
			}
			try
			{
				return Convert.ToString(value) ?? "";
			}
			catch
			{
				return "";
			}
		}
	}
	internal static class IdentifyProtocol
	{
		internal const byte EventCode = 220;

		internal const byte SubIdentify = 1;

		internal const byte SubQuery = 2;

		internal const byte SubReply = 3;

		internal const byte KeySub = 1;

		internal const byte KeyVersion = 2;

		internal const byte KeyPlus = 3;

		internal const byte KeyRecording = 4;

		internal const byte KeyDurationMs = 5;

		internal const byte KeyNetEvents = 6;

		internal const byte KeySamples = 7;

		internal const byte KeySession = 8;
	}
	internal static class Loc
	{
		internal const int ModeAuto = 0;

		internal const int ModeEnglish = 1;

		internal const int ModeChinese = 2;

		private static readonly Dictionary<string, string> English = new Dictionary<string, string>(StringComparer.Ordinal);

		private static readonly Dictionary<string, string> Chinese = new Dictionary<string, string>(StringComparer.Ordinal);

		private static readonly Dictionary<string, string> ChineseToEnglish = new Dictionary<string, string>(StringComparer.Ordinal);

		private static bool _initialized;

		private static string _lastResolved = "";

		internal static string Language { get; private set; } = "en";

		internal static string LanguageDirectory
		{
			get
			{
				try
				{
					string settingsPath = RecordSettings.SettingsPath;
					string text = (string.IsNullOrEmpty(settingsPath) ? null : Path.GetDirectoryName(settingsPath));
					if (!string.IsNullOrEmpty(text))
					{
						return Path.Combine(text, "lang");
					}
				}
				catch
				{
				}
				return Path.Combine(Paths.ConfigPath, "PeakRecord", "lang");
			}
		}

		internal static void Initialize()
		{
			_initialized = true;
			ExtractDefaultFiles();
			LoadFiles();
			ResolveLanguage();
		}

		internal static void Reload()
		{
			if (!_initialized)
			{
				Initialize();
				return;
			}
			ExtractDefaultFiles();
			LoadFiles();
			ResolveLanguage();
		}

		internal static void ResolveLanguage()
		{
			string text = "en";
			try
			{
				text = RecordSettings.LanguageMode switch
				{
					2 => "zh", 
					1 => "en", 
					_ => DetectGameLanguage(), 
				};
			}
			catch
			{
				text = "en";
			}
			Language = text;
			if (!string.Equals(_lastResolved, text, StringComparison.Ordinal))
			{
				_lastResolved = text;
				Plugin.Log?.LogInfo("[本地化] 语言=" + text + " (" + DescribeGameLanguage() + ", 设置=" + SafeModeName() + "), 文件目录=" + LanguageDirectory);
			}
		}

		private static string DetectGameLanguage()
		{
			//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_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_0009: Invalid comparison between Unknown and I4
			//IL_000b: Unknown result type (might be due to invalid IL or missing references)
			//IL_000e: Invalid comparison between Unknown and I4
			try
			{
				Language cURRENT_LANGUAGE = LocalizedText.CURRENT_LANGUAGE;
				if ((int)cURRENT_LANGUAGE == 9 || (int)cURRENT_LANGUAGE == 10)
				{
					return "zh";
				}
			}
			catch
			{
			}
			return "en";
		}

		private static string DescribeGameLanguage()
		{
			try
			{
				return "游戏语言=" + ((object)Unsafe.As<Language, Language>(ref LocalizedText.CURRENT_LANGUAGE)/*cast due to .constrained prefix*/).ToString();
			}
			catch
			{
				return "游戏语言=未知";
			}
		}

		private static string SafeModeName()
		{
			try
			{
				return RecordSettings.LanguageMode switch
				{
					2 => "中文", 
					1 => "English", 
					_ => "自动", 
				};
			}
			catch
			{
				return "?";
			}
		}

		internal static string T(string key)
		{
			if (string.IsNullOrEmpty(key))
			{
				return key;
			}
			try
			{
				string value;
				if (Language == "zh")
				{
					return Chinese.TryGetValue(key, out value) ? value : key;
				}
				string value2;
				return English.TryGetValue(key, out value2) ? value2 : key;
			}
			catch
			{
				return key;
			}
		}

		internal static string F(string key, params object[] args)
		{
			string text = T(key);
			if (args == null || args.Length == 0)
			{
				return text;
			}
			try
			{
				return string.Format(text, args);
			}
			catch
			{
				return text;
			}
		}

		internal static string Tr(string text)
		{
			if (string.IsNullOrEmpty(text))
			{
				return text;
			}
			try
			{
				string value;
				if (Language == "zh")
				{
					return Chinese.TryGetValue(text, out value) ? value : text;
				}
				string value3;
				if (ChineseToEnglish.TryGetValue(text, out var value2))
				{
					return English.TryGetValue(value2, out value3) ? value3 : value2;
				}
				string value4;
				return English.TryGetValue(text, out value4) ? value4 : text;
			}
			catch
			{
				return text;
			}
		}

		private static void LoadFiles()
		{
			English.Clear();
			Chinese.Clear();
			ChineseToEnglish.Clear();
			LoadOne("en.json", English);
			LoadOne("zh.json", Chinese);
			foreach (KeyValuePair<string, string> item in Chinese)
			{
				if (!string.IsNullOrEmpty(item.Value) && !ChineseToEnglish.ContainsKey(item.Value))
				{
					ChineseToEnglish[item.Value] = item.Key;
				}
			}
		}

		private static void LoadOne(string fileName, Dictionary<string, string> target)
		{
			try
			{
				string text = Path.Combine(LanguageDirectory, fileName);
				if (!File.Exists(text))
				{
					return;
				}
				Dictionary<string, string> dictionary = JsonConvert.DeserializeObject<Dictionary<string, string>>(File.ReadAllText(text));
				if (dictionary == null)
				{
					return;
				}
				foreach (KeyValuePair<string, string> item in dictionary)
				{
					if (!string.IsNullOrEmpty(item.Key))
					{
						target[item.Key] = item.Value ?? "";
					}
				}
				Plugin.Log?.LogInfo("[本地化] 已载入 " + text + " (" + dictionary.Count + " 条)。");
			}
			catch (Exception ex)
			{
				Plugin.Log?.LogWarning("[本地化] 读取 " + fileName + " 失败: " + ex.Message);
			}
		}

		private static void ExtractDefaultFiles()
		{
			try
			{
				Directory.CreateDirectory(LanguageDirectory);
				ExtractOne("en.json");
				ExtractOne("zh.json");
			}
			catch (Exception ex)
			{
				Plugin.Log?.LogWarning("[本地化] 释放默认语言文件失败: " + ex.Message);
			}
		}

		private static void ExtractOne(string fileName)
		{
			string text = Path.Combine(LanguageDirectory, fileName);
			if (File.Exists(text))
			{
				return;
			}
			try
			{
				Assembly assembly = typeof(Loc).Assembly;
				string text2 = null;
				string[] manifestResourceNames = assembly.GetManifestResourceNames();
				for (int i = 0; i < manifestResourceNames.Length; i++)
				{
					if (manifestResourceNames[i].EndsWith("." + fileName, StringComparison.OrdinalIgnoreCase))
					{
						text2 = manifestResourceNames[i];
						break;
					}
				}
				if (text2 == null)
				{
					Plugin.Log?.LogWarning("[本地化] DLL 内没有内嵌 " + fileName);
					return;
				}
				using (Stream stream = assembly.GetManifestResourceStream(text2))
				{
					if (stream == null)
					{
						return;
					}
					using FileStream