Decompiled source of MimesisEscape v0.2.4

Mods/MimesisEscape.dll

Decompiled 2 days ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security.Cryptography;
using ArabicSupport;
using Bifrost.Cooked;
using HarmonyLib;
using MelonLoader;
using Microsoft.CodeAnalysis;
using MimesisEscape;
using Mimic.Actors;
using Mimic.InputSystem;
using ReluProtocol;
using ReluProtocol.Enum;
using Steamworks;
using TMPro;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.Events;
using UnityEngine.InputSystem;
using UnityEngine.InputSystem.Controls;
using UnityEngine.UI;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: MelonInfo(typeof(EscapeMod), "Mimesis Escape QTE", "0.2.4", "Local mod", null)]
[assembly: MelonGame("ReLUGames", "MIMESIS")]
[assembly: TargetFramework(".NETFramework,Version=v4.7.2", FrameworkDisplayName = ".NET Framework 4.7.2")]
[assembly: AssemblyCompany("MimesisEscape")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("0.2.4.0")]
[assembly: AssemblyInformationalVersion("0.2.4")]
[assembly: AssemblyProduct("MimesisEscape")]
[assembly: AssemblyTitle("MimesisEscape")]
[assembly: AssemblyVersion("0.2.4.0")]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

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

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

		public NullableContextAttribute(byte P_0)
		{
			Flag = P_0;
		}
	}
	[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 MimesisEscape
{
	internal sealed class CaptureAdapter
	{
		private static readonly FieldInfo CreatureField = AccessTools.Field(typeof(AttachController), "_creature");

		private static readonly FieldInfo InfoField = AccessTools.Field(typeof(AttachController), "_attachInfo");

		private static readonly FieldInfo PdataField = AccessTools.Field(typeof(Hub), "pdata");

		private static readonly MethodInfo WorldGetter = AccessTools.PropertyGetter(typeof(Hub), "vworld");

		private static readonly FieldInfo StatesField = AccessTools.Field(typeof(InputManager), "states");

		private readonly Action<string> log;

		private GameMainBase? main;

		private VWorld? world;

		private VCreature? caster;

		private VActor? victim;

		private ProtoActor? avatar;

		private AttachController? controller;

		private AttachMasterInfo? info;

		private VCreature? owner;

		private VActor? attached;

		internal bool HasCapture => controller != null;

		internal int CurrentGrabId => info?.MasterID ?? 0;

		internal static PersistentData? Pdata
		{
			get
			{
				if (!((Object)(object)Hub.s == (Object)null))
				{
					object? value = PdataField.GetValue(Hub.s);
					return (PersistentData?)((value is PersistentData) ? value : null);
				}
				return null;
			}
		}

		internal static VWorld? World
		{
			get
			{
				if (!((Object)(object)Hub.s == (Object)null))
				{
					object? obj = WorldGetter.Invoke(Hub.s, null);
					return (VWorld?)((obj is VWorld) ? obj : null);
				}
				return null;
			}
		}

		internal CaptureAdapter(Action<string> log)
		{
			this.log = log;
		}

		internal bool Begin(AttachController source, int targetId, Key key, out double duration)
		{
			//IL_0020: Unknown result type (might be due to invalid IL or missing references)
			//IL_0026: Invalid comparison between Unknown and I4
			//IL_01a4: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c1: Unknown result type (might be due to invalid IL or missing references)
			duration = 0.0;
			if (!HasCapture)
			{
				PersistentData? pdata = Pdata;
				if (pdata != null && (int)pdata.ClientMode <= 0 && Pdata.SessionJoined && World != null)
				{
					GameMainBase val = Hub.Main;
					ProtoActor val2 = ((val != null) ? val.GetMyAvatar() : null);
					object? value = CreatureField.GetValue(source);
					VCreature val3 = (VCreature)((value is VCreature) ? value : null);
					object? value2 = InfoField.GetValue(source);
					AttachMasterInfo val4 = (AttachMasterInfo)((value2 is AttachMasterInfo) ? value2 : null);
					if ((Object)(object)val2 == (Object)null || !val2.IsHost || !val2.AmIAvatar() || val2.dead || val3 == null || val4 == null || !CaptureKinds.Supported(val4.MasterID))
					{
						return false;
					}
					VActor val5 = ((VActor)val3).VRoom.FindActorByObjectID(targetId);
					object obj = (val4.IsReverseGrab ? ((object)val3) : ((object)val5));
					VPlayer val6 = (VPlayer)((obj is VPlayer) ? obj : null);
					object obj2 = (val4.IsReverseGrab ? ((object)val5) : ((object)val3));
					VCreature val7 = (VCreature)((obj2 is VCreature) ? obj2 : null);
					ProtoActor val8 = ((val7 == null) ? null : val.GetActorByActorID(((VActor)val7).ObjectID));
					if (val6 == null || val7 == null || (Object)(object)val8 == (Object)null || ((VActor)val6).ObjectID != val2.ActorID || !CaptureKinds.Matches(val4.MasterID, val4.IsReverseGrab, ((VActor)val7).MasterID, val8.IsMimic()) || !((VActor)val6).IsAliveStatus() || !((VActor)val7).IsAliveStatus() || ((val5 != null) ? val5.AttachControlUnit : null) == null || val5.AttachControlUnit.AttachedActorID != ((VActor)val3).ObjectID || !val5.AttachControlUnit.IsAttached(0) || !source.IsAttaching() || val4.Duration <= 0)
					{
						return false;
					}
					string text = BindingConflict(((Component)Hub.s).GetComponentInChildren<InputManager>(), key);
					if (text.Length > 0)
					{
						log($"QTE skipped: key {key} conflicts with {text}. Set an unused key in UserData/MimesisEscape.cfg.");
						return false;
					}
					main = val;
					world = World;
					caster = val7;
					victim = (VActor?)(object)val6;
					avatar = val2;
					controller = source;
					info = val4;
					owner = val3;
					attached = val5;
					duration = (double)val4.Duration / 1000.0;
					return true;
				}
			}
			return false;
		}

		internal string InvalidReason()
		{
			//IL_0048: Unknown result type (might be due to invalid IL or missing references)
			if (!HasCapture)
			{
				return "no capture";
			}
			if (!((Object)(object)Hub.Main != (Object)(object)main) && World == world)
			{
				PersistentData? pdata = Pdata;
				if (pdata != null && pdata.SessionJoined && (int)Pdata.ClientMode == 0)
				{
					if ((Object)(object)avatar == (Object)null || (Object)(object)main.GetMyAvatar() != (Object)(object)avatar || !avatar.IsHost || !avatar.AmIAvatar())
					{
						return "local player changed";
					}
					if (avatar.dead || !victim.IsAliveStatus())
					{
						return "player died";
					}
					if (!((VActor)caster).IsAliveStatus())
					{
						return "grabber died";
					}
					if (((VActor)caster).VRoom.IsSessionEnding || ((VActor)caster).VRoom.FindActorByObjectID(victim.ObjectID) != victim)
					{
						return "room ended or player removed";
					}
					if (InfoField.GetValue(controller) == info && controller.IsAttaching())
					{
						VActor? obj = attached;
						if (obj != null)
						{
							AttachController attachControlUnit = obj.AttachControlUnit;
							if (((attachControlUnit != null) ? new bool?(attachControlUnit.IsAttached(0)) : ((bool?)null)) == true && attached.AttachControlUnit.AttachedActorID == ((VActor)owner).ObjectID && ((VActor)owner).AttachControlUnit == controller)
							{
								return "";
							}
						}
					}
					return "native or external release";
				}
			}
			return "scene/session/role changed";
		}

		internal static string CurrentBindingConflict(Key key)
		{
			//IL_001a: Unknown result type (might be due to invalid IL or missing references)
			return BindingConflict(((Object)(object)Hub.s == (Object)null) ? null : ((Component)Hub.s).GetComponentInChildren<InputManager>(), key);
		}

		internal static bool AllowsPlayerInput(Key key)
		{
			//IL_009b: Unknown result type (might be due to invalid IL or missing references)
			InputManager val = (((Object)(object)Hub.s == (Object)null) ? null : ((Component)Hub.s).GetComponentInChildren<InputManager>());
			UIManager val2 = (((Object)(object)Hub.s == (Object)null) ? null : ((Component)Hub.s).GetComponentInChildren<UIManager>());
			DebugConsole val3 = (((Object)(object)Hub.s == (Object)null) ? null : ((Component)Hub.s).GetComponentInChildren<DebugConsole>());
			if (!Application.isFocused || Keyboard.current == null || (Object)(object)val == (Object)null || (Object)(object)val2 == (Object)null || (Object)(object)val3 == (Object)null || !val.IsCapturing() || val2.isGameMenuOpen || val2.isChangingKeyBind || val3.IsConsoleActive() || BindingConflict(val, key).Length > 0)
			{
				return false;
			}
			EventSystem current = EventSystem.current;
			GameObject val4 = ((current != null) ? current.currentSelectedGameObject : null);
			if ((Object)(object)val4 != (Object)null && ((Object)(object)val4.GetComponentInParent<TMP_InputField>() != (Object)null || (Object)(object)val4.GetComponentInParent<InputField>() != (Object)null))
			{
				return false;
			}
			if (!Object.FindObjectsByType<TMP_InputField>((FindObjectsSortMode)0).Any((TMP_InputField x) => x.isFocused))
			{
				return !Object.FindObjectsByType<InputField>((FindObjectsSortMode)0).Any((InputField x) => x.isFocused);
			}
			return false;
		}

		internal bool Release()
		{
			if (InvalidReason().Length > 0)
			{
				return false;
			}
			if (controller.DetachByRequest(victim.ObjectID, attached.ObjectID, (DetachReason)(info.IsReverseGrab ? 1 : 2)))
			{
				return !attached.AttachControlUnit.IsAttached(0);
			}
			return false;
		}

		internal void Clear()
		{
			main = null;
			world = null;
			caster = null;
			victim = null;
			avatar = null;
			controller = null;
			info = null;
			owner = null;
			attached = null;
		}

		internal static string BindingConflict(InputManager? manager, Key key)
		{
			//IL_003e: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)manager == (Object)null || Keyboard.current == null || !(StatesField.GetValue(manager) is Dictionary<InputAction, ActionState> { Count: not 0 } dictionary))
			{
				return "unavailable input bindings";
			}
			KeyControl control = Keyboard.current[key];
			return string.Join(", ", (from entry in dictionary
				where entry.Value.assignedKeys.Contains(control)
				select ((object)entry.Key/*cast due to .constrained prefix*/).ToString()).Distinct());
		}
	}
	internal static class CaptureKinds
	{
		internal const int Mimesis = 30001;

		internal const int MamaMonkey = 50001;

		internal const int QuokkaGlider = 60001;

		internal static bool Supported(int grab)
		{
			if (grab != 30001 && grab != 50001)
			{
				return grab == 60001;
			}
			return true;
		}

		internal static bool Reverse(int grab)
		{
			return grab == 60001;
		}

		internal static bool Matches(int grab, bool reverse, int monsterMasterId, bool isMimic)
		{
			switch (grab)
			{
			default:
				if (grab == 60001 && reverse)
				{
					return monsterMasterId == 20000007;
				}
				return false;
			case 50001:
				if (!reverse)
				{
					return monsterMasterId == 20000005;
				}
				return false;
			case 30001:
				return !reverse && isMimic;
			}
		}
	}
	internal sealed class EscapeNetwork
	{
		private sealed class HostCapture
		{
			internal VPlayer Player;

			internal VCreature Caster;

			internal AttachController Controller;

			internal AttachMasterInfo Info;

			internal VCreature Owner;

			internal VActor Attached;

			internal ReleaseTicket Ticket;
		}

		private sealed class ClientCapture
		{
			internal GameMainBase Main;

			internal ProtoActor Avatar;

			internal ProtoActor Caster;

			internal ProtoActor Owner;

			internal ProtoActor Attached;

			internal int GrabId;

			internal Guid Request = Guid.NewGuid();

			internal Guid Ticket;

			internal double ObservedAt;

			internal double RequestedAt;

			internal bool Requested;

			internal bool Started;

			internal bool Finished;

			internal bool ReleaseSent;

			internal bool Detached;
		}

		internal const string Command = "mimesisescape_v2";

		private static readonly FieldInfo Commands = AccessTools.Field(typeof(VWorld), "AdminCommandFuncs");

		private static readonly FieldInfo Slots = AccessTools.Field(typeof(AttachController), "_attachingActorIDs");

		private static readonly FieldInfo Creature = AccessTools.Field(typeof(AttachController), "_creature");

		private static readonly FieldInfo Info = AccessTools.Field(typeof(AttachController), "_attachInfo");

		private static readonly FieldInfo GrabHelper = AccessTools.Field(typeof(ProtoActor), "grabHelper");

		private static readonly FieldInfo GrabTarget = AccessTools.Field(GrabHelper.FieldType, "target");

		private static readonly FieldInfo GrabId = AccessTools.Field(GrabHelper.FieldType, "grabMasterID");

		private static readonly MethodInfo TimeGetter = AccessTools.PropertyGetter(typeof(Hub), "timeutil");

		private readonly Dictionary<int, HostCapture> tickets = new Dictionary<int, HostCapture>();

		private readonly Action<string> log;

		private readonly Action<double> startQte;

		private readonly Action<string> endQte;

		private readonly Func<double> hostSeconds;

		private VWorld? ticketWorld;

		private ClientCapture? client;

		private VWorld? registeredWorld;

		private AdminCommandFunc? registeredHandler;

		private object? protectedDispatcher;

		private FieldInfo? preDispatchField;

		private OnPreDispatchEventHandler? originalPreDispatch;

		private OnPreDispatchEventHandler? guardedPreDispatch;

		private readonly ConditionalWeakTable<object, RequestBudget> budgets = new ConditionalWeakTable<object, RequestBudget>();

		private readonly Stopwatch ingressClock = Stopwatch.StartNew();

		internal bool HasClientCapture
		{
			get
			{
				ClientCapture? clientCapture = client;
				if (clientCapture != null && clientCapture.Started)
				{
					return !client.Finished;
				}
				return false;
			}
		}

		internal EscapeNetwork(Action<string> log, Action<double> startQte, Action<string> endQte, Func<double> hostSeconds)
		{
			this.log = log;
			this.startQte = startQte;
			this.endQte = endQte;
			this.hostSeconds = hostSeconds;
		}

		internal void ProtectDispatcher(VWorld world)
		{
			//IL_0086: Unknown result type (might be due to invalid IL or missing references)
			//IL_0090: Expected O, but got Unknown
			//IL_00a4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ae: Expected O, but got Unknown
			object value = AccessTools.Field(typeof(VWorld), "_serverDispatchers").GetValue(world);
			Dictionary<MsgType, IDispatcher> dictionary = (Dictionary<MsgType, IDispatcher>)AccessTools.Field(typeof(ServerDispatchManager), "_messageDispatcherMap").GetValue(value);
			protectedDispatcher = dictionary[(MsgType)8000001];
			preDispatchField = AccessTools.Field(protectedDispatcher.GetType(), "PreDispatchEventHandler");
			originalPreDispatch = (OnPreDispatchEventHandler)preDispatchField.GetValue(protectedDispatcher);
			OnPreDispatchEventHandler previous = originalPreDispatch;
			guardedPreDispatch = (OnPreDispatchEventHandler)delegate(IMsg msg, IContext context)
			{
				AdminCommandReq val = (AdminCommandReq)(object)((msg is AdminCommandReq) ? msg : null);
				if (val != null && val.command == "mimesisescape_v2" && (context == null || !budgets.GetValue(context, (object _) => new RequestBudget()).Take(ingressClock.ElapsedMilliseconds) || !QteWire.Valid(val.args, fromClient: true)))
				{
					return false;
				}
				OnPreDispatchEventHandler obj = previous;
				return obj == null || obj.Invoke(msg, context);
			};
			preDispatchField.SetValue(protectedDispatcher, guardedPreDispatch);
		}

		internal void Register(VWorld world)
		{
			//IL_005b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0065: Expected O, but got Unknown
			Dictionary<string, AdminCommandFunc> obj = (Dictionary<string, AdminCommandFunc>)Commands.GetValue(world);
			if (obj.ContainsKey("mimesisescape_v2"))
			{
				throw new InvalidOperationException("QTE network command already registered.");
			}
			Unregister();
			registeredWorld = world;
			registeredHandler = (AdminCommandFunc)((VPlayer player, AdminCommandArgs args) => HandleHost(world, player, args));
			obj.Add("mimesisescape_v2", registeredHandler);
			log("Host QTE network handler registered (protocol 2).");
		}

		internal void ObserveHostAttach(AttachController controller, int victimId)
		{
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			//IL_001b: Invalid comparison between Unknown and I4
			VWorld world = CaptureAdapter.World;
			if (world == null)
			{
				return;
			}
			PersistentData? pdata = CaptureAdapter.Pdata;
			if (pdata == null || (int)pdata.ClientMode > 0)
			{
				return;
			}
			if (ticketWorld != world)
			{
				tickets.Clear();
				ticketWorld = world;
			}
			object? value = Creature.GetValue(controller);
			VCreature val = (VCreature)((value is VCreature) ? value : null);
			object? value2 = Info.GetValue(controller);
			AttachMasterInfo val2 = (AttachMasterInfo)((value2 is AttachMasterInfo) ? value2 : null);
			VActor val3 = ((val != null) ? ((VActor)val).VRoom.FindActorByObjectID(victimId) : null);
			object obj = ((val2 != null && val2.IsReverseGrab) ? ((object)val) : ((object)val3));
			VPlayer val4 = (VPlayer)((obj is VPlayer) ? obj : null);
			object obj2 = ((val2 != null && val2.IsReverseGrab) ? ((object)val3) : ((object)val));
			VCreature val5 = (VCreature)((obj2 is VCreature) ? obj2 : null);
			if (val4 != null)
			{
				tickets.Remove(((VActor)val4).ObjectID);
			}
			if (val == null || val3 == null || val5 == null || val4 == null || val4.IsHost || val2 == null)
			{
				return;
			}
			int masterID = val2.MasterID;
			bool isReverseGrab = val2.IsReverseGrab;
			int masterID2 = ((VActor)val5).MasterID;
			CreatureAIInfo creatureAIData = val5.GetCreatureAIData();
			if (CaptureKinds.Matches(masterID, isReverseGrab, masterID2, creatureAIData != null && creatureAIData.IsMimic()) && val2.Duration > 0 && TryStart(controller, val3.ObjectID, out var start))
			{
				long num = (long)Math.Min(val2.Duration, hostSeconds() * 1000.0);
				if (num > 0)
				{
					tickets[((VActor)val4).ObjectID] = new HostCapture
					{
						Player = val4,
						Caster = val5,
						Owner = val,
						Attached = val3,
						Controller = controller,
						Info = val2,
						Ticket = new ReleaseTicket(((VActor)val4).ObjectID, ((VActor)val5).ObjectID, start, start + num)
					};
				}
			}
		}

		private static bool TryStart(AttachController controller, int victim, out long start)
		{
			start = 0L;
			if (!(Slots.GetValue(controller) is Dictionary<int, (int, long)?> dictionary))
			{
				return false;
			}
			foreach ((int, long)? value in dictionary.Values)
			{
				if (value.HasValue && value.Value.Item1 == victim)
				{
					start = value.Value.Item2;
					return true;
				}
			}
			return false;
		}

		private bool Valid(HostCapture state, out long nativeStart)
		{
			//IL_002f: Unknown result type (might be due to invalid IL or missing references)
			nativeStart = 0L;
			if (CaptureAdapter.World == ticketWorld)
			{
				PersistentData? pdata = CaptureAdapter.Pdata;
				if (pdata != null && pdata.SessionJoined && (int)CaptureAdapter.Pdata.ClientMode == 0 && !((VActor)state.Caster).VRoom.IsSessionEnding && (object)((VActor)state.Caster).VRoom.FindActorByObjectID(((VActor)state.Player).ObjectID) == state.Player && ((VActor)state.Player).IsAliveStatus() && ((VActor)state.Caster).IsAliveStatus() && Info.GetValue(state.Controller) == state.Info && state.Controller.IsAttaching() && ((VActor)state.Owner).AttachControlUnit == state.Controller)
				{
					AttachController attachControlUnit = state.Attached.AttachControlUnit;
					if (attachControlUnit != null && attachControlUnit.IsAttached(0) && state.Attached.AttachControlUnit.AttachedActorID == ((VActor)state.Owner).ObjectID && TryStart(state.Controller, state.Attached.ObjectID, out nativeStart))
					{
						return nativeStart == state.Ticket.NativeStart;
					}
				}
			}
			return false;
		}

		private MsgErrorCode HandleHost(VWorld world, VPlayer sender, AdminCommandArgs args)
		{
			//IL_026f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0033: 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_0273: Unknown result type (might be due to invalid IL or missing references)
			//IL_0180: Unknown result type (might be due to invalid IL or missing references)
			//IL_0185: Unknown result type (might be due to invalid IL or missing references)
			//IL_0127: Unknown result type (might be due to invalid IL or missing references)
			//IL_012e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0217: Unknown result type (might be due to invalid IL or missing references)
			//IL_0241: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				if (world != CaptureAdapter.World || !tickets.TryGetValue(((VActor)sender).ObjectID, out HostCapture value) || sender != value.Player || !Valid(value, out var nativeStart))
				{
					return Reject(sender, args);
				}
				long now = Now();
				string text = args["op"];
				if (text == "begin" && Guid.TryParseExact(args["request"], "N", out var result) && int.TryParse(args["caster"], out var result2) && result2 == ((VActor)value.Caster).ObjectID && value.Ticket.Remaining(now) > 0)
				{
					string[] obj = new string[6]
					{
						"op=grant^request=",
						result.ToString("N"),
						"^token=",
						null,
						null,
						null
					};
					Guid token = value.Ticket.Token;
					obj[3] = token.ToString("N");
					obj[4] = "^ms=";
					obj[5] = value.Ticket.Remaining(now).ToString(CultureInfo.InvariantCulture);
					((VActor)sender).SendToMe((IMsg)(object)Message(string.Concat(obj)));
					return (MsgErrorCode)0;
				}
				if (text != "release" || !Guid.TryParseExact(args["token"], "N", out var result3) || !value.Ticket.TryConsume(result3, ((VActor)sender).ObjectID, ((VActor)value.Caster).ObjectID, nativeStart, now, nativeCaptureValid: true))
				{
					return Reject(sender, args);
				}
				bool flag = value.Controller.DetachByRequest(((VActor)sender).ObjectID, value.Attached.ObjectID, (DetachReason)(value.Info.IsReverseGrab ? 1 : 2)) && !value.Attached.AttachControlUnit.IsAttached(0);
				tickets.Remove(((VActor)sender).ObjectID);
				((VActor)sender).SendToMe((IMsg)(object)Message("op=result^token=" + result3.ToString("N") + "^ok=" + (flag ? "1" : "0")));
				log(flag ? "Client QTE: native ActiveByVictim release completed on host." : "Client QTE: native release rejected; no retry.");
				return (MsgErrorCode)((!flag) ? 16 : 0);
			}
			catch (Exception ex)
			{
				log("Client QTE request rejected: " + ex.GetType().Name + ".");
				return (MsgErrorCode)16;
			}
		}

		private static AdminCommandReq Message(string args)
		{
			//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_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_0018: Expected O, but got Unknown
			return new AdminCommandReq
			{
				command = "mimesisescape_v2",
				args = args
			};
		}

		private static long Now()
		{
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			return ((TimeUtil)TimeGetter.Invoke(Hub.s, null)).GetCurrentTickMilliSec();
		}

		private static MsgErrorCode Reject(VPlayer sender, AdminCommandArgs args)
		{
			//IL_0051: Unknown result type (might be due to invalid IL or missing references)
			if (args["op"] == "release" && Guid.TryParseExact(args["token"], "N", out var result))
			{
				((VActor)sender).SendToMe((IMsg)(object)Message("op=result^token=" + result.ToString("N") + "^ok=0"));
			}
			return (MsgErrorCode)16;
		}

		internal void ObserveClientAttach(ProtoActor caster, AttachActorSig sig)
		{
			//IL_003c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0042: Invalid comparison between Unknown and I4
			//IL_00a1: Unknown result type (might be due to invalid IL or missing references)
			GameMainBase main = Hub.Main;
			ProtoActor val = ((main != null) ? main.GetMyAvatar() : null);
			if ((Object)(object)val == (Object)null || val.IsHost || !val.AmIAvatar() || ((IActorMsg)sig).actorID != caster.ActorID)
			{
				return;
			}
			if ((int)sig.state == 1)
			{
				if ((Object)(object)client?.Owner == (Object)(object)caster && client.Attached.ActorID == sig.targetID)
				{
					client.Detached = true;
					if (client.ReleaseSent)
					{
						log("Client QTE: native detach observed after release request.");
					}
				}
			}
			else
			{
				if ((int)sig.state != 0 || !CaptureKinds.Supported(sig.grabMasterID))
				{
					return;
				}
				bool flag = CaptureKinds.Reverse(sig.grabMasterID);
				if ((flag ? ((IActorMsg)sig).actorID : sig.targetID) == val.ActorID)
				{
					ProtoActor actorByActorID = main.GetActorByActorID(sig.targetID);
					ProtoActor val2 = (ProtoActor)(flag ? ((object)actorByActorID) : ((object)caster));
					if (!((Object)(object)actorByActorID == (Object)null) && !((Object)(object)val2 == (Object)null) && CaptureKinds.Matches(sig.grabMasterID, flag, val2.monsterMasterID, val2.IsMimic()) && (client == null || !((Object)(object)client.Main == (Object)(object)main) || !((Object)(object)client.Owner == (Object)(object)caster) || !((Object)(object)client.Attached == (Object)(object)actorByActorID) || client.Detached))
					{
						endQte("new client capture");
						client = new ClientCapture
						{
							Main = main,
							Avatar = val,
							Caster = val2,
							Owner = caster,
							Attached = actorByActorID,
							GrabId = sig.grabMasterID,
							ObservedAt = Time.realtimeSinceStartupAsDouble
						};
					}
				}
			}
		}

		private static bool VisualMatches(ClientCapture state)
		{
			if ((Object)(object)state.Avatar == (Object)null || (Object)(object)state.Caster == (Object)null || (Object)(object)state.Owner == (Object)null || (Object)(object)state.Attached == (Object)null || state.Avatar.dead || state.Caster.dead || !state.Attached.IsGrabbedByOther)
			{
				return false;
			}
			object value = GrabHelper.GetValue(state.Owner);
			if (value != null && GrabTarget.GetValue(value) == state.Attached)
			{
				return (int)GrabId.GetValue(value) == state.GrabId;
			}
			return false;
		}

		internal string InvalidClientReason()
		{
			//IL_004d: Unknown result type (might be due to invalid IL or missing references)
			if (client == null || client.Detached)
			{
				return "native or external release";
			}
			if (!((Object)(object)Hub.Main != (Object)(object)client.Main))
			{
				PersistentData? pdata = CaptureAdapter.Pdata;
				if (pdata != null && pdata.SessionJoined && (int)CaptureAdapter.Pdata.ClientMode != 0 && !((Object)(object)client.Main.GetMyAvatar() != (Object)(object)client.Avatar) && client.Avatar.AmIAvatar())
				{
					if (!VisualMatches(client))
					{
						return "native release or death";
					}
					return "";
				}
			}
			return "scene/session/role changed";
		}

		internal void Tick(Key key)
		{
			//IL_0132: Unknown result type (might be due to invalid IL or missing references)
			if (ticketWorld != CaptureAdapter.World)
			{
				tickets.Clear();
				ticketWorld = CaptureAdapter.World;
			}
			long nativeStart;
			int[] array = (from x in tickets
				where !Valid(x.Value, out nativeStart) || x.Value.Ticket.Remaining(Now()) == 0
				select x.Key).ToArray();
			foreach (int key2 in array)
			{
				tickets.Remove(key2);
			}
			ClientCapture clientCapture = client;
			if (clientCapture == null || clientCapture.Finished)
			{
				return;
			}
			double realtimeSinceStartupAsDouble = Time.realtimeSinceStartupAsDouble;
			if (!((Object)(object)Hub.Main != (Object)(object)clientCapture.Main))
			{
				PersistentData? pdata = CaptureAdapter.Pdata;
				if (pdata != null && pdata.SessionJoined && !((Object)(object)clientCapture.Avatar == (Object)null) && !clientCapture.Avatar.dead)
				{
					if (realtimeSinceStartupAsDouble - clientCapture.ObservedAt >= 30.0 && !clientCapture.Started)
					{
						clientCapture.Finished = true;
						log("Client QTE unavailable: no valid grant from host before native capture expired. Host needs the same mod version.");
					}
					else if (!clientCapture.Requested && VisualMatches(clientCapture))
					{
						string text = CaptureAdapter.CurrentBindingConflict(key);
						if (text.Length > 0 || !Application.isFocused)
						{
							clientCapture.Finished = true;
							log("Client QTE skipped: input unavailable or key conflict: " + text + ".");
						}
						else
						{
							clientCapture.Requested = true;
							clientCapture.RequestedAt = realtimeSinceStartupAsDouble;
							clientCapture.Main.SendPacket((IMsg)(object)Message("op=begin^request=" + clientCapture.Request.ToString("N") + "^caster=" + clientCapture.Caster.ActorID));
						}
					}
					return;
				}
			}
			clientCapture.Finished = true;
		}

		internal void Receive(IMsg packet)
		{
			//IL_0075: Unknown result type (might be due to invalid IL or missing references)
			//IL_007b: Expected O, but got Unknown
			AdminCommandReq val = (AdminCommandReq)(object)((packet is AdminCommandReq) ? packet : null);
			if (val == null || val.command != "mimesisescape_v2" || !QteWire.Valid(val.args, fromClient: false) || client == null || (Object)(object)Hub.Main != (Object)(object)client.Main || (Object)(object)client.Avatar == (Object)null || client.Avatar.IsHost)
			{
				return;
			}
			AdminCommandArgs val2 = new AdminCommandArgs(val.args);
			ClientCapture clientCapture = client;
			Guid result4;
			if (val2["op"] == "grant" && !clientCapture.Finished && clientCapture.Requested && !clientCapture.Started && Guid.TryParseExact(val2["request"], "N", out var result) && result == clientCapture.Request && Guid.TryParseExact(val2["token"], "N", out var result2) && result2 != Guid.Empty && long.TryParse(val2["ms"], out var result3) && result3 > 0 && result3 <= 30000 && InvalidClientReason().Length == 0)
			{
				double num = ReleaseTicket.ClientWindow((double)result3 / 1000.0, clientCapture.RequestedAt, Time.realtimeSinceStartupAsDouble);
				if (num <= 0.0)
				{
					clientCapture.Finished = true;
					return;
				}
				clientCapture.Ticket = result2;
				clientCapture.Started = true;
				startQte(num);
				log("Capture started: grab " + clientCapture.GrabId + "; role=client; host granted a one-use release ticket.");
			}
			else if (val2["op"] == "result" && clientCapture.ReleaseSent && Guid.TryParseExact(val2["token"], "N", out result4) && result4 == clientCapture.Ticket)
			{
				log((val2["ok"] == "1") ? "Client QTE: host confirmed native release." : "Client QTE: host rejected release; no retry.");
			}
		}

		internal bool RequestRelease()
		{
			ClientCapture clientCapture = client;
			if (clientCapture == null || !HasClientCapture || clientCapture.ReleaseSent || InvalidClientReason().Length > 0)
			{
				return false;
			}
			clientCapture.ReleaseSent = true;
			clientCapture.Finished = true;
			clientCapture.Main.SendPacket((IMsg)(object)Message("op=release^token=" + clientCapture.Ticket.ToString("N")));
			return true;
		}

		internal void CancelLocal()
		{
			if (client != null)
			{
				client.Finished = true;
			}
		}

		internal void Reset()
		{
			client = null;
			tickets.Clear();
		}

		internal void Dispose()
		{
			Reset();
			Unregister();
		}

		private void Unregister()
		{
			if (protectedDispatcher != null && object.Equals(preDispatchField.GetValue(protectedDispatcher), guardedPreDispatch))
			{
				preDispatchField.SetValue(protectedDispatcher, originalPreDispatch);
			}
			protectedDispatcher = null;
			originalPreDispatch = null;
			guardedPreDispatch = null;
			preDispatchField = null;
			if (registeredWorld != null)
			{
				Dictionary<string, AdminCommandFunc> dictionary = (Dictionary<string, AdminCommandFunc>)Commands.GetValue(registeredWorld);
				if (dictionary.TryGetValue("mimesisescape_v2", out var value) && (Delegate?)(object)value == (Delegate?)(object)registeredHandler)
				{
					dictionary.Remove("mimesisescape_v2");
				}
			}
			registeredWorld = null;
			registeredHandler = null;
		}
	}
	internal sealed class EscapeText
	{
		internal readonly string Title;

		internal readonly string Prompt;

		internal readonly string Conflict;

		internal readonly string Error;

		internal readonly string Hud;

		internal readonly string Seconds;

		internal EscapeText(string title, string prompt, string conflict, string error, string hud, string seconds)
		{
			Title = title;
			Prompt = prompt;
			Conflict = conflict;
			Error = error;
			Hud = hud;
			Seconds = seconds;
		}
	}
	internal static class EscapeTranslations
	{
		private static readonly Dictionary<string, EscapeText> Texts = new Dictionary<string, EscapeText>(StringComparer.OrdinalIgnoreCase)
		{
			["en"] = new EscapeText("Escape (QTE)", "Press a key (Esc to cancel)", "{0} is in use — choose another or Esc", "Could not save — try again", "Escape", "s"),
			["ko"] = new EscapeText("탈출 (QTE)", "키를 누르세요 (Esc: 취소)", "{0} 사용 중 — 다른 키 또는 Esc", "저장 실패 — 다시 선택하세요", "탈출", "초"),
			["es"] = new EscapeText("Liberarse (QTE)", "Pulsa una tecla (Esc: cancelar)", "{0} en uso — otra tecla o Esc", "Error al guardar — inténtalo de nuevo", "Liberarse", "s"),
			["ja"] = new EscapeText("脱出 (QTE)", "キーを押す(Esc:キャンセル)", "{0} は使用中 — 別のキーか Esc", "保存失敗 — もう一度選択", "脱出", "秒"),
			["fr"] = new EscapeText("Libération (QTE)", "Appuyez sur une touche (Échap : annuler)", "{0} utilisée — autre touche ou Échap", "Échec de l’enregistrement — réessayez", "Libération", "s"),
			["de"] = new EscapeText("Befreiung (QTE)", "Taste drücken (Esc: Abbrechen)", "{0} belegt — andere Taste oder Esc", "Speichern fehlgeschlagen — erneut wählen", "Befreiung", "s"),
			["zh_cn"] = new EscapeText("挣脱(QTE)", "按下按键(Esc 取消)", "{0} 已占用 — 换一个键或按 Esc", "保存失败 — 请重新选择", "挣脱", "秒"),
			["zh_tw"] = new EscapeText("掙脫(QTE)", "按下按鍵(Esc 取消)", "{0} 已被使用 — 換一個鍵或按 Esc", "儲存失敗 — 請重新選擇", "掙脫", "秒"),
			["pt_br"] = new EscapeText("Libertar-se (QTE)", "Pressione uma tecla (Esc: cancelar)", "{0} em uso — outra tecla ou Esc", "Falha ao salvar — tente novamente", "Libertar-se", "s"),
			["it"] = new EscapeText("Liberazione (QTE)", "Premi un tasto (Esc: annulla)", "{0} occupato — altro tasto o Esc", "Salvataggio fallito — riprova", "Liberazione", "s"),
			["ru"] = new EscapeText("Освобождение (QTE)", "Нажмите клавишу (Esc — отмена)", "{0} занята — другая клавиша или Esc", "Ошибка сохранения — повторите выбор", "Освобождение", "с"),
			["uk"] = new EscapeText("Звільнення (QTE)", "Натисніть клавішу (Esc — скасувати)", "{0} зайнята — інша клавіша або Esc", "Помилка збереження — оберіть знову", "Звільнення", "с"),
			["vi"] = new EscapeText("Thoát (QTE)", "Nhấn phím (Esc để hủy)", "{0} đã dùng — chọn phím khác hoặc Esc", "Không thể lưu — hãy chọn lại", "Thoát", "giây"),
			["th"] = new EscapeText("หลบหน\u0e35 (QTE)", "กดป\u0e38\u0e48ม (Esc เพ\u0e37\u0e48อยกเล\u0e34ก)", "{0} ถ\u0e39กใช\u0e49แล\u0e49ว — เล\u0e37อกป\u0e38\u0e48มอ\u0e37\u0e48นหร\u0e37อ Esc", "บ\u0e31นท\u0e36กไม\u0e48สำเร\u0e47จ — เล\u0e37อกอ\u0e35กคร\u0e31\u0e49ง", "หลบหน\u0e35", "ว\u0e34"),
			["tr"] = new EscapeText("Kurtulma (QTE)", "Bir tuşa basın (Esc: iptal)", "{0} kullanımda — başka tuş veya Esc", "Kaydedilemedi — yeniden seçin", "Kurtulma", "sn"),
			["pl"] = new EscapeText("Uwolnienie (QTE)", "Naciśnij klawisz (Esc: anuluj)", "{0} zajęty — inny klawisz lub Esc", "Nie udało się zapisać — wybierz ponownie", "Uwolnienie", "s"),
			["ar"] = new EscapeText("التحرر (QTE)", "اضغط مفتاح\u064bا (Esc للإلغاء)", "{0} مستخدم — اختر مفتاح\u064bا آخر أو Esc", "تعذر الحفظ — حاول مجدد\u064bا", "التحرر", "ث"),
			["da"] = new EscapeText("Slip fri (QTE)", "Tryk på en tast (Esc: annuller)", "{0} bruges — vælg en anden tast eller Esc", "Kunne ikke gemme — prøv igen", "Slip fri", "s")
		};

		internal static EscapeText Get(string? language)
		{
			if (language != null && Texts.TryGetValue(language, out EscapeText value) && value != null)
			{
				return value;
			}
			return Texts["en"];
		}
	}
	internal static class GameLocalization
	{
		private static readonly FieldInfo LanguageField = AccessTools.Field(typeof(Hub), "lcman");

		private static readonly FieldInfo RtlField = AccessTools.Field(typeof(Hub), "rtlEnforcer");

		internal static string Language
		{
			get
			{
				object obj2;
				if (!((Object)(object)Hub.s == (Object)null))
				{
					object? value = LanguageField.GetValue(Hub.s);
					object? obj = ((value is L10NManager) ? value : null);
					obj2 = ((obj != null) ? ((L10NManager)obj).language : null);
					if (obj2 == null)
					{
						return "en";
					}
				}
				else
				{
					obj2 = "en";
				}
				return (string)obj2;
			}
		}

		internal static EscapeText Text => EscapeTranslations.Get(Language);

		internal static void ApplyDirection(TMP_Text text)
		{
			RTLEnforcer val = (RTLEnforcer)(((Object)(object)Hub.s == (Object)null) ? null : /*isinst with value type is only supported in some contexts*/);
			if ((Object)(object)val != (Object)null)
			{
				val.ApplyText(text);
			}
			else if (Language == "ar")
			{
				text.isRightToLeftText = true;
				text.text = ArabicFixer.FixForRTL(text.text, true, false);
			}
			else
			{
				text.isRightToLeftText = false;
			}
		}
	}
	internal sealed class KeybindSettings
	{
		private readonly Func<Key> currentKey;

		private readonly Action<Key> saveKey;

		private UIPrefab_ControlSetting? screen;

		private UIPrefab_KeybindListItem? row;

		private UIManager? ui;

		private bool waiting;

		private bool released;

		private double deadline;

		private string? displayedLanguage;

		internal KeybindSettings(Func<Key> currentKey, Action<Key> saveKey)
		{
			this.currentKey = currentKey;
			this.saveKey = saveKey;
		}

		internal void Attach(UIPrefab_ControlSetting target)
		{
			//IL_0070: Unknown result type (might be due to invalid IL or missing references)
			//IL_007a: Expected O, but got Unknown
			if ((Object)(object)screen != (Object)(object)target || (Object)(object)row == (Object)null)
			{
				Dispose();
				screen = target;
				row = Object.Instantiate<GameObject>(((Component)target.UE_UIPrefab_KeybindListItem).gameObject, target.UE_Contents).GetComponent<UIPrefab_KeybindListItem>();
				((Object)row).name = "MimesisEscapeKeybind";
				Toggle uE_UI_Toggle_IconBox_KeyboardMouse = row.UE_UI_Toggle_IconBox_KeyboardMouse;
				uE_UI_Toggle_IconBox_KeyboardMouse.group = null;
				uE_UI_Toggle_IconBox_KeyboardMouse.onValueChanged = new ToggleEvent();
				((UnityEvent<bool>)(object)uE_UI_Toggle_IconBox_KeyboardMouse.onValueChanged).AddListener((UnityAction<bool>)delegate(bool on)
				{
					if (on)
					{
						Listen();
					}
				});
				row.SetGamepadKey("", false);
				((UIPrefabScript)row).Show(true);
				if (!((Component)row).gameObject.activeSelf)
				{
					((Component)row).gameObject.SetActive(true);
				}
			}
			UIPrefab_KeybindListItem val = ((IEnumerable<UIPrefab_KeybindListItem>)((Component)target.UE_Contents).GetComponentsInChildren<UIPrefab_KeybindListItem>()).FirstOrDefault((Func<UIPrefab_KeybindListItem, bool>)delegate(UIPrefab_KeybindListItem item)
			{
				//IL_001a: Unknown result type (might be due to invalid IL or missing references)
				//IL_0020: Invalid comparison between Unknown and I4
				if ((Object)(object)item != (Object)(object)row)
				{
					Mapping mapping = item.mapping;
					if (mapping == null)
					{
						return false;
					}
					return (int)mapping.action == 6;
				}
				return false;
			});
			((Component)row).transform.SetAsLastSibling();
			if ((Object)(object)val != (Object)null)
			{
				((Component)row).transform.SetSiblingIndex(((Component)val).transform.GetSiblingIndex() + 1);
			}
			if (!waiting)
			{
				Refresh();
			}
		}

		private void Refresh()
		{
			//IL_0053: Unknown result type (might be due to invalid IL or missing references)
			//IL_0058: Unknown result type (might be due to invalid IL or missing references)
			//IL_003c: Unknown result type (might be due to invalid IL or missing references)
			if (!((Object)(object)row == (Object)null))
			{
				row.ResetToggleState();
				SetInfoText(GameLocalization.Text.Title);
				string text = ((Keyboard.current == null) ? ((object)currentKey()/*cast due to .constrained prefix*/).ToString() : ((InputControl)Keyboard.current[currentKey()]).name);
				row.SetKeyboardMouseKey("k_" + text, true);
			}
		}

		private void Listen()
		{
			if (!((Object)(object)screen == (Object)null) && !((Object)(object)row == (Object)null) && !((Object)(object)Hub.s == (Object)null) && Keyboard.current != null)
			{
				ui = ((Component)Hub.s).GetComponentInChildren<UIManager>();
				if ((Object)(object)ui == (Object)null || ui.isChangingKeyBind)
				{
					row.ResetToggleState();
					return;
				}
				ui.isChangingKeyBind = true;
				waiting = true;
				released = false;
				deadline = Time.realtimeSinceStartupAsDouble + 15.0;
				row.SetWaitingForInput(false, true);
				SetInfoText(GameLocalization.Text.Prompt);
			}
		}

		internal void Tick()
		{
			//IL_00bb: Unknown result type (might be due to invalid IL or missing references)
			//IL_0107: Unknown result type (might be due to invalid IL or missing references)
			//IL_0155: Unknown result type (might be due to invalid IL or missing references)
			//IL_0173: Unknown result type (might be due to invalid IL or missing references)
			//IL_0197: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)screen != (Object)null && (Object)(object)row != (Object)null && ((Component)screen).gameObject.activeInHierarchy && displayedLanguage != GameLocalization.Language)
			{
				if (waiting)
				{
					SetInfoText(GameLocalization.Text.Prompt);
				}
				else
				{
					Refresh();
				}
			}
			if (!waiting)
			{
				return;
			}
			if ((Object)(object)screen == (Object)null || !((Component)screen).gameObject.activeInHierarchy || !Application.isFocused || Keyboard.current == null || Time.realtimeSinceStartupAsDouble >= deadline)
			{
				Cancel();
				return;
			}
			Keyboard current = Keyboard.current;
			if (!released)
			{
				released = !((IEnumerable<KeyControl>)(object)current.allKeys).Any((KeyControl button) => ((ButtonControl)button).isPressed);
				return;
			}
			if (((ButtonControl)current.escapeKey).wasPressedThisFrame)
			{
				Cancel();
				return;
			}
			KeyControl val = ((IEnumerable<KeyControl>)(object)current.allKeys).FirstOrDefault((Func<KeyControl, bool>)((KeyControl button) => ((ButtonControl)button).wasPressedThisFrame));
			if (val == null)
			{
				return;
			}
			if (CaptureAdapter.BindingConflict(((Object)(object)Hub.s == (Object)null) ? null : ((Component)Hub.s).GetComponentInChildren<InputManager>(), val.keyCode).Length > 0)
			{
				SetInfoText(string.Format(GameLocalization.Text.Conflict, val.keyCode));
				released = false;
				return;
			}
			try
			{
				saveKey(val.keyCode);
				Cancel();
			}
			catch (Exception)
			{
				SetInfoText(GameLocalization.Text.Error);
				released = false;
				throw;
			}
		}

		private void SetInfoText(string text)
		{
			if (!((Object)(object)row == (Object)null))
			{
				row.SetInfoText(text);
				GameLocalization.ApplyDirection(row.UE_InfoText);
				displayedLanguage = GameLocalization.Language;
			}
		}

		internal void Cancel()
		{
			if (waiting)
			{
				waiting = false;
				if ((Object)(object)ui != (Object)null)
				{
					ui.isChangingKeyBind = false;
				}
				Refresh();
				EventSystem current = EventSystem.current;
				if (current != null)
				{
					current.SetSelectedGameObject((GameObject)null);
				}
			}
		}

		internal void Dispose()
		{
			Cancel();
			if ((Object)(object)row != (Object)null)
			{
				Object.Destroy((Object)(object)((Component)row).gameObject);
			}
			row = null;
			screen = null;
		}
	}
	public sealed class EscapeMod : MelonMod
	{
		private static EscapeMod? instance;

		private readonly QteSession qte = new QteSession();

		private readonly QteHud hud = new QteHud();

		private CaptureAdapter? capture;

		private EscapeNetwork? network;

		private bool clientAttempt;

		private KeybindSettings? keybindSettings;

		private Key key = (Key)99;

		private int required = 5;

		private double seconds = 3.0;

		private long captureNumber;

		private bool ready;

		private bool reportedRole;

		private bool reportedSteam;

		private bool reportedBindings;

		private bool show;

		private static string ConfigPath => Path.Combine(Path.GetDirectoryName(Application.dataPath), "UserData", "MimesisEscape.cfg");

		private void Log(string message)
		{
			((MelonBase)this).LoggerInstance.Msg(message);
		}

		public override void OnInitializeMelon()
		{
			//IL_0127: Unknown result type (might be due to invalid IL or missing references)
			//IL_0134: Expected O, but got Unknown
			//IL_0162: Unknown result type (might be due to invalid IL or missing references)
			//IL_016f: Expected O, but got Unknown
			//IL_019d: Unknown result type (might be due to invalid IL or missing references)
			//IL_01aa: Expected O, but got Unknown
			//IL_01d8: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e5: Expected O, but got Unknown
			//IL_0225: Unknown result type (might be due to invalid IL or missing references)
			//IL_0232: Expected O, but got Unknown
			//IL_0260: Unknown result type (might be due to invalid IL or missing references)
			//IL_026d: Expected O, but got Unknown
			//IL_02c8: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				VerifyFile("Managed/Assembly-CSharp.dll", "5a1c9b77719b9282d4b91a070f5db2a127adbe74a95346eb8f1a45872a795759");
				VerifyFile("StreamingAssets/masterdata/GrabData.json", "f4ec14e623f6ee6ade39a36430049b6e9ad898ec836c0fbfd78887c1955b29cf");
				VerifyFile("StreamingAssets/masterdata/AbnormalData.json", "5ab6f6c0c3927e014a44949ee2d707534aaf0b18460b63004f68d8a7659f755b");
				VerifyFile("StreamingAssets/masterdata/MonsterSkillSequenceData.json", "477d83cc9336dad97deacdc29c8b3bb4c657f3a2fe1e7762dcf3ce44533ae206");
				VerifyFile("StreamingAssets/masterdata/MonsterData.json", "733a7cbc74ac13a3fe90cd179318e454b461098b701d3becb0b7be919b45e788");
				VerifyFile("StreamingAssets/masterdata/MonsterSkillData.json", "8fca4c756d0e41ec0d4009c7d25e16bea6303a996ce89804a5e9e95bfb218a28");
				ReadConfig();
				capture = new CaptureAdapter(Log);
				network = new EscapeNetwork(Log, BeginClientCapture, EndCapture, () => seconds);
				keybindSettings = new KeybindSettings(() => key, SaveKey);
				instance = this;
				((MelonBase)this).HarmonyInstance.Patch((MethodBase)AccessTools.Method(typeof(AttachController), "AttachBySkill", new Type[2]
				{
					typeof(int),
					typeof(int)
				}, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(typeof(EscapeMod), "AfterAttach", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				((MelonBase)this).HarmonyInstance.Patch((MethodBase)AccessTools.Method(typeof(UIPrefab_ControlSetting), "RefreshKeybindItems", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(typeof(EscapeMod), "AfterKeybindRefresh", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				((MelonBase)this).HarmonyInstance.Patch((MethodBase)AccessTools.Method(typeof(VWorld), "RegisterCommand", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(typeof(EscapeMod), "AfterRegisterCommands", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				((MelonBase)this).HarmonyInstance.Patch((MethodBase)AccessTools.Method(typeof(VWorld), "RegisterAdminProtocol", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(typeof(EscapeMod), "AfterRegisterAdminProtocol", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				((MelonBase)this).HarmonyInstance.Patch((MethodBase)AccessTools.Method(typeof(ProtoActor), "OnPacket", new Type[1] { typeof(AttachActorSig) }, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(typeof(EscapeMod), "AfterAttachPacket", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				((MelonBase)this).HarmonyInstance.Patch((MethodBase)AccessTools.Method(typeof(NetworkManagerV2), "TryDequeueMsg", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(typeof(EscapeMod), "AfterDequeue", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				ready = true;
				Application.focusChanged += OnFocusChanged;
				Log("Loaded for Steam build 26558062 / game " + Application.version + " / Unity " + Application.unityVersion + "; " + $"Mimesis, Mama Monkey and Quokka Glider grabs; host + opt-in clients (same mod required on host); {required} separate {key} presses / {seconds.ToString(CultureInfo.InvariantCulture)} s. Hashes verified.");
			}
			catch (Exception ex)
			{
				Disable(ex);
			}
		}

		private static void AfterKeybindRefresh(UIPrefab_ControlSetting __instance)
		{
			EscapeMod? escapeMod = instance;
			if (escapeMod == null || !escapeMod.ready)
			{
				return;
			}
			try
			{
				instance.keybindSettings.Attach(__instance);
			}
			catch (Exception ex)
			{
				((MelonBase)instance).LoggerInstance.Error("Key settings UI: " + ex.Message);
			}
		}

		private static void AfterAttach(AttachController __instance, int grabMasterID, int attachedActorID, bool __result)
		{
			if (!__result || !CaptureKinds.Supported(grabMasterID))
			{
				return;
			}
			EscapeMod? escapeMod = instance;
			if (escapeMod == null || !escapeMod.ready)
			{
				return;
			}
			try
			{
				instance.network.ObserveHostAttach(__instance, attachedActorID);
				instance.BeginCapture(__instance, attachedActorID);
			}
			catch (Exception ex)
			{
				instance.Disable(ex);
			}
		}

		private static void AfterRegisterCommands(VWorld __instance)
		{
			EscapeMod? escapeMod = instance;
			if (escapeMod == null || !escapeMod.ready)
			{
				return;
			}
			try
			{
				instance.network.Register(__instance);
			}
			catch (Exception ex)
			{
				instance.Disable(ex);
			}
		}

		private static void AfterRegisterAdminProtocol(VWorld __instance)
		{
			EscapeMod? escapeMod = instance;
			if (escapeMod == null || !escapeMod.ready)
			{
				return;
			}
			try
			{
				instance.network.ProtectDispatcher(__instance);
			}
			catch (Exception ex)
			{
				instance.Disable(ex);
			}
		}

		private static void AfterAttachPacket(ProtoActor __instance, AttachActorSig sig)
		{
			EscapeMod? escapeMod = instance;
			if (escapeMod == null || !escapeMod.ready)
			{
				return;
			}
			try
			{
				instance.network.ObserveClientAttach(__instance, sig);
			}
			catch (Exception ex)
			{
				instance.Disable(ex);
			}
		}

		private static void AfterDequeue(bool __result, (bool, IMsg) msgPair)
		{
			if (!__result)
			{
				return;
			}
			EscapeMod? escapeMod = instance;
			if (escapeMod == null || !escapeMod.ready)
			{
				return;
			}
			try
			{
				instance.network.Receive(msgPair.Item2);
			}
			catch (Exception ex)
			{
				instance.Disable(ex);
			}
		}

		private void BeginClientCapture(double grantedSeconds)
		{
			//IL_004e: Unknown result type (might be due to invalid IL or missing references)
			qte.Cancel();
			clientAttempt = true;
			qte.Begin(++captureNumber, Time.realtimeSinceStartupAsDouble, required, Math.Min(seconds, grantedSeconds), Keyboard.current == null || ((ButtonControl)Keyboard.current[key]).isPressed);
		}

		private void BeginCapture(AttachController controller, int victim)
		{
			//IL_0009: Unknown result type (might be due to invalid IL or missing references)
			//IL_0056: Unknown result type (might be due to invalid IL or missing references)
			if (capture.Begin(controller, victim, key, out var duration))
			{
				double duration2 = Math.Min(seconds, duration);
				qte.Begin(++captureNumber, Time.realtimeSinceStartupAsDouble, required, duration2, Keyboard.current == null || ((ButtonControl)Keyboard.current[key]).isPressed);
				Log(string.Format("Capture started: grab {0}; QTE window={1} s; native={2:0.###} s; role=host.", capture.CurrentGrabId, duration2.ToString("0.###", CultureInfo.InvariantCulture), duration));
			}
		}

		public override void OnLateUpdate()
		{
			//IL_016a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0148: Unknown result type (might be due to invalid IL or missing references)
			//IL_0240: Unknown result type (might be due to invalid IL or missing references)
			//IL_0258: Unknown result type (might be due to invalid IL or missing references)
			//IL_036b: Unknown result type (might be due to invalid IL or missing references)
			if (!ready)
			{
				return;
			}
			try
			{
				try
				{
					keybindSettings.Tick();
				}
				catch (Exception ex)
				{
					((MelonBase)this).LoggerInstance.Error("Key binding was not saved: " + ex.Message);
				}
				if (!reportedSteam)
				{
					try
					{
						int appBuildId = SteamApps.GetAppBuildId();
						string text = default(string);
						bool currentBetaName = SteamApps.GetCurrentBetaName(ref text, 128);
						Log(string.Format("Steam identity: build={0}; branch={1}.", appBuildId, currentBetaName ? text : "public (no beta)"));
						reportedSteam = true;
						if (appBuildId != 26558062)
						{
							throw new NotSupportedException("Steam build changed; mod disabled pending audit.");
						}
					}
					catch (InvalidOperationException)
					{
					}
				}
				GameMainBase main = Hub.Main;
				ProtoActor val = ((main != null) ? main.GetMyAvatar() : null);
				if (!reportedBindings && (Object)(object)Hub.s != (Object)null)
				{
					InputManager componentInChildren = ((Component)Hub.s).GetComponentInChildren<InputManager>();
					if (componentInChildren != null && componentInChildren.data?.data?.Count > 0 && Keyboard.current != null)
					{
						Log($"Input audit: E={CaptureAdapter.BindingConflict(componentInChildren, (Key)19)}; F6={CaptureAdapter.BindingConflict(componentInChildren, (Key)99)}; configured={key}.");
						reportedBindings = true;
					}
				}
				network.Tick(key);
				if ((Object)(object)val == (Object)null)
				{
					reportedRole = false;
				}
				else if (!reportedRole)
				{
					PersistentData? pdata = CaptureAdapter.Pdata;
					if (pdata != null && pdata.SessionJoined)
					{
						reportedRole = true;
						bool isHost = val.IsHost;
						Log(isHost ? "Role=host. QTE enabled for supported local grabs." : "Role=client. QTE requires a per-capture grant from a host running the same mod; unmodded players are unaffected.");
					}
				}
				if (!clientAttempt && !capture.HasCapture)
				{
					show = false;
					hud.Hide();
					return;
				}
				string text2 = (clientAttempt ? network.InvalidClientReason() : capture.InvalidReason());
				if (text2.Length > 0)
				{
					EndCapture(text2);
					return;
				}
				if (!Application.isFocused)
				{
					EndCapture("focus lost");
					return;
				}
				bool flag = CaptureAdapter.AllowsPlayerInput(key);
				Keyboard current = Keyboard.current;
				KeyControl val2 = ((current != null) ? current[key] : null);
				QteState state = qte.State;
				bool num = qte.Tick(Time.realtimeSinceStartupAsDouble, val2 != null && ((ButtonControl)val2).isPressed, val2 != null && ((ButtonControl)val2).wasPressedThisFrame, flag);
				show = qte.State == QteState.Active && flag;
				if (num)
				{
					if (clientAttempt)
					{
						bool flag2 = network.RequestRelease();
						Log(flag2 ? "QTE succeeded: release requested from host; awaiting native confirmation." : "QTE succeeded but capture is no longer valid; no release request or retry.");
						clientAttempt = false;
					}
					else
					{
						bool flag3 = capture.Release();
						Log(flag3 ? "QTE succeeded: native ActiveByVictim release completed on host." : "QTE succeeded but native release was rejected; no retry or fallback mutations.");
						capture.Clear();
					}
					show = false;
				}
				else if (state == QteState.Active && qte.State == QteState.Failed)
				{
					Log("QTE timed out; native grab continues unchanged.");
				}
				if (show)
				{
					hud.Show(Hub.Main, $"{GameLocalization.Text.Hud}  [{key}]   {qte.Progress}/{qte.Required}   {qte.Remaining(Time.realtimeSinceStartupAsDouble):0.0} {GameLocalization.Text.Seconds}");
				}
				else
				{
					hud.Hide();
				}
			}
			catch (Exception ex3)
			{
				Disable(ex3);
			}
		}

		private void EndCapture(string reason)
		{
			CaptureAdapter? captureAdapter = capture;
			if ((captureAdapter != null && captureAdapter.HasCapture) || clientAttempt)
			{
				if (qte.State == QteState.Active)
				{
					Log("QTE cancelled: " + reason + ".");
				}
				qte.Cancel();
				capture?.Clear();
			}
			network?.CancelLocal();
			clientAttempt = false;
			show = false;
			hud.Hide();
		}

		public override void OnSceneWasLoaded(int buildIndex, string sceneName)
		{
			keybindSettings?.Cancel();
			EndCapture("scene loaded");
			network?.Reset();
			hud.Dispose();
		}

		public override void OnSceneWasUnloaded(int buildIndex, string sceneName)
		{
			keybindSettings?.Cancel();
			EndCapture("scene unloaded");
			network?.Reset();
			hud.Dispose();
		}

		public override void OnApplicationQuit()
		{
			EndCapture("application quit");
		}

		private void OnFocusChanged(bool focused)
		{
			if (!focused)
			{
				keybindSettings?.Cancel();
				EndCapture("focus lost");
			}
		}

		public override void OnDeinitializeMelon()
		{
			ready = false;
			Application.focusChanged -= OnFocusChanged;
			keybindSettings?.Dispose();
			EndCapture("mod unloaded");
			network?.Dispose();
			hud.Dispose();
			((MelonBase)this).HarmonyInstance.UnpatchSelf();
			instance = null;
		}

		private void Disable(Exception ex)
		{
			ready = false;
			keybindSettings?.Cancel();
			EndCapture("error");
			network?.Dispose();
			((MelonBase)this).LoggerInstance.Error("QTE disabled: " + ex.GetType().Name + ": " + ex.Message);
		}

		private static void VerifyFile(string relative, string expected)
		{
			using SHA256 sHA = SHA256.Create();
			using FileStream inputStream = File.OpenRead(Path.Combine(Application.dataPath, relative));
			if (BitConverter.ToString(sHA.ComputeHash(inputStream)).Replace("-", "").ToLowerInvariant() != expected)
			{
				throw new NotSupportedException("Unaudited game file: " + relative);
			}
		}

		private unsafe void SaveKey(Key selected)
		{
			//IL_00db: Unknown result type (might be due to invalid IL or missing references)
			//IL_00dc: Unknown result type (might be due to invalid IL or missing references)
			string configPath = ConfigPath;
			List<string> list = File.ReadAllLines(configPath).ToList();
			bool flag = false;
			for (int i = 0; i < list.Count; i++)
			{
				if (!list[i].TrimStart(Array.Empty<char>()).StartsWith("#") && !(list[i].Split(new char[1] { '=' })[0].Trim() != "Key"))
				{
					list[i] = "Key=" + ((object)(*(Key*)(&selected))/*cast due to .constrained prefix*/).ToString();
					flag = true;
				}
			}
			if (!flag)
			{
				list.Add("Key=" + ((object)(*(Key*)(&selected))/*cast due to .constrained prefix*/).ToString());
			}
			File.WriteAllLines(configPath + ".tmp", list);
			File.Replace(configPath + ".tmp", configPath, null);
			EndCapture("key binding changed");
			key = selected;
			Log("QTE key saved from settings: " + ((object)(*(Key*)(&selected))/*cast due to .constrained prefix*/).ToString() + ". Applies immediately.");
		}

		private void ReadConfig()
		{
			//IL_00d7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e9: Unknown result type (might be due to invalid IL or missing references)
			string configPath = ConfigPath;
			Directory.CreateDirectory(Path.GetDirectoryName(configPath));
			if (!File.Exists(configPath))
			{
				File.WriteAllText(configPath, "# Restart game after editing. Unity Input System Key enum.\nKey=F6\nPresses=5\nSeconds=3\n");
			}
			string[] array = File.ReadAllLines(configPath);
			for (int i = 0; i < array.Length; i++)
			{
				string text = array[i].Trim();
				if (text.Length == 0 || text.StartsWith("#"))
				{
					continue;
				}
				string[] array2 = text.Split(new char[1] { '=' }, 2);
				if (array2.Length != 2)
				{
					throw new FormatException("Expected Name=Value in MimesisEscape.cfg.");
				}
				string text2 = array2[1].Trim();
				switch (array2[0].Trim())
				{
				case "Key":
					if (!Enum.TryParse<Key>(text2, ignoreCase: true, out key) || !Enum.IsDefined(typeof(Key), key) || (int)key == 0)
					{
						throw new FormatException("Unknown Unity Input System key in config; value omitted.");
					}
					break;
				case "Presses":
					if (!int.TryParse(text2, NumberStyles.Integer, CultureInfo.InvariantCulture, out required))
					{
						throw new FormatException("Invalid Presses in config; value omitted.");
					}
					break;
				case "Seconds":
					if (!double.TryParse(text2, NumberStyles.Float, CultureInfo.InvariantCulture, out seconds))
					{
						throw new FormatException("Invalid Seconds in config; value omitted.");
					}
					break;
				default:
					throw new FormatException("Unknown config entry; name and value omitted.");
				}
			}
			if (required < 1 || required > 100 || double.IsNaN(seconds) || double.IsInfinity(seconds) || seconds <= 0.0 || seconds > 30.0)
			{
				throw new FormatException("Presses must be 1..100 and Seconds must be >0..30.");
			}
		}
	}
	internal sealed class QteHud
	{
		private static readonly FieldInfo CrosshairField = AccessTools.Field(typeof(GameMainBase), "crosshairui");

		private GameMainBase? owner;

		private TextMeshProUGUI? label;

		internal void Show(GameMainBase? main, string text)
		{
			//IL_00ae: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b4: Expected O, but got Unknown
			//IL_012e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0135: Unknown result type (might be due to invalid IL or missing references)
			//IL_0147: Unknown result type (might be due to invalid IL or missing references)
			//IL_0152: Unknown result type (might be due to invalid IL or missing references)
			//IL_0166: Unknown result type (might be due to invalid IL or missing references)
			//IL_01aa: Unknown result type (might be due to invalid IL or missing references)
			//IL_01bb: Unknown result type (might be due to invalid IL or missing references)
			//IL_01dd: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)main == (Object)null)
			{
				Hide();
				return;
			}
			object? value = CrosshairField.GetValue(main);
			UIPrefab_crosshair val = (UIPrefab_crosshair)((value is UIPrefab_crosshair) ? value : null);
			if ((Object)(object)val == (Object)null)
			{
				Hide();
				return;
			}
			TMP_Text uE_UI_Text = val.UE_UI_Text;
			Canvas componentInParent = ((Component)uE_UI_Text).GetComponentInParent<Canvas>();
			if ((Object)(object)uE_UI_Text.font == (Object)null || (Object)(object)componentInParent == (Object)null)
			{
				Hide();
				return;
			}
			if ((Object)(object)label == (Object)null || (Object)(object)owner != (Object)(object)main)
			{
				Dispose();
				owner = main;
				GameObject val2 = new GameObject("MimesisEscapePrompt", new Type[2]
				{
					typeof(RectTransform),
					typeof(TextMeshProUGUI)
				});
				val2.layer = ((Component)uE_UI_Text).gameObject.layer;
				val2.transform.SetParent(((Component)componentInParent.rootCanvas).transform, false);
				label = val2.GetComponent<TextMeshProUGUI>();
				((Graphic)label).raycastTarget = false;
				((TMP_Text)label).richText = false;
				((TMP_Text)label).alignment = (TextAlignmentOptions)514;
				RectTransform rectTransform = ((TMP_Text)label).rectTransform;
				Vector2 val3 = default(Vector2);
				((Vector2)(ref val3))..ctor(0.5f, 0.28f);
				rectTransform.anchorMax = val3;
				rectTransform.anchorMin = val3;
				rectTransform.pivot = new Vector2(0.5f, 0.5f);
				rectTransform.anchoredPosition = Vector2.zero;
				rectTransform.sizeDelta = new Vector2(900f, 80f);
			}
			((TMP_Text)label).font = uE_UI_Text.font;
			((TMP_Text)label).fontSharedMaterial = uE_UI_Text.fontSharedMaterial;
			((TMP_Text)label).fontSize = uE_UI_Text.fontSize;
			((TMP_Text)label).fontStyle = uE_UI_Text.fontStyle;
			((Graphic)label).color = ((Graphic)uE_UI_Text).color;
			((TMP_Text)label).enableVertexGradient = uE_UI_Text.enableVertexGradient;
			((TMP_Text)label).colorGradient = uE_UI_Text.colorGradient;
			((TMP_Text)label).characterSpacing = uE_UI_Text.characterSpacing;
			((TMP_Text)label).wordSpacing = uE_UI_Text.wordSpacing;
			((TMP_Text)label).lineSpacing = uE_UI_Text.lineSpacing;
			((TMP_Text)label).text = text;
			GameLocalization.ApplyDirection((TMP_Text)(object)label);
			((Component)label).gameObject.SetActive(true);
		}

		internal void Hide()
		{
			if ((Object)(object)label != (Object)null)
			{
				((Component)label).gameObject.SetActive(false);
			}
		}

		internal void Dispose()
		{
			if ((Object)(object)label != (Object)null)
			{
				Object.Destroy((Object)(object)((Component)label).gameObject);
			}
			label = null;
			owner = null;
		}
	}
	public enum QteState
	{
		Idle,
		Active,
		Succeeded,
		Failed,
		Cancelled
	}
	public sealed class QteSession
	{
		private long lastCapture = long.MinValue;

		private bool armed;

		public QteState State { get; private set; }

		public int Progress { get; private set; }

		public int Required { get; private set; }

		public double Deadline { get; private set; }

		public bool Begin(long capture, double now, int required, double duration, bool keyAlreadyDown)
		{
			if (capture == lastCapture || State == QteState.Active)
			{
				return false;
			}
			if (!Finite(now) || !Finite(duration) || duration <= 0.0 || required < 1)
			{
				throw new ArgumentOutOfRangeException("duration");
			}
			lastCapture = capture;
			Progress = 0;
			Required = required;
			Deadline = now + duration;
			armed = !keyAlreadyDown;
			State = QteState.Active;
			return true;
		}

		public bool Tick(double now, bool down, bool pressedThisFrame, bool inputAllowed)
		{
			if (State != QteState.Active)
			{
				return false;
			}
			if (!Finite(now) || now >= Deadline)
			{
				State = QteState.Failed;
				return false;
			}
			if (!inputAllowed)
			{
				armed = false;
				return false;
			}
			if (!down)
			{
				armed = true;
				return false;
			}
			if (!armed)
			{
				return false;
			}
			armed = false;
			if (!pressedThisFrame)
			{
				return false;
			}
			Progress++;
			if (Progress < Required)
			{
				return false;
			}
			State = QteState.Succeeded;
			return true;
		}

		public void Cancel()
		{
			if (State == QteState.Active)
			{
				State = QteState.Cancelled;
			}
		}

		public double Remaining(double now)
		{
			return Math.Max(0.0, Deadline - now);
		}

		private static bool Finite(double value)
		{
			if (!double.IsNaN(value))
			{
				return !double.IsInfinity(value);
			}
			return false;
		}
	}
	internal static class QteWire
	{
		internal const int MaxLength = 192;

		internal static bool Valid(string? text, bool fromClient)
		{
			if (string.IsNullOrEmpty(text) || text.Length > 192)
			{
				return false;
			}
			string[] array = text.Split(new char[1] { '^' });
			if (fromClient)
			{
				if (array.Length == 3 && array[0] == "op=begin")
				{
					if (GuidField(array[1], "request="))
					{
						return PositiveInt(array[2], "caster=", int.MaxValue);
					}
					return false;
				}
				if (array.Length == 2 && array[0] == "op=release")
				{
					return GuidField(array[1], "token=");
				}
				return false;
			}
			if (array.Length == 4 && array[0] == "op=grant")
			{
				if (GuidField(array[1], "request=") && GuidField(array[2], "token="))
				{
					return PositiveInt(array[3], "ms=", 30000);
				}
				return false;
			}
			if (array.Length == 3 && array[0] == "op=result" && GuidField(array[1], "token="))
			{
				if (!(array[2] == "ok=0"))
				{
					return array[2] == "ok=1";
				}
				return true;
			}
			return false;
		}

		private static bool GuidField(string field, string prefix)
		{
			if (field.StartsWith(prefix, StringComparison.Ordinal) && field.Length == prefix.Length + 32 && Guid.TryParseExact(field.Substring(prefix.Length), "N", out var result))
			{
				return result != Guid.Empty;
			}
			return false;
		}

		private static bool PositiveInt(string field, string prefix, int max)
		{
			if (field.StartsWith(prefix, StringComparison.Ordinal) && int.TryParse(field.Substring(prefix.Length), NumberStyles.None, CultureInfo.InvariantCulture, out var result) && result > 0)
			{
				return result <= max;
			}
			return false;
		}
	}
	internal sealed class RequestBudget
	{
		private long windowStart = -1000L;

		private int count;

		internal bool Take(long nowMilliseconds)
		{
			lock (this)
			{
				if (nowMilliseconds < windowStart)
				{
					return false;
				}
				if (nowMilliseconds - windowStart >= 1000)
				{
					windowStart = nowMilliseconds;
					count = 0;
				}
				return ++count <= 8;
			}
		}
	}
	internal sealed class ReleaseTicket
	{
		internal readonly Guid Token = CreateToken();

		internal readonly int Victim;

		internal readonly int Caster;

		internal readonly long NativeStart;

		internal readonly long Deadline;

		private bool consumed;

		private static Guid CreateToken()
		{
			byte[] array = new byte[16];
			using (RandomNumberGenerator randomNumberGenerator = RandomNumberGenerator.Create())
			{
				randomNumberGenerator.GetBytes(array);
			}
			return new Guid(array);
		}

		internal ReleaseTicket(int victim, int caster, long nativeStart, long deadline)
		{
			if (deadline <= nativeStart)
			{
				throw new ArgumentOutOfRangeException("deadline");
			}
			Victim = victim;
			Caster = caster;
			NativeStart = nativeStart;
			Deadline = deadline;
		}

		internal long Remaining(long now)
		{
			return Math.Max(0L, Deadline - now);
		}

		internal bool TryConsume(Guid token, int authenticatedVictim, int currentCaster, long currentStart, long now, bool nativeCaptureValid)
		{
			if (consumed || !nativeCaptureValid || token != Token || authenticatedVictim != Victim || currentCaster != Caster || currentStart != NativeStart || now < NativeStart || now >= Deadline)
			{
				return false;
			}
			consumed = true;
			return true;
		}

		internal static double ClientWindow(double remainingSeconds, double requestSentAt, double receivedAt)
		{
			if (double.IsNaN(remainingSeconds) || double.IsInfinity(remainingSeconds) || double.IsNaN(requestSentAt) || double.IsInfinity(requestSentAt) || double.IsNaN(receivedAt) || double.IsInfinity(receivedAt) || receivedAt < requestSentAt)
			{
				return 0.0;
			}
			return Math.Max(0.0, remainingSeconds - (receivedAt - requestSentAt));
		}
	}
}