Decompiled source of Staff of the Fold v1.0.4

BepInEx/plugins/StaffOfTheFold/StaffOfTheFold.dll

Decompiled 2 days ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Text;
using System.Threading;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using FoldSupport;
using HarmonyLib;
using Jotunn.Configs;
using Jotunn.Entities;
using Jotunn.Managers;
using Jotunn.Utils;
using LiveCamera;
using Microsoft.CodeAnalysis;
using StaffOfTheFold.ReturnCrystalAssets;
using SurfaceGravity;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.Rendering;
using UnityEngine.UI;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")]
[assembly: AssemblyCompany("StaffOfTheFold")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.4.0")]
[assembly: AssemblyInformationalVersion("1.0.4+4791dac851306d4b02e63f9897a0b01f31786274")]
[assembly: AssemblyProduct("Staff of the Fold")]
[assembly: AssemblyTitle("StaffOfTheFold")]
[assembly: AssemblyVersion("1.0.4.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;
		}
	}
}
[BepInPlugin("com.kakimakidev.staffofthefold.item", "Staff of the Fold - Item", "1.0.4")]
[BepInDependency(/*Could not decode attribute arguments.*/)]
public sealed class FoldStaffItemPlugin : BaseUnityPlugin
{
	private string assetDirectory;

	private Material material;

	private Mesh[] meshes;

	private Sprite icon;

	private static readonly Func<Texture2D, byte[], bool, bool> decodeTexture = CreateTextureDecoder();

	private static Func<Texture2D, byte[], bool, bool> CreateTextureDecoder()
	{
		MethodInfo method = Type.GetType("UnityEngine.ImageConversion, UnityEngine.ImageConversionModule", throwOnError: true).GetMethod("LoadImage", new Type[3]
		{
			typeof(Texture2D),
			typeof(byte[]),
			typeof(bool)
		});
		if (method == null)
		{
			throw new MissingMethodException("Unity's byte-array PNG decoder is unavailable.");
		}
		return (Func<Texture2D, byte[], bool, bool>)Delegate.CreateDelegate(typeof(Func<Texture2D, byte[], bool, bool>), method);
	}

	private void Awake()
	{
		assetDirectory = Path.Combine(Path.GetDirectoryName(((BaseUnityPlugin)this).Info.Location), "Assets");
		try
		{
			LoadAssets();
			PrefabManager.OnVanillaPrefabsAvailable += RegisterStaff;
		}
		catch (Exception ex)
		{
			((BaseUnityPlugin)this).Logger.LogError((object)("Could not load the emerald staff assets: " + ex));
		}
	}

	private void LoadAssets()
	{
		//IL_00b3: Unknown result type (might be due to invalid IL or missing references)
		//IL_00c2: Unknown result type (might be due to invalid IL or missing references)
		StaffMeshData[] source = StaffMeshReader.Read(Path.Combine(assetDirectory, "EmeraldStaff.meshbin"));
		meshes = source.Select(BuildMesh).ToArray();
		((BaseUnityPlugin)this).Logger.LogInfo((object)("Loaded emerald staff meshes: " + string.Join(", ", meshes.Select((Mesh m) => ((Object)m).name + " (" + m.triangles.Length / 3 + " triangles)"))));
		Texture2D val = LoadTexture("emerald_staff_icon.png", linear: false, (FilterMode)1);
		icon = Sprite.Create(val, new Rect(0f, 0f, (float)((Texture)val).width, (float)((Texture)val).height), new Vector2(0.5f, 0.5f), 100f);
		((Object)icon).name = "FoldStaffItem_Icon";
	}

	private Texture2D LoadTexture(string name, bool linear, FilterMode filter = (FilterMode)0)
	{
		//IL_0005: Unknown result type (might be due to invalid IL or missing references)
		//IL_000b: Expected O, but got Unknown
		//IL_004a: Unknown result type (might be due to invalid IL or missing references)
		Texture2D val = new Texture2D(2, 2, (TextureFormat)4, true, linear);
		if (!decodeTexture(val, File.ReadAllBytes(Path.Combine(assetDirectory, name)), arg3: false))
		{
			throw new InvalidDataException("Could not decode " + name);
		}
		((Object)val).name = name;
		((Texture)val).wrapMode = (TextureWrapMode)1;
		((Texture)val).filterMode = filter;
		((Texture)val).anisoLevel = 1;
		val.Apply(true, true);
		return val;
	}

	private Material BuildMaterial(GameObject vanilla)
	{
		//IL_016d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0172: Unknown result type (might be due to invalid IL or missing references)
		//IL_017e: Expected O, but got Unknown
		//IL_019b: Unknown result type (might be due to invalid IL or missing references)
		//IL_01a1: Expected O, but got Unknown
		//IL_02bb: Unknown result type (might be due to invalid IL or missing references)
		Shader val = (from m in vanilla.GetComponentsInChildren<Renderer>(true).SelectMany((Renderer val4) => val4.sharedMaterials)
			where Object.op_Implicit((Object)(object)m) && Object.op_Implicit((Object)(object)m.shader)
			select m.shader).FirstOrDefault((Func<Shader, bool>)((Shader s) => ((Object)s).name == "Standard"));
		if (!Object.op_Implicit((Object)(object)val))
		{
			GameObject prefab = PrefabManager.Instance.GetPrefab("StaffIceShards");
			if (Object.op_Implicit((Object)(object)prefab))
			{
				val = (from m in prefab.GetComponentsInChildren<Renderer>(true).SelectMany((Renderer val4) => val4.sharedMaterials)
					where Object.op_Implicit((Object)(object)m) && Object.op_Implicit((Object)(object)m.shader)
					select m.shader).FirstOrDefault((Func<Shader, bool>)((Shader s) => ((Object)s).name == "Standard"));
			}
		}
		if (!Object.op_Implicit((Object)(object)val))
		{
			throw new InvalidOperationException("The vanilla Standard staff shader was not found.");
		}
		Material val2 = new Material(val)
		{
			name = "EmeraldStaff_Standard"
		};
		val2.SetTexture("_MainTex", (Texture)(object)LoadTexture("emerald_staff_albedo.png", linear: false, (FilterMode)0));
		Texture2D val3 = new Texture2D(2, 2, (TextureFormat)4, true, true);
		if (!decodeTexture(val3, File.ReadAllBytes(Path.Combine(assetDirectory, "emerald_staff_normal.png")), arg3: false))
		{
			throw new InvalidDataException("Could not decode normal map.");
		}
		Color32[] pixels = val3.GetPixels32();
		for (int num = 0; num < pixels.Length; num++)
		{
			byte r = pixels[num].r;
			pixels[num].r = byte.MaxValue;
			pixels[num].a = r;
		}
		val3.SetPixels32(pixels);
		((Texture)val3).filterMode = (FilterMode)0;
		((Texture)val3).wrapMode = (TextureWrapMode)1;
		val3.Apply(true, true);
		val2.SetTexture("_BumpMap", (Texture)(object)val3);
		val2.SetFloat("_BumpScale", 0f);
		val2.SetTexture("_MetallicGlossMap", (Texture)(object)LoadTexture("emerald_staff_metallic_smoothness.png", linear: true, (FilterMode)0));
		val2.SetFloat("_GlossMapScale", 1f);
		val2.SetFloat("_SmoothnessTextureChannel", 0f);
		val2.SetTexture("_EmissionMap", (Texture)(object)LoadTexture("emerald_staff_emission.png", linear: false, (FilterMode)0));
		val2.SetColor("_EmissionColor", new Color(1.1f, 1.1f, 1.1f, 1f));
		val2.SetFloat("_Mode", 0f);
		val2.SetFloat("_ZWrite", 1f);
		val2.SetFloat("_SrcBlend", 1f);
		val2.SetFloat("_DstBlend", 0f);
		val2.DisableKeyword("_NORMALMAP");
		val2.EnableKeyword("_METALLICGLOSSMAP");
		val2.EnableKeyword("_EMISSION");
		val2.globalIlluminationFlags = (MaterialGlobalIlluminationFlags)1;
		return val2;
	}

	private static Mesh BuildMesh(StaffMeshData data)
	{
		//IL_0086: Unknown result type (might be due to invalid IL or missing references)
		//IL_008b: Unknown result type (might be due to invalid IL or missing references)
		//IL_00b8: Unknown result type (might be due to invalid IL or missing references)
		//IL_00bd: Unknown result type (might be due to invalid IL or missing references)
		//IL_00dd: Unknown result type (might be due to invalid IL or missing references)
		//IL_00e2: Unknown result type (might be due to invalid IL or missing references)
		//IL_00f5: Unknown result type (might be due to invalid IL or missing references)
		//IL_00fa: 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_010d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0114: Unknown result type (might be due to invalid IL or missing references)
		//IL_011b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0127: Unknown result type (might be due to invalid IL or missing references)
		//IL_012d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0134: Expected O, but got Unknown
		int num = data.vertices.Length / 3;
		if (data.vertices.Length % 3 != 0 || data.normals.Length != data.vertices.Length || data.uv.Length != num * 2)
		{
			throw new InvalidDataException("Mesh attribute lengths differ.");
		}
		Vector3[] array = (Vector3[])(object)new Vector3[num];
		Vector3[] array2 = (Vector3[])(object)new Vector3[num];
		Vector2[] array3 = (Vector2[])(object)new Vector2[num];
		for (int i = 0; i < num; i++)
		{
			array[i] = new Vector3(data.vertices[i * 3], data.vertices[i * 3 + 1], data.vertices[i * 3 + 2]);
			array2[i] = new Vector3(data.normals[i * 3], data.normals[i * 3 + 1], data.normals[i * 3 + 2]);
			array3[i] = new Vector2(data.uv[i * 2], data.uv[i * 2 + 1]);
		}
		Mesh val = new Mesh
		{
			name = data.name,
			vertices = array,
			normals = array2,
			uv = array3,
			triangles = data.triangles
		};
		val.RecalculateBounds();
		val.RecalculateTangents();
		return val;
	}

	private void RegisterStaff()
	{
		//IL_005d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0063: Expected O, but got Unknown
		//IL_011e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0123: Unknown result type (might be due to invalid IL or missing references)
		//IL_0194: Unknown result type (might be due to invalid IL or missing references)
		//IL_0199: 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_01b7: Unknown result type (might be due to invalid IL or missing references)
		//IL_021a: Unknown result type (might be due to invalid IL or missing references)
		//IL_021f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0238: Unknown result type (might be due to invalid IL or missing references)
		//IL_023d: 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_025b: Unknown result type (might be due to invalid IL or missing references)
		try
		{
			if (ItemManager.Instance.GetItem("StaffOfTheFold") == null)
			{
				GameObject prefab = PrefabManager.Instance.GetPrefab("StaffGreenRoots");
				if (!Object.op_Implicit((Object)(object)prefab))
				{
					throw new InvalidOperationException("StaffGreenRoots is unavailable in this game version.");
				}
				if (!Object.op_Implicit((Object)(object)material))
				{
					material = BuildMaterial(prefab);
				}
				CustomItem val = new CustomItem("StaffOfTheFold", "StaffGreenRoots");
				Transform val2 = val.ItemPrefab.transform.Find("attach/default");
				if (!Object.op_Implicit((Object)(object)val2) || !Object.op_Implicit((Object)(object)((Component)val2).GetComponent<MeshFilter>()) || !Object.op_Implicit((Object)(object)((Component)val2).GetComponent<MeshRenderer>()))
				{
					throw new InvalidOperationException("The native staff visual hierarchy has changed.");
				}
				Renderer[] componentsInChildren = val.ItemPrefab.GetComponentsInChildren<Renderer>(true);
				for (int i = 0; i < componentsInChildren.Length; i++)
				{
					componentsInChildren[i].enabled = false;
				}
				Light[] componentsInChildren2 = val.ItemPrefab.GetComponentsInChildren<Light>(true);
				for (int i = 0; i < componentsInChildren2.Length; i++)
				{
					((Behaviour)componentsInChildren2[i]).enabled = false;
				}
				ParticleSystem[] componentsInChildren3 = val.ItemPrefab.GetComponentsInChildren<ParticleSystem>(true);
				foreach (ParticleSystem obj in componentsInChildren3)
				{
					obj.Stop(true, (ParticleSystemStopBehavior)0);
					EmissionModule emission = obj.emission;
					((EmissionModule)(ref emission)).enabled = false;
				}
				MeshRenderer component = ((Component)val2).GetComponent<MeshRenderer>();
				((Component)val2).GetComponent<MeshFilter>().sharedMesh = meshes[0];
				((Renderer)component).sharedMaterials = (Material[])(object)new Material[1] { material };
				((Renderer)component).enabled = true;
				Renderer[] array = (Renderer[])(object)new Renderer[3]
				{
					(Renderer)component,
					default(Renderer),
					default(Renderer)
				};
				for (int j = 1; j < 3; j++)
				{
					GameObject val3 = new GameObject("EmeraldStaff_LOD" + j)
					{
						layer = ((Component)val2).gameObject.layer
					};
					val3.transform.SetParent(val2, false);
					val3.AddComponent<MeshFilter>().sharedMesh = meshes[j];
					MeshRenderer val4 = val3.AddComponent<MeshRenderer>();
					((Renderer)val4).sharedMaterial = material;
					array[j] = (Renderer)(object)val4;
				}
				LODGroup val5 = ((Component)val2).gameObject.AddComponent<LODGroup>();
				val5.SetLODs((LOD[])(object)new LOD[3]
				{
					new LOD(0.32f, (Renderer[])(object)new Renderer[1] { array[0] }),
					new LOD(0.12f, (Renderer[])(object)new Renderer[1] { array[1] }),
					new LOD(0.015f, (Renderer[])(object)new Renderer[1] { array[2] })
				});
				val5.RecalculateBounds();
				SharedData shared = val.ItemDrop.m_itemData.m_shared;
				shared.m_name = "Staff of the Fold";
				shared.m_description = "A great emerald set in weathered rootwood and bronze. Opens a hidden home where gravity follows its walls.";
				shared.m_icons = (Sprite[])(object)new Sprite[1] { icon };
				shared.m_maxQuality = 1;
				if (!ItemManager.Instance.AddItem(val))
				{
					throw new InvalidOperationException("Item registration was rejected.");
				}
				((BaseUnityPlugin)this).Logger.LogInfo((object)"Registered StaffOfTheFold. Spawn with: spawn StaffOfTheFold 1");
			}
		}
		catch (Exception ex)
		{
			((BaseUnityPlugin)this).Logger.LogError((object)("Could not register the emerald staff: " + ex));
		}
		finally
		{
			PrefabManager.OnVanillaPrefabsAvailable -= RegisterStaff;
		}
	}

	private void OnDestroy()
	{
		PrefabManager.OnVanillaPrefabsAvailable -= RegisterStaff;
	}
}
public sealed class StaffMeshData
{
	public string name;

	public float[] vertices;

	public float[] normals;

	public float[] uv;

	public int[] triangles;
}
public static class StaffMeshReader
{
	public static StaffMeshData[] Read(string path)
	{
		using FileStream stream = File.OpenRead(path);
		return Read(stream);
	}

	public static StaffMeshData[] Read(Stream stream)
	{
		using BinaryReader binaryReader = new BinaryReader(stream, Encoding.UTF8, leaveOpen: true);
		if (binaryReader.ReadUInt32() != 1414745413)
		{
			throw new InvalidDataException("Invalid EMST mesh signature.");
		}
		int num = binaryReader.ReadInt32();
		if (num != 1)
		{
			throw new InvalidDataException("Unsupported EMST mesh version: " + num);
		}
		int num2 = binaryReader.ReadInt32();
		if (num2 != 3)
		{
			throw new InvalidDataException("Expected three LODs; found " + num2);
		}
		StaffMeshData[] array = new StaffMeshData[num2];
		for (int i = 0; i < num2; i++)
		{
			int num3 = binaryReader.ReadInt32();
			if (num3 < 1 || num3 > 128)
			{
				throw new InvalidDataException("Invalid mesh name length.");
			}
			byte[] array2 = binaryReader.ReadBytes(num3);
			if (array2.Length != num3)
			{
				throw new EndOfStreamException("Truncated mesh name.");
			}
			int num4 = binaryReader.ReadInt32();
			int num5 = binaryReader.ReadInt32();
			if (num4 < 3 || num4 > 65535 || num5 < 3 || num5 > 600000 || num5 % 3 != 0)
			{
				throw new InvalidDataException("Invalid mesh vertex or index count.");
			}
			StaffMeshData staffMeshData = new StaffMeshData
			{
				name = Encoding.UTF8.GetString(array2),
				vertices = ReadFloats(binaryReader, num4 * 3),
				normals = ReadFloats(binaryReader, num4 * 3),
				uv = ReadFloats(binaryReader, num4 * 2),
				triangles = new int[num5]
			};
			for (int j = 0; j < num5; j++)
			{
				int num6 = binaryReader.ReadInt32();
				if (num6 < 0 || num6 >= num4)
				{
					throw new InvalidDataException("Mesh index is out of bounds.");
				}
				staffMeshData.triangles[j] = num6;
			}
			array[i] = staffMeshData;
		}
		if (stream.Position != stream.Length)
		{
			throw new InvalidDataException("Unexpected trailing mesh data.");
		}
		return array;
	}

	private static float[] ReadFloats(BinaryReader reader, int count)
	{
		float[] array = new float[count];
		for (int i = 0; i < count; i++)
		{
			float num = reader.ReadSingle();
			if (float.IsNaN(num) || float.IsInfinity(num))
			{
				throw new InvalidDataException("Non-finite mesh attribute.");
			}
			array[i] = num;
		}
		return array;
	}
}
namespace FoldSupport
{
	internal static class ModulePatches
	{
		internal static void Apply(Harmony harmony, Type module)
		{
			string text = module.Namespace;
			if (string.IsNullOrEmpty(text))
			{
				throw new ArgumentException("A patch module must have a namespace.", "module");
			}
			try
			{
				Type[] types = module.Assembly.GetTypes();
				foreach (Type type in types)
				{
					if (type.Namespace == text || (type.Namespace != null && type.Namespace.StartsWith(text + ".", StringComparison.Ordinal)))
					{
						harmony.CreateClassProcessor(type).Patch();
					}
				}
			}
			catch
			{
				harmony.UnpatchSelf();
				throw;
			}
		}
	}
}
namespace SurfaceGravity
{
	[HarmonyPatch]
	internal static class GizmoCopyCompatibility
	{
		private static readonly string[] Rotators = new string[4] { "ComfyGizmo.DefaultRotator", "ComfyGizmo.InternalRotator", "ComfyGizmo.RoofRotator", "ComfyGizmo.LocalFrameRotator" };

		private static int compatibilityWarning;

		private static List<MethodBase> FindTargets()
		{
			List<MethodBase> list = new List<MethodBase>();
			bool flag = false;
			string[] rotators = Rotators;
			for (int i = 0; i < rotators.Length; i++)
			{
				Type type = AccessTools.TypeByName(rotators[i]);
				if (type == null)
				{
					continue;
				}
				flag = true;
				MethodInfo[] methods = type.GetMethods(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
				foreach (MethodInfo methodInfo in methods)
				{
					if (IsCopyMethod(methodInfo))
					{
						list.Add(methodInfo);
						break;
					}
				}
			}
			if (flag && list.Count != Rotators.Length)
			{
				Warn("Gizmo rotation-copy methods changed: found " + list.Count + " of " + Rotators.Length + ". Unavailable rotation modes keep their existing copy behavior.");
			}
			return list;
		}

		private static bool IsCopyMethod(MethodBase method)
		{
			if (!(method is MethodInfo methodInfo) || methodInfo.Name != "MatchPieceRotation" || methodInfo.IsStatic || methodInfo.IsAbstract || methodInfo.ContainsGenericParameters || methodInfo.ReturnType != typeof(void))
			{
				return false;
			}
			ParameterInfo[] parameters = methodInfo.GetParameters();
			if (parameters.Length == 1)
			{
				return parameters[0].ParameterType == typeof(Piece);
			}
			return false;
		}

		[HarmonyPrepare]
		private static bool CanPatch()
		{
			return FindTargets().Count != 0;
		}

		[HarmonyTargetMethods]
		private static IEnumerable<MethodBase> Targets()
		{
			return FindTargets();
		}

		internal static Vector3 RelativeEulerAngles(Transform target)
		{
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			//IL_001c: Unknown result type (might be due to invalid IL or missing references)
			//IL_001d: 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_0028: Unknown result type (might be due to invalid IL or missing references)
			//IL_002d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0030: Unknown result type (might be due to invalid IL or missing references)
			if (!SurfaceBuilding.PlacementSupported || !SurfaceBuilding.TryFrame(Player.m_localPlayer, out var frame))
			{
				return target.eulerAngles;
			}
			Quaternion val = Quaternion.Inverse(frame) * target.rotation;
			return ((Quaternion)(ref val)).eulerAngles;
		}

		internal static Quaternion RelativeLocalRotation(Transform target)
		{
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			//IL_001c: Unknown result type (might be due to invalid IL or missing references)
			//IL_001d: 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_0028: Unknown result type (might be due to invalid IL or missing references)
			if (!SurfaceBuilding.PlacementSupported || !SurfaceBuilding.TryFrame(Player.m_localPlayer, out var frame))
			{
				return target.localRotation;
			}
			return Quaternion.Inverse(frame) * target.rotation;
		}

		[HarmonyTranspiler]
		private static IEnumerable<CodeInstruction> RelativeCopy(IEnumerable<CodeInstruction> instructions, MethodBase __originalMethod)
		{
			//IL_021e: Unknown result type (might be due to invalid IL or missing references)
			//IL_022f: Expected O, but got Unknown
			List<CodeInstruction> list = new List<CodeInstruction>(instructions);
			string text = __originalMethod?.DeclaringType?.FullName;
			int num = ((text == Rotators[0] || text == Rotators[1]) ? 1 : ((text == Rotators[2]) ? 2 : 0));
			int num2 = ((text == Rotators[3]) ? 2 : 0);
			MethodInfo methodInfo = AccessTools.PropertyGetter(typeof(Transform), "eulerAngles");
			MethodInfo methodInfo2 = AccessTools.PropertyGetter(typeof(Transform), "localRotation");
			MethodInfo methodInfo3 = AccessTools.PropertyGetter(typeof(Transform), "rotation");
			int num3 = 0;
			int num4 = 0;
			int num5 = 0;
			foreach (CodeInstruction item in list)
			{
				if (CodeInstructionExtensions.Calls(item, methodInfo))
				{
					num3++;
				}
				if (CodeInstructionExtensions.Calls(item, methodInfo2))
				{
					num4++;
				}
				if (CodeInstructionExtensions.Calls(item, methodInfo3))
				{
					num5++;
				}
			}
			if (!IsCopyMethod(__originalMethod) || num + num2 == 0 || num3 != num || num4 != num2 || num5 != 0)
			{
				Warn("Surface-relative Gizmo copying skipped for " + (text ?? "unknown rotator") + ": found " + num3 + " Euler, " + num4 + " local and " + num5 + " world rotation reads (expected " + num + ", " + num2 + ", 0). Existing copy behavior is retained.");
				return list;
			}
			List<CodeInstruction> list2 = new List<CodeInstruction>(list.Count);
			MethodInfo methodInfo4 = AccessTools.Method(typeof(GizmoCopyCompatibility), (num2 != 0) ? "RelativeLocalRotation" : "RelativeEulerAngles", (Type[])null, (Type[])null);
			MethodInfo methodInfo5 = ((num2 != 0) ? methodInfo2 : methodInfo);
			foreach (CodeInstruction item2 in list)
			{
				list2.Add(CodeInstructionExtensions.Calls(item2, methodInfo5) ? CodeInstructionExtensions.WithBlocks(CodeInstructionExtensions.WithLabels(new CodeInstruction(OpCodes.Call, (object)methodInfo4), (IEnumerable<Label>)item2.labels), (IEnumerable<ExceptionBlock>)item2.blocks) : item2);
			}
			return list2;
		}

		private static void Warn(string message)
		{
			if (Interlocked.Exchange(ref compatibilityWarning, 1) == 0)
			{
				Plugin.LogBuildingCompatibilityWarning(message);
			}
		}
	}
	[BepInPlugin("com.kakimakidev.staffofthefold.gravity", "Surface Gravity", "0.2.14")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	public sealed class Plugin : BaseUnityPlugin
	{
		private struct EyePose
		{
			public Transform Eye;

			public Vector3 Position;
		}

		private struct JumpPose
		{
			public Character Character;

			public Rigidbody Body;

			public Vector3 Velocity;

			public Vector3 Normal;
		}

		internal const string PluginGuid = "com.kakimakidev.staffofthefold.gravity";

		internal const string DisplayName = "Surface Gravity";

		internal const string Version = "0.2.14";

		private static Plugin instance;

		private ConfigEntry<KeyboardShortcut> toggle;

		private Harmony harmony;

		private Player player;

		private Rigidbody body;

		private Transform visual;

		private Vector3 visualPosition;

		private Quaternion visualRotation;

		private bool gravity;

		private bool grounded;

		private float jumpCooldown;

		private float startHeight;

		private Transform flippedCamera;

		private Transform flippedSkyCamera;

		private Quaternion cameraRotation;

		private Quaternion skyCameraRotation;

		private bool adaptingJump;

		private bool jumpLaunched;

		private static readonly FieldRef<Character, bool> Running = AccessTools.FieldRefAccess<Character, bool>("m_running");

		private static readonly FieldRef<Character, bool> WalkMode = AccessTools.FieldRefAccess<Character, bool>("m_walk");

		private static readonly FieldRef<Character, Vector3> GroundNormal = AccessTools.FieldRefAccess<Character, Vector3>("m_lastGroundNormal");

		private static readonly Func<Player, Vector3, float, bool> CheckRun = AccessTools.MethodDelegate<Func<Player, Vector3, float, bool>>(AccessTools.DeclaredMethod(typeof(Player), "CheckRun", (Type[])null, (Type[])null), (object)null, true);

		private static readonly Func<Character, float> RunFactor = AccessTools.MethodDelegate<Func<Character, float>>(AccessTools.Method(typeof(Character), "GetRunSpeedFactor", (Type[])null, (Type[])null), (object)null, true);

		private static readonly FieldRef<Character, Vector3> MoveDir = AccessTools.FieldRefAccess<Character, Vector3>("m_moveDir");

		private static readonly FieldRef<Character, GameObject> Visual = AccessTools.FieldRefAccess<Character, GameObject>("m_visual");

		private static readonly FieldRef<Character, float> MaxAltitude = AccessTools.FieldRefAccess<Character, float>("m_maxAirAltitude");

		private static readonly FieldRef<Character, float> FallTimer = AccessTools.FieldRefAccess<Character, float>("m_fallTimer");

		internal static void LogBuildingCompatibilityWarning(string message)
		{
			Plugin plugin = instance;
			if (plugin != null)
			{
				((BaseUnityPlugin)plugin).Logger.LogWarning((object)message);
			}
		}

		private void Awake()
		{
			//IL_0021: Unknown result type (might be due to invalid IL or missing references)
			//IL_003b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0045: Expected O, but got Unknown
			//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)
			instance = this;
			toggle = ((BaseUnityPlugin)this).Config.Bind<KeyboardShortcut>("Controls", "Toggle", new KeyboardShortcut((KeyCode)289, Array.Empty<KeyCode>()), "Toggle the local player's manual gravity flip outside automatic surface-gravity areas.");
			harmony = new Harmony("com.kakimakidev.staffofthefold.gravity");
			ModulePatches.Apply(harmony, typeof(Plugin));
			((BaseUnityPlugin)this).Logger.LogInfo((object)("Surface Gravity ready. " + ((object)toggle.Value/*cast due to .constrained prefix*/).ToString() + " toggles the manual flip outside automatic surface-gravity areas."));
		}

		private unsafe void Update()
		{
			//IL_0090: Unknown result type (might be due to invalid IL or missing references)
			//IL_0095: Unknown result type (might be due to invalid IL or missing references)
			//IL_0175: Unknown result type (might be due to invalid IL or missing references)
			//IL_017a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0186: Unknown result type (might be due to invalid IL or missing references)
			//IL_018b: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ad: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e0: Unknown result type (might be due to invalid IL or missing references)
			//IL_01fc: Unknown result type (might be due to invalid IL or missing references)
			//IL_0201: Unknown result type (might be due to invalid IL or missing references)
			if (Object.op_Implicit((Object)(object)player) && SurfaceWalk.WantsControl(Player.m_localPlayer))
			{
				Restore();
			}
			SurfaceWalk.Tick();
			if (SurfaceWalk.IsActive((Character)(object)Player.m_localPlayer))
			{
				return;
			}
			if (Object.op_Implicit((Object)(object)player) && ((Object)(object)player != (Object)(object)Player.m_localPlayer || ((Character)player).IsDead() || ((Character)player).IsTeleporting() || ((Character)player).IsAttached() || ((Character)player).IsSwimming()))
			{
				Restore();
			}
			KeyboardShortcut value = toggle.Value;
			if (!((KeyboardShortcut)(ref value)).IsDown() || (Object)(object)ZNetScene.instance == (Object)null || (Object.op_Implicit((Object)(object)Chat.instance) && Chat.instance.HasFocus()) || Console.IsVisible() || TextInput.IsVisible() || Menu.IsVisible() || InventoryGui.IsVisible())
			{
				return;
			}
			if (Object.op_Implicit((Object)(object)player))
			{
				Restore();
				return;
			}
			Player localPlayer = Player.m_localPlayer;
			if (Object.op_Implicit((Object)(object)localPlayer) && !((Character)localPlayer).IsDead() && !((Character)localPlayer).IsTeleporting() && !((Character)localPlayer).IsAttached() && !((Character)localPlayer).IsSwimming() && !((Character)localPlayer).InIntro())
			{
				body = ((Component)localPlayer).GetComponent<Rigidbody>();
				GameObject val = Visual.Invoke((Character)(object)localPlayer);
				if (Object.op_Implicit((Object)(object)body) && Object.op_Implicit((Object)(object)val))
				{
					player = localPlayer;
					visual = val.transform;
					visualPosition = visual.localPosition;
					visualRotation = visual.localRotation;
					gravity = body.useGravity;
					startHeight = ((Component)player).transform.position.y;
					grounded = false;
					jumpCooldown = 0f;
					body.useGravity = false;
					body.linearVelocity = Vector3.zero;
					Player obj = player;
					value = toggle.Value;
					((Character)obj).Message((MessageType)2, "Gravity flip ON (" + ((object)(*(KeyboardShortcut*)(&value))/*cast due to .constrained prefix*/).ToString() + " to restore)", 0, (Sprite)null, false);
					((BaseUnityPlugin)this).Logger.LogInfo((object)"Local-player manual gravity flip enabled.");
				}
			}
		}

		private void LateUpdate()
		{
			UpdateVisual();
		}

		private void UpdateVisual()
		{
			//IL_0022: Unknown result type (might be due to invalid IL or missing references)
			//IL_0027: 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_0052: Unknown result type (might be due to invalid IL or missing references)
			//IL_005c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0061: Unknown result type (might be due to invalid IL or missing references)
			//IL_0066: Unknown result type (might be due to invalid IL or missing references)
			if (Object.op_Implicit((Object)(object)player) && Object.op_Implicit((Object)(object)visual))
			{
				visual.localPosition = visualPosition + Vector3.up * ((Character)player).GetCollider().height;
				visual.localRotation = visualRotation * Quaternion.AngleAxis(180f, Vector3.forward);
			}
		}

		private void Restore()
		{
			//IL_001a: 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_0059: Unknown result type (might be due to invalid IL or missing references)
			//IL_008b: Unknown result type (might be due to invalid IL or missing references)
			RestoreCamera();
			if (Object.op_Implicit((Object)(object)visual))
			{
				visual.localPosition = visualPosition;
				visual.localRotation = visualRotation;
			}
			if (Object.op_Implicit((Object)(object)body))
			{
				body.useGravity = gravity;
				body.linearVelocity = Vector3.zero;
			}
			if (Object.op_Implicit((Object)(object)player))
			{
				MaxAltitude.Invoke((Character)(object)player) = ((Component)player).transform.position.y;
				FallTimer.Invoke((Character)(object)player) = 0f;
				Running.Invoke((Character)(object)player) = false;
				((Character)player).Message((MessageType)2, "Gravity flip OFF", 0, (Sprite)null, false);
			}
			player = null;
			body = null;
			visual = null;
			grounded = false;
			((BaseUnityPlugin)this).Logger.LogInfo((object)"Normal local-player movement restored.");
		}

		private void OnDisable()
		{
			SurfaceWalk.Shutdown();
			if (Object.op_Implicit((Object)(object)player))
			{
				Restore();
			}
		}

		private void OnDestroy()
		{
			SurfaceWalk.Shutdown();
			if (Object.op_Implicit((Object)(object)player))
			{
				Restore();
			}
			Harmony obj = harmony;
			if (obj != null)
			{
				obj.UnpatchSelf();
			}
			instance = null;
		}

		internal static bool ManualFlipActive(Character character)
		{
			if (Object.op_Implicit((Object)(object)instance) && Object.op_Implicit((Object)(object)instance.player) && (Object)(object)character == (Object)(object)instance.player && (Object)(object)character == (Object)(object)Player.m_localPlayer)
			{
				return !SurfaceWalk.IsActive(character);
			}
			return false;
		}

		private void RestoreCamera()
		{
			//IL_0014: 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)
			if (Object.op_Implicit((Object)(object)flippedCamera))
			{
				flippedCamera.rotation = cameraRotation;
			}
			if (Object.op_Implicit((Object)(object)flippedSkyCamera))
			{
				flippedSkyCamera.rotation = skyCameraRotation;
			}
			flippedCamera = null;
			flippedSkyCamera = null;
		}

		[HarmonyPatch(typeof(GameCamera), "UpdateCamera")]
		[HarmonyPrefix]
		private static void BeforeCamera()
		{
			if (Object.op_Implicit((Object)(object)instance))
			{
				instance.RestoreCamera();
				instance.UpdateVisual();
			}
		}

		[HarmonyPatch(typeof(GameCamera), "GetCameraBaseOffset")]
		[HarmonyPostfix]
		private static void CameraBase(Player __0, ref Vector3 __result)
		{
			//IL_0012: 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_0022: Unknown result type (might be due to invalid IL or missing references)
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			if (ManualFlipActive((Character)(object)__0) && !GameCamera.InFreeFly())
			{
				__result = ((Character)__0).GetHeadPoint() - ((Component)__0).transform.position;
			}
		}

		[HarmonyPatch(typeof(GameCamera), "GetCameraOffset")]
		[HarmonyPostfix]
		private static void CameraOffset(Player __0, ref Vector3 __result)
		{
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			//IL_001b: Unknown result type (might be due to invalid IL or missing references)
			//IL_001c: Unknown result type (might be due to invalid IL or missing references)
			//IL_001d: 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_0028: Unknown result type (might be due to invalid IL or missing references)
			//IL_002d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0030: Unknown result type (might be due to invalid IL or missing references)
			//IL_003e: Unknown result type (might be due to invalid IL or missing references)
			//IL_004b: Unknown result type (might be due to invalid IL or missing references)
			//IL_004c: Unknown result type (might be due to invalid IL or missing references)
			//IL_004d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0052: Unknown result type (might be due to invalid IL or missing references)
			if (ManualFlipActive((Character)(object)__0) && !GameCamera.InFreeFly())
			{
				Quaternion rotation = ((Character)__0).m_eye.rotation;
				Vector3 val = Quaternion.Inverse(rotation) * __result;
				val.x = 0f - val.x;
				val.y = 0f - val.y;
				__result = rotation * val;
			}
		}

		[HarmonyPatch(typeof(GameCamera), "GetCameraPosition")]
		[HarmonyPrefix]
		private static void CameraPositionBefore(out EyePose __state)
		{
			//IL_0030: Unknown result type (might be due to invalid IL or missing references)
			//IL_0035: 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)
			__state = default(EyePose);
			Player localPlayer = Player.m_localPlayer;
			if (ManualFlipActive((Character)(object)localPlayer) && !GameCamera.InFreeFly())
			{
				__state.Eye = ((Character)localPlayer).m_eye;
				__state.Position = ((Character)localPlayer).m_eye.position;
				((Character)localPlayer).m_eye.position = ((Character)localPlayer).GetHeadPoint();
			}
		}

		[HarmonyPatch(typeof(GameCamera), "GetCameraPosition")]
		[HarmonyFinalizer]
		private static void CameraPositionAfter(EyePose __state)
		{
			//IL_0014: Unknown result type (might be due to invalid IL or missing references)
			if (Object.op_Implicit((Object)(object)__state.Eye))
			{
				__state.Eye.position = __state.Position;
			}
		}

		[HarmonyPatch(typeof(Player), "SetControls")]
		[HarmonyPrefix]
		private static void Controls(Player __instance, ref Vector3 movedir)
		{
			if (ManualFlipActive((Character)(object)__instance))
			{
				movedir.x = 0f - movedir.x;
			}
		}

		[HarmonyPatch(typeof(Player), "SetMouseLook")]
		[HarmonyPrefix]
		private static void MouseLook(Player __instance, ref Vector2 __0)
		{
			//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_0014: Unknown result type (might be due to invalid IL or missing references)
			if (ManualFlipActive((Character)(object)__instance))
			{
				__0 = -__0;
			}
		}

		[HarmonyPatch(typeof(GameCamera), "UpdateCamera")]
		[HarmonyPostfix]
		[HarmonyPriority(0)]
		private static void AfterCamera(Camera ___m_camera, Camera ___m_skyCamera)
		{
			//IL_0033: Unknown result type (might be due to invalid IL or missing references)
			//IL_0038: Unknown result type (might be due to invalid IL or missing references)
			//IL_003d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0051: Unknown result type (might be due to invalid IL or missing references)
			//IL_0056: Unknown result type (might be due to invalid IL or missing references)
			//IL_0062: Unknown result type (might be due to invalid IL or missing references)
			//IL_0067: Unknown result type (might be due to invalid IL or missing references)
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a0: 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_00b1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b6: 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)
			if (Object.op_Implicit((Object)(object)instance) && ManualFlipActive((Character)(object)Player.m_localPlayer) && !GameCamera.InFreeFly() && Object.op_Implicit((Object)(object)___m_camera))
			{
				Plugin plugin = instance;
				Quaternion val = Quaternion.AngleAxis(180f, Vector3.forward);
				plugin.flippedCamera = ((Component)___m_camera).transform;
				plugin.cameraRotation = plugin.flippedCamera.rotation;
				plugin.flippedCamera.rotation = plugin.cameraRotation * val;
				if (Object.op_Implicit((Object)(object)___m_skyCamera) && (Object)(object)((Component)___m_skyCamera).transform != (Object)(object)plugin.flippedCamera)
				{
					plugin.flippedSkyCamera = ((Component)___m_skyCamera).transform;
					plugin.skyCameraRotation = plugin.flippedSkyCamera.rotation;
					plugin.flippedSkyCamera.rotation = plugin.skyCameraRotation * val;
				}
			}
		}

		[HarmonyPatch(typeof(Character), "UpdateMotion")]
		[HarmonyPrefix]
		private static bool Motion(Character __instance, float dt)
		{
			//IL_003e: Unknown result type (might be due to invalid IL or missing references)
			//IL_007c: 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_0084: Unknown result type (might be due to invalid IL or missing references)
			//IL_0090: 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_00b6: 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_011c: 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_015a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0164: Unknown result type (might be due to invalid IL or missing references)
			//IL_0169: Unknown result type (might be due to invalid IL or missing references)
			//IL_0182: 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_01f0: Unknown result type (might be due to invalid IL or missing references)
			//IL_0210: Unknown result type (might be due to invalid IL or missing references)
			//IL_0214: Unknown result type (might be due to invalid IL or missing references)
			//IL_0219: Unknown result type (might be due to invalid IL or missing references)
			//IL_0221: Unknown result type (might be due to invalid IL or missing references)
			//IL_0226: Unknown result type (might be due to invalid IL or missing references)
			//IL_0228: Unknown result type (might be due to invalid IL or missing references)
			//IL_0234: Unknown result type (might be due to invalid IL or missing references)
			//IL_023b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0240: Unknown result type (might be due to invalid IL or missing references)
			//IL_0249: Unknown result type (might be due to invalid IL or missing references)
			//IL_024e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0252: 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_0268: Unknown result type (might be due to invalid IL or missing references)
			//IL_028b: Unknown result type (might be due to invalid IL or missing references)
			//IL_02a9: Unknown result type (might be due to invalid IL or missing references)
			//IL_02ca: Unknown result type (might be due to invalid IL or missing references)
			//IL_02cf: Unknown result type (might be due to invalid IL or missing references)
			//IL_02d1: Unknown result type (might be due to invalid IL or missing references)
			//IL_02dd: Unknown result type (might be due to invalid IL or missing references)
			//IL_035d: Unknown result type (might be due to invalid IL or missing references)
			if (!ManualFlipActive(__instance))
			{
				return true;
			}
			Plugin plugin = instance;
			if (__instance.IsDead() || __instance.IsTeleporting() || __instance.IsAttached() || __instance.IsSwimming())
			{
				plugin.Restore();
				return true;
			}
			if (((Component)__instance).transform.position.y > plugin.startHeight + 30f)
			{
				plugin.Restore();
				return true;
			}
			plugin.jumpCooldown = Mathf.Max(0f, plugin.jumpCooldown - dt);
			Bounds bounds = ((Collider)__instance.GetCollider()).bounds;
			float num = Mathf.Min(((Bounds)(ref bounds)).extents.x, ((Bounds)(ref bounds)).extents.z) * 0.9f;
			Vector3 val = default(Vector3);
			((Vector3)(ref val))..ctor(((Bounds)(ref bounds)).center.x, ((Bounds)(ref bounds)).max.y - num - 0.08f, ((Bounds)(ref bounds)).center.z);
			int mask = LayerMask.GetMask(new string[5] { "Default", "static_solid", "Default_small", "piece", "terrain" });
			RaycastHit val2 = default(RaycastHit);
			plugin.grounded = plugin.jumpCooldown <= 0f && Physics.SphereCast(val, num, Vector3.up, ref val2, 0.2f, mask, (QueryTriggerInteraction)1) && ((RaycastHit)(ref val2)).normal.y < -0.5f;
			Vector3 val3 = Vector3.ClampMagnitude(MoveDir.Invoke(__instance), 1f);
			val3.y = 0f;
			bool flag = CheckRun(plugin.player, val3, dt);
			Running.Invoke(__instance) = flag;
			float num2 = (flag ? (__instance.m_runSpeed * RunFactor(__instance)) : (WalkMode.Invoke(__instance) ? __instance.m_walkSpeed : ((__instance.IsCrouching() || __instance.IsEncumbered()) ? __instance.m_crouchSpeed : __instance.m_speed)));
			__instance.GetSEMan().ApplyStatusEffectSpeedMods(ref num2, val3);
			if (flag && ((Vector3)(ref val3)).sqrMagnitude > 0f)
			{
				((Vector3)(ref val3)).Normalize();
			}
			Vector3 val4 = val3 * num2;
			Vector3 linearVelocity = plugin.body.linearVelocity;
			Vector3 val5 = Vector3.MoveTowards(new Vector3(linearVelocity.x, 0f, linearVelocity.z), val4, 25f * dt);
			((Vector3)(ref linearVelocity))..ctor(val5.x, plugin.grounded ? 0f : Mathf.Min(linearVelocity.y + Mathf.Abs(Physics.gravity.y) * dt, 12f), val5.z);
			plugin.body.useGravity = false;
			plugin.body.linearVelocity = linearVelocity;
			if (((Vector3)(ref val3)).sqrMagnitude > 0.01f)
			{
				((Component)__instance).transform.rotation = Quaternion.RotateTowards(((Component)__instance).transform.rotation, Quaternion.LookRotation(val3), 540f * dt);
			}
			Animator componentInChildren = ((Component)__instance).GetComponentInChildren<Animator>();
			if (Object.op_Implicit((Object)(object)componentInChildren))
			{
				componentInChildren.SetFloat("forward_speed", ((Vector3)(ref val5)).magnitude);
				componentInChildren.SetFloat("sideway_speed", 0f);
				componentInChildren.SetFloat("turn_speed", 0f);
				componentInChildren.SetBool("onGround", plugin.grounded);
				componentInChildren.SetBool("inWater", false);
			}
			MaxAltitude.Invoke(__instance) = ((Component)__instance).transform.position.y;
			FallTimer.Invoke(__instance) = 0f;
			return false;
		}

		[HarmonyPatch(typeof(Character), "UpdateGroundContact")]
		[HarmonyPrefix]
		private static bool GroundContact(Character __instance)
		{
			return !ManualFlipActive(__instance);
		}

		[HarmonyPatch(typeof(Character), "UpdateGroundTilt")]
		[HarmonyPrefix]
		private static bool GroundTilt(Character __instance)
		{
			return !ManualFlipActive(__instance);
		}

		[HarmonyPatch(typeof(Character), "IsOnGround")]
		[HarmonyPrefix]
		private static bool OnGround(Character __instance, ref bool __result)
		{
			if (!ManualFlipActive(__instance))
			{
				return true;
			}
			__result = instance.grounded;
			return false;
		}

		[HarmonyPatch(typeof(Character), "Jump")]
		[HarmonyPrefix]
		private static void JumpBefore(Character __instance, out JumpPose __state)
		{
			//IL_0030: Unknown result type (might be due to invalid IL or missing references)
			//IL_0035: 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_0051: Unknown result type (might be due to invalid IL or missing references)
			//IL_0056: Unknown result type (might be due to invalid IL or missing references)
			//IL_0059: Unknown result type (might be due to invalid IL or missing references)
			//IL_006b: Unknown result type (might be due to invalid IL or missing references)
			//IL_007c: 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)
			__state = default(JumpPose);
			if (ManualFlipActive(__instance))
			{
				Plugin plugin = instance;
				__state.Character = __instance;
				__state.Body = plugin.body;
				__state.Velocity = plugin.body.linearVelocity;
				__state.Normal = GroundNormal.Invoke(__instance);
				Vector3 velocity = __state.Velocity;
				velocity.y = 0f - velocity.y;
				plugin.body.linearVelocity = velocity;
				GroundNormal.Invoke(__instance) = Vector3.up;
				plugin.adaptingJump = true;
				plugin.jumpLaunched = false;
			}
		}

		[HarmonyPatch(typeof(Character), "ForceJump")]
		[HarmonyPrefix]
		private static void JumpDirection(Character __instance, ref Vector3 __0)
		{
			if (ManualFlipActive(__instance) && instance.adaptingJump)
			{
				__0.y = 0f - __0.y;
				instance.jumpLaunched = true;
				instance.grounded = false;
				instance.jumpCooldown = 0.3f;
			}
		}

		[HarmonyPatch(typeof(Character), "Jump")]
		[HarmonyFinalizer]
		private static void JumpAfter(JumpPose __state)
		{
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_0055: Unknown result type (might be due to invalid IL or missing references)
			if (!Object.op_Implicit((Object)(object)__state.Character))
			{
				return;
			}
			GroundNormal.Invoke(__state.Character) = __state.Normal;
			if (Object.op_Implicit((Object)(object)instance))
			{
				if (!instance.jumpLaunched && Object.op_Implicit((Object)(object)__state.Body))
				{
					__state.Body.linearVelocity = __state.Velocity;
				}
				instance.adaptingJump = false;
			}
		}
	}
	[HarmonyPatch(typeof(Player), "UpdatePlacementGhost")]
	[HarmonyAfter(new string[] { "bruce.valheim.comfymods.gizmo", "com.custom.shipbuildmod" })]
	internal static class SurfaceBuilding
	{
		private static readonly Quaternion ManualFrame = Quaternion.AngleAxis(180f, Vector3.forward);

		private static int compatibilityWarning;

		internal static bool PlacementSupported { get; private set; }

		internal static bool TryFrame(Player player, out Quaternion frame)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_0062: Unknown result type (might be due to invalid IL or missing references)
			//IL_0067: Unknown result type (might be due to invalid IL or missing references)
			//IL_0077: Unknown result type (might be due to invalid IL or missing references)
			//IL_007c: Unknown result type (might be due to invalid IL or missing references)
			frame = Quaternion.identity;
			if (!Object.op_Implicit((Object)(object)player) || (Object)(object)player != (Object)(object)Player.m_localPlayer || ((Character)player).IsDead() || ((Character)player).IsTeleporting() || ((Character)player).IsAttached() || ((Character)player).IsSwimming() || ((Character)player).InIntro() || ((Character)player).IsDebugFlying() || GameCamera.InFreeFly())
			{
				return false;
			}
			if (SurfaceWalk.IsActive((Character)(object)player))
			{
				frame = SurfaceWalk.Frame;
				return true;
			}
			if (Plugin.ManualFlipActive((Character)(object)player))
			{
				frame = ManualFrame;
				return true;
			}
			return false;
		}

		internal static Quaternion Orient(Quaternion nativeRotation, Player player)
		{
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_000d: 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_000a: Unknown result type (might be due to invalid IL or missing references)
			if (!TryFrame(player, out var frame))
			{
				return nativeRotation;
			}
			return frame * nativeRotation;
		}

		internal static float RelativeVertical(Vector3 normal, Player player)
		{
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			//IL_0018: Unknown result type (might be due to invalid IL or missing references)
			//IL_000a: Unknown result type (might be due to invalid IL or missing references)
			if (!TryFrame(player, out var frame))
			{
				return normal.y;
			}
			return Vector3.Dot(normal, frame * Vector3.up);
		}

		internal static Vector3 ConnectedDown(Player player)
		{
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_0011: 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)
			//IL_000a: Unknown result type (might be due to invalid IL or missing references)
			if (!TryFrame(player, out var frame))
			{
				return Vector3.down;
			}
			return frame * Vector3.down;
		}

		internal static Quaternion LocalRotation(Quaternion worldRotation, Player player)
		{
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_0013: 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_0019: 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)
			if (!PlacementSupported || !TryFrame(player, out var frame))
			{
				return worldRotation;
			}
			return Quaternion.Inverse(frame) * worldRotation;
		}

		[HarmonyTranspiler]
		private static IEnumerable<CodeInstruction> RelativePlacement(IEnumerable<CodeInstruction> instructions)
		{
			//IL_0177: Unknown result type (might be due to invalid IL or missing references)
			//IL_0181: Expected O, but got Unknown
			//IL_019e: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a8: Expected O, but got Unknown
			//IL_023a: Unknown result type (might be due to invalid IL or missing references)
			//IL_024b: Expected O, but got Unknown
			//IL_0279: Unknown result type (might be due to invalid IL or missing references)
			//IL_0283: Expected O, but got Unknown
			//IL_01d7: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e8: Expected O, but got Unknown
			//IL_0216: Unknown result type (might be due to invalid IL or missing references)
			//IL_0220: Expected O, but got Unknown
			List<CodeInstruction> list = new List<CodeInstruction>(instructions);
			MethodInfo methodInfo = AccessTools.Method(typeof(Quaternion), "Euler", new Type[3]
			{
				typeof(float),
				typeof(float),
				typeof(float)
			}, (Type[])null);
			FieldInfo objB = AccessTools.Field(typeof(Vector3), "y");
			MethodInfo methodInfo2 = AccessTools.PropertyGetter(typeof(Vector3), "down");
			int num = -1;
			int num2 = -1;
			int num3 = 0;
			int num4 = 0;
			for (int i = 0; i < list.Count; i++)
			{
				if (CodeInstructionExtensions.Calls(list[i], methodInfo) || IsShipRotation(list[i]))
				{
					num = i;
					num4++;
				}
				if (IsGizmoRotation(list[i]))
				{
					num2 = i;
					num3++;
				}
			}
			int num5 = num;
			bool flag = num4 == 1;
			if (num3 != 0)
			{
				flag &= num3 == 1 && num2 == num + 1 && num2 + 1 < list.Count && IsStore(list[num2 + 1]);
				num5 = num2;
			}
			else if (num >= 0 && num + 1 < list.Count && IsRotationOverride(list[num + 1]))
			{
				flag = false;
			}
			List<CodeInstruction> list2 = new List<CodeInstruction>();
			int num6 = 0;
			int num7 = 0;
			for (int j = 0; j < list.Count; j++)
			{
				CodeInstruction val = list[j];
				if (j == num5)
				{
					list2.Add(val);
					list2.Add(new CodeInstruction(OpCodes.Ldarg_0, (object)null));
					list2.Add(new CodeInstruction(OpCodes.Call, (object)AccessTools.Method(typeof(SurfaceBuilding), "Orient", (Type[])null, (Type[])null)));
				}
				else if (val.opcode == OpCodes.Ldfld && object.Equals(val.operand, objB))
				{
					list2.Add(CodeInstructionExtensions.WithBlocks(CodeInstructionExtensions.WithLabels(new CodeInstruction(OpCodes.Ldarg_0, (object)null), (IEnumerable<Label>)val.labels), (IEnumerable<ExceptionBlock>)val.blocks));
					list2.Add(new CodeInstruction(OpCodes.Call, (object)AccessTools.Method(typeof(SurfaceBuilding), "RelativeVertical", (Type[])null, (Type[])null)));
					num6++;
				}
				else if (CodeInstructionExtensions.Calls(val, methodInfo2))
				{
					list2.Add(CodeInstructionExtensions.WithBlocks(CodeInstructionExtensions.WithLabels(new CodeInstruction(OpCodes.Ldarg_0, (object)null), (IEnumerable<Label>)val.labels), (IEnumerable<ExceptionBlock>)val.blocks));
					list2.Add(new CodeInstruction(OpCodes.Call, (object)AccessTools.Method(typeof(SurfaceBuilding), "ConnectedDown", (Type[])null, (Type[])null)));
					num7++;
				}
				else
				{
					list2.Add(val);
				}
			}
			PlacementSupported = flag && num6 == 3 && num7 == 1;
			if (!PlacementSupported)
			{
				if (Interlocked.Exchange(ref compatibilityWarning, 1) == 0)
				{
					Plugin.LogBuildingCompatibilityWarning("Surface-aligned building skipped for Player.UpdatePlacementGhost: found " + num4 + " yaw, " + num6 + " surface-normal reads and " + num7 + " connection rays (expected 1, 3, 1); recognized rotation sequence=" + flag + ". Another mod or game update changed the method. Existing placement is retained; gravity movement remains available.");
				}
				return list;
			}
			return list2;
		}

		private static bool IsRotationOverride(CodeInstruction instruction)
		{
			if (instruction.opcode != OpCodes.Call || !(instruction.operand is MethodInfo { IsStatic: not false } methodInfo) || methodInfo.ReturnType != typeof(Quaternion))
			{
				return false;
			}
			ParameterInfo[] parameters = methodInfo.GetParameters();
			if (parameters.Length == 1)
			{
				return parameters[0].ParameterType == typeof(Quaternion);
			}
			return false;
		}

		private static bool IsShipRotation(CodeInstruction instruction)
		{
			if (instruction.opcode != OpCodes.Call || !(instruction.operand is MethodInfo methodInfo) || methodInfo.DeclaringType?.FullName != "ShipBuildingMod.Player_Patches" || methodInfo.Name != "GetGhostRotation" || !methodInfo.IsStatic || methodInfo.ReturnType != typeof(Quaternion))
			{
				return false;
			}
			ParameterInfo[] parameters = methodInfo.GetParameters();
			if (parameters.Length == 3 && parameters[0].ParameterType == typeof(float) && parameters[1].ParameterType == typeof(float))
			{
				return parameters[2].ParameterType == typeof(float);
			}
			return false;
		}

		private static bool IsGizmoRotation(CodeInstruction instruction)
		{
			if (IsRotationOverride(instruction) && instruction.operand is MethodInfo methodInfo && methodInfo.DeclaringType?.FullName == "ComfyGizmo.PlayerPatch")
			{
				return methodInfo.Name == "PlaceRotationDelegate";
			}
			return false;
		}

		private static bool IsStore(CodeInstruction instruction)
		{
			if (!(instruction.opcode == OpCodes.Stloc) && !(instruction.opcode == OpCodes.Stloc_S) && !(instruction.opcode == OpCodes.Stloc_0) && !(instruction.opcode == OpCodes.Stloc_1) && !(instruction.opcode == OpCodes.Stloc_2))
			{
				return instruction.opcode == OpCodes.Stloc_3;
			}
			return true;
		}
	}
	[HarmonyPatch(typeof(Player), "CopyPiece")]
	internal static class SurfaceBuildingCopy
	{
		private static int compatibilityWarning;

		[HarmonyTranspiler]
		private static IEnumerable<CodeInstruction> RelativeCopy(IEnumerable<CodeInstruction> instructions)
		{
			//IL_0050: Unknown result type (might be due to invalid IL or missing references)
			//IL_005a: Expected O, but got Unknown
			//IL_0076: Unknown result type (might be due to invalid IL or missing references)
			//IL_0080: Expected O, but got Unknown
			List<CodeInstruction> list = new List<CodeInstruction>(instructions);
			List<CodeInstruction> list2 = new List<CodeInstruction>();
			MethodInfo methodInfo = AccessTools.PropertyGetter(typeof(Transform), "rotation");
			int num = 0;
			foreach (CodeInstruction item in list)
			{
				list2.Add(item);
				if (CodeInstructionExtensions.Calls(item, methodInfo))
				{
					list2.Add(new CodeInstruction(OpCodes.Ldarg_0, (object)null));
					list2.Add(new CodeInstruction(OpCodes.Call, (object)AccessTools.Method(typeof(SurfaceBuilding), "LocalRotation", (Type[])null, (Type[])null)));
					num++;
				}
			}
			if (num != 1)
			{
				if (Interlocked.Exchange(ref compatibilityWarning, 1) == 0)
				{
					Plugin.LogBuildingCompatibilityWarning("Surface-relative build copying skipped for Player.CopyPiece: found " + num + " source rotations (expected 1). Existing copy behavior is retained.");
				}
				return list;
			}
			return list2;
		}
	}
	[HarmonyPatch]
	internal static class SurfaceCamera
	{
		private struct CameraSettings
		{
			internal bool Changed;

			internal bool ShipTilt;
		}

		private static readonly FieldRef<Character, Quaternion> LookYaw = AccessTools.FieldRefAccess<Character, Quaternion>("m_lookYaw");

		private static readonly FieldRef<Player, float> LookPitch = AccessTools.FieldRefAccess<Player, float>("m_lookPitch");

		private static readonly FieldRef<GameCamera, Vector3> PlayerPosition = AccessTools.FieldRefAccess<GameCamera, Vector3>("m_playerPos");

		private static readonly FieldRef<GameCamera, Vector3> PlayerVelocity = AccessTools.FieldRefAccess<GameCamera, Vector3>("m_playerVel");

		private static readonly FieldRef<GameCamera, Vector3> BaseOffset = AccessTools.FieldRefAccess<GameCamera, Vector3>("m_currentBaseOffset");

		private static readonly FieldRef<GameCamera, Vector3> BaseVelocity = AccessTools.FieldRefAccess<GameCamera, Vector3>("m_offsetBaseVel");

		private static readonly FieldRef<GameCamera, Vector3> CameraUp = AccessTools.FieldRefAccess<GameCamera, Vector3>("m_smoothedCameraUp");

		private static readonly FieldRef<GameCamera, Vector3> CameraUpVelocity = AccessTools.FieldRefAccess<GameCamera, Vector3>("m_smoothedCameraUpVel");

		private static readonly Action<Player> UpdateEye = AccessTools.MethodDelegate<Action<Player>>(AccessTools.DeclaredMethod(typeof(Player), "UpdateEyeRotation", (Type[])null, (Type[])null), (object)null, true);

		internal static void RebaseCamera(Player player)
		{
			//IL_0035: Unknown result type (might be due to invalid IL or missing references)
			//IL_003a: Unknown result type (might be due to invalid IL or missing references)
			//IL_004a: Unknown result type (might be due to invalid IL or missing references)
			//IL_004f: 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_0070: Unknown result type (might be due to invalid IL or missing references)
			//IL_0075: Unknown result type (might be due to invalid IL or missing references)
			//IL_007a: Unknown result type (might be due to invalid IL or missing references)
			//IL_008a: Unknown result type (might be due to invalid IL or missing references)
			//IL_008f: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a5: 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_00ba: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bf: Unknown result type (might be due to invalid IL or missing references)
			GameCamera instance = GameCamera.instance;
			if (Object.op_Implicit((Object)(object)instance) && Object.op_Implicit((Object)(object)player) && Object.op_Implicit((Object)(object)((Character)player).m_eye))
			{
				PlayerPosition.Invoke(instance) = ((Component)player).transform.position;
				PlayerVelocity.Invoke(instance) = Vector3.zero;
				BaseOffset.Invoke(instance) = ((Character)player).m_eye.position - ((Component)player).transform.position;
				BaseVelocity.Invoke(instance) = Vector3.zero;
				CameraUp.Invoke(instance) = ((Component)player).transform.up;
				CameraUpVelocity.Invoke(instance) = Vector3.zero;
			}
		}

		[HarmonyPatch(typeof(GameCamera), "GetCameraPosition")]
		[HarmonyTranspiler]
		private static IEnumerable<CodeInstruction> RelativePitch(IEnumerable<CodeInstruction> instructions)
		{
			List<CodeInstruction> list = new List<CodeInstruction>(instructions);
			FieldInfo objB = AccessTools.Field(typeof(Vector3), "y");
			MethodInfo methodInfo = AccessTools.Method(typeof(Utils), "SmoothStep", new Type[3]
			{
				typeof(float),
				typeof(float),
				typeof(float)
			}, (Type[])null);
			int num = 0;
			for (int i = 0; i + 1 < list.Count; i++)
			{
				if (!(list[i].opcode != OpCodes.Ldfld) && object.Equals(list[i].operand, objB) && CodeInstructionExtensions.Calls(list[i + 1], methodInfo))
				{
					list[i].opcode = OpCodes.Call;
					list[i].operand = AccessTools.Method(typeof(SurfaceCamera), "RelativeVertical", (Type[])null, (Type[])null);
					num++;
				}
			}
			if (num != 1)
			{
				throw new InvalidOperationException("Native camera pitch layout changed; expected one gravity-relative pitch site.");
			}
			return list;
		}

		private static float RelativeVertical(Vector3 vector)
		{
			//IL_0013: 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_001b: Unknown result type (might be due to invalid IL or missing references)
			if (!SurfaceWalk.IsViewActive((Character)(object)Player.m_localPlayer) || GameCamera.InFreeFly())
			{
				return vector.y;
			}
			return Vector3.Dot(vector, SurfaceWalk.Up);
		}

		[HarmonyPatch(typeof(GameCamera), "GetCameraPosition")]
		[HarmonyPrefix]
		private static void BeginPose(ref bool ___m_shipCameraTilt, out CameraSettings __state)
		{
			__state = default(CameraSettings);
			Player localPlayer = Player.m_localPlayer;
			if (SurfaceWalk.IsViewActive((Character)(object)localPlayer) && Object.op_Implicit((Object)(object)((Character)localPlayer).m_eye) && !GameCamera.InFreeFly())
			{
				__state = new CameraSettings
				{
					Changed = true,
					ShipTilt = ___m_shipCameraTilt
				};
				___m_shipCameraTilt = false;
			}
		}

		[HarmonyPatch(typeof(GameCamera), "GetCameraPosition")]
		[HarmonyFinalizer]
		private static Exception EndPose(Exception __exception, ref bool ___m_shipCameraTilt, CameraSettings __state)
		{
			if (__state.Changed)
			{
				___m_shipCameraTilt = __state.ShipTilt;
			}
			return __exception;
		}

		[HarmonyPatch(typeof(Player), "SetMouseLookForward")]
		[HarmonyPrefix]
		private static bool LookForward(Player __instance, bool __0)
		{
			return FaceBody(__instance, __0, backward: false);
		}

		[HarmonyPatch(typeof(Player), "SetMouseLookBackward")]
		[HarmonyPrefix]
		private static bool LookBackward(Player __instance, bool __0)
		{
			return FaceBody(__instance, __0, backward: true);
		}

		private static bool FaceBody(Player player, bool resetPitch, bool backward)
		{
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_0029: Unknown result type (might be due to invalid IL or missing references)
			//IL_002b: Unknown result type (might be due to invalid IL or missing references)
			if (!SurfaceWalk.IsViewActive((Character)(object)player))
			{
				return true;
			}
			Vector3 forward = ((Component)player).transform.forward * (backward ? (-1f) : 1f);
			SetTangentYaw(player, forward);
			if (resetPitch)
			{
				LookPitch.Invoke(player) = 0f;
			}
			UpdateEye(player);
			return false;
		}

		private static void SetTangentYaw(Player player, Vector3 forward)
		{
			//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_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_000b: 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)
			//IL_002f: 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_0039: Unknown result type (might be due to invalid IL or missing references)
			//IL_003e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0066: Unknown result type (might be due to invalid IL or missing references)
			//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_0075: 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_0058: Unknown result type (might be due to invalid IL or missing references)
			Vector3 val = Vector3.ProjectOnPlane(forward, SurfaceWalk.Up);
			if (((Vector3)(ref val)).sqrMagnitude < 1E-05f)
			{
				val = Vector3.ProjectOnPlane(LookYaw.Invoke((Character)(object)player) * Vector3.forward, SurfaceWalk.Up);
			}
			if (((Vector3)(ref val)).sqrMagnitude < 1E-05f)
			{
				val = ((Component)player).transform.forward;
			}
			LookYaw.Invoke((Character)(object)player) = Quaternion.LookRotation(((Vector3)(ref val)).normalized, SurfaceWalk.Up);
		}

		[HarmonyPatch(typeof(Character), "SetLookDir")]
		[HarmonyPrefix]
		private static void CaptureLookDirection(Character __instance, Vector3 __0, float __1, out Vector3? __state)
		{
			//IL_001c: Unknown result type (might be due to invalid IL or missing references)
			__state = ((SurfaceWalk.IsViewActive(__instance) && __1 <= 0f) ? new Vector3?(__0) : ((Vector3?)null));
		}

		[HarmonyPatch(typeof(Character), "SetLookDir")]
		[HarmonyPostfix]
		private static void RestoreTangentLook(Character __instance, Vector3? __state)
		{
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			//IL_0019: Expected O, but got Unknown
			//IL_001c: Unknown result type (might be due to invalid IL or missing references)
			if (__state.HasValue && SurfaceWalk.IsViewActive(__instance))
			{
				Player val = (Player)__instance;
				SetTangentYaw(val, __state.Value);
				UpdateEye(val);
			}
		}
	}
	[HarmonyPatch(typeof(Humanoid), "DoInteractAnimation")]
	internal static class SurfaceInteractions
	{
		[HarmonyTranspiler]
		private static IEnumerable<CodeInstruction> RelativeFacing(IEnumerable<CodeInstruction> instructions, ILGenerator generator)
		{
			//IL_01f5: Unknown result type (might be due to invalid IL or missing references)
			//IL_01fc: Expected O, but got Unknown
			//IL_023a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0240: Expected O, but got Unknown
			//IL_025d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0263: Expected O, but got Unknown
			//IL_0271: Unknown result type (might be due to invalid IL or missing references)
			//IL_0277: Expected O, but got Unknown
			List<CodeInstruction> list = new List<CodeInstruction>(instructions);
			MethodInfo sync = AccessTools.Method(typeof(Physics), "SyncTransforms", (Type[])null, (Type[])null);
			MethodInfo methodInfo = AccessTools.PropertySetter(typeof(Transform), "rotation");
			MethodInfo methodInfo2 = AccessTools.Method(typeof(Quaternion), "LookRotation", new Type[1] { typeof(Vector3) }, (Type[])null);
			FieldInfo objB = AccessTools.Field(typeof(Vector3), "y");
			int num = list.FindIndex((CodeInstruction instruction) => CodeInstructionExtensions.Calls(instruction, sync));
			if (num != 18 || list.FindLastIndex((CodeInstruction instruction) => CodeInstructionExtensions.Calls(instruction, sync)) != num || list[0].opcode != OpCodes.Ldarg_1 || list[3].opcode != OpCodes.Ldarg_0 || list[9].opcode != OpCodes.Ldc_R4 || !object.Equals(list[9].operand, 0f) || list[10].opcode != OpCodes.Stfld || !object.Equals(list[10].operand, objB) || !CodeInstructionExtensions.Calls(list[16], methodInfo2) || !CodeInstructionExtensions.Calls(list[17], methodInfo))
			{
				throw new InvalidOperationException("Native interaction facing layout changed; expected the initial rotation block before SyncTransforms.");
			}
			for (int num2 = 0; num2 < num; num2++)
			{
				if (list[num2].blocks.Count != 0 || list[num2].opcode.FlowControl == FlowControl.Branch || list[num2].opcode.FlowControl == FlowControl.Cond_Branch)
				{
					throw new InvalidOperationException("Native interaction facing block has unexpected control flow.");
				}
			}
			Label label = generator.DefineLabel();
			list[num].labels.Add(label);
			CodeInstruction val = new CodeInstruction(OpCodes.Ldarg_0, (object)null);
			val.labels.AddRange(list[0].labels);
			list[0].labels.Clear();
			list.InsertRange(0, (IEnumerable<CodeInstruction>)(object)new CodeInstruction[4]
			{
				val,
				new CodeInstruction(OpCodes.Ldarg_1, (object)null),
				new CodeInstruction(OpCodes.Call, (object)AccessTools.Method(typeof(SurfaceWalk), "TryFaceInteraction", (Type[])null, (Type[])null)),
				new CodeInstruction(OpCodes.Brtrue, (object)label)
			});
			return list;
		}
	}
	[HarmonyPatch(typeof(Player), "UpdateStations")]
	internal static class SurfaceStationFacing
	{
		private static int warning;

		[HarmonyTranspiler]
		private static IEnumerable<CodeInstruction> RelativeFacing(IEnumerable<CodeInstruction> instructions, ILGenerator generator)
		{
			//IL_0255: Unknown result type (might be due to invalid IL or missing references)
			//IL_026c: Expected O, but got Unknown
			//IL_0279: Unknown result type (might be due to invalid IL or missing references)
			//IL_0283: Expected O, but got Unknown
			//IL_02ab: Unknown result type (might be due to invalid IL or missing references)
			//IL_02b1: Expected O, but got Unknown
			//IL_02ce: Unknown result type (might be due to invalid IL or missing references)
			//IL_02d4: Expected O, but got Unknown
			//IL_02ea: Unknown result type (might be due to invalid IL or missing references)
			//IL_02f0: Expected O, but got Unknown
			List<CodeInstruction> list = new List<CodeInstruction>(instructions);
			MethodInfo camera = AccessTools.Method(typeof(Character), "AlwaysRotateCamera", (Type[])null, (Type[])null);
			MethodInfo methodInfo = AccessTools.Method(typeof(Quaternion), "LookRotation", new Type[1] { typeof(Vector3) }, (Type[])null);
			MethodInfo rotate = AccessTools.PropertySetter(typeof(Transform), "rotation");
			FieldInfo fieldInfo = AccessTools.Field(typeof(Player), "m_currentStation");
			int num = list.FindIndex((CodeInstruction c) => CodeInstructionExtensions.Calls(c, camera));
			int num2 = list.FindIndex((CodeInstruction c) => CodeInstructionExtensions.Calls(c, rotate));
			int num3 = num + 2;
			bool flag = num >= 0 && num2 > num3 && num2 + 1 < list.Count && list.FindLastIndex((CodeInstruction c) => CodeInstructionExtensions.Calls(c, camera)) == num && list.FindLastIndex((CodeInstruction c) => CodeInstructionExtensions.Calls(c, rotate)) == num2 && (list[num + 1].opcode == OpCodes.Brtrue || list[num + 1].opcode == OpCodes.Brtrue_S) && list[num + 1].operand is Label item && list[num2 + 1].labels.Contains(item) && list[num3].opcode == OpCodes.Ldarg_0 && CodeInstructionExtensions.LoadsField(list[num3 + 1], fieldInfo, false);
			int num4 = 0;
			if (flag)
			{
				for (int num5 = num3; num5 <= num2; num5++)
				{
					if (CodeInstructionExtensions.Calls(list[num5], methodInfo))
					{
						num4++;
					}
					if (list[num5].blocks.Count != 0 || (num5 > num3 && list[num5].labels.Count != 0) || list[num5].opcode.FlowControl == FlowControl.Branch || list[num5].opcode.FlowControl == FlowControl.Cond_Branch)
					{
						flag = false;
					}
				}
			}
			if (!flag || num4 != 1)
			{
				if (Interlocked.Exchange(ref warning, 1) == 0)
				{
					Plugin.LogBuildingCompatibilityWarning("Surface-relative station facing skipped: Player.UpdateStations facing block changed. Native station behavior is retained.");
				}
				return list;
			}
			CodeInstruction val = CodeInstructionExtensions.WithLabels(new CodeInstruction(OpCodes.Ldarg_0, (object)null), (IEnumerable<Label>)list[num3].labels);
			list[num3] = new CodeInstruction(list[num3]);
			list[num3].labels.Clear();
			list.InsertRange(num3, (IEnumerable<CodeInstruction>)(object)new CodeInstruction[4]
			{
				val,
				new CodeInstruction(OpCodes.Ldarg_1, (object)null),
				new CodeInstruction(OpCodes.Call, (object)AccessTools.Method(typeof(SurfaceWalk), "TryFaceStation", (Type[])null, (Type[])null)),
				new CodeInstruction(OpCodes.Brtrue, list[num + 1].operand)
			});
			return list;
		}
	}
	public interface ISurfaceWalkArea
	{
		bool Contains(Vector3 world);

		bool TryGetSurface(RaycastHit hit, out SurfaceWalkContact contact);

		bool IsAdjacent(int firstFace, int secondFace);
	}
	public interface ISurfaceWalkAttachmentArea
	{
		bool SupportsAttachment(Transform attachPoint);
	}
	public interface ISurfaceWalkTransitArea
	{
		bool TryGetTransit(Player player, float dt, out SurfaceWalkTransitPose pose);

		void CancelTransit(Player player);
	}
	public readonly struct SurfaceWalkTransitPose
	{
		public readonly Vector3 Position;

		public readonly Vector3 Up;

		public readonly Vector3 Velocity;

		public readonly Vector3 Impulse;

		public readonly bool Completed;

		public readonly bool HasBodyRotation;

		public readonly bool PhysicsDriven;

		public readonly Quaternion BodyRotation;

		public SurfaceWalkTransitPose(Vector3 position, Vector3 up, bool completed)
			: this(position, up, completed, Vector3.zero)
		{
		}//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_0004: Unknown result type (might be due to invalid IL or missing references)


		public SurfaceWalkTransitPose(Vector3 position, Vector3 up, bool completed, Vector3 velocity)
		{
			//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_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_0016: Unknown result type (might be due to invalid IL or missing references)
			//IL_0018: 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)
			//IL_0037: 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)
			Position = position;
			Up = up;
			Completed = completed;
			Velocity = velocity;
			HasBodyRotation = false;
			BodyRotation = Quaternion.identity;
			PhysicsDriven = false;
			Impulse = Vector3.zero;
		}

		public SurfaceWalkTransitPose(Vector3 position, Vector3 up, bool completed, Vector3 velocity, Quaternion bodyRotation)
		{
			//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_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_0016: Unknown result type (might be due to invalid IL or missing references)
			//IL_0018: 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_0027: 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_0039: Unknown result type (might be due to invalid IL or missing references)
			Position = position;
			Up = up;
			Completed = completed;
			Velocity = velocity;
			HasBodyRotation = true;
			BodyRotation = bodyRotation;
			PhysicsDriven = false;
			Impulse = Vector3.zero;
		}

		private SurfaceWalkTransitPose(Vector3 up, Quaternion bodyRotation, Vector3 impulse)
		{
			//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_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_000e: 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_0015: 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)
			//IL_0033: 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_003a: Unknown result type (might be due to invalid IL or missing references)
			//IL_003b: Unknown result type (might be due to invalid IL or missing references)
			Position = (Velocity = Vector3.zero);
			Up = up;
			Completed = false;
			HasBodyRotation = (PhysicsDriven = true);
			BodyRotation = bodyRotation;
			Impulse = impulse;
		}

		public static SurfaceWalkTransitPose Flight(Vector3 up, Quaternion bodyRotation, Vector3 impulse)
		{
			//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)
			return new SurfaceWalkTransitPose(up, bodyRotation, impulse);
		}
	}
	public readonly struct SurfaceWalkContact
	{
		public readonly Vector3 Point;

		public readonly Vector3 Normal;

		public readonly int FaceId;

		public readonly int PanelId;

		public SurfaceWalkContact(Vector3 point, Vector3 normal, int faceId, int panelId)
		{
			//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_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)
			Point = point;
			Normal = normal;
			FaceId = faceId;
			PanelId = panelId;
		}
	}
	[HarmonyPatch]
	public static class SurfaceWalk
	{
		private sealed class Lease : IDisposable
		{
			internal ISurfaceWalkArea Area;

			public void Dispose()
			{
				if (Area != null)
				{
					Areas.Remove(this);
					if (state != null && state.Lease == this)
					{
						Restore();
					}
					Area = null;
				}
			}
		}

		private sealed class State
		{
			internal Lease Lease;

			internal Player Player;

			internal Rigidbody Body;

			internal CapsuleCollider Capsule;

			internal ZSyncTransform Sync;

			internal bool Gravity;

			internal bool SyncGravity;

			internal RigidbodyConstraints Constraints;

			internal CollisionDetectionMode CollisionMode;

			internal Transform Visual;

			internal Quaternion VisualRotation;

			internal Vector3 Up = Vector3.up;

			internal Vector3 TargetUp = Vector3.up;

			internal Quaternion Frame = Quaternion.identity;

			internal int Face = -1;

			internal int Panel = -1;

			internal float ChangeCooldown;

			internal float JumpCooldown;

			internal float AirTime;

			internal bool Grounded;

			internal Vector3 GroundNormal;

			internal Collider GroundCollider;

			internal Vector3 GroundPoint;

			internal int ControlsDepth;

			internal int JumpDepth;

			internal bool JumpLaunched;

			internal bool WallJumpArmed;

			internal bool JumpPressed;

			internal float WallJumpRequest;

			internal float WallSprintTime;

			internal int WallIntentPanel = -1;

			internal Vector3 WallIntentNormal;
		}

		private delegate void VelocityModifier(Character character, ref Vector3 velocity);

		private struct ControlsPose
		{
			internal State State;

			internal Vector3 Look;

			internal Quaternion Frame;
		}

		private struct JumpPose
		{
			internal State State;

			internal Vector3 Velocity;

			internal Vector3 Move;

			internal Vector3 Normal;

			internal Vector3 Current;
		}

		private struct DodgePose
		{
			internal State State;

			internal Vector3 Direction;

			internal Quaternion Rotation;
		}

		private static readonly List<Lease> Areas = new List<Lease>();

		private static State state;

		private static readonly RaycastHit[] Hits = (RaycastHit[])(object)new RaycastHit[64];

		private static readonly Collider[] Overlaps = (Collider[])(object)new Collider[96];

		private static readonly Vector3[] SearchDirections = (Vector3[])(object)new Vector3[6]
		{
			Vector3.down,
			Vector3.up,
			Vector3.left,
			Vector3.right,
			Vector3.forward,
			Vector3.back
		};

		private static int collisionMask;

		private static readonly FieldRef<Character, Vector3> Move = Field<Vector3>("m_moveDir");

		private static readonly FieldRef<Character, Vector3> Look = Field<Vector3>("m_lookDir");

		private static readonly FieldRef<Character, Quaternion> Yaw = Field<Quaternion>("m_lookYaw");

		private static readonly FieldRef<Character, Vector3> CurrentVelocity = Field<Vector3>("m_currentVel");

		private static readonly FieldRef<Character, Vector3> LastPosition = Field<Vector3>("m_lastPos");

		private static readonly FieldRef<Character, Vector3> GroundNormal = Field<Vector3>("m_lastGroundNormal");

		private static readonly FieldRef<Character, Vector3> GroundPoint = Field<Vector3>("m_lastGroundPoint");

		private static readonly FieldRef<Character, Collider> GroundCollider = Field<Collider>("m_lastGroundCollider");

		private static readonly FieldRef<Character, Rigidbody> GroundBody = Field<Rigidbody>("m_lastGroundBody");

		private static readonly FieldRef<Character, Heightmap> GroundHeightmap = Field<Heightmap>("m_lastGroundHeightmap");

		private static readonly FieldRef<Character, bool> Contact = Field<bool>("m_groundContact");

		private static readonly FieldRef<Character, bool> Running = Field<bool>("m_running");

		private static readonly FieldRef<Character, bool> Walking = Field<bool>("m_walking");

		private static readonly FieldRef<Character, bool> Walk = Field<bool>("m_walk");

		private static readonly FieldRef<Character, bool> Sliding = Field<bool>("m_sliding");

		private static readonly FieldRef<Character, bool> Slipping = Field<bool>("m_slipping");

		private static readonly FieldRef<Character, bool> WallRunning = Field<bool>("m_wallRunning");

		private static readonly FieldRef<Character, float> JumpTimer = Field<float>("m_jumpTimer");

		private static readonly FieldRef<Character, float> GroundTouch = Field<float>("m_lastGroundTouch");

		private static readonly FieldRef<Character, float> HitWorldTime = Field<float>("m_hitWorldTime");

		private static readonly FieldRef<Character, float> MaxAltitude = Field<float>("m_maxAirAltitude");

		private static readonly FieldRef<Character, float> FallTimer = Field<float>("m_fallTimer");

		private static readonly FieldRef<Character, Vector3> RootMotion = Field<Vector3>("m_rootMotion");

		private static readonly FieldRef<Character, GameObject> Visual = Field<GameObject>("m_visual");

		private static readonly FieldRef<Character, ZSyncAnimation> Animation = Field<ZSyncAnimation>("m_zanim");

		private static readonly FieldRef<ZSyncTransform, bool> SyncGravity = AccessTools.FieldRefAccess<ZSyncTransform, bool>("m_useGravity");

		private static readonly FieldRef<Player, Vector3> DodgeDirection = AccessTools.FieldRefAccess<Player, Vector3>("m_queuedDodgeDir");

		private static readonly FieldRef<Player, float> TeleportCooldown = AccessTools.FieldRefAccess<Player, float>("m_teleportCooldown");

		private static readonly Func<Player, Vector3, float, bool> CheckRun = AccessTools.MethodDelegate<Func<Player, Vector3, float, bool>>(AccessTools.DeclaredMethod(typeof(Player), "CheckRun", (Type[])null, (Type[])null), (object)null, true);

		private static readonly Func<Player, float> JogFactor = AccessTools.MethodDelegate<Func<Player, float>>(AccessTools.DeclaredMethod(typeof(Player), "GetJogSpeedFactor", (Type[])null, (Type[])null), (object)null, true);

		private static readonly Func<Player, float> RunFactor = AccessTools.MethodDelegate<Func<Player, float>>(AccessTools.DeclaredMethod(typeof(Player), "GetRunSpeedFactor", (Type[])null, (Type[])null), (object)null, true);

		private static readonly Func<Humanoid, float> AttackMoveFactor = AccessTools.MethodDelegate<Func<Humanoid, float>>(AccessTools.DeclaredMethod(typeof(Humanoid), "GetAttackSpeedFactorMovement", (Type[])null, (Type[])null), (object)null, true);

		private static readonly Func<Humanoid, float> AttackTurnFactor = AccessTools.MethodDelegate<Func<Humanoid, float>>(AccessTools.DeclaredMethod(typeof(Humanoid), "GetAttackSpeedFactorRotation", (Type[])null, (Type[])null), (object)null, true);

		private static readonly Func<Player, bool> FaceCamera = AccessTools.MethodDelegate<Func<Player, bool>>(AccessTools.DeclaredMethod(typeof(Player), "AlwaysRotateCamera", (Type[])null, (Type[])null), (object)null, true);

		private static readonly Action<Player, float> Sneak = AccessTools.MethodDelegate<Action<Player, float>>(AccessTools.DeclaredMethod(typeof(Player), "OnSneaking", (Type[])null, (Type[])null), (object)null, true);

		private static readonly Action<Character> Friction = AccessTools.MethodDelegate<Action<Character>>(AccessTools.DeclaredMethod(typeof(Character), "UpdateBodyFriction", (Type[])null, (Type[])null), (object)null, true);

		private static readonly Action<Player> UpdateEye = AccessTools.MethodDelegate<Action<Player>>(AccessTools.DeclaredMethod(typeof(Player), "UpdateEyeRotation", (Type[])null, (Type[])null), (object)null, true);

		private static readonly VelocityModifier ApplyRoot = AccessTools.MethodDelegate<VelocityModifier>(AccessTools.DeclaredMethod(typeof(Character), "ApplyRootMotion", (Type[])null, (Type[])null), (object)null, true);

		private static readonly VelocityModifier ApplyPushback = AccessTools.MethodDelegate<VelocityModifier>(AccessTools.DeclaredMethod(typeof(Character), "AddPushbackForce", (Type[])null, (Type[])null), (object)null, true);

		internal static Player Player => state?.Player;

		internal static Vector3 Up
		{
			get
			{
				//IL_0012: 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)
				if (state == null)
				{
					return Vector3.up;
				}
				return state.Up;
			}
		}

		internal static Quaternion Frame
		{
			get
			{
				//IL_0012: 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)
				if (state == null)
				{
					return Quaternion.identity;
				}
				return state.Frame;
			}
		}

		internal static Quaternion RotationDelta { get; private set; } = Quaternion.identity;

		private static FieldRef<Character, T> Field<T>(string name)
		{
			return AccessTools.FieldRefAccess<Character, T>(name);
		}

		public static IDisposable Register(ISurfaceWalkArea area)
		{
			if (area == null)
			{
				throw new ArgumentNullException("area");
			}
			Lease lease = new Lease
			{
				Area = area
			};
			Areas.Add(lease);
			return lease;
		}

		private static bool Eligible(Player player)
		{
			if (Object.op_Implicit((Object)(object)player) && (Object)(object)player == (Object)(object)Player.m_localPlayer && Object.op_Implicit((Object)(object)ZNetScene.instance) && !((Character)player).IsDead() && !((Character)player).IsTeleporting() && !((Character)player).IsAttached() && !((Character)player).IsSwimming() && !((Character)player).InIntro())
			{
				return !((Character)player).IsDebugFlying();
			}
			return false;
		}

		private static Lease FindArea(Player player)
		{
			//IL_0049: Unknown result type (might be due to invalid IL or missing references)
			//IL_008c: Unknown result type (might be due to invalid IL or missing references)
			if (!Eligible(player))
			{
				return null;
			}
			if (state != null && (Object)(object)state.Player == (Object)(object)player && state.Lease.Area != null && state.Lease.Area.Contains(((Component)player).transform.position))
			{
				return state.Lease;
			}
			for (int i = 0; i < Areas.Count; i++)
			{
				if (Areas[i].Area != null && Areas[i].Area.Contains(((Component)player).transform.position))
				{
					return Areas[i];
				}
			}
			return null;
		}

		internal static bool WantsControl(Player player)
		{
			return FindArea(player) != null;
		}

		internal static bool IsViewActive(Character character)
		{
			if (state != null && Object.op_Implicit((Object)(object)character) && (Object)(object)character == (Object)(object)state.Player)
			{
				return (Object)(object)character == (Object)(object)Player.m_localPlayer;
			}
			return false;
		}

		internal static bool IsActive(Character character)
		{
			if (IsViewActive(character))
			{
				return !((Character)state.Player).IsAttached();
			}
			return false;
		}

		internal static bool TryFaceInteraction(Humanoid actor, GameObject target)
		{
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			//IL_0022: Unknown result type (might be due to invalid IL or missing references)
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			if (IsViewActive((Character)(object)actor) && Object.op_Implicit((Object)(object)target))
			{
				return TryFaceDirection(actor, target.transform.position - ((Component)actor).transform.position, 360f);
			}
			return false;
		}

		internal static bool TryFaceStation(Player player, float dt)
		{
			//IL_0020: 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_0030: Unknown result type (might be due to invalid IL or missing references)
			if (!IsViewActive((Character)(object)player))
			{
				return false;
			}
			CraftingStation currentCraftingStation = player.GetCurrentCraftingStation();
			if (Object.op_Implicit((Object)(object)currentCraftingStation))
			{
				return TryFaceDirection((Humanoid)(object)player, ((Component)currentCraftingStation).transform.position - ((Component)player).transform.position, Mathf.Max(0f, ((Character)player).m_turnSpeed * dt));
			}
			return false;
		}

		[HarmonyPatch(typeof(Player), "FaceLookDirection")]
		[HarmonyPrefix]
		private static bool FaceLookDirection(Player __instance)
		{
			//IL_002e: Unknown result type (might be due to invalid IL or missing references)
			//IL_003e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0043: Unknown result type (might be due to invalid IL or missing references)
			//IL_0022: Unknown result type (might be due to invalid IL or missing references)
			//IL_0048: Unknown result type (might be due to invalid IL or missing references)
			//IL_004a: Unknown result type (might be due to invalid IL or missing references)
			if (!IsViewActive((Character)(object)__instance))
			{
				return true;
			}
			Vector3 direction = ((state.ControlsDepth > 0) ? (state.Frame * Look.Invoke((Character)(object)__instance)) : Look.Invoke((Character)(object)__instance));
			if (!TryFaceDirection((Humanoid)(object)__instance, direction, 360f))
			{
				return true;
			}
			Physics.SyncTransforms();
			return false;
		}

		internal static bool TryFaceDirection(Humanoid actor, Vector3 direction, float maxDegrees)
		{
			//IL_0041: Unknown result type (might be due to invalid IL or missing references)
			//IL_0047: Unknown result type (might be due to invalid IL or missing references)
			//IL_0052: Unknown result type (might be due to invalid IL or missing references)
			//IL_0057: Unknown result type (might be due to invalid IL or missing references)
			//IL_0061: Unknown result type (might be due to invalid IL or missing references)
			//IL_0066: Unknown result type (might be due to invalid IL or missing references)
			//IL_006b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0095: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a1: Unknown result type (might be due to invalid IL or missing references)
			//IL_007e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0083: Unknown result type (might be due to invalid IL or missing references)
			//IL_0085: Unknown result type (might be due to invalid IL or missing references)
			//IL_008a: Unknown result type (might be due to invalid IL or missing references)
			if (!IsViewActive((Character)(object)actor))
			{
				return false;
			}
			if (((Character)state.Player).IsAttached())
			{
				return true;
			}
			if (!Eligible(state.Player) || !Object.op_Implicit((Object)(object)state.Body))
			{
				return false;
			}
			Quaternion val = Quaternion.LookRotation(Planar(direction, state.Up, ((Component)actor).transform.forward), state.Up);
			if (maxDegrees < 180f)
			{
				val = Quaternion.RotateTowards(state.Body.rotation, val, maxDegrees);
			}
			state.Body.rotation = val;
			((Component)actor).transform.rotation = val;
			UpdateEye(state.Player);
			return true;
		}

		private static Lease AttachmentArea(Player player)
		{
			//IL_0070: Unknown result type (might be due to invalid IL or missing references)
			if (!Object.op_Implicit((Object)(object)player) || (Object)(object)player != (Object)(object)Player.m_localPlayer || ((Character)player).IsDead() || ((Character)player).IsTeleporting() || !((Character)player).IsAttached())
			{
				return null;
			}
			Transform attachPoint = player.GetAttachPoint();
			if (!Object.op_Implicit((Object)(object)attachPoint))
			{
				return null;
			}
			foreach (Lease area in Areas)
			{
				if (area.Area is ISurfaceWalkAttachmentArea surfaceWalkAttachmentArea && area.Area.Contains(((Component)player).transform.position) && surfaceWalkAttachmentArea.SupportsAttachment(attachPoint))
				{
					return area;
				}
			}
			return null;
		}

		internal static void Tick()
		{
			//IL_0086: Unknown result type (might be due to invalid IL or missing references)
			//IL_008b: 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_0094: Unknown result type (might be due to invalid IL or missing references)
			//IL_009a: Unknown result type (might be due to invalid IL or missing references)
			//IL_009f: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a0: 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_00b1: 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_00b3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ba: 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_00c6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cb: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cc: 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_00e1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ee: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f8: 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_0102: Unknown result type (might be due to invalid IL or missing references)
			//IL_0109: Unknown result type (might be due to invalid IL or missing references)
			//IL_010e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0113: Unknown result type (might be due to invalid IL or missing references)
			//IL_0114: Unknown result type (might be due to invalid IL or missing references)
			//IL_0119: Unknown result type (might be due to invalid IL or missing references)
			//IL_013a: Unknown result type (might be due to invalid IL or missing references)
			//IL_013f: Unknown result type (might be due to invalid IL or missing references)
			Player localPlayer = Player.m_localPlayer;
			Lease lease = AttachmentArea(localPlayer);
			if (lease != null)
			{
				if (state != null && (state.Lease != lease || (Obj