Decompiled source of RoR2LatencyMod v0.1.0

plugins/RoR2LatencyMod/RoR2LatencyMod.dll

Decompiled 3 weeks ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Text;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Configuration;
using BepInEx.Logging;
using EntityStates;
using EntityStates.Enforcer;
using EntityStates.Loader;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using R2API.Utils;
using RiskOfOptions;
using RiskOfOptions.OptionConfigs;
using RiskOfOptions.Options;
using RoR2;
using RoR2.Networking;
using RoR2.Projectile;
using RoR2.UI;
using TMPro;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.Networking;
using UnityEngine.UI;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("RoR2LatencyMod")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0+91f2f59e5a67596e7c19c10efe5d2e9897f69d98")]
[assembly: AssemblyProduct("RoR2LatencyMod")]
[assembly: AssemblyTitle("RoR2LatencyMod")]
[assembly: AssemblyVersion("1.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 RoR2LatencyMod
{
	public sealed class DiagLog
	{
		private readonly Action<string> info;

		private readonly Action<string> warning;

		private readonly Func<double> nowSeconds;

		private readonly double throttleSeconds;

		private readonly Dictionary<string, double> lastEmitByKey = new Dictionary<string, double>(StringComparer.Ordinal);

		public DiagLog(Action<string> info, Action<string> warning, Func<double> nowSeconds, double throttleSeconds = 1.0)
		{
			this.info = info;
			this.warning = warning;
			this.nowSeconds = nowSeconds;
			this.throttleSeconds = Math.Max(0.0, throttleSeconds);
		}

		public void Info(string message)
		{
			info?.Invoke(message);
		}

		public void Warning(string message)
		{
			warning?.Invoke(message);
		}

		public void Throttled(string key, string message)
		{
			if (key == null)
			{
				throw new ArgumentNullException("key");
			}
			double num = nowSeconds();
			if (!lastEmitByKey.TryGetValue(key, out var value) || !(num < value + throttleSeconds))
			{
				lastEmitByKey[key] = num;
				info?.Invoke(message);
			}
		}
	}
	public sealed class EnforcerDashLengthPatch : SkillPatch
	{
		private const string Tag = "EnforcerDashLength";

		private static EnforcerDashLengthPatch instance;

		public Func<float> LengthMultiplier { get; }

		protected override bool RequiresRemoteClient => false;

		public EnforcerDashLengthPatch(Func<float> lengthMultiplier, DiagLog diag = null)
			: base("EnforcerDashLength", PatchSide.Client, () => true, diag)
		{
			LengthMultiplier = lengthMultiplier;
		}

		protected override void Install()
		{
			//IL_0053: Unknown result type (might be due to invalid IL or missing references)
			//IL_006a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0077: Expected O, but got Unknown
			MethodInfo methodInfo = AccessTools.Method(typeof(BaseShieldDashPrepCharge), "ModifyNextState", new Type[1] { typeof(EntityState) }, (Type[])null);
			if (methodInfo == null)
			{
				throw new MissingMemberException("BaseShieldDashPrepCharge.ModifyNextState not found");
			}
			instance = this;
			new Harmony("com.wray.ror2latency." + base.Name).Patch((MethodBase)methodInfo, (HarmonyMethod)null, new HarmonyMethod(typeof(EnforcerDashLengthPatch), "ModifyNextStatePostfix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			base.Diag?.Info("EnforcerDashLength: installed (owner-side dash duration multiplier).");
		}

		private static void ModifyNextStatePostfix(EntityState __instance, EntityState nextState)
		{
			EnforcerDashLengthPatch self = instance;
			if (self == null || !self.ShouldRun())
			{
				return;
			}
			IShieldDashSpeedAndDuration dash = (IShieldDashSpeedAndDuration)(object)((nextState is IShieldDashSpeedAndDuration) ? nextState : null);
			if (dash != null)
			{
				self.Guard(delegate
				{
					self.Scale(__instance, dash);
				});
			}
		}

		private void Scale(EntityState prep, IShieldDashSpeedAndDuration dash)
		{
			double num = PredictionMath.BuffMultiplier((LengthMultiplier != null) ? LengthMultiplier() : 1f);
			NetworkIdentity val = (((Object)(object)prep.outer != (Object)null) ? prep.outer.networkIdentity : null);
			if (!(num <= 1.0) && !((Object)(object)val == (Object)null) && Util.HasEffectiveAuthority(val))
			{
				float inOverrideDurationFromAuthority = dash.inOverrideDurationFromAuthority;
				dash.inOverrideDurationFromAuthority = (float)((double)inOverrideDurationFromAuthority * num);
				base.Diag?.Info(string.Format("{0}: dash duration x{1:F2} ({2:F2}s -> {3:F2}s).", "EnforcerDashLength", num, inOverrideDurationFromAuthority, dash.inOverrideDurationFromAuthority));
			}
		}
	}
	public sealed class EnforcerExitSmoothingPatch : SkillPatch
	{
		private sealed class SmoothState
		{
			public CharacterBody Body;

			public CharacterMotor CharacterMotor;

			public object Motor;

			public Vector3 Start;

			public Vector3 Target;

			public float Duration;

			public float Elapsed;

			public Vector3 LastApplied;

			public float WallStart;

			public double OneWay;
		}

		private const string Tag = "EnforcerExitSmoothing";

		private const float MinSmoothMeters = 0.05f;

		private const float MaxSmoothMeters = 10f;

		private const float TeleportSlackMeters = 2.5f;

		private static EnforcerExitSmoothingPatch instance;

		private static FieldInfo passengerBodyField;

		private static PropertyInfo motorProperty;

		private static PropertyInfo transientPositionProperty;

		private static MethodInfo setPositionMethod;

		private static FieldInfo characterMotorVelocityField;

		private readonly ConditionalWeakTable<CharacterMotor, SmoothState> states = new ConditionalWeakTable<CharacterMotor, SmoothState>();

		private int activeCount;

		public Func<float> ExitSmoothSeconds { get; }

		public EnforcerExitSmoothingPatch(Func<bool> isEnabled, Func<float> exitSmoothSeconds, DiagLog diag = null, LatencyEstimator latency = null)
			: base("EnforcerExitSmoothing", PatchSide.Client, isEnabled, diag, latency)
		{
			ExitSmoothSeconds = exitSmoothSeconds;
		}

		protected override void Install()
		{
			//IL_022a: Unknown result type (might be due to invalid IL or missing references)
			//IL_022f: 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)
			//IL_0256: Unknown result type (might be due to invalid IL or missing references)
			//IL_0263: Expected O, but got Unknown
			//IL_0263: Expected O, but got Unknown
			//IL_0276: Unknown result type (might be due to invalid IL or missing references)
			//IL_0283: Expected O, but got Unknown
			passengerBodyField = AccessTools.Field(typeof(VehicleShieldDashExit), "passengerBody");
			motorProperty = typeof(CharacterMotor).GetProperty("Motor");
			characterMotorVelocityField = typeof(CharacterMotor).GetField("velocity", BindingFlags.Instance | BindingFlags.Public);
			MethodInfo methodInfo = AccessTools.Method(typeof(VehicleShieldDashExit), "OnPassengerExitAuthority", new Type[1] { typeof(GameObject) }, (Type[])null);
			MethodInfo methodInfo2 = AccessTools.Method(typeof(CharacterMotor), "BeforeCharacterUpdate", new Type[1] { typeof(float) }, (Type[])null);
			if (passengerBodyField == null || motorProperty == null || characterMotorVelocityField == null || methodInfo == null || methodInfo2 == null)
			{
				throw new MissingMemberException("EnforcerExitSmoothing members missing: " + $"passengerBody={passengerBodyField != null}, Motor={motorProperty != null}, " + $"velocity={characterMotorVelocityField != null}, " + $"OnPassengerExitAuthority={methodInfo != null}, " + $"BeforeCharacterUpdate={methodInfo2 != null}");
			}
			Type propertyType = motorProperty.PropertyType;
			transientPositionProperty = propertyType.GetProperty("TransientPosition");
			setPositionMethod = propertyType.GetMethod("SetPosition", new Type[2]
			{
				typeof(Vector3),
				typeof(bool)
			});
			if (transientPositionProperty == null || setPositionMethod == null)
			{
				throw new MissingMemberException($"{propertyType.FullName} members missing: TransientPosition={transientPositionProperty != null}, " + $"SetPosition={setPositionMethod != null}");
			}
			Harmony val = new Harmony("com.wray.ror2latency." + base.Name);
			val.Patch((MethodBase)methodInfo, new HarmonyMethod(typeof(EnforcerExitSmoothingPatch), "OnPassengerExitAuthorityPrefix", (Type[])null), new HarmonyMethod(typeof(EnforcerExitSmoothingPatch), "OnPassengerExitAuthorityPostfix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			val.Patch((MethodBase)methodInfo2, (HarmonyMethod)null, new HarmonyMethod(typeof(EnforcerExitSmoothingPatch), "BeforeCharacterUpdatePostfix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			instance = this;
			base.Diag?.Info("EnforcerExitSmoothing: installed. 退场跳变来源 VehicleShieldDashExit.cs:124-144(private OnPassengerExitAuthority,:138 Motor.SetPosition(vehicleAuthorityPosition) 硬贴;客户端 :78-122 OnEnter 订阅座位 :915 onPassengerExit)→ 改为 0.1–0.2s 本地插值。");
		}

		private static void OnPassengerExitAuthorityPrefix(VehicleShieldDashExit __instance, out SmoothState __state)
		{
			__state = null;
			EnforcerExitSmoothingPatch self = instance;
			if (self != null)
			{
				SmoothState captured = null;
				self.Guard(delegate
				{
					captured = self.CaptureExit(__instance);
				});
				__state = captured;
			}
		}

		private static void OnPassengerExitAuthorityPostfix(SmoothState __state)
		{
			EnforcerExitSmoothingPatch self = instance;
			if (self != null && __state != null)
			{
				self.Guard(delegate
				{
					self.BeginSmoothingSafe(__state);
				});
			}
		}

		private void BeginSmoothingSafe(SmoothState state)
		{
			//IL_0018: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				BeginSmoothing(state);
			}
			catch
			{
				RemoveState(state);
				try
				{
					SetMotorPosition(state.Motor, state.Target);
				}
				catch
				{
				}
				throw;
			}
		}

		private static void BeforeCharacterUpdatePostfix(CharacterMotor __instance, float deltaTime)
		{
			EnforcerExitSmoothingPatch self = instance;
			if (self != null && self.activeCount != 0 && self.states.TryGetValue(__instance, out var state))
			{
				self.Guard(delegate
				{
					self.StepSafe(state, deltaTime);
				});
			}
		}

		private void StepSafe(SmoothState state, float deltaTime)
		{
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				Step(state, deltaTime);
			}
			catch
			{
				RemoveState(state);
				try
				{
					SetMotorPosition(state.Motor, state.Target);
				}
				catch
				{
				}
				throw;
			}
		}

		private SmoothState CaptureExit(VehicleShieldDashExit exitState)
		{
			//IL_00ab: 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_00bc: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c5: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a2: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a4: 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_01ab: Unknown result type (might be due to invalid IL or missing references)
			//IL_01be: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c0: Unknown result type (might be due to invalid IL or missing references)
			if (exitState == null || !ShouldRun())
			{
				return null;
			}
			object? value = passengerBodyField.GetValue(exitState);
			CharacterBody val = (CharacterBody)((value is CharacterBody) ? value : null);
			if (val == null || !val.hasEffectiveAuthority || val.characterMotor == null || (Object)(object)val.healthComponent == (Object)null || !val.healthComponent.alive || (Object)(object)val.currentVehicle != (Object)null)
			{
				return null;
			}
			if (EnforcerLocalEndPatch.SuppressesExitSmoothing(exitState))
			{
				return null;
			}
			double num = ((ExitSmoothSeconds != null) ? ((double)ExitSmoothSeconds()) : 0.0);
			if (num <= 0.0)
			{
				return null;
			}
			object value2 = motorProperty.GetValue(val.characterMotor);
			if (value2 == null)
			{
				return null;
			}
			Vector3 vehicleAuthorityPosition = exitState.vehicleAuthorityPosition;
			Vector3 val2 = (Vector3)transientPositionProperty.GetValue(value2);
			float num2 = Vector3.Distance(val2, vehicleAuthorityPosition);
			if (num2 <= 0.05f)
			{
				return null;
			}
			double num3 = EnforcerGhostDashPatch.RecentPredictedTravelMeters();
			if (PredictionMath.ExitSmoothingIsTeleport(num2, num3, 10.0))
			{
				base.Diag?.Info(string.Format("{0}: hard snap, distance={1:F2}m, predicted={2:F2}m, ", "EnforcerExitSmoothing", num2, num3) + $"limit={((num3 > 0.0) ? PredictionMath.HandoffDistanceLimit(num3) : 10.0):F1}m " + "(teleport/respawn, not dash-end drift)");
				return null;
			}
			double oneWay = 0.0;
			if (base.Latency != null && base.Latency.TryGetOneWayLatency(out var oneWaySeconds))
			{
				oneWay = oneWaySeconds;
			}
			return new SmoothState
			{
				Body = val,
				CharacterMotor = val.characterMotor,
				Motor = value2,
				Start = val2,
				Target = vehicleAuthorityPosition,
				Duration = (float)PredictionMath.ClampInterpolationDuration(num),
				LastApplied = val2,
				WallStart = Time.time,
				OneWay = oneWay
			};
		}

		private void BeginSmoothing(SmoothState state)
		{
			//IL_0036: Unknown result type (might be due to invalid IL or missing references)
			//IL_007d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0083: Unknown result type (might be due to invalid IL or missing references)
			CharacterBody body = state.Body;
			if (!((Object)(object)body == (Object)null) && body.hasEffectiveAuthority && body.characterMotor != null && !((Object)(object)body.currentVehicle != (Object)null))
			{
				SetMotorPosition(state.Motor, state.Start);
				RemoveState(state);
				states.Add(state.CharacterMotor, state);
				activeCount++;
				base.Diag?.Info(string.Format("{0}: start distance={1:F2}m ", "EnforcerExitSmoothing", Vector3.Distance(state.Start, state.Target)) + $"duration={state.Duration:F2}s U={state.OneWay:F3}s " + $"start=({state.Start.x:F2},{state.Start.y:F2},{state.Start.z:F2}) " + $"target=({state.Target.x:F2},{state.Target.y:F2},{state.Target.z:F2})");
			}
		}

		private void Step(SmoothState state, float deltaTime)
		{
			//IL_006b: Unknown result type (might be due to invalid IL or missing references)
			//IL_01af: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b5: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ba: Unknown result type (might be due to invalid IL or missing references)
			//IL_01bf: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d9: Unknown result type (might be due to invalid IL or missing references)
			//IL_01de: Unknown result type (might be due to invalid IL or missing references)
			//IL_02d0: Unknown result type (might be due to invalid IL or missing references)
			//IL_02d6: Unknown result type (might be due to invalid IL or missing references)
			//IL_02de: Unknown result type (might be due to invalid IL or missing references)
			//IL_02e3: Unknown result type (might be due to invalid IL or missing references)
			//IL_02eb: Unknown result type (might be due to invalid IL or missing references)
			//IL_02f3: Unknown result type (might be due to invalid IL or missing references)
			//IL_02f5: Unknown result type (might be due to invalid IL or missing references)
			//IL_0255: Unknown result type (might be due to invalid IL or missing references)
			//IL_0295: Unknown result type (might be due to invalid IL or missing references)
			//IL_029b: Unknown result type (might be due to invalid IL or missing references)
			if (deltaTime <= 0f)
			{
				return;
			}
			if (Time.time - state.WallStart > state.Duration + 1f)
			{
				RemoveState(state);
				base.Diag?.Info(string.Format("{0}: abort reason=stale at elapsed={1:F3}s", "EnforcerExitSmoothing", state.Elapsed));
				return;
			}
			if (!ShouldRun())
			{
				RemoveState(state);
				SetMotorPosition(state.Motor, state.Target);
				base.Diag?.Info(string.Format("{0}: abort reason=disabled at elapsed={1:F3}s (snapped to target)", "EnforcerExitSmoothing", state.Elapsed));
				return;
			}
			CharacterBody body = state.Body;
			if ((Object)(object)body == (Object)null)
			{
				RemoveState(state);
				base.Diag?.Info(string.Format("{0}: abort reason=destroyed at elapsed={1:F3}s", "EnforcerExitSmoothing", state.Elapsed));
				return;
			}
			if (!body.hasEffectiveAuthority)
			{
				RemoveState(state);
				base.Diag?.Info(string.Format("{0}: abort reason=authority-lost at elapsed={1:F3}s", "EnforcerExitSmoothing", state.Elapsed));
				return;
			}
			if ((Object)(object)body.healthComponent == (Object)null || !body.healthComponent.alive)
			{
				RemoveState(state);
				base.Diag?.Info(string.Format("{0}: abort reason=death at elapsed={1:F3}s", "EnforcerExitSmoothing", state.Elapsed));
				return;
			}
			if ((Object)(object)body.currentVehicle != (Object)null)
			{
				RemoveState(state);
				base.Diag?.Info(string.Format("{0}: abort reason=new-vehicle at elapsed={1:F3}s", "EnforcerExitSmoothing", state.Elapsed));
				return;
			}
			Vector3 val = GetMotorPosition(state.Motor) - state.LastApplied;
			float magnitude = ((Vector3)(ref val)).magnitude;
			Vector3 val2 = (Vector3)characterMotorVelocityField.GetValue(state.CharacterMotor);
			float num = 2.5f + ((Vector3)(ref val2)).magnitude * deltaTime;
			if (magnitude > num)
			{
				RemoveState(state);
				base.Diag?.Info(string.Format("{0}: abort reason=teleport moved={1:F2}m at elapsed={2:F3}s", "EnforcerExitSmoothing", magnitude, state.Elapsed));
				return;
			}
			state.Elapsed += deltaTime;
			if (state.Elapsed >= state.Duration)
			{
				RemoveState(state);
				SetMotorPosition(state.Motor, state.Target);
				base.Diag?.Info(string.Format("{0}: done elapsed={1:F3}s duration={2:F2}s ", "EnforcerExitSmoothing", state.Elapsed, state.Duration) + $"distance={Vector3.Distance(state.Start, state.Target):F2}m");
			}
			else
			{
				double num2 = PredictionMath.InterpolationAlpha(state.Elapsed, state.Duration);
				Vector3 val3 = Vector3.LerpUnclamped(state.Start, state.Target, (float)num2);
				SetMotorPosition(state.Motor, val3);
				state.LastApplied = val3;
			}
		}

		private void RemoveState(SmoothState state)
		{
			if (states.Remove(state.CharacterMotor))
			{
				activeCount--;
			}
		}

		private static Vector3 GetMotorPosition(object motor)
		{
			//IL_000b: Unknown result type (might be due to invalid IL or missing references)
			return (Vector3)transientPositionProperty.GetValue(motor);
		}

		private static void SetMotorPosition(object motor, Vector3 position)
		{
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			setPositionMethod.Invoke(motor, new object[2] { position, true });
		}
	}
	public sealed class EnforcerFeedbackPatch : SkillPatch
	{
		private sealed class StateTracking
		{
			public CharacterBody Body;

			public double EnterTime;

			public double TimeoutSeconds;

			public double TimeoutRtt;

			public double EarlyFeedbackTime = double.NegativeInfinity;

			public bool FallbackFired;

			public bool VanillaExitSeen;

			public bool AnimationResetDone;
		}

		private const string Tag = "EnforcerFeedback";

		private static EnforcerFeedbackPatch instance;

		private static int arrivalSequence;

		private static readonly Dictionary<Type, Type> BodyToVehicleState = new Dictionary<Type, Type>
		{
			{
				typeof(ProxyShieldDashHeavy),
				typeof(VehicleShieldDashHeavy)
			},
			{
				typeof(ProxyShieldDashLight),
				typeof(VehicleShieldDashLight)
			}
		};

		private readonly ConditionalWeakTable<EntityState, StateTracking> tracking = new ConditionalWeakTable<EntityState, StateTracking>();

		private readonly Dictionary<Type, MethodInfo> feedbackByType = new Dictionary<Type, MethodInfo>();

		private readonly Dictionary<Type, FieldInfo> vehicleEnteredByType = new Dictionary<Type, FieldInfo>();

		private readonly Dictionary<Type, FieldInfo> referencerByType = new Dictionary<Type, FieldInfo>();

		private readonly HashSet<Type> vehicleDashStateTypes = new HashSet<Type>();

		private static readonly int ShieldTackleLoopStateHash = Animator.StringToHash("ShieldTackleLoop");

		private static readonly int ShieldTackleExitStateHash = Animator.StringToHash("ShieldTackleExit");

		private const string FullBodyOverrideLayer = "FullBody, Override";

		private static readonly FieldInfo exitPassengerBodyField = typeof(VehicleShieldDashExit).GetField("passengerBody", BindingFlags.Instance | BindingFlags.NonPublic);

		private static readonly PropertyInfo controllerVehicleProperty = typeof(EnforcerVehicleDashController).GetProperty("currentVehicle", BindingFlags.Instance | BindingFlags.NonPublic);

		public Func<float> FeedbackFallbackSeconds { get; }

		public Func<float> FeedbackFallbackMaxSeconds { get; }

		public EnforcerFeedbackPatch(Func<bool> isEnabled, Func<float> feedbackFallbackSeconds, Func<float> feedbackFallbackMaxSeconds, DiagLog diag = null, LatencyEstimator latency = null)
			: base("EnforcerFeedback", PatchSide.Client, isEnabled, diag, latency)
		{
			FeedbackFallbackSeconds = feedbackFallbackSeconds;
			FeedbackFallbackMaxSeconds = feedbackFallbackMaxSeconds;
		}

		protected override void Install()
		{
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_0016: Expected O, but got Unknown
			//IL_0217: Unknown result type (might be due to invalid IL or missing references)
			//IL_022c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0239: Expected O, but got Unknown
			//IL_0239: Expected O, but got Unknown
			//IL_024c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0261: Unknown result type (might be due to invalid IL or missing references)
			//IL_026e: Expected O, but got Unknown
			//IL_026e: Expected O, but got Unknown
			//IL_0282: Unknown result type (might be due to invalid IL or missing references)
			//IL_028f: Expected O, but got Unknown
			Harmony val = new Harmony("com.wray.ror2latency." + base.Name);
			foreach (KeyValuePair<Type, Type> item in BodyToVehicleState)
			{
				Type key = item.Key;
				MethodInfo methodInfo = AccessTools.Method(key, "OnVehicleEnteredState", Type.EmptyTypes, (Type[])null);
				FieldInfo fieldInfo = FindField(key, "vehicleEnteredState");
				FieldInfo fieldInfo2 = FindField(key, "referencerToVehicle");
				if (methodInfo == null || fieldInfo == null || fieldInfo2 == null)
				{
					throw new MissingMemberException($"{key.FullName} members missing: OnVehicleEnteredState={methodInfo != null}, " + $"vehicleEnteredState={fieldInfo != null}, referencerToVehicle={fieldInfo2 != null}");
				}
				feedbackByType[key] = methodInfo;
				vehicleEnteredByType[key] = fieldInfo;
				referencerByType[key] = fieldInfo2;
				vehicleDashStateTypes.Add(item.Value);
			}
			MethodInfo methodInfo2 = AccessTools.Method(typeof(EntityStateMachine), "SetState", new Type[1] { typeof(EntityState) }, (Type[])null);
			MethodInfo methodInfo3 = AccessTools.Method(typeof(EntityStateMachine), "FixedUpdate", Type.EmptyTypes, (Type[])null);
			MethodInfo methodInfo4 = AccessTools.Method(typeof(VehicleSeat), "SetPassenger", new Type[1] { typeof(GameObject) }, (Type[])null);
			if (methodInfo2 == null || methodInfo3 == null || methodInfo4 == null)
			{
				throw new MissingMemberException($"Hooks missing: EntityStateMachine.SetState={methodInfo2 != null}, " + $"EntityStateMachine.FixedUpdate={methodInfo3 != null}, " + $"VehicleSeat.SetPassenger={methodInfo4 != null}");
			}
			val.Patch((MethodBase)methodInfo2, new HarmonyMethod(typeof(EnforcerFeedbackPatch), "VehicleStateArrivalPrefix", (Type[])null), new HarmonyMethod(typeof(EnforcerFeedbackPatch), "BodyStateEnterPostfix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			val.Patch((MethodBase)methodInfo3, new HarmonyMethod(typeof(EnforcerFeedbackPatch), "SuppressDuplicateFeedbackPrefix", (Type[])null), new HarmonyMethod(typeof(EnforcerFeedbackPatch), "MachineFixedUpdatePostfix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			val.Patch((MethodBase)methodInfo4, (HarmonyMethod)null, new HarmonyMethod(typeof(EnforcerFeedbackPatch), "SeatPassengerPostfix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			instance = this;
			base.Diag?.Info("EnforcerFeedback: installed (early local feedback, stuck fallback, arrival-order logging).");
		}

		private static void BodyStateEnterPostfix(EntityStateMachine __instance)
		{
			EnforcerFeedbackPatch self = instance;
			if (self == null)
			{
				return;
			}
			EntityState state = __instance.state;
			if (state != null && BodyToVehicleState.ContainsKey(((object)state).GetType()))
			{
				self.Guard(delegate
				{
					self.OnBodyStateEnter(state);
				});
			}
		}

		private static void SuppressDuplicateFeedbackPrefix(EntityStateMachine __instance)
		{
			EnforcerFeedbackPatch self = instance;
			if (self == null)
			{
				return;
			}
			EntityState state = __instance.state;
			if (IsBodyDashState(state))
			{
				self.Guard(delegate
				{
					self.SuppressDuplicateFeedback(state);
				});
			}
		}

		private static void MachineFixedUpdatePostfix(EntityStateMachine __instance)
		{
			EnforcerFeedbackPatch self = instance;
			if (self == null)
			{
				return;
			}
			EntityState state = __instance.state;
			if (IsBodyDashState(state))
			{
				self.Guard(delegate
				{
					self.OnMachineFixedUpdate(__instance, state);
				});
			}
		}

		private static bool IsBodyDashState(EntityState state)
		{
			if (state != null)
			{
				return BodyToVehicleState.ContainsKey(((object)state).GetType());
			}
			return false;
		}

		private static void VehicleStateArrivalPrefix(object __instance, EntityState newState)
		{
			//IL_002b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0035: Expected O, but got Unknown
			EnforcerFeedbackPatch self = instance;
			if (self == null || newState == null)
			{
				return;
			}
			EntityStateMachine machine = (EntityStateMachine)__instance;
			if (self.vehicleDashStateTypes.Contains(((object)newState).GetType()) || newState is VehicleShieldDashExit)
			{
				self.Guard(delegate
				{
					self.LogVehicleStateArrival(machine, newState);
					self.MarkVanillaExitIfNeeded(machine, newState);
				});
			}
			self.SafeRestoreAfterStateExit(machine, newState);
		}

		private static void SeatPassengerPostfix(object __instance, GameObject newPassengerBodyObject)
		{
			EnforcerFeedbackPatch self = instance;
			if (self != null && !((Object)(object)newPassengerBodyObject == (Object)null))
			{
				self.Guard(delegate
				{
					//IL_000c: Unknown result type (might be due to invalid IL or missing references)
					//IL_001c: Expected O, but got Unknown
					self.LogSeatArrival((VehicleSeat)__instance, newPassengerBodyObject);
				});
			}
		}

		private void OnBodyStateEnter(EntityState state)
		{
			if (state == null || !ShouldRun() || !IsLocalAuthority(state))
			{
				return;
			}
			Type type = ((object)state).GetType();
			if (BodyToVehicleState.ContainsKey(type))
			{
				float time = Time.time;
				if (!tracking.TryGetValue(state, out var value))
				{
					value = new StateTracking();
					tracking.Add(state, value);
				}
				value.EnterTime = time;
				value.Body = (((Object)(object)state.outer != (Object)null) ? state.outer.commonComponents.characterBody : null);
				base.Latency?.Measured?.ObserveEnter(time);
				value.TimeoutRtt = TimeoutRttSeconds();
				value.TimeoutSeconds = EffectiveFallbackSeconds(value.TimeoutRtt);
				if (feedbackByType.TryGetValue(type, out var value2))
				{
					value.EarlyFeedbackTime = time;
					value2.Invoke(state, null);
					double num = OneWaySeconds();
					base.Diag?.Throttled("EnforcerFeedback.enter." + type.Name, string.Format("{0}: early local feedback on enter ({1}) U={2:F3}s {3}", "EnforcerFeedback", type.Name, num, base.Latency?.Describe()));
				}
			}
		}

		private void SuppressDuplicateFeedback(EntityState state)
		{
			if (state == null || !ShouldRun())
			{
				return;
			}
			Type type = ((object)state).GetType();
			if (BodyToVehicleState.TryGetValue(type, out var value) && IsLocalAuthority(state) && tracking.TryGetValue(state, out var value2) && !double.IsNegativeInfinity(value2.EarlyFeedbackTime) && vehicleEnteredByType.TryGetValue(type, out var value3) && !(bool)value3.GetValue(state) && referencerByType.TryGetValue(type, out var value4))
			{
				object? value5 = value4.GetValue(state);
				EnforcerVehicleDashController val = (EnforcerVehicleDashController)((value5 is EnforcerVehicleDashController) ? value5 : null);
				EntityState val2 = (((Object)(object)val != (Object)null) ? val.GetVehicleState() : null);
				if (val2 != null && value.IsInstanceOfType(val2))
				{
					value3.SetValue(state, true);
					base.Diag?.Info("EnforcerFeedback: early feedback already played; vanilla OnVehicleEnteredState suppressed when " + ((object)val2).GetType().Name + " arrived for " + type.Name + ".");
				}
			}
		}

		private void OnMachineFixedUpdate(EntityStateMachine machine, EntityState state)
		{
			Type type = ((object)state).GetType();
			if (ShouldRun() && IsLocalAuthority(state) && tracking.TryGetValue(state, out var value) && !value.FallbackFired && vehicleEnteredByType.TryGetValue(type, out var value2) && !(bool)value2.GetValue(state) && !machine.HasPendingState())
			{
				double num = (double)Time.time - value.EnterTime;
				double num2 = value.TimeoutSeconds;
				Func<float> feedbackFallbackSeconds = FeedbackFallbackSeconds;
				if (feedbackFallbackSeconds == null || !(feedbackFallbackSeconds() > 0f))
				{
					num2 = PredictionMath.ExtendStuckTimeout(num2, TimeoutRttSeconds(), FeedbackFallbackMaxSeconds?.Invoke() ?? 3f);
				}
				if (!(num < num2))
				{
					value.FallbackFired = true;
					TryRestoreExitAnimation(value, "stuck fallback -> Main");
					machine.SetNextStateToMain();
					double num3 = OneWaySeconds();
					base.Diag?.Info(string.Format("{0}: stuck fallback -> Main after {1:F2}s (timeout {2:F2}s, ", "EnforcerFeedback", num, num2) + $"cached={value.TimeoutSeconds:F2}s, timeoutRTT={value.TimeoutRtt:F3}s, U={num3:F3}s {base.Latency?.Describe()}); " + "vehicleEnteredState=false, vehicleState=" + VehicleStateName(state) + ", pending=false; reason=vehicle state never observed");
				}
			}
		}

		private void LogVehicleStateArrival(EntityStateMachine machine, EntityState newState)
		{
			if (!ShouldRun() || !vehicleDashStateTypes.Contains(((object)newState).GetType()))
			{
				return;
			}
			int num = ++arrivalSequence;
			double num2 = OneWaySeconds();
			VehicleSeat component = ((Component)machine).GetComponent<VehicleSeat>();
			CharacterBody val = ((component != null) ? component.currentPassengerBody : null);
			string text = "";
			if ((Object)(object)val != (Object)null && val.hasEffectiveAuthority)
			{
				EntityStateMachine val2 = EntityStateMachine.FindByCustomName(((Component)val).gameObject, "Body");
				EntityState val3 = (((Object)(object)val2 != (Object)null) ? val2.state : null);
				if (val3 == null || !BodyToVehicleState.ContainsKey(((object)val3).GetType()))
				{
					text = " late=local bodyState=" + (((object)val3)?.GetType().Name ?? "none");
				}
			}
			base.Diag?.Info(string.Format("{0}: arrival #{1} t={2:F3} vehicleState={3} ", "EnforcerFeedback", num, Time.time, ((object)newState).GetType().Name) + $"object={((Object)((Component)machine).gameObject).name} U={num2:F3}s {base.Latency?.Describe()}{text}");
		}

		private void LogSeatArrival(VehicleSeat seat, GameObject passenger)
		{
			if (ShouldRun() && !((Object)(object)passenger.GetComponent<EnforcerVehicleDashController>() == (Object)null))
			{
				int num = ++arrivalSequence;
				double num2 = OneWaySeconds();
				CharacterBody component = passenger.GetComponent<CharacterBody>();
				string text = "";
				if ((Object)(object)component != (Object)null && component.hasEffectiveAuthority && base.Latency?.Measured != null && base.Latency.Measured.TryConsumeArrival(Time.time, out var sampleSeconds))
				{
					base.Latency.Measured.TryGetMedian(out var medianSeconds);
					text = $" measuredSample={sampleSeconds:F3}s median={medianSeconds:F3}s " + $"n={base.Latency.Measured.SampleCount}";
				}
				base.Diag?.Info(string.Format("{0}: arrival #{1} t={2:F3} seatPassenger={3} ", "EnforcerFeedback", num, Time.time, Util.GetBestBodyName(passenger)) + $"vehicle={((Object)((Component)seat).gameObject).name} U={num2:F3}s {base.Latency?.Describe()}{text}");
			}
		}

		private string VehicleStateName(EntityState state)
		{
			if (!referencerByType.TryGetValue(((object)state).GetType(), out var value))
			{
				return "unknown";
			}
			object? value2 = value.GetValue(state);
			object? obj = ((value2 is EnforcerVehicleDashController) ? value2 : null);
			return ((obj == null) ? null : ((object)((EnforcerVehicleDashController)obj).GetVehicleState())?.GetType().Name) ?? "none";
		}

		private double EffectiveFallbackSeconds(double rtt)
		{
			float num = FeedbackFallbackSeconds?.Invoke() ?? 0f;
			if (num > 0f)
			{
				return num;
			}
			float num2 = FeedbackFallbackMaxSeconds?.Invoke() ?? 3f;
			return PredictionMath.StuckTimeout(rtt, num2);
		}

		private double TimeoutRttSeconds()
		{
			if (base.Latency == null || !base.Latency.TryGetTimeoutRoundTrip(out var roundTripSeconds))
			{
				return 0.0;
			}
			return roundTripSeconds;
		}

		private void MarkVanillaExitIfNeeded(EntityStateMachine vehicleMachine, EntityState newState)
		{
			if (!(newState is VehicleShieldDashExit))
			{
				return;
			}
			object? obj = exitPassengerBodyField?.GetValue(newState);
			CharacterBody val = (CharacterBody)((obj is CharacterBody) ? obj : null);
			if ((Object)(object)val == (Object)null || !val.hasEffectiveAuthority)
			{
				return;
			}
			EntityStateMachine val2 = EntityStateMachine.FindByCustomName(((Component)val).gameObject, "Body");
			EntityState val3 = (((Object)(object)val2 != (Object)null) ? val2.state : null);
			if (val3 != null && tracking.TryGetValue(val3, out var value))
			{
				EnforcerVehicleDashController component = ((Component)val).GetComponent<EnforcerVehicleDashController>();
				GameObject val4 = (GameObject)(((Object)(object)component != (Object)null && controllerVehicleProperty != null) ? /*isinst with value type is only supported in some contexts*/: null);
				if (!((Object)(object)val4 == (Object)null) && !((Object)(object)vehicleMachine == (Object)null) && !((Object)(object)val4 != (Object)(object)((Component)vehicleMachine).gameObject))
				{
					value.VanillaExitSeen = true;
					base.Diag?.Info("EnforcerFeedback: vanilla exit animation seen for " + ((object)val3).GetType().Name + "; local ShieldTackleExit reset will not run again.");
				}
			}
		}

		private void SafeRestoreAfterStateExit(EntityStateMachine machine, EntityState newState)
		{
			try
			{
				EntityState state = machine.state;
				if (state != null && BodyToVehicleState.ContainsKey(((object)state).GetType()) && !BodyToVehicleState.ContainsKey(((object)newState).GetType()) && tracking.TryGetValue(state, out var value))
				{
					tracking.Remove(state);
					if (!value.AnimationResetDone && !value.VanillaExitSeen && !double.IsNegativeInfinity(value.EarlyFeedbackTime))
					{
						TryRestoreExitAnimation(value, "proxy state exited -> " + ((object)newState).GetType().Name);
					}
				}
			}
			catch (Exception ex)
			{
				base.Diag?.Warning("EnforcerFeedback: exit animation reset skipped (" + ex.GetType().Name + ": " + ex.Message + ").");
			}
		}

		private void TryRestoreExitAnimation(StateTracking entry, string reason)
		{
			//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)
			if (entry == null || entry.AnimationResetDone || double.IsNegativeInfinity(entry.EarlyFeedbackTime))
			{
				return;
			}
			if (entry.VanillaExitSeen)
			{
				entry.AnimationResetDone = true;
				return;
			}
			object obj;
			if (!((Object)(object)entry.Body != (Object)null))
			{
				obj = null;
			}
			else
			{
				ModelLocator modelLocator = entry.Body.modelLocator;
				obj = ((modelLocator != null) ? modelLocator.modelAnimator : null);
			}
			Animator val = (Animator)obj;
			if ((Object)(object)val == (Object)null)
			{
				base.Diag?.Warning("EnforcerFeedback: exit animation reset skipped: model animator unavailable (" + reason + ").");
				return;
			}
			int layerIndex = val.GetLayerIndex("FullBody, Override");
			if (layerIndex < 0)
			{
				base.Diag?.Warning("EnforcerFeedback: exit animation reset skipped: layer 'FullBody, Override' missing.");
				return;
			}
			AnimatorStateInfo currentAnimatorStateInfo = val.GetCurrentAnimatorStateInfo(layerIndex);
			int shortNameHash = ((AnimatorStateInfo)(ref currentAnimatorStateInfo)).shortNameHash;
			val.speed = 1f;
			val.Update(0f);
			val.PlayInFixedTime(ShieldTackleExitStateHash, layerIndex, 0f);
			entry.AnimationResetDone = true;
			EnforcerLocalEndPatch.NotifyExitAnimationPlayed(entry.Body);
			base.Diag?.Info("EnforcerFeedback: animation reset FullBody, Override=ShieldTackleExit reason=" + reason + "; before=" + HashLabel(shortNameHash) + "; duplicates are harmless, vanilla exit may replay it later.");
		}

		private static string HashLabel(int hash)
		{
			if (hash != ShieldTackleLoopStateHash)
			{
				if (hash != ShieldTackleExitStateHash)
				{
					return hash.ToString();
				}
				return "ShieldTackleExit";
			}
			return "ShieldTackleLoop";
		}

		private double OneWaySeconds()
		{
			double oneWaySeconds = 0.0;
			base.Latency?.TryGetOneWayLatency(out oneWaySeconds);
			return oneWaySeconds;
		}

		private static bool IsLocalAuthority(EntityState state)
		{
			NetworkIdentity val = (((Object)(object)state.outer != (Object)null) ? state.outer.networkIdentity : null);
			if ((Object)(object)val != (Object)null)
			{
				return Util.HasEffectiveAuthority(val);
			}
			return false;
		}

		private static FieldInfo FindField(Type type, string name)
		{
			Type type2 = type;
			while (type2 != null)
			{
				FieldInfo field = type2.GetField(name, BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
				if (field != null)
				{
					return field;
				}
				type2 = type2.BaseType;
			}
			return null;
		}
	}
	public sealed class EnforcerGhostDashPatch : SkillPatch
	{
		internal struct LocalEndGhostStatus
		{
			public bool Found;

			public CharacterBody Body;

			public EntityStateMachine BodyMachine;

			public EntityState BodyState;

			public double StartTime;

			public double MotionSeconds;

			public double Duration;

			public double TraveledSeconds;

			public double PredictedTravel;

			public double OneWay;

			public bool LeadRecorded;

			public bool Handoff;

			public bool MotionDone;

			public bool StateExited;

			public bool VehicleStateSeen;
		}

		private sealed class GhostState
		{
			public CharacterBody Body;

			public CharacterMotor CharacterMotor;

			public object Motor;

			public EntityStateMachine Machine;

			public EntityState BodyState;

			public FieldInfo VehicleEnteredField;

			public FieldInfo ForwardRotationField;

			public FieldInfo AimOffsetField;

			public bool Initialized;

			public Vector3 Origin;

			public Vector3 Position;

			public Vector3 LastApplied;

			public Vector3 Direction;

			public Quaternion AimOffset;

			public Vector3 CoreOffset;

			public float DirectionScale;

			public float SpeedCoefficient;

			public float Duration;

			public double InitialSpeed;

			public double DashDistance;

			public double LeadSeconds;

			public double LeadDistance;

			public bool LeadRecorded;

			public AnimationCurve Curve;

			public string CurveSource;

			public double StartTime;

			public double TraveledSeconds;

			public double OneWay;

			public double TimeoutSecondsCached;

			public double TimeoutRttCached;

			public bool WallStopped;

			public bool VehicleStateSeen;

			public bool Handoff;

			public bool Blending;

			public VehicleSeat Seat;

			public Vector3 HoldFrom;

			public double HoldStartTime;

			public double HoldTimeoutSeconds;

			public Vector3 BlendFrom;

			public double BlendStartTime;

			public float BlendDuration;

			public bool LoggedFirstStep;

			public bool MotionDoneLogged;

			public double MotionSeconds => LeadSeconds + (double)Duration;

			public double PredictedTravel => LeadDistance + DashDistance;
		}

		private const string Tag = "EnforcerGhostDash";

		private const float MinHandoffMeters = 0.05f;

		private const float TeleportSlackMeters = 2.5f;

		private static EnforcerGhostDashPatch instance;

		private static PropertyInfo motorProperty;

		private static PropertyInfo transientPositionProperty;

		private static MethodInfo setPositionMethod;

		private static FieldInfo seatPassengerField;

		private static PropertyInfo controllerVehicleProperty;

		private static readonly Dictionary<Type, Type> ProxyToVehicleState = new Dictionary<Type, Type>
		{
			{
				typeof(ProxyShieldDashHeavy),
				typeof(VehicleShieldDashHeavy)
			},
			{
				typeof(ProxyShieldDashLight),
				typeof(VehicleShieldDashLight)
			}
		};

		private readonly Dictionary<Type, FieldInfo> vehicleEnteredByType = new Dictionary<Type, FieldInfo>();

		private readonly Dictionary<Type, FieldInfo> forwardRotationByType = new Dictionary<Type, FieldInfo>();

		private readonly Dictionary<Type, FieldInfo> aimOffsetByType = new Dictionary<Type, FieldInfo>();

		private readonly Dictionary<Type, FieldInfo> speedBoostByType = new Dictionary<Type, FieldInfo>();

		private readonly Dictionary<Type, AnimationCurve> curvesByVehicleType = new Dictionary<Type, AnimationCurve>();

		private readonly Dictionary<Type, string> curveSourceByVehicleType = new Dictionary<Type, string>();

		private readonly ConditionalWeakTable<CharacterMotor, GhostState> states = new ConditionalWeakTable<CharacterMotor, GhostState>();

		private int activeStates;

		private const double PredictedTravelFreshSeconds = 2.0;

		private static double lastPredictedTravelMeters;

		private static double lastPredictedTravelTime = double.NegativeInfinity;

		private static bool lastPredictedTravelRecorded;

		private readonly Func<float> fixedTimeoutSeconds;

		private readonly Func<float> timeoutMaxSeconds;

		internal static double RecentPredictedTravelMeters()
		{
			if (!lastPredictedTravelRecorded)
			{
				return 0.0;
			}
			double num = (double)Time.time - lastPredictedTravelTime;
			if (!(num >= 0.0) || !(num <= 2.0))
			{
				return 0.0;
			}
			return lastPredictedTravelMeters;
		}

		private static void RememberPredictedTravel(GhostState ghost)
		{
			lastPredictedTravelMeters = (ghost.Initialized ? ghost.PredictedTravel : 0.0);
			lastPredictedTravelTime = Time.time;
			lastPredictedTravelRecorded = true;
		}

		public EnforcerGhostDashPatch(Func<bool> isEnabled, Func<float> fixedTimeoutSeconds, Func<float> timeoutMaxSeconds, DiagLog diag = null, LatencyEstimator latency = null)
			: base("EnforcerGhostDash", PatchSide.Client, isEnabled, diag, latency)
		{
			this.fixedTimeoutSeconds = fixedTimeoutSeconds;
			this.timeoutMaxSeconds = timeoutMaxSeconds;
		}

		protected override void Install()
		{
			//IL_03f4: Unknown result type (might be due to invalid IL or missing references)
			//IL_03f9: Unknown result type (might be due to invalid IL or missing references)
			//IL_040b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0419: Expected O, but got Unknown
			//IL_041a: Unknown result type (might be due to invalid IL or missing references)
			//IL_042d: Unknown result type (might be due to invalid IL or missing references)
			//IL_043a: Expected O, but got Unknown
			//IL_044c: Unknown result type (might be due to invalid IL or missing references)
			//IL_045a: Expected O, but got Unknown
			motorProperty = typeof(CharacterMotor).GetProperty("Motor");
			seatPassengerField = AccessTools.Field(typeof(VehicleSeat), "passengerBodyObject");
			controllerVehicleProperty = typeof(EnforcerVehicleDashController).GetProperty("currentVehicle", BindingFlags.Instance | BindingFlags.NonPublic);
			MethodInfo methodInfo = AccessTools.Method(typeof(EntityStateMachine), "SetState", new Type[1] { typeof(EntityState) }, (Type[])null);
			MethodInfo methodInfo2 = AccessTools.Method(typeof(CharacterMotor), "BeforeCharacterUpdate", new Type[1] { typeof(float) }, (Type[])null);
			MethodInfo methodInfo3 = AccessTools.Method(typeof(VehicleSeat), "UpdatePassengerPosition", new Type[2]
			{
				typeof(Vector3),
				typeof(Quaternion)
			}, (Type[])null);
			if (motorProperty == null || seatPassengerField == null || controllerVehicleProperty == null || methodInfo == null || methodInfo2 == null || methodInfo3 == null)
			{
				throw new MissingMemberException("EnforcerGhostDash members missing: " + $"Motor={motorProperty != null}, passengerBodyObject={seatPassengerField != null}, " + $"controller.currentVehicle={controllerVehicleProperty != null}, " + $"EntityStateMachine.SetState={methodInfo != null}, " + $"BeforeCharacterUpdate={methodInfo2 != null}, " + $"VehicleSeat.UpdatePassengerPosition={methodInfo3 != null}");
			}
			Type propertyType = motorProperty.PropertyType;
			transientPositionProperty = propertyType.GetProperty("TransientPosition");
			setPositionMethod = propertyType.GetMethod("SetPosition", new Type[2]
			{
				typeof(Vector3),
				typeof(bool)
			});
			if (transientPositionProperty == null || setPositionMethod == null)
			{
				throw new MissingMemberException($"{propertyType.FullName} members missing: TransientPosition={transientPositionProperty != null}, " + $"SetPosition={setPositionMethod != null}");
			}
			foreach (KeyValuePair<Type, Type> item in ProxyToVehicleState)
			{
				FieldInfo fieldInfo = FindField(item.Key, "vehicleEnteredState");
				FieldInfo fieldInfo2 = FindField(item.Key, "forwardRotation");
				FieldInfo fieldInfo3 = FindField(item.Key, "aimRotationOffsetFromAuthority");
				FieldInfo fieldInfo4 = FindField(item.Key, "normalizedBoostFromSpeedItems");
				if (fieldInfo == null || fieldInfo2 == null || fieldInfo3 == null || fieldInfo4 == null)
				{
					throw new MissingMemberException($"{item.Key.FullName} members missing: vehicleEnteredState={fieldInfo != null}, " + $"forwardRotation={fieldInfo2 != null}, " + $"aimRotationOffsetFromAuthority={fieldInfo3 != null}, " + $"normalizedBoostFromSpeedItems={fieldInfo4 != null}");
				}
				vehicleEnteredByType[item.Key] = fieldInfo;
				forwardRotationByType[item.Key] = fieldInfo2;
				aimOffsetByType[item.Key] = fieldInfo3;
				speedBoostByType[item.Key] = fieldInfo4;
			}
			EnforcerStartLeadPatch.ResolveRaycast();
			Harmony val = new Harmony("com.wray.ror2latency." + base.Name);
			val.Patch((MethodBase)methodInfo, new HarmonyMethod(typeof(EnforcerGhostDashPatch), "StateSetPrefix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			val.Patch((MethodBase)methodInfo2, (HarmonyMethod)null, new HarmonyMethod(typeof(EnforcerGhostDashPatch), "BeforeCharacterUpdatePostfix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			val.Patch((MethodBase)methodInfo3, new HarmonyMethod(typeof(EnforcerGhostDashPatch), "UpdatePassengerPositionPrefix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			instance = this;
			base.Diag?.Info("EnforcerGhostDash: installed (local dash ghost on ProxyShieldDash entry, lead + full dash curve, seat-snap suppression for the local ghost only, hold-until-caught-up then 0.1-0.2s blend).");
		}

		internal static bool TryGetGhostLeadInputs(EntityState state, out Vector3 origin, out Vector3 direction, out double speed)
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			//IL_00eb: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fc: Unknown result type (might be due to invalid IL or missing references)
			//IL_0101: Unknown result type (might be due to invalid IL or missing references)
			origin = default(Vector3);
			direction = default(Vector3);
			speed = 0.0;
			EnforcerGhostDashPatch self = instance;
			if (self == null || (Object)(object)state?.outer == (Object)null)
			{
				return false;
			}
			if (!self.ShouldRun())
			{
				return false;
			}
			CharacterMotor characterMotor = state.outer.commonComponents.characterMotor;
			if (characterMotor == null || !self.states.TryGetValue(characterMotor, out var ghost))
			{
				return false;
			}
			if ((Object)(object)ghost.Machine != (Object)(object)state.outer || ghost.BodyState != state)
			{
				return false;
			}
			if (!ghost.Initialized)
			{
				bool initialized = false;
				self.Guard(delegate
				{
					initialized = self.InitializeGhost(ghost);
				});
				if (!initialized)
				{
					return false;
				}
			}
			origin = ghost.Origin;
			direction = ghost.Direction;
			speed = Math.Max(0.0, ghost.InitialSpeed);
			return true;
		}

		internal static void SetGhostLead(EntityState state, double leadSeconds, double leadDistance)
		{
			EnforcerGhostDashPatch self = instance;
			self?.Guard(delegate
			{
				self.ApplyGhostLead(state, leadSeconds, leadDistance);
			});
		}

		internal static bool IsDashProxyState(EntityState state)
		{
			if (state != null)
			{
				return ProxyToVehicleState.ContainsKey(((object)state).GetType());
			}
			return false;
		}

		internal static bool TryGetLocalEndStatus(CharacterMotor motor, out LocalEndGhostStatus status)
		{
			status = default(LocalEndGhostStatus);
			EnforcerGhostDashPatch enforcerGhostDashPatch = instance;
			if (enforcerGhostDashPatch == null || motor == null || !enforcerGhostDashPatch.ShouldRun())
			{
				return false;
			}
			if (!enforcerGhostDashPatch.states.TryGetValue(motor, out var value))
			{
				return false;
			}
			status = Snapshot(value);
			return true;
		}

		internal static bool StepLocalEndGhost(CharacterMotor motor, float deltaTime, out LocalEndGhostStatus status)
		{
			status = default(LocalEndGhostStatus);
			EnforcerGhostDashPatch self = instance;
			if (self == null || motor == null || !self.ShouldRun())
			{
				return false;
			}
			if (!self.states.TryGetValue(motor, out var ghost))
			{
				return false;
			}
			self.Guard(delegate
			{
				self.StepGhost(ghost, deltaTime);
			});
			if (!self.states.TryGetValue(motor, out ghost))
			{
				return false;
			}
			status = Snapshot(ghost);
			return true;
		}

		internal static void StopLocalEndGhost(CharacterMotor motor, string reason)
		{
			EnforcerGhostDashPatch self = instance;
			if (self != null && motor != null && self.states.TryGetValue(motor, out var ghost))
			{
				self.Guard(delegate
				{
					self.Stop(ghost, reason);
				});
			}
		}

		private static LocalEndGhostStatus Snapshot(GhostState ghost)
		{
			return new LocalEndGhostStatus
			{
				Found = true,
				Body = ghost.Body,
				BodyMachine = ghost.Machine,
				BodyState = ghost.BodyState,
				StartTime = ghost.StartTime,
				MotionSeconds = ghost.MotionSeconds,
				Duration = ghost.Duration,
				TraveledSeconds = ghost.TraveledSeconds,
				PredictedTravel = ghost.PredictedTravel,
				OneWay = ghost.OneWay,
				LeadRecorded = ghost.LeadRecorded,
				Handoff = ghost.Handoff,
				MotionDone = (ghost.WallStopped || ghost.TraveledSeconds >= ghost.MotionSeconds - 1E-06),
				StateExited = ((Object)(object)ghost.Machine == (Object)null || ghost.Machine.state != ghost.BodyState),
				VehicleStateSeen = ghost.VehicleStateSeen
			};
		}

		private void ApplyGhostLead(EntityState state, double leadSeconds, double leadDistance)
		{
			CharacterMotor val = state?.outer?.commonComponents.characterMotor;
			if (val != null && states.TryGetValue(val, out var value) && value.BodyState == state)
			{
				if (value.LeadRecorded || value.TraveledSeconds > 0.0 || value.Handoff)
				{
					base.Diag?.Warning("EnforcerGhostDash: duplicate lead ignored (already moving/handed off).");
					return;
				}
				value.LeadRecorded = true;
				value.LeadDistance = Math.Max(0.0, leadDistance);
				value.LeadSeconds = ((value.LeadDistance > 0.001) ? Math.Max(0.0, leadSeconds) : 0.0);
				base.Diag?.Info(string.Format("{0}: lead recorded for ghost: {1:F3}s / {2:F2}m ", "EnforcerGhostDash", value.LeadSeconds, value.LeadDistance) + $"(dash curve adds {value.DashDistance:F2}m, total predicted {value.PredictedTravel:F2}m).");
			}
		}

		private static void StateSetPrefix(EntityStateMachine __instance, EntityState newState)
		{
			EnforcerGhostDashPatch self = instance;
			if (self != null && newState != null && ProxyToVehicleState.ContainsKey(((object)newState).GetType()))
			{
				self.Guard(delegate
				{
					self.BeginGhost(__instance, newState);
				});
			}
		}

		private static void BeforeCharacterUpdatePostfix(CharacterMotor __instance, float deltaTime)
		{
			EnforcerGhostDashPatch self = instance;
			if (self != null && self.activeStates != 0 && self.states.TryGetValue(__instance, out var ghost))
			{
				self.Guard(delegate
				{
					self.StepGhost(ghost, deltaTime);
				});
			}
		}

		private static bool UpdatePassengerPositionPrefix(VehicleSeat __instance)
		{
			EnforcerGhostDashPatch self = instance;
			if (self == null)
			{
				return true;
			}
			if (EnforcerLocalEndPatch.TryControlSeat(__instance))
			{
				return false;
			}
			if (self.activeStates == 0)
			{
				return true;
			}
			bool skip = false;
			self.Guard(delegate
			{
				skip = self.ShouldSkipSeatSnap(__instance);
			});
			return !skip;
		}

		private void BeginGhost(EntityStateMachine machine, EntityState state)
		{
			//IL_000a: Unknown result type (might be due to invalid IL or missing references)
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00be: 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_0130: Unknown result type (might be due to invalid IL or missing references)
			//IL_0136: Unknown result type (might be due to invalid IL or missing references)
			//IL_0138: Unknown result type (might be due to invalid IL or missing references)
			//IL_013e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0140: 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_0157: Unknown result type (might be due to invalid IL or missing references)
			//IL_015c: Unknown result type (might be due to invalid IL or missing references)
			//IL_020e: Unknown result type (might be due to invalid IL or missing references)
			//IL_021d: Unknown result type (might be due to invalid IL or missing references)
			//IL_022c: Unknown result type (might be due to invalid IL or missing references)
			if (!ShouldRun())
			{
				return;
			}
			CommonComponentCache commonComponents = machine.commonComponents;
			CharacterBody characterBody = commonComponents.characterBody;
			CharacterMotor characterMotor = commonComponents.characterMotor;
			if ((Object)(object)characterBody == (Object)null || characterMotor == null || (Object)(object)characterBody.healthComponent == (Object)null || !characterBody.healthComponent.alive || !Util.HasEffectiveAuthority(machine.networkIdentity) || (Object)(object)characterBody.currentVehicle != (Object)null)
			{
				return;
			}
			if (base.Latency == null || !base.Latency.TryGetOneWayLatency(out var oneWaySeconds) || oneWaySeconds <= 0.0)
			{
				base.Diag?.Throttled("EnforcerGhostDash.nolatency", "EnforcerGhostDash: no ghost, one-way latency unavailable (host or no RTT sample).");
				return;
			}
			object value = motorProperty.GetValue(characterMotor);
			if (value != null)
			{
				Vector3 val = (Vector3)transientPositionProperty.GetValue(value);
				GhostState ghostState = new GhostState
				{
					Body = characterBody,
					CharacterMotor = characterMotor,
					Motor = value,
					Machine = machine,
					BodyState = state,
					VehicleEnteredField = vehicleEnteredByType[((object)state).GetType()],
					ForwardRotationField = forwardRotationByType[((object)state).GetType()],
					AimOffsetField = aimOffsetByType[((object)state).GetType()],
					Origin = val,
					Position = val,
					LastApplied = val,
					CoreOffset = characterBody.corePosition - ((Component)characterBody).transform.position,
					StartTime = Time.time,
					OneWay = oneWaySeconds
				};
				ghostState.TimeoutRttCached = TimeoutRttSeconds();
				ghostState.TimeoutSecondsCached = TimeoutSeconds(ghostState.TimeoutRttCached);
				GhostState value2;
				bool num = states.TryGetValue(characterMotor, out value2);
				states.Remove(characterMotor);
				states.Add(characterMotor, ghostState);
				if (!num)
				{
					activeStates++;
				}
				base.Diag?.Info("EnforcerGhostDash: ghost armed state=" + ((object)state).GetType().Name + " " + $"pos=({val.x:F2},{val.y:F2},{val.z:F2}) U={oneWaySeconds:F3}s RTT={2.0 * oneWaySeconds:F3}s " + $"cap={0.25:F2}s " + $"timeout={ghostState.TimeoutSecondsCached:F2}s timeoutRTT={ghostState.TimeoutRttCached:F3}s {base.Latency?.Describe()} " + "speed/direction resolved on first step (after ModifyNextState/OnEnter).");
			}
		}

		private bool InitializeGhost(GhostState ghost)
		{
			//IL_006b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0070: Unknown result type (might be due to invalid IL or missing references)
			//IL_0082: Unknown result type (might be due to invalid IL or missing references)
			//IL_0087: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ab: 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_00b2: 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_00bc: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fd: Unknown result type (might be due to invalid IL or missing references)
			//IL_0101: Unknown result type (might be due to invalid IL or missing references)
			//IL_0106: Unknown result type (might be due to invalid IL or missing references)
			//IL_0195: 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)
			//IL_019d: Unknown result type (might be due to invalid IL or missing references)
			//IL_019f: Unknown result type (might be due to invalid IL or missing references)
			//IL_020e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0271: Unknown result type (might be due to invalid IL or missing references)
			//IL_027d: Unknown result type (might be due to invalid IL or missing references)
			EntityState bodyState = ghost.BodyState;
			IShieldDashSpeedAndDuration val = (IShieldDashSpeedAndDuration)(object)((bodyState is IShieldDashSpeedAndDuration) ? bodyState : null);
			if (val == null)
			{
				Stop(ghost, "state does not expose IShieldDashSpeedAndDuration");
				return false;
			}
			float inOverrideDurationFromAuthority = val.inOverrideDurationFromAuthority;
			float inOverrideSpeedCoefficientFromAuthority = val.inOverrideSpeedCoefficientFromAuthority;
			if (inOverrideDurationFromAuthority <= 0f || inOverrideSpeedCoefficientFromAuthority <= 0f)
			{
				Stop(ghost, $"invalid duration={inOverrideDurationFromAuthority:F2}s coefficient={inOverrideSpeedCoefficientFromAuthority:F2}");
				return false;
			}
			Vector3 val2 = (Vector3)ghost.ForwardRotationField.GetValue(ghost.BodyState);
			Quaternion val3 = (Quaternion)ghost.AimOffsetField.GetValue(ghost.BodyState);
			if (((Vector3)(ref val2)).sqrMagnitude < 1E-06f)
			{
				Stop(ghost, "forwardRotation is zero");
				return false;
			}
			Vector3 val4 = Quaternion.LookRotation(val2, Vector3.up) * val3 * Vector3.forward;
			Vector3 val5 = default(Vector3);
			((Vector3)(ref val5))..ctor(val4.x, 0f, val4.z);
			float magnitude = ((Vector3)(ref val5)).magnitude;
			if (magnitude < 0.0001f)
			{
				Stop(ghost, "aim direction is vertical");
				return false;
			}
			val5 /= magnitude;
			float num = (float)speedBoostByType[((object)ghost.BodyState).GetType()].GetValue(ghost.BodyState);
			float num2 = ghost.Body.moveSpeed / Mathf.Max(ghost.Body.baseMoveSpeed * ghost.Body.sprintingSpeedMultiplier, 1f);
			float num3 = inOverrideSpeedCoefficientFromAuthority * Mathf.Lerp(1f, num2, num);
			Type vehicleStateType = ProxyToVehicleState[((object)ghost.BodyState).GetType()];
			string source;
			AnimationCurve curve = GetCurve(vehicleStateType, out source);
			ghost.Direction = val5;
			ghost.AimOffset = val3;
			ghost.DirectionScale = magnitude;
			ghost.SpeedCoefficient = num3;
			ghost.Duration = inOverrideDurationFromAuthority;
			ghost.Curve = curve;
			ghost.CurveSource = source;
			ghost.InitialSpeed = ((curve != null) ? curve.Evaluate(0f) : 1f) * num3 * magnitude;
			ghost.DashDistance = MeanCurveValue(curve) * (double)inOverrideDurationFromAuthority * (double)num3 * (double)magnitude;
			ghost.Initialized = true;
			float num4 = Mathf.Asin(Mathf.Clamp(val4.y, -1f, 1f)) * 57.29578f;
			base.Diag?.Info("EnforcerGhostDash: ghost init state=" + ((object)ghost.BodyState).GetType().Name + " " + $"dir=({val5.x:F2},{val5.z:F2}) horizontalScale={magnitude:F3} " + $"pitch={num4:F1}deg speedCoeff={num3:F2}m/s initialSpeed={ghost.InitialSpeed:F2}m/s " + $"overrideCoeff={inOverrideSpeedCoefficientFromAuthority:F2} duration={inOverrideDurationFromAuthority:F2}s dashDistance={ghost.DashDistance:F2}m " + "curve=" + source + " assumptions: horizontal-only motion, local moveSpeed stat, curve evaluated at t=elapsed/duration.");
			return true;
		}

		private static double MeanCurveValue(AnimationCurve curve)
		{
			if (curve == null)
			{
				return 1.0;
			}
			double num = 0.0;
			for (int i = 0; i < 16; i++)
			{
				num += (double)curve.Evaluate(((float)i + 0.5f) / 16f);
			}
			return num / 16.0;
		}

		private static void FollowSteering(GhostState ghost)
		{
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			//IL_001a: Unknown result type (might be due to invalid IL or missing references)
			//IL_002c: Unknown result type (might be due to invalid IL or missing references)
			//IL_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_003c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0041: Unknown result type (might be due to invalid IL or missing references)
			//IL_0046: Unknown result type (might be due to invalid IL or missing references)
			//IL_004b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0050: Unknown result type (might be due to invalid IL or missing references)
			//IL_0053: Unknown result type (might be due to invalid IL or missing references)
			//IL_005e: Unknown result type (might be due to invalid IL or missing references)
			//IL_007b: Unknown result type (might be due to invalid IL or missing references)
			//IL_007d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0082: Unknown result type (might be due to invalid IL or missing references)
			CharacterDirection characterDirection = ghost.Body.characterDirection;
			if (!Object.op_Implicit((Object)(object)characterDirection))
			{
				return;
			}
			Vector3 forward = characterDirection.forward;
			if (!(((Vector3)(ref forward)).sqrMagnitude < 1E-06f))
			{
				Vector3 val = Quaternion.LookRotation(characterDirection.forward, Vector3.up) * ghost.AimOffset * Vector3.forward;
				Vector3 val2 = default(Vector3);
				((Vector3)(ref val2))..ctor(val.x, 0f, val.z);
				float magnitude = ((Vector3)(ref val2)).magnitude;
				if (!(magnitude < 0.0001f))
				{
					ghost.Direction = val2 / magnitude;
					ghost.DirectionScale = magnitude;
				}
			}
		}

		private void StepGhost(GhostState ghost, float deltaTime)
		{
			//IL_02f7: Unknown result type (might be due to invalid IL or missing references)
			//IL_0324: Unknown result type (might be due to invalid IL or missing references)
			//IL_043a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0440: Unknown result type (might be due to invalid IL or missing references)
			//IL_0445: Unknown result type (might be due to invalid IL or missing references)
			//IL_044b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0517: Unknown result type (might be due to invalid IL or missing references)
			//IL_051d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0525: Unknown result type (might be due to invalid IL or missing references)
			//IL_052a: Unknown result type (might be due to invalid IL or missing references)
			//IL_052f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0532: Unknown result type (might be due to invalid IL or missing references)
			//IL_0655: Unknown result type (might be due to invalid IL or missing references)
			//IL_0661: Unknown result type (might be due to invalid IL or missing references)
			//IL_05c3: Unknown result type (might be due to invalid IL or missing references)
			//IL_05cf: Unknown result type (might be due to invalid IL or missing references)
			CharacterBody body = ghost.Body;
			if (!ShouldRun())
			{
				Stop(ghost, "config off / host / tripped");
			}
			else if ((Object)(object)body == (Object)null || body.characterMotor != ghost.CharacterMotor)
			{
				Stop(ghost, "body lost");
			}
			else if ((Object)(object)body.healthComponent == (Object)null || !body.healthComponent.alive)
			{
				Stop(ghost, "death");
			}
			else if (!body.hasEffectiveAuthority)
			{
				Stop(ghost, "lost authority");
			}
			else if ((Object)(object)ghost.Machine == (Object)null || ghost.Machine.state != ghost.BodyState)
			{
				Stop(ghost, "dash state exited");
			}
			else
			{
				if (!ghost.Initialized && !InitializeGhost(ghost))
				{
					return;
				}
				RememberPredictedTravel(ghost);
				if (!ghost.LeadRecorded)
				{
					Stop(ghost, "StartLead did not report a start (disabled/failed); no ghost");
					return;
				}
				if (ghost.Handoff)
				{
					AdvanceHandoff(ghost);
					return;
				}
				double num = (double)Time.time - ghost.StartTime;
				if (!ghost.VehicleStateSeen && VehicleStateSeen(ghost))
				{
					ghost.VehicleStateSeen = true;
					base.Diag?.Info(string.Format("{0}: vehicle state seen after {1:F2}s (U={2:F3}s); ", "EnforcerGhostDash", num, ghost.OneWay) + $"ghost=({ghost.Position.x:F2},{ghost.Position.z:F2}) " + $"vehicle={VehiclePositionText(body)} gap={VehicleGap(ghost):F2}m; " + $"traveled={ghost.TraveledSeconds:F2}s/{ghost.MotionSeconds:F2}s, still simulating.");
				}
				if ((Object)(object)body.currentVehicle != (Object)null && !EnforcerLocalEndPatch.OwnsGhost(body))
				{
					BeginHandoff(ghost, body.currentVehicle);
					if (ghost.Handoff)
					{
						AdvanceHandoff(ghost);
					}
					return;
				}
				double num2 = ghost.TimeoutSecondsCached;
				Func<float> func = fixedTimeoutSeconds;
				if (func == null || !(func() > 0f))
				{
					num2 = PredictionMath.ExtendStuckTimeout(num2, TimeoutRttSeconds(), timeoutMaxSeconds?.Invoke() ?? 3f);
				}
				if ((Object)(object)body.currentVehicle == (Object)null && num >= num2)
				{
					Stop(ghost, $"timeout after {num:F2}s (timeout {num2:F2}s), vehicle never arrived");
					return;
				}
				if (MovedExternally(ghost))
				{
					Stop(ghost, "position moved externally while ghosting");
					return;
				}
				if (ghost.WallStopped || ghost.TraveledSeconds >= ghost.MotionSeconds - 1E-06)
				{
					if (!ghost.MotionDoneLogged)
					{
						ghost.MotionDoneLogged = true;
						base.Diag?.Info(string.Format("{0}: ghost motion done at t={1:F2}s (motion={2:F2}s, ", "EnforcerGhostDash", num, ghost.MotionSeconds) + $"predicted={ghost.PredictedTravel:F2}m, wall={ghost.WallStopped}); holding for the seat.");
					}
					ApplyPosition(ghost, ghost.Position);
					return;
				}
				double num3 = PredictionMath.GhostStepSeconds(deltaTime, ghost.TraveledSeconds, ghost.MotionSeconds);
				if (num3 <= 0.0)
				{
					ApplyPosition(ghost, ghost.Position);
					return;
				}
				double traveledSeconds = ghost.TraveledSeconds;
				double num4 = traveledSeconds + num3;
				double num5 = Overlap(traveledSeconds, num4, 0.0, ghost.LeadSeconds);
				double leadSeconds = ghost.LeadSeconds;
				double num6 = ghost.LeadSeconds + (double)ghost.Duration;
				double num7 = Overlap(traveledSeconds, num4, leadSeconds, num6);
				double num8 = ((ghost.LeadSeconds > 1E-06) ? (ghost.LeadDistance / ghost.LeadSeconds) : 0.0);
				float num9 = Mathf.Clamp((float)((Math.Max(leadSeconds, Math.Min(num4, num6)) - leadSeconds) / (double)ghost.Duration), 0f, 1f);
				float num10 = ((ghost.Curve != null) ? ghost.Curve.Evaluate(num9) : 1f);
				if (num7 > 0.0)
				{
					FollowSteering(ghost);
				}
				double num11 = num10 * ghost.SpeedCoefficient * ghost.DirectionScale;
				double num12 = num8 * num5 + num11 * num7;
				double num13 = double.PositiveInfinity;
				if (num12 > 0.01)
				{
					num13 = EnforcerStartLeadPatch.RaycastDistance(ghost.Position + ghost.CoreOffset, ghost.Direction, (float)(num12 + 0.01));
				}
				double num14 = PredictionMath.GhostStepWallLimit(num12, num13);
				if (!double.IsPositiveInfinity(num13) && num14 < num12 - 0.001)
				{
					ghost.WallStopped = true;
					base.Diag?.Info(string.Format("{0}: wall stop at t={1:F2}s wallDistance={2:F2}m ", "EnforcerGhostDash", num, num13) + $"desired={num12:F3}m applied={num14:F3}m pos=({ghost.Position.x:F2},{ghost.Position.z:F2}); " + "holding position until handoff/timeout.");
				}
				Vector3 val = ghost.Position + ghost.Direction * (float)num14;
				ApplyPosition(ghost, val);
				ghost.TraveledSeconds += num3;
				if (!ghost.LoggedFirstStep)
				{
					ghost.LoggedFirstStep = true;
					base.Diag?.Info(string.Format("{0}: first step t={1:F2}s curve={2:F2} speed={3:F2}m/s ", "EnforcerGhostDash", num, num10, num11) + $"lead={num8 * num5:F3}m dash={num11 * num7:F3}m " + $"step={num14:F3}m pos=({val.x:F2},{val.z:F2}).");
				}
				else
				{
					base.Diag?.Throttled("EnforcerGhostDash.step", string.Format("{0}: ghost t={1:F2}s curve={2:F2} speed={3:F2}m/s ", "EnforcerGhostDash", num, num10, num11) + $"traveled={ghost.TraveledSeconds:F2}s/{ghost.MotionSeconds:F2}s " + $"pos=({val.x:F2},{val.z:F2}) U={ghost.OneWay:F3}s.");
				}
			}
		}

		private static double Overlap(double start, double end, double low, double high)
		{
			return Math.Max(0.0, Math.Min(end, high) - Math.Max(start, low));
		}

		private void BeginHandoff(GhostState ghost, VehicleSeat seat)
		{
			//IL_009e: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00aa: Unknown result type (might be due to invalid IL or missing references)
			//IL_00af: 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_00b1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ca: Unknown result type (might be due to invalid IL or missing references)
			//IL_0184: 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_0197: Unknown result type (might be due to invalid IL or missing references)
			//IL_0198: Unknown result type (might be due to invalid IL or missing references)
			//IL_019e: Unknown result type (might be due to invalid IL or missing references)
			//IL_019f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0215: Unknown result type (might be due to invalid IL or missing references)
			//IL_0223: Unknown result type (might be due to invalid IL or missing references)
			//IL_0231: Unknown result type (might be due to invalid IL or missing references)
			//IL_023f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0310: Unknown result type (might be due to invalid IL or missing references)
			//IL_0311: Unknown result type (might be due to invalid IL or missing references)
			if (ghost.Handoff || (Object)(object)seat == (Object)null || (Object)(object)seat.seatPosition == (Object)null || (Object)(object)ghost.Body == (Object)null)
			{
				return;
			}
			object? value = seatPassengerField.GetValue(seat);
			GameObject val = (GameObject)((value is GameObject) ? value : null);
			if ((Object)(object)val == (Object)null || (Object)(object)val != (Object)(object)((Component)ghost.Body).gameObject || !ghost.Body.hasEffectiveAuthority || (Object)(object)ghost.Body.currentVehicle != (Object)(object)seat || (!ghost.Initialized && !InitializeGhost(ghost)))
			{
				return;
			}
			Vector3 val2 = (Vector3)transientPositionProperty.GetValue(ghost.Motor);
			Vector3 position = seat.seatPosition.position;
			float num = Vector3.Distance(val2, position);
			double num2 = (double)Time.time - ghost.StartTime;
			double lateral;
			double num3 = AlongTrack(val2, position, ghost.Direction, out lateral);
			if (num <= 0.05f)
			{
				Stop(ghost, $"seat already at ghost, gap={num:F2}m");
				return;
			}
			if (PredictionMath.HandoffIsTeleport(num, ghost.PredictedTravel))
			{
				base.Diag?.Info(string.Format("{0}: seat too far, gap={1:F2}m > limit ", "EnforcerGhostDash", num) + $"{PredictionMath.HandoffDistanceLimit(ghost.PredictedTravel):F1}m " + $"(predicted={ghost.PredictedTravel:F1}m); ghost ends, vanilla seat snap.");
				Stop(ghost, "seat too far (teleport/respawn)");
				return;
			}
			ghost.Handoff = true;
			ghost.Blending = false;
			ghost.Seat = seat;
			ghost.HoldFrom = val2;
			ghost.HoldStartTime = Time.time;
			ghost.BlendFrom = val2;
			ghost.LastApplied = val2;
			ghost.HoldTimeoutSeconds = PredictionMath.HoldTimeout(TimeoutRttSeconds(), timeoutMaxSeconds?.Invoke() ?? 3f);
			base.Diag?.Info(string.Format("{0}: handoff begin after {1:F2}s (U={2:F3}s) ", "EnforcerGhostDash", num2, ghost.OneWay) + $"ghost=({val2.x:F2},{val2.z:F2}) seat=({position.x:F2},{position.z:F2}) " + $"gap={num:F2}m along={num3:F2}m lateral={lateral:F2}m " + $"traveled={ghost.TraveledSeconds:F2}s/{ghost.MotionSeconds:F2}s " + $"predicted={ghost.PredictedTravel:F2}m holdTimeout={ghost.HoldTimeoutSeconds:F2}s " + $"vehicleStateSeen={ghost.VehicleStateSeen} disablePassengerMotor={seat.disablePassengerMotor} " + "vehicle=" + VehiclePositionText(ghost.Body) + ".");
			if (PredictionMath.HandoffCaughtUp(num3, lateral))
			{
				StartBlend(ghost, val2, position);
			}
		}

		private void AdvanceHandoff(GhostState ghost)
		{
			//IL_00b9: 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: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cf: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00db: Unknown result type (might be due to invalid IL or missing references)
			//IL_011d: Unknown result type (might be due to invalid IL or missing references)
			//IL_011e: Unknown result type (might be due to invalid IL or missing references)
			//IL_02f6: Unknown result type (might be due to invalid IL or missing references)
			//IL_02fb: Unknown result type (might be due to invalid IL or missing references)
			//IL_02ff: Unknown result type (might be due to invalid IL or missing references)
			//IL_0304: Unknown result type (might be due to invalid IL or missing references)
			//IL_0307: Unknown result type (might be due to invalid IL or missing references)
			//IL_0143: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a8: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b6: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c4: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d2: Unknown result type (might be due to invalid IL or missing references)
			//IL_034d: Unknown result type (might be due to invalid IL or missing references)
			//IL_034f: Unknown result type (might be due to invalid IL or missing references)
			//IL_02a1: Unknown result type (might be due to invalid IL or missing references)
			//IL_02a2: Unknown result type (might be due to invalid IL or missing references)
			if (!ghost.Handoff)
			{
				return;
			}
			if ((Object)(object)ghost.Body == (Object)null || (Object)(object)ghost.Body.healthComponent == (Object)null || !ghost.Body.healthComponent.alive)
			{
				Stop(ghost, "death during handoff");
				return;
			}
			if (!ghost.Body.hasEffectiveAuthority)
			{
				Stop(ghost, "lost authority during handoff");
				return;
			}
			if ((Object)(object)ghost.Seat == (Object)null || (Object)(object)ghost.Seat.seatPosition == (Object)null || (Object)(object)ghost.Body.currentVehicle != (Object)(object)ghost.Seat)
			{
				Stop(ghost, "seat lost during handoff (ejection)");
				return;
			}
			Vector3 val = (Vector3)transientPositionProperty.GetValue(ghost.Motor);
			Vector3 position = ghost.Seat.seatPosition.position;
			float num = Vector3.Distance(val, position);
			double lateral;
			double num2 = AlongTrack(val, position, ghost.Direction, out lateral);
			if (MovedExternally(ghost))
			{
				Stop(ghost, "position moved externally during handoff");
				return;
			}
			double num3 = Time.time;
			if (!ghost.Blending)
			{
				if (PredictionMath.HandoffCaughtUp(num2, lateral))
				{
					StartBlend(ghost, val, position);
				}
				else
				{
					double num4 = num3 - ghost.HoldStartTime;
					if (num4 < ghost.HoldTimeoutSeconds)
					{
						ApplyPosition(ghost, ghost.HoldFrom);
						base.Diag?.Throttled("EnforcerGhostDash.hold", string.Format("{0}: holding for seat {1:F2}s/{2:F2}s ", "EnforcerGhostDash", num4, ghost.HoldTimeoutSeconds) + $"gap={num:F2}m along={num2:F2}m lateral={lateral:F2}m " + $"seat=({position.x:F2},{position.z:F2}) ghost=({val.x:F2},{val.z:F2}).");
						return;
					}
					if (PredictionMath.HandoffIsTeleport(num, ghost.PredictedTravel))
					{
						base.Diag?.Info(string.Format("{0}: hold timeout {1:F2}s, gap={2:F2}m too far to blend ", "EnforcerGhostDash", num4, num) + $"(limit {PredictionMath.HandoffDistanceLimit(ghost.PredictedTravel):F1}m); vanilla seat snap.");
						Stop(ghost, "hold timeout, target too far");
						return;
					}
					base.Diag?.Info(string.Format("{0}: hold timeout {1:F2}s, blending to seat anyway ", "EnforcerGhostDash", num4) + $"(gap={num:F2}m along={num2:F2}m lateral={lateral:F2}m).");
					StartBlend(ghost, val, position);
				}
			}
			if (!ghost.Blending)
			{
				return;
			}
			if (PredictionMath.HandoffIsTeleport(num, ghost.PredictedTravel))
			{
				Stop(ghost, $"blend target jumped to {num:F2}m (teleport/respawn)");
				return;
			}
			double num5 = num3 - ghost.BlendStartTime;
			double num6 = PredictionMath.InterpolationAlpha(num5, ghost.BlendDuration);
			Vector3 val2 = Vector3.Lerp(ghost.BlendFrom, position, (float)num6);
			ApplyPosition(ghost, val2);
			if (num6 >= 1.0)
			{
				base.Diag?.Info(string.Format("{0}: handoff done in {1:F2}s (blend {2:F2}s) ", "EnforcerGhostDash", num5, ghost.BlendDuration) + $"residual={Vector3.Distance(val2, position):F2}m; vanilla seat snap resumes.");
				Stop(ghost, "handoff complete");
			}
		}

		private void StartBlend(GhostState ghost, Vector3 from, Vector3 target)
		{
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			//IL_0009: Unknown result type (might be due to invalid IL or missing references)
			//IL_0065: Unknown result type (might be due to invalid IL or missing references)
			//IL_0073: Unknown result type (might be due to invalid IL or missing references)
			//IL_0081: Unknown result type (might be due to invalid IL or missing references)
			//IL_008f: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a6: Unknown result type (might be due to invalid IL or missing references)
			ghost.Blending = true;
			ghost.BlendFrom = from;
			ghost.BlendStartTime = Time.time;
			ghost.BlendDuration = (float)PredictionMath.ClampInterpolationDuration(ghost.OneWay);
			base.Diag?.Info(string.Format("{0}: caught up after {1:F2}s; blend to seat ", "EnforcerGhostDash", (double)Time.time - ghost.HoldStartTime) + $"from=({from.x:F2},{from.z:F2}) to=({target.x:F2},{target.z:F2}) " + $"gap={Vector3.Distance(from, target):F2}m duration={ghost.BlendDuration:F2}s.");
		}

		private bool ShouldSkipSeatSnap(VehicleSeat seat)
		{
			if ((Object)(object)seat == (Object)null)
			{
				return false;
			}
			object? value = seatPassengerField.GetValue(seat);
			GameObject val = (GameObject)((value is GameObject) ? value : null);
			CharacterBody val2 = (((Object)(object)val != (Object)null) ? val.GetComponent<CharacterBody>() : null);
			CharacterMotor val3 = (((Object)(object)val2 != (Object)null) ? val2.characterMotor : null);
			if (val3 == null || !states.TryGetValue(val3, out var value2) || (Object)(object)value2.Body != (Object)(object)val2)
			{
				return false;
			}
			if (!ShouldRun())
			{
				Stop(value2, "config off / host / tripped during handoff");
				return false;
			}
			if (value2.Handoff && (Object)(object)value2.Seat != (Object)(object)seat)
			{
				Stop(value2, "seat changed during handoff");
				return false;
			}
			if (!value2.Handoff)
			{
				if ((Object)(object)value2.Machine == (Object)null || value2.Machine.state != value2.BodyState)
				{
					Stop(value2, "stale ghost, dash state already exited");
					return false;
				}
				BeginHandoff(value2, seat);
			}
			AdvanceHandoff(value2);
			if (value2.Handoff)
			{
				return (Object)(object)value2.Seat == (Object)(object)seat;
			}
			return false;
		}

		private static double AlongTrack(Vector3 from, Vector3 to, Vector3 direction, out double lateral)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_0014: Unknown result type (might be due to invalid IL or missing references)
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			//IL_001d: Unknown result type (might be due to invalid IL or missing references)
			//IL_001e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0020: Unknown result type (might be due to invalid IL or missing references)
			//IL_0025: Unknown result type (might be due to invalid IL or missing references)
			//IL_002a: Unknown result type (might be due to invalid IL or missing references)
			Vector3 val = to - from;
			val.y = 0f;
			float num = Vector3.Dot(val, direction);
			Vector3 val2 = val - direction * num;
			lateral = ((Vector3)(ref val2)).magnitude;
			return num;
		}

		private static bool VehicleStateSeen(GhostState ghost)
		{
			try
			{
				bool flag = default(bool);
				int num;
				if (ghost.VehicleEnteredField != null)
				{
					object value = ghost.VehicleEnteredField.GetValue(ghost.BodyState);
					if (value is bool)
					{
						flag = (bool)value;
						num = 1;
					}
					else
					{
						num = 0;
					}
				}
				else
				{
					num = 0;
				}
				return (byte)((uint)num & (flag ? 1u : 0u)) != 0;
			}
			catch (Exception)
			{
				return false;
			}
		}

		private bool MovedExternally(GhostState ghost)
		{
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			return Vector3.Distance((Vector3)transientPositionProperty.GetValue(ghost.Motor), ghost.LastApplied) > 2.5f;
		}

		private static void ApplyPosition(GhostState ghost, Vector3 position)
		{
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			//IL_002a: Unknown result type (might be due to invalid IL or missing references)
			//IL_002b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0031: Unknown result type (might be due to invalid IL or missing references)
			//IL_0032: Unknown result type (might be due to invalid IL or missing references)
			setPositionMethod.Invoke(ghost.Motor, new object[2] { position, true });
			ghost.Position = position;
			ghost.LastApplied = position;
		}

		private double TimeoutSeconds(double rtt)
		{
			float num = fixedTimeoutSeconds?.Invoke() ?? 0f;
			if (!(num > 0f))
			{
				return PredictionMath.StuckTimeout(rtt, timeoutMaxSeconds?.Invoke() ?? 3f);
			}
			return num;
		}

		private double TimeoutRttSeconds()
		{
			if (base.Latency == null || !base.Latency.TryGetTimeoutRoundTrip(out var roundTripSeconds))
			{
				return 0.0;
			}
			return roundTripSeconds;
		}

		private void Stop(GhostState ghost, string reason)
		{
			RememberPredictedTravel(ghost);
			bool handoff = ghost.Handoff;
			double num = (ghost.Blending ? ((double)Time.time - ghost.BlendStartTime) : 0.0);
			ghost.Handoff = false;
			ghost.Blending = false;
			states.Remove(ghost.CharacterMotor);
			activeStates = Math.Max(0, activeStates - 1);
			base.Diag?.Info(string.Format("{0}: ghost stopped: {1}; pos=({2:F2},{3:F2}) ", "EnforcerGhostDash", reason, ghost.Position.x, ghost.Position.z) + $"elapsed={(double)Time.time - ghost.StartTime:F2}s handoff={handoff} " + $"blendElapsed={num:F2}s traveled={ghost.TraveledSeconds:F2}s/" + $"{ghost.MotionSeconds:F2}s predicted={ghost.PredictedTravel:F2}m.");
		}

		private AnimationCurve GetCurve(Type vehicleStateType, out string source)
		{
			//IL_0036: Unknown result type (might be due to invalid IL or missing references)
			//IL_003c: Expected O, but got Unknown
			if (curvesByVehicleType.TryGetValue(vehicleStateType, out var value))
			{
				source = curveSourceByVehicleType[vehicleStateType];
				return value;
			}
			AnimationCurve val = null;
			FieldInfo field = vehicleStateType.GetField("forwardVelocityCurve", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
			try
			{
				EntityState obj = (EntityState)Activator.CreateInstance(vehicleStateType);
				val = (AnimationCurve)((field != null) ? /*isinst with value type is only supported in some contexts*/: null);
				source = ((val != null) ? (vehicleStateType.Name + ".forwardVelocityCurve") : (vehicleStateType.Name + " curve missing -> constant 1.0"));
			}
			catch (Exception ex)
			{
				source = vehicleStateType.Name + " curve unavailable (" + ex.GetType().Name + ") -> constant 1.0";
			}
			curvesByVehicleType[vehicleStateType] = val;
			curveSourceByVehicleType[vehicleStateType] = source;
			return val;
		}

		private static string VehiclePositionText(CharacterBody body)
		{
			//IL_001e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0023: 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_0034: Unknown result type (might be due to invalid IL or missing references)
			//IL_003f: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				GameObject val = FindVehicle(body);
				if ((Object)(object)val == (Object)null)
				{
					return "none";
				}
				Vector3 position = val.transform.position;
				return $"({position.x:F2},{position.y:F2},{position.z:F2})";
			}
			catch (Exception)
			{
				return "error";
			}
		}

		private static float VehicleGap(GhostState ghost)
		{
			//IL_001d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0028: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				GameObject val = FindVehicle(ghost.Body);
				return ((Object)(object)val != (Object)null) ? Vector3.Distance(ghost.Position, val.transform.position) : (-1f);
			}
			catch (Exception)
			{
				return -1f;
			}
		}

		private static GameObject FindVehicle(CharacterBody body)
		{
			EnforcerVehicleDashController val = (((Object)(object)body != (Object)null) ? ((Component)body).GetComponent<EnforcerVehicleDashController>() : null);
			if (!((Object)(object)val != (Object)null) || !(controllerVehicleProperty != null))
			{
				return null;
			}
			object? value = controllerVehicleProperty.GetValue(val);
			return (GameObject)((value is GameObject) ? value : null);
		}

		private static FieldInfo FindField(Type type, string name)
		{
			Type type2 = type;
			while (type2 != null)
			{
				FieldInfo field = type2.GetField(name, BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
				if (field != null)
				{
					return field;
				}
				type2 = type2.BaseType;
			}
			return null;
		}
	}
	public sealed class EnforcerLocalEndPatch : SkillPatch
	{
		private sealed class Latch
		{
			public CharacterBody Body;

			public CharacterMotor Motor;

			public EntityStateMachine BodyMachine;

			public EntityState DashState;

			public GameObject Vehicle;

			public uint VehicleNetId;

			public double StartTime;

			public double MotionSeconds;

			public double Duration;

			public double PredictedTravel;

			public double OneWay;

			public bool Fired;

			public bool AnimPlayed;

			public bool VanillaExitSeen;

			public bool ExitHandled;

			public double ExpireAt;

			public bool EjectFailureLogged;
		}

		private sealed class LocalEndHistory
		{
			public uint VehicleNetId;

			public double FiredAt;

			public double WindowSeconds;

			public bool AnimPlayed;
		}

		private const string Tag = "EnforcerLocalEnd";

		private const double WatchdogSeconds = 0.15;

		private static EnforcerLocalEndPatch instance;

		private static PropertyInfo motorProperty;

		private static FieldInfo baseVelocityField;

		private static FieldInfo seatPassengerField;

		private static FieldInfo exitPassengerField;

		private static FieldInfo exitAnimationPlayedField;

		private static MethodInfo setPassengerMethod;

		private static MethodInfo exitAuthorityMethod;

		private static PropertyInfo controllerVehicleProperty;

		private static FieldInfo vehicleIdField;

		private readonly ConditionalWeakTable<CharacterMotor, Latch> latches = new ConditionalWeakTable<CharacterMotor, Latch>();

		private readonly ConditionalWeakTable<CharacterBody, LocalEndHistory> history = new ConditionalWeakTable<CharacterBody, LocalEndHistory>();

		public EnforcerLocalEndPatch(Func<bool> isEnabled, DiagLog diag = null, LatencyEstimator latency = null)
			: base("EnforcerLocalEnd", PatchSide.Client, isEnabled, diag, latency)
		{
		}

		protected override void Install()
		{
			//IL_0347: Unknown result type (might be due to invalid IL or missing references)
			//IL_034c: Unknown result type (might be due to invalid IL or missing references)
			//IL_035e: Unknown result type (might be due to invalid IL or missing references)
			//IL_036c: Expected O, but got Unknown
			//IL_036d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0380: Unknown result type (might be due to invalid IL or missing references)
			//IL_038d: Expected O, but got Unknown
			//IL_038e: Unknown result type (might be due to invalid IL or missing references)
			//IL_03a0: Unknown result type (might be due to invalid IL or missing references)
			//IL_03ae: Expected O, but got Unknown
			//IL_03c0: Unknown result type (might be due to invalid IL or missing references)
			//IL_03ce: Expected O, but got Unknown
			motorProperty = typeof(CharacterMotor).GetProperty("Motor");
			if (motorProperty != null)
			{
				baseVelocityField = motorProperty.PropertyType.GetField("BaseVelocity");
			}
			seatPassengerField = AccessTools.Field(typeof(VehicleSeat), "passengerBodyObject");
			exitPassengerField = AccessTools.Field(typeof(VehicleShieldDashExit), "passengerBody");
			exitAnimationPlayedField = AccessTools.Field(typeof(VehicleShieldDashExit), "hasPlayedExitAnimation");
			setPassengerMethod = AccessTools.Method(typeof(VehicleSeat), "SetPassenger", new Type[1] { typeof(GameObject) }, (Type[])null);
			exitAuthorityMethod = AccessTools.Method(typeof(VehicleShieldDashExit), "OnPassengerExitAuthority", new Type[1] { typeof(GameObject) }, (Type[])null);
			controllerVehicleProperty = typeof(EnforcerVehicleDashController).GetProperty("currentVehicle", BindingFlags.Instance | BindingFlags.NonPublic);
			vehicleIdField = typeof(EnforcerVehicleDashController).GetField("currentVehicleID");
			MethodInfo methodInfo = AccessTools.Method(typeof(EntityStateMachine), "SetState", new Type[1] { typeof(EntityState) }, (Type[])null);
			MethodInfo methodInfo2 = AccessTools.Method(typeof(CharacterMotor), "BeforeCharacterUpdate", new Type[1] { typeof(float) }, (Type[])null);
			MethodInfo methodInfo3 = AccessTools.Method(typeof(VehicleShieldDashExit), "OnPassengerExitAuthority", new Type[1] { typeof(GameObject) }, (Type[])null);
			MethodInfo methodInfo4 = AccessTools.Method(typeof(VehicleSeat), "ForcePassengerState", Type.EmptyTypes, (Type[])null);
			if (motorProperty == null || baseVelocityField == null || seatPassengerField == null || exitPassengerField == null || exitAnimationPlayedField == null || setPassengerMethod == null || methodInfo3 == null || controllerVehicleProperty == null || methodInfo == null || methodInfo2 == null || methodInfo4 == null)
			{
				throw new MissingMemberException("EnforcerLocalEnd members missing: " + $"Motor={motorProperty != null}, BaseVelocity={baseVelocityField != null}, " + $"passengerBodyObject={seatPassengerField != null}, passengerBody={exitPassengerField != null}, " + $"hasPlayedExitAnimation={exitAnimationPlayedField != null}, SetPassenger={setPassengerMethod != null}, " + $"OnPassengerExitAuthority={methodInfo3 != null}, currentVehicle={controllerVehicleProperty != null}, " + $"SetState={methodInfo != null}, BeforeCharacterUpdate={methodInfo2 != null}, " + $"ForcePassengerState={methodInfo4 != null}");
			}
			Harmony val = new Harmony("com.wray.ror2latency." + base.Name);
			val.Patch((MethodBase)methodInfo, new HarmonyMethod(typeof(EnforcerLocalEndPatch), "StateSetPrefix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			val.Patch((MethodBase)methodInfo2, (HarmonyMethod)null, new HarmonyMethod(typeof(EnforcerLocalEndPatch), "MotorPostfix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			val.Patch((MethodBase)methodInfo3, new HarmonyMethod(typeof(EnforcerLocalEndPatch), "ExitAuthorityPrefix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			val.Patch((MethodBase)methodInfo4, new HarmonyMethod(typeof(EnforcerLocalEndPatch), "ForcePassengerStatePrefix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			instance = this;
			base.Diag?.Info("EnforcerLocalEnd: installed (fire at ghost motion end, local eject, idempotent vanilla-exit absorb).");
		}

		[HarmonyPriority(0)]
		private static void MotorPostfix(CharacterMotor __instance)
		{
			EnforcerLocalEndPatch self = instance;
			if (self != null && __instance != null)
			{
				self.Guard(delegate
				{
					self.TickMotor(__instance);
				});
			}
		}

		internal static bool TryControlSeat(VehicleSeat seat)
		{
			EnforcerLocalEndPatch self = instance;
			if (self == null)
			{
				return false;
			}
			bool suppress = false;
			self.Guard(delegate
			{
				suppress = self.ControlSeat(seat);
			});
			return suppress;
		}

		internal static bool OwnsGhost(CharacterBody body)
		{
			EnforcerLocalEndPatch self = instance;
			if (self == null || (Object)(object)body == (Object)null)
			{
				return false;
			}
			bool owns = false;
			self.Guard(delegate
			{
				owns = self.OwnsGhostCore(body);
			});
			return owns;
		}

		internal static bool SuppressesExitSmoothing(VehicleShieldDashExit exit)
		{
			EnforcerLocalEndPatch self = instance;
			if (self == null || exit == null)
			{
				return false;
			}
			bool suppress = false;
			self.Guard(delegate
			{
				suppress = self.SuppressExitSmoothingCore(exit);
			});
			return suppress;
		}

		internal static void NotifyExitAnimationPlayed(CharacterBody body)
		{
			EnforcerLocalEndPatch self = instance;
			if (self == null || (Object)(object)body == (Object)null)
			{
				return;
			}
			self.Guard(delegate
			{
				Latch latch = self.FindLatch(body);
				if (latch != null && latch.Fired)
				{
					latch.AnimPlayed = true;
				}
				if (self.history.TryGetValue(body, out var value) && (double)Time.time <= value.FiredAt + value.WindowSeconds)
				{
					value.AnimPlayed = true;
				}
			});
		}

		private void TickMotor(CharacterMotor motor)
		{
			if (!latches.TryGetValue(motor, out var value))
			{
				TryArm(motor);
			}
			else if (value.Fired)
			{
				if (EnforcerGhostDashPatch.TryGetLocalEndStatus(motor, out var status) && status.Found && status.BodyState != value.DashState)
				{
					Remove(value, "new dash");
					TryArm(motor);
				}
				else
				{
					CheckExpiry(value);
				}
			}
			else if (!ShouldRun())
			{
				Remove(value, "disabled");
			}
			else if (!Alive(value.Body))
			{
				Remove(value, "death");
			}
			else if (value.VanillaExitSeen)
			{
				Remove(value, "vanilla exit first");
			}
			else if (!((Object)(object)value.Body.currentVehicle != (Object)null))
			{
				if (!EnforcerGhostDashPatch.TryGetLocalEndStatus(motor, out var status2))
				{
					Remove(value, "ghost stopped before local end");
				}
				else
				{
					ValidateAndFire(value, status2, "motor");
				}
			}
		}

		private Latch TryArm(CharacterMotor motor)
		{
			if (!ShouldRun())
			{
				return null;
			}
			if (!EnforcerGhostDashPatch.TryGetLocalEndStatus(motor, out var status))
			{
				return null;
			}
			if (!status.Found || !status.LeadRecorded || status.Handoff || status.StateExited)
			{
				return null;
			}
			CharacterBody body = status.Body;
			if (!Alive(body) || !body.hasEffectiveAuthority)
			{
				return null;
			}
			Latch latch = new Latch
			{
				Body = body,
				Motor = motor,
				BodyMachine = status.BodyMachine,
				DashState = status.BodyState,
				Vehicle = FindVehicle(body),
				VehicleNetId = ReadVehicleNetId(body),
				StartTime = status.StartTime,
				MotionSeconds = status.MotionSeconds,
				Duration = status.Duration,
				PredictedTravel = status.PredictedTravel,
				OneWay = status.OneWay
			};
			latches.Remove(motor);
			latches.Add(motor, latch);
			base.Diag?.Info("Enforce