Decompiled source of RefuseCarryFriend v0.1.0

RefuseCarryFriend.dll

Decompiled an hour ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using BepInEx;
using BepInEx.Configuration;
using ExitGames.Client.Photon;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using Photon.Pun;
using Photon.Realtime;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyVersion("0.0.0.0")]
[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;
		}
	}
}
namespace RefuseCarryFriend
{
	internal enum UiLanguage
	{
		Auto,
		Chinese,
		English
	}
	internal static class L10n
	{
		public static UiLanguage Mode = UiLanguage.Auto;

		private static bool _chinese = true;

		public static bool IsChinese => _chinese;

		public static void Refresh()
		{
			switch (Mode)
			{
			case UiLanguage.Chinese:
				_chinese = true;
				break;
			case UiLanguage.English:
				_chinese = false;
				break;
			default:
				_chinese = DetectChinese();
				break;
			}
		}

		public static string T(string zh, string en)
		{
			if (!_chinese)
			{
				return en;
			}
			return zh;
		}

		public static string ConfigLabel(string raw)
		{
			if (string.IsNullOrEmpty(raw))
			{
				return null;
			}
			switch (raw)
			{
			case "General":
				if (!_chinese)
				{
					return "General";
				}
				return "通用设置";
			case "Escape Key":
				if (!_chinese)
				{
					return "Escape Key";
				}
				return "脱落按键";
			case "Refuse Key":
				if (!_chinese)
				{
					return "Refuse Key";
				}
				return "拒绝按键";
			case "Refuse Being Carried":
				if (!_chinese)
				{
					return "Refuse Being Carried";
				}
				return "拒绝被背起";
			case "Show Hint":
				if (!_chinese)
				{
					return "Show Hint";
				}
				return "显示提示";
			case "Retry Window (s)":
				if (!_chinese)
				{
					return "Retry Window (s)";
				}
				return "重试时长 (秒)";
			case "Language":
				if (!_chinese)
				{
					return "Language";
				}
				return "语言";
			case "Refuse Carry Friend":
			case "RefuseCarryFriend":
				if (!_chinese)
				{
					return "Refuse Carry Friend";
				}
				return "拒绝被背起";
			default:
				return null;
			}
		}

		private static bool DetectChinese()
		{
			//IL_001c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0021: Unknown result type (might be due to invalid IL or missing references)
			//IL_0022: Unknown result type (might be due to invalid IL or missing references)
			//IL_0024: Invalid comparison between Unknown and I4
			//IL_0026: Unknown result type (might be due to invalid IL or missing references)
			//IL_0029: Invalid comparison between Unknown and I4
			//IL_002b: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Invalid comparison between Unknown and I4
			string text = TryReadGameLocaleCode();
			if (!string.IsNullOrEmpty(text))
			{
				return text.StartsWith("zh", StringComparison.OrdinalIgnoreCase);
			}
			try
			{
				SystemLanguage systemLanguage = Application.systemLanguage;
				return (int)systemLanguage == 6 || (int)systemLanguage == 40 || (int)systemLanguage == 41;
			}
			catch
			{
				return true;
			}
		}

		private static string TryReadGameLocaleCode()
		{
			try
			{
				Type type = AccessTools.TypeByName("UnityEngine.Localization.Settings.LocalizationSettings");
				if (type == null)
				{
					return null;
				}
				object obj = type.GetProperty("SelectedLocale", BindingFlags.Static | BindingFlags.Public)?.GetValue(null);
				if (obj == null)
				{
					return null;
				}
				object obj2 = obj.GetType().GetProperty("Identifier")?.GetValue(obj);
				if (obj2 == null)
				{
					return null;
				}
				return obj2.GetType().GetProperty("Code")?.GetValue(obj2) as string;
			}
			catch
			{
				return null;
			}
		}
	}
	[BepInPlugin("zichen.refusecarryfriend", "RefuseCarryFriend", "0.1.0")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	public sealed class RefuseCarryPlugin : BaseUnityPlugin
	{
		private sealed class LiveLabel
		{
			public WeakReference Tmp;

			public string Raw;
		}

		public const string Guid = "zichen.refusecarryfriend";

		public const string Version = "0.1.0";

		private const byte CarryEventCode = 188;

		private const byte RefuseEventCode = 189;

		private const string RefuseMagic = "RCF1";

		private const int ActionCarry = 1;

		private const int ActionDrop = 2;

		private const int TargetTypePlayer = 1;

		private const int RefuseActionBlocked = 2;

		private static readonly FieldInfo F_AvatarTumble = AccessTools.Field(typeof(PlayerAvatar), "tumble");

		private static readonly FieldInfo F_AvatarIsTumbling = AccessTools.Field(typeof(PlayerAvatar), "isTumbling");

		private static readonly FieldInfo F_TumbleIsTumbling = AccessTools.Field(typeof(PlayerTumble), "isTumbling");

		private static readonly FieldInfo F_TumbleInputDisable = AccessTools.Field(typeof(PlayerController), "tumbleInputDisableTimer");

		private static readonly Dictionary<Type, FieldInfo> LabelFieldCache = new Dictionary<Type, FieldInfo>(8);

		private static readonly Dictionary<Type, PropertyInfo> TextPropCache = new Dictionary<Type, PropertyInfo>(8);

		private static readonly List<LiveLabel> LiveLabels = new List<LiveLabel>(64);

		private static readonly HashSet<int> RefusedActors = new HashSet<int>(8);

		private static RefuseCarryPlugin _instance;

		private static FieldInfo F_IsRKeyHold;

		private ConfigEntry<UiLanguage> _cfgLanguage;

		private ConfigEntry<KeyCode> _cfgEscapeKey;

		private ConfigEntry<KeyCode> _cfgRefuseKey;

		private ConfigEntry<bool> _cfgRefuse;

		private ConfigEntry<bool> _cfgHint;

		private ConfigEntry<float> _cfgRetryWindow;

		private Harmony _harmony;

		private LoadBalancingClient _client;

		private int _carrierViewId;

		private float _carrierSince;

		private float _retryUntil;

		private float _nextRetry;

		private float _lastBreakFree;

		private float _nextAnnounce;

		private float _nextPrune;

		private bool _wasInRoom;

		private int _lastLocalViewId;

		private float _lastNotifySent;

		private string _toastText;

		private float _toastUntil;

		private GUIStyle _hintStyle;

		private GUIStyle _hintShadow;

		private GUIStyle _toastStyle;

		private GUIStyle _toastShadow;

		private int _styleSize;

		private void Awake()
		{
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0016: Expected O, but got Unknown
			//IL_0123: Unknown result type (might be due to invalid IL or missing references)
			//IL_012d: Expected O, but got Unknown
			_instance = this;
			_harmony = new Harmony("zichen.refusecarryfriend");
			_cfgLanguage = ((BaseUnityPlugin)this).Config.Bind<UiLanguage>("General", "Language", UiLanguage.Auto, "界面语言 / UI language(Auto = 跟随游戏语言 / follow game locale)");
			ApplyLanguage();
			_cfgLanguage.SettingChanged += delegate
			{
				ApplyLanguage();
				RefreshLiveLabels();
			};
			_cfgEscapeKey = ((BaseUnityPlugin)this).Config.Bind<KeyCode>("General", "Escape Key", (KeyCode)32, "被背起时按此键脱落 / Key used to break free while being carried.");
			_cfgRefuseKey = ((BaseUnityPlugin)this).Config.Bind<KeyCode>("General", "Refuse Key", (KeyCode)282, "一键切换允许/拒绝被背起 / Key to toggle allow & refuse being carried.");
			_cfgRefuse = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "Refuse Being Carried", false, "开启后自动脱落并拒绝任何人背你(可用上面的按键实时切换)/ When on, auto break free and refuse any carrier.");
			_cfgRefuse.SettingChanged += delegate
			{
				SetToast(_cfgRefuse.Value ? L10n.T("拒绝被背起", "Refusing carry") : L10n.T("允许被背起", "Allowing carry"), 3f);
				SendRefuseState(_cfgRefuse.Value);
				if (_cfgRefuse.Value && _carrierViewId != 0)
				{
					TryBreakFree();
				}
			};
			_cfgHint = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "Show Hint", true, "被背起时在左下角显示提示 / Show a small hint in the bottom-left corner while carried.");
			_cfgRetryWindow = ((BaseUnityPlugin)this).Config.Bind<float>("General", "Retry Window (s)", 2.5f, new ConfigDescription("按键后持续强制站立的时长(秒)/ How long to keep forcing stand-up after breaking free.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 10f), Array.Empty<object>()));
			InstallMenuHooks();
			InstallCarryHooks();
			((BaseUnityPlugin)this).Logger.LogInfo((object)"RefuseCarryFriend v0.1.0 已加载。");
		}

		private void Update()
		{
			//IL_0037: Unknown result type (might be due to invalid IL or missing references)
			//IL_008e: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				SyncClient();
				TickRoomState();
				TickAnnounce();
				TickRefusalPrune();
				TickRetry();
				if (!PhotonNetwork.InRoom)
				{
					ClearCarrier();
				}
				TickCarrierTimeout();
				if (Input.GetKeyDown(_cfgRefuseKey.Value))
				{
					ToggleRefuse();
				}
				if (!((Object)(object)PlayerAvatar.instance == (Object)null) && !SemiFunc.MenuLevel())
				{
					if (_cfgRefuse.Value && _carrierViewId != 0)
					{
						TryBreakFree();
					}
					else if (_carrierViewId != 0 && (Input.GetKeyDown(_cfgEscapeKey.Value) || SemiFunc.InputDown((InputKey)1)))
					{
						TryBreakFree();
					}
				}
			}
			catch (Exception ex)
			{
				((BaseUnityPlugin)this).Logger.LogWarning((object)("Update 异常: " + ex.Message));
			}
		}

		private void ApplyLanguage()
		{
			L10n.Mode = _cfgLanguage.Value;
			L10n.Refresh();
			_styleSize = 0;
		}

		private void ToggleRefuse()
		{
			_cfgRefuse.Value = !_cfgRefuse.Value;
		}

		private void SyncClient()
		{
			LoadBalancingClient networkingClient = PhotonNetwork.NetworkingClient;
			if (networkingClient != _client)
			{
				if (_client != null)
				{
					_client.EventReceived -= OnPhotonEvent;
				}
				_client = networkingClient;
				ClearCarrier();
				if (_client != null)
				{
					_client.EventReceived += OnPhotonEvent;
				}
			}
		}

		private void OnPhotonEvent(EventData data)
		{
			try
			{
				if (data == null)
				{
					return;
				}
				if (data.Code == 189)
				{
					HandleRefuseEvent(data);
				}
				else
				{
					if (data.Code != 188 || !(data.CustomData is object[] array) || array.Length < 4)
					{
						return;
					}
					int num = Convert.ToInt32(array[^1]);
					if (num != 1 && num != 2)
					{
						return;
					}
					int num2 = LocalViewId();
					if (num2 == 0)
					{
						return;
					}
					int num3 = Convert.ToInt32(array[0]);
					if (Convert.ToInt32(array[1]) != num2)
					{
						return;
					}
					if (num == 1)
					{
						if (num3 != 0)
						{
							_carrierViewId = num3;
							_carrierSince = Time.time;
							_retryUntil = 0f;
							if (_cfgRefuse.Value)
							{
								TryBreakFree();
							}
						}
					}
					else if (num3 == 0 || num3 == _carrierViewId)
					{
						ClearCarrier();
					}
				}
			}
			catch
			{
			}
		}

		private void TickRoomState()
		{
			bool flag = PhotonNetwork.InRoom && SemiFunc.IsMultiplayer();
			if (flag != _wasInRoom)
			{
				_wasInRoom = flag;
				ClearCarrier();
				RefusedActors.Clear();
				_lastLocalViewId = 0;
				_nextAnnounce = Time.time;
				if (flag && _cfgRefuse.Value)
				{
					SendRefuseState(refusing: true);
				}
			}
		}

		private void TickAnnounce()
		{
			if (_cfgRefuse.Value && _wasInRoom)
			{
				int num = LocalViewId();
				if (num != 0 && num != _lastLocalViewId)
				{
					_lastLocalViewId = num;
					_nextAnnounce = 0f;
				}
				if (!(Time.time < _nextAnnounce))
				{
					_nextAnnounce = Time.time + 2.5f;
					SendRefuseState(refusing: true);
				}
			}
		}

		private void TickRefusalPrune()
		{
			if (Time.time < _nextPrune)
			{
				return;
			}
			_nextPrune = Time.time + 5f;
			if (RefusedActors.Count == 0)
			{
				return;
			}
			Room currentRoom = PhotonNetwork.CurrentRoom;
			if (currentRoom == null)
			{
				RefusedActors.Clear();
				return;
			}
			List<int> list = null;
			foreach (int refusedActor in RefusedActors)
			{
				if (!currentRoom.Players.ContainsKey(refusedActor))
				{
					if (list == null)
					{
						list = new List<int>(4);
					}
					list.Add(refusedActor);
				}
			}
			if (list != null)
			{
				for (int i = 0; i < list.Count; i++)
				{
					RefusedActors.Remove(list[i]);
				}
			}
		}

		private void SendRefuseState(bool refusing)
		{
			//IL_0031: Unknown result type (might be due to invalid IL or missing references)
			//IL_0036: Unknown result type (might be due to invalid IL or missing references)
			//IL_0038: Unknown result type (might be due to invalid IL or missing references)
			//IL_003d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0047: Expected O, but got Unknown
			try
			{
				if (PhotonNetwork.InRoom && PhotonNetwork.NetworkingClient != null)
				{
					object[] array = new object[2]
					{
						"RCF1",
						refusing ? 1 : 0
					};
					PhotonNetwork.RaiseEvent((byte)189, (object)array, new RaiseEventOptions
					{
						Receivers = (ReceiverGroup)0
					}, SendOptions.SendReliable);
				}
			}
			catch (Exception ex)
			{
				((BaseUnityPlugin)this).Logger.LogWarning((object)("广播拒绝状态失败: " + ex.Message));
			}
		}

		private void HandleRefuseEvent(EventData data)
		{
			if (!(data.CustomData is object[] array) || array.Length < 2 || !(array[0] is string) || (string)array[0] != "RCF1")
			{
				return;
			}
			if (array.Length >= 4 && Convert.ToInt32(array[3]) == 2)
			{
				HandleBlockedNotify(Convert.ToInt32(array[1]), Convert.ToInt32(array[2]));
				return;
			}
			int sender = data.Sender;
			if (sender > 0)
			{
				if (Convert.ToInt32(array[1]) != 0)
				{
					RefusedActors.Add(sender);
				}
				else
				{
					RefusedActors.Remove(sender);
				}
			}
		}

		private void HandleBlockedNotify(int targetViewId, int carrierViewId)
		{
			int num = LocalViewId();
			if (num != 0)
			{
				if (num == carrierViewId)
				{
					string text = NameOfView(targetViewId);
					SetToast(string.IsNullOrEmpty(text) ? L10n.T("对方拒绝被背起", "They refuse to be carried") : L10n.T(text + " 拒绝被背起", text + " refuses to be carried"), 2.5f);
				}
				else if (num == targetViewId)
				{
					string text2 = NameOfView(carrierViewId);
					SetToast(string.IsNullOrEmpty(text2) ? L10n.T("已拒绝被背起请求", "Carry request refused") : L10n.T(text2 + " 想背你,已拒绝", text2 + " tried to carry you — refused"), 2.5f);
				}
			}
		}

		private void ShowBlockedToast(int targetViewId, int carrierViewId)
		{
			HandleBlockedNotify(targetViewId, carrierViewId);
			if (!(Time.time - _lastNotifySent < 0.75f))
			{
				_lastNotifySent = Time.time;
				SendBlockedNotify(targetViewId, carrierViewId);
			}
		}

		private void SendBlockedNotify(int targetViewId, int carrierViewId)
		{
			//IL_0040: Unknown result type (might be due to invalid IL or missing references)
			//IL_0045: Unknown result type (might be due to invalid IL or missing references)
			//IL_0047: Unknown result type (might be due to invalid IL or missing references)
			//IL_004c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0056: Expected O, but got Unknown
			try
			{
				if (PhotonNetwork.InRoom && PhotonNetwork.NetworkingClient != null)
				{
					object[] array = new object[4] { "RCF1", targetViewId, carrierViewId, 2 };
					PhotonNetwork.RaiseEvent((byte)189, (object)array, new RaiseEventOptions
					{
						Receivers = (ReceiverGroup)0
					}, SendOptions.SendReliable);
				}
			}
			catch (Exception ex)
			{
				((BaseUnityPlugin)this).Logger.LogWarning((object)("广播拒绝提示失败: " + ex.Message));
			}
		}

		private void SetToast(string text, float seconds)
		{
			_toastText = text;
			_toastUntil = Time.time + Mathf.Max(0.1f, seconds);
		}

		private void InstallCarryHooks()
		{
			//IL_008b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0099: Expected O, but got Unknown
			//IL_00fe: Unknown result type (might be due to invalid IL or missing references)
			//IL_010c: Expected O, but got Unknown
			//IL_0181: Unknown result type (might be due to invalid IL or missing references)
			//IL_018f: Expected O, but got Unknown
			try
			{
				Type type = AccessTools.TypeByName("Zichen_CarryFriend.CarryFriendBehaviour");
				if (type == null)
				{
					((BaseUnityPlugin)this).Logger.LogInfo((object)"未检测到 CarryFriend,仅使用事件协议(被背时立即挣脱)。");
					return;
				}
				int num = 0;
				MethodInfo methodInfo = AccessTools.Method(type, "ProcessCarryTransfer", new Type[3]
				{
					typeof(int),
					typeof(int),
					typeof(int)
				}, (Type[])null);
				if (methodInfo != null)
				{
					_harmony.Patch((MethodBase)methodInfo, new HarmonyMethod(AccessTools.Method(typeof(RefuseCarryPlugin), "ProcessCarryTransferPrefix", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
					num++;
				}
				MethodInfo methodInfo2 = AccessTools.Method(type, "ExecuteCarryEvent", new Type[3]
				{
					typeof(PlayerAvatar),
					typeof(int),
					typeof(int)
				}, (Type[])null);
				if (methodInfo2 != null)
				{
					_harmony.Patch((MethodBase)methodInfo2, new HarmonyMethod(AccessTools.Method(typeof(RefuseCarryPlugin), "ExecuteCarryEventPrefix", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
					num++;
				}
				MethodInfo methodInfo3 = AccessTools.Method(type, "HandleCarryAction", new Type[4]
				{
					typeof(int),
					typeof(int),
					typeof(int),
					typeof(int)
				}, (Type[])null);
				if (methodInfo3 != null)
				{
					_harmony.Patch((MethodBase)methodInfo3, new HarmonyMethod(AccessTools.Method(typeof(RefuseCarryPlugin), "HandleCarryActionPrefix", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
					num++;
				}
				((BaseUnityPlugin)this).Logger.LogInfo((object)("CarryFriend 背起拦截已挂载(" + num + " 个方法)。"));
				if (num == 0)
				{
					((BaseUnityPlugin)this).Logger.LogWarning((object)"检测到 CarryFriend,但未找到拦截目标,真实拒绝可能不生效。");
				}
			}
			catch (Exception ex)
			{
				((BaseUnityPlugin)this).Logger.LogWarning((object)("CarryFriend 拦截失败: " + ex.Message));
			}
		}

		private static bool ProcessCarryTransferPrefix(int __0, int __1, int __2)
		{
			try
			{
				if (__2 != 1)
				{
					return true;
				}
				return !BlockCarry(__0, __1, notify: true);
			}
			catch
			{
				return true;
			}
		}

		private static bool ExecuteCarryEventPrefix(object __instance, PlayerAvatar __0, int __1, int __2)
		{
			try
			{
				if (__2 != 1)
				{
					return true;
				}
				bool flag = false;
				if (F_IsRKeyHold == null && __instance != null)
				{
					F_IsRKeyHold = AccessTools.Field(__instance.GetType(), "_isRKeyHold");
				}
				if (F_IsRKeyHold != null)
				{
					flag = (bool)F_IsRKeyHold.GetValue(__instance);
				}
				int num = ViewIdOf(__0);
				int carrierViewId = (flag ? __1 : num);
				int num2 = (flag ? num : __1);
				if (num2 == 0)
				{
					return true;
				}
				if (flag && num2 == num)
				{
					if (!IsRefusingView(num))
					{
						return true;
					}
					if ((Object)(object)_instance != (Object)null)
					{
						_instance.SetToast(L10n.T("你已拒绝被背起", "You are refusing to be carried"), 2f);
					}
					return false;
				}
				return !BlockCarry(carrierViewId, num2, notify: true);
			}
			catch
			{
				return true;
			}
		}

		private static bool HandleCarryActionPrefix(int __0, int __1, int __2, int __3)
		{
			try
			{
				if (__3 != 1 || __2 != 1)
				{
					return true;
				}
				int num = LocalViewId();
				bool notify = num != 0 && (num == __0 || num == __1);
				if (!BlockCarry(__0, __1, notify))
				{
					return true;
				}
				if (num != 0 && num == __1 && (Object)(object)_instance != (Object)null)
				{
					_instance._carrierViewId = __0;
					_instance._carrierSince = Time.time;
					_instance.TryBreakFree();
				}
				return false;
			}
			catch
			{
				return true;
			}
		}

		private static bool BlockCarry(int carrierViewId, int targetViewId, bool notify)
		{
			if (targetViewId == 0 || !IsRefusingView(targetViewId))
			{
				return false;
			}
			if (notify && (Object)(object)_instance != (Object)null)
			{
				_instance.ShowBlockedToast(targetViewId, carrierViewId);
			}
			return true;
		}

		private static bool IsRefusingView(int viewId)
		{
			if (viewId == 0)
			{
				return false;
			}
			PlayerAvatar instance = PlayerAvatar.instance;
			if ((Object)(object)instance != (Object)null && ViewIdOf(instance) == viewId)
			{
				if ((Object)(object)_instance != (Object)null)
				{
					return _instance._cfgRefuse.Value;
				}
				return false;
			}
			PlayerAvatar val = FindAvatarByViewId(viewId);
			if ((Object)(object)val == (Object)null || (Object)(object)val.photonView == (Object)null)
			{
				return false;
			}
			return RefusedActors.Contains(val.photonView.OwnerActorNr);
		}

		private static PlayerAvatar FindAvatarByViewId(int viewId)
		{
			PlayerAvatar instance = PlayerAvatar.instance;
			if ((Object)(object)instance != (Object)null && ViewIdOf(instance) == viewId)
			{
				return instance;
			}
			GameDirector instance2 = GameDirector.instance;
			if ((Object)(object)instance2 == (Object)null || instance2.PlayerList == null)
			{
				return null;
			}
			List<PlayerAvatar> playerList = instance2.PlayerList;
			for (int i = 0; i < playerList.Count; i++)
			{
				PlayerAvatar val = playerList[i];
				if ((Object)(object)val != (Object)null && ViewIdOf(val) == viewId)
				{
					return val;
				}
			}
			return null;
		}

		private static string NameOfView(int viewId)
		{
			PlayerAvatar val = FindAvatarByViewId(viewId);
			if ((Object)(object)val == (Object)null || (Object)(object)val.photonView == (Object)null || val.photonView.Owner == null)
			{
				return null;
			}
			return val.photonView.Owner.NickName;
		}

		private void ClearCarrier()
		{
			_carrierViewId = 0;
			_carrierSince = 0f;
			_retryUntil = 0f;
		}

		private void TickCarrierTimeout()
		{
			if (_carrierViewId != 0 && !(Time.time - _carrierSince < 4f))
			{
				PlayerAvatar instance = PlayerAvatar.instance;
				if ((Object)(object)instance == (Object)null || !IsTumbling(instance))
				{
					ClearCarrier();
				}
			}
		}

		private void TryBreakFree()
		{
			if (Time.time - _lastBreakFree < 0.2f)
			{
				return;
			}
			_lastBreakFree = Time.time;
			PlayerAvatar instance = PlayerAvatar.instance;
			if (!((Object)(object)instance == (Object)null))
			{
				int num = ViewIdOf(instance);
				int carrierViewId = _carrierViewId;
				ClearCarrier();
				if (num != 0 && carrierViewId != 0)
				{
					BroadcastDrop(carrierViewId, num);
					((BaseUnityPlugin)this).Logger.LogInfo((object)("挣脱:请求放下 (carrier view " + carrierViewId + ")"));
				}
				ForceStandUp(instance);
				_retryUntil = Time.time + Mathf.Max(0f, _cfgRetryWindow.Value);
				_nextRetry = 0f;
			}
		}

		private void BroadcastDrop(int carrierViewId, int targetViewId)
		{
			//IL_003b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0040: Unknown result type (might be due to invalid IL or missing references)
			//IL_0042: Unknown result type (might be due to invalid IL or missing references)
			//IL_0048: Expected O, but got Unknown
			//IL_004f: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				if (PhotonNetwork.InRoom && PhotonNetwork.NetworkingClient != null)
				{
					object[] array = new object[4] { carrierViewId, targetViewId, 1, 2 };
					RaiseEventOptions val = new RaiseEventOptions
					{
						Receivers = (ReceiverGroup)0
					};
					PhotonNetwork.RaiseEvent((byte)188, (object)array, val, SendOptions.SendReliable);
				}
			}
			catch (Exception ex)
			{
				((BaseUnityPlugin)this).Logger.LogWarning((object)("发送解除事件失败: " + ex.Message));
			}
		}

		private void TickRetry()
		{
			if (Time.time >= _retryUntil || Time.time < _nextRetry)
			{
				return;
			}
			PlayerAvatar instance = PlayerAvatar.instance;
			if (!((Object)(object)instance == (Object)null))
			{
				PlayerTumble tumble = GetTumble(instance);
				if (!((Object)(object)tumble == (Object)null) && IsTumbling(tumble))
				{
					_nextRetry = Time.time + 0.25f;
					RequestStandUp(tumble);
				}
			}
		}

		private void ForceStandUp(PlayerAvatar avatar)
		{
			try
			{
				PlayerController instance = PlayerController.instance;
				if ((Object)(object)instance != (Object)null)
				{
					if (F_TumbleInputDisable != null)
					{
						F_TumbleInputDisable.SetValue(instance, 0f);
					}
					((Behaviour)instance).enabled = true;
					instance.Crouching = false;
				}
				PlayerTumble tumble = GetTumble(avatar);
				if ((Object)(object)tumble != (Object)null)
				{
					RequestStandUp(tumble);
				}
			}
			catch (Exception ex)
			{
				((BaseUnityPlugin)this).Logger.LogWarning((object)("本地恢复失败: " + ex.Message));
			}
		}

		private void RequestStandUp(PlayerTumble tumble)
		{
			try
			{
				if (!((Object)(object)tumble == (Object)null) && IsTumbling(tumble))
				{
					tumble.TumbleRequest(false, false);
				}
			}
			catch
			{
			}
		}

		private static PlayerTumble GetTumble(PlayerAvatar avatar)
		{
			if ((Object)(object)avatar == (Object)null || F_AvatarTumble == null)
			{
				return null;
			}
			try
			{
				object? value = F_AvatarTumble.GetValue(avatar);
				return (PlayerTumble)((value is PlayerTumble) ? value : null);
			}
			catch
			{
				return null;
			}
		}

		private static bool IsTumbling(PlayerAvatar avatar)
		{
			if ((Object)(object)avatar == (Object)null || F_AvatarIsTumbling == null)
			{
				return false;
			}
			try
			{
				return (bool)F_AvatarIsTumbling.GetValue(avatar);
			}
			catch
			{
				return false;
			}
		}

		private static bool IsTumbling(PlayerTumble tumble)
		{
			if ((Object)(object)tumble == (Object)null || F_TumbleIsTumbling == null)
			{
				return false;
			}
			try
			{
				return (bool)F_TumbleIsTumbling.GetValue(tumble);
			}
			catch
			{
				return false;
			}
		}

		private static int ViewIdOf(PlayerAvatar avatar)
		{
			if ((Object)(object)avatar == (Object)null || (Object)(object)avatar.photonView == (Object)null)
			{
				return 0;
			}
			return avatar.photonView.ViewID;
		}

		private static int LocalViewId()
		{
			return ViewIdOf(PlayerAvatar.instance);
		}

		private void OnGUI()
		{
			if (Event.current != null)
			{
				if (_cfgHint.Value && _carrierViewId != 0)
				{
					DrawCarriedHint();
				}
				if (Time.time < _toastUntil && !string.IsNullOrEmpty(_toastText))
				{
					DrawToast();
				}
			}
		}

		private void DrawCarriedHint()
		{
			//IL_00a8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c9: Unknown result type (might be due to invalid IL or missing references)
			float num = Mathf.Max(0.75f, (float)Screen.height / 1080f);
			int num2 = Mathf.RoundToInt(19f * num);
			EnsureStyles(num2);
			string text = L10n.T("被背起时空格脱落", "Press SPACE to break free");
			string text2 = (_cfgRefuse.Value ? L10n.T("按 F1 切换 允许/拒绝 被背起(当前:拒绝)", "F1: allow / refuse being carried (now: REFUSED)") : L10n.T("按 F1 切换 允许/拒绝 被背起(当前:允许)", "F1: allow / refuse being carried (now: ALLOWED)"));
			float num3 = (float)num2 * 1.4f;
			float num4 = 18f * num;
			float num5 = (float)Screen.height - 18f * num - num3 * 2f;
			float num6 = (float)Screen.width * 0.5f;
			DrawShadowed(new Rect(num4, num5, num6, num3), text, _hintStyle, _hintShadow, num);
			DrawShadowed(new Rect(num4, num5 + num3, num6, num3), text2, _hintStyle, _hintShadow, num);
		}

		private void DrawToast()
		{
			//IL_006b: Unknown result type (might be due to invalid IL or missing references)
			float num = Mathf.Max(0.75f, (float)Screen.height / 1080f);
			int num2 = Mathf.RoundToInt(31f * num);
			EnsureStyles(num2);
			string toastText = _toastText;
			float num3 = (float)num2 * 2f;
			float num4 = 18f * num;
			float num5 = (float)Screen.width * 0.55f;
			DrawShadowed(new Rect(num4, (float)Screen.height * 0.5f - num3 * 0.5f, num5, num3), toastText, _toastStyle, _toastShadow, num);
		}

		private static void DrawShadowed(Rect rect, string text, GUIStyle style, GUIStyle shadow, float scale)
		{
			//IL_002e: 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)
			GUI.Label(new Rect(((Rect)(ref rect)).x + 1.5f * scale, ((Rect)(ref rect)).y + 1.5f * scale, ((Rect)(ref rect)).width, ((Rect)(ref rect)).height), text, shadow);
			GUI.Label(rect, text, style);
		}

		private void EnsureStyles(int size)
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_0029: Unknown result type (might be due to invalid IL or missing references)
			//IL_0030: Unknown result type (might be due to invalid IL or missing references)
			//IL_0037: Unknown result type (might be due to invalid IL or missing references)
			//IL_003e: Unknown result type (might be due to invalid IL or missing references)
			//IL_004a: Expected O, but got Unknown
			//IL_0055: Unknown result type (might be due to invalid IL or missing references)
			//IL_0066: Unknown result type (might be due to invalid IL or missing references)
			//IL_0070: Expected O, but got Unknown
			//IL_008f: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00be: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ca: Expected O, but got Unknown
			//IL_00d5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f0: Expected O, but got Unknown
			//IL_010f: Unknown result type (might be due to invalid IL or missing references)
			if (_styleSize != size || _hintStyle == null)
			{
				_styleSize = size;
				_hintStyle = new GUIStyle(GUI.skin.label)
				{
					fontSize = size,
					alignment = (TextAnchor)3,
					fontStyle = (FontStyle)0,
					wordWrap = false
				};
				_hintStyle.normal.textColor = Color.white;
				_hintShadow = new GUIStyle(_hintStyle);
				_hintShadow.normal.textColor = new Color(0f, 0f, 0f, 0.75f);
				_toastStyle = new GUIStyle(GUI.skin.label)
				{
					fontSize = size,
					alignment = (TextAnchor)3,
					fontStyle = (FontStyle)1,
					wordWrap = true
				};
				_toastStyle.normal.textColor = Color.white;
				_toastShadow = new GUIStyle(_toastStyle);
				_toastShadow.normal.textColor = new Color(0f, 0f, 0f, 0.8f);
			}
		}

		private void InstallMenuHooks()
		{
			//IL_00d2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00df: Expected O, but got Unknown
			try
			{
				Type type = AccessTools.TypeByName("MenuLib.MenuAPI");
				if (type == null)
				{
					((BaseUnityPlugin)this).Logger.LogInfo((object)"未检测到 MenuLib,跳过配置菜单中文化。");
					return;
				}
				MethodInfo methodInfo = AccessTools.Method(typeof(RefuseCarryPlugin), "MenuLabelPostfix", (Type[])null, (Type[])null);
				string[] array = new string[6] { "CreateREPOLabel", "CreateREPOButton", "CreateREPOToggle", "CreateREPOSlider", "CreateREPOInputField", "CreateREPOPopupPage" };
				int num = 0;
				MethodInfo[] methods = type.GetMethods(BindingFlags.Static | BindingFlags.Public);
				foreach (MethodInfo methodInfo2 in methods)
				{
					if (Array.IndexOf(array, methodInfo2.Name) < 0)
					{
						continue;
					}
					ParameterInfo[] parameters = methodInfo2.GetParameters();
					if (parameters.Length != 0 && !(parameters[0].ParameterType != typeof(string)))
					{
						try
						{
							_harmony.Patch((MethodBase)methodInfo2, (HarmonyMethod)null, new HarmonyMethod(methodInfo), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
							num++;
						}
						catch
						{
						}
					}
				}
				((BaseUnityPlugin)this).Logger.LogInfo((object)("配置菜单中英切换已挂载(" + num + " 个 UI 方法)。"));
			}
			catch (Exception ex)
			{
				((BaseUnityPlugin)this).Logger.LogWarning((object)("配置菜单劫持失败: " + ex.Message));
			}
		}

		private static void MenuLabelPostfix(object[] __args, object __result)
		{
			try
			{
				if (__args == null || __args.Length == 0 || __result == null)
				{
					return;
				}
				string text = __args[0] as string;
				if (string.IsNullOrEmpty(text))
				{
					return;
				}
				string text2 = L10n.ConfigLabel(text);
				if (text2 != null)
				{
					object labelTmp = GetLabelTmp(__result);
					if (labelTmp != null)
					{
						SetTmpText(labelTmp, text2);
						LiveLabels.Add(new LiveLabel
						{
							Tmp = new WeakReference(labelTmp),
							Raw = text
						});
					}
				}
			}
			catch
			{
			}
		}

		private static object GetLabelTmp(object component)
		{
			try
			{
				Type type = component.GetType();
				if (!LabelFieldCache.TryGetValue(type, out var value))
				{
					value = AccessTools.Field(type, "labelTMP") ?? AccessTools.Field(type, "headerTMP");
					LabelFieldCache[type] = value;
				}
				return value?.GetValue(component);
			}
			catch
			{
				return null;
			}
		}

		private static void SetTmpText(object tmp, string text)
		{
			try
			{
				if (tmp != null)
				{
					Type type = tmp.GetType();
					if (!TextPropCache.TryGetValue(type, out var value))
					{
						value = type.GetProperty("text", BindingFlags.Instance | BindingFlags.Public);
						TextPropCache[type] = value;
					}
					value?.SetValue(tmp, text);
				}
			}
			catch
			{
			}
		}

		private static void RefreshLiveLabels()
		{
			if (LiveLabels.Count > 512)
			{
				LiveLabels.Clear();
			}
			for (int num = LiveLabels.Count - 1; num >= 0; num--)
			{
				LiveLabel liveLabel = LiveLabels[num];
				object target = liveLabel.Tmp.Target;
				Object val = (Object)((target is Object) ? target : null);
				if (target == null || (val != (Object)null && val == (Object)null))
				{
					LiveLabels.RemoveAt(num);
				}
				else
				{
					string text = L10n.ConfigLabel(liveLabel.Raw);
					if (text == null)
					{
						LiveLabels.RemoveAt(num);
					}
					else
					{
						SetTmpText(target, text);
					}
				}
			}
		}
	}
}