Decompiled source of JoofOTHFramework v1.2.0

UserLibs/JoofOTHFramework.dll

Decompiled 18 hours ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using System.Text;
using System.Text.Json;
using System.Threading;
using HarmonyLib;
using Il2Cpp;
using Il2CppFusion;
using Il2CppFusion.Sockets;
using Il2CppInterop.Common;
using Il2CppInterop.Runtime;
using Il2CppInterop.Runtime.InteropTypes;
using Il2CppInterop.Runtime.InteropTypes.Arrays;
using Il2CppSystem;
using Il2CppVehiclePhysics;
using JoofOTHFramework;
using MelonLoader;
using MelonLoader.NativeUtils;
using MelonLoader.Preferences;
using Microsoft.CodeAnalysis;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETCoreApp,Version=v6.0", FrameworkDisplayName = ".NET 6.0")]
[assembly: AssemblyCompany("JoofOTHFramework")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.2.0.0")]
[assembly: AssemblyInformationalVersion("1.2.0+eabe5bdf42b7f93972bce20293c052843a78c357")]
[assembly: AssemblyProduct("JoofOTHFramework")]
[assembly: AssemblyTitle("JoofOTHFramework")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.2.0.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
internal class <Module>
{
	static <Module>()
	{
		Core.Init();
	}
}
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace JoofOTHFramework
{
	public static class HillNet
	{
		private class Envelope
		{
			public string T { get; set; }

			public string C { get; set; }

			public string J { get; set; }

			public List<string> Channels { get; set; }
		}

		private class Channel
		{
			public Action<NetworkRunner, PlayerRef, string> Handler;
		}

		private class Peer
		{
			public PlayerRef Ref;

			public HashSet<string> Channels = new HashSet<string>();
		}

		private sealed class SpanBuffer : IDisposable
		{
			private static IntPtr spanClass;

			private static int pointerOffset = -1;

			private static int lengthOffset = -1;

			private readonly Il2CppStructArray<byte> array;

			public ReadOnlySpan<byte> Span { get; }

			public SpanBuffer(byte[] data)
			{
				if (pointerOffset < 0)
				{
					ResolveLayout();
				}
				array = new Il2CppStructArray<byte>(data);
				IntPtr intPtr = IL2CPP.il2cpp_object_new(spanClass);
				Marshal.WriteIntPtr(intPtr + pointerOffset, ((Il2CppObjectBase)array).Pointer + 4 * IntPtr.Size);
				Marshal.WriteInt32(intPtr + lengthOffset, data.Length);
				Span = new ReadOnlySpan<byte>(intPtr);
			}

			private static void ResolveLayout()
			{
				spanClass = Il2CppClassPointerStore<ReadOnlySpan<byte>>.NativeClassPtr;
				if (spanClass == IntPtr.Zero)
				{
					throw new Exception("Couldn't resolve ReadOnlySpan<byte> class");
				}
				(pointerOffset, lengthOffset) = NetReceiveHook.SpanLayout(spanClass);
			}

			public void Dispose()
			{
				GC.KeepAlive(array);
			}
		}

		internal const int Magic = 1330923587;

		private const int ProtocolVersion = 1;

		private const int MaxHellos = 6;

		private static readonly Dictionary<string, Channel> channels = new Dictionary<string, Channel>();

		private static readonly Dictionary<int, Peer> peers = new Dictionary<int, Peer>();

		private static HashSet<string> hostChannels;

		private static IntPtr lastRunner;

		private static int hellosSent;

		private static int lastTickFrame = -1;

		private static int runnerFrame = -1;

		private static NetworkRunner runnerThisFrame;

		private static bool helloTriggers;

		public static NetworkRunner Runner
		{
			get
			{
				int frameCount = Time.frameCount;
				if (frameCount != runnerFrame)
				{
					runnerFrame = frameCount;
					runnerThisFrame = FindRunner();
				}
				return runnerThisFrame;
			}
		}

		public static bool IsAuthority
		{
			get
			{
				NetworkRunner runner = Runner;
				if (runner != null)
				{
					return runner.IsServer;
				}
				return true;
			}
		}

		public static event Action SessionReset;

		public static event Action<int> PlayerLeft;

		public static event Action<PlayerRef> PlayerReady;

		public static event Action HostReady;

		private static NetworkRunner FindRunner()
		{
			//IL_002b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0031: Invalid comparison between Unknown and I4
			try
			{
				OverlandNetworkRunner instance = OverlandNetworkRunner.Instance;
				NetworkRunner val = (((Object)(object)instance != (Object)null) ? instance.NetworkRunner : null);
				return ((Object)(object)val != (Object)null && val.IsRunning && (int)val.GameMode != 1) ? val : null;
			}
			catch
			{
				return null;
			}
		}

		public static bool HostHas(string channel)
		{
			if (hostChannels != null)
			{
				return hostChannels.Contains(channel);
			}
			return false;
		}

		public static bool PlayerHas(int playerId, string channel)
		{
			if (peers.TryGetValue(playerId, out var value))
			{
				return value.Channels.Contains(channel);
			}
			return false;
		}

		public static void Register<T>(string channel, Action<NetworkRunner, PlayerRef, T> handler) where T : class
		{
			NetReceiveHook.Install();
			InstallHelloTriggers();
			channels[channel] = new Channel
			{
				Handler = delegate(NetworkRunner runner, PlayerRef from, string json)
				{
					//IL_0041: Unknown result type (might be due to invalid IL or missing references)
					T val;
					try
					{
						val = JsonSerializer.Deserialize<T>(json);
					}
					catch (Exception ex)
					{
						Core.Log.Warning("Bad " + channel + " message: " + ex.Message);
						return;
					}
					if (val != null)
					{
						handler(runner, from, val);
					}
				}
			};
		}

		public static void Tick()
		{
			if (!Core.Quitting && Time.frameCount != lastTickFrame)
			{
				lastTickFrame = Time.frameCount;
				CheckSession(Runner);
			}
		}

		private static void CheckSession(NetworkRunner runner)
		{
			IntPtr intPtr = (((Object)(object)runner != (Object)null) ? ((Il2CppObjectBase)runner).Pointer : IntPtr.Zero);
			if (intPtr == lastRunner)
			{
				return;
			}
			lastRunner = intPtr;
			peers.Clear();
			hostChannels = null;
			hellosSent = 0;
			Delegate[] array = HillNet.SessionReset?.GetInvocationList() ?? Array.Empty<Delegate>();
			foreach (Delegate obj in array)
			{
				try
				{
					((Action)obj)();
				}
				catch (Exception ex)
				{
					Core.Log.Error(ex.ToString());
				}
			}
			SayHello(runner);
		}

		private static void SayHello(NetworkRunner runner)
		{
			if (!((Object)(object)runner == (Object)null) && !runner.IsServer && hostChannels == null && channels.Count != 0 && hellosSent < 6)
			{
				Send(runner, null, new Envelope
				{
					T = "hello",
					Channels = channels.Keys.ToList()
				});
				if (++hellosSent == 3)
				{
					Core.Log.Msg("Host doesn't seem to have Over the Hill mods; host-side features are off until it answers.");
				}
			}
		}

		private static void InstallHelloTriggers()
		{
			if (helloTriggers)
			{
				return;
			}
			helloTriggers = true;
			Tracking.Cars.Added += delegate(VehicleBase car)
			{
				NetworkObject val = ((SimulationBehaviour)car).Object;
				if ((Object)(object)val != (Object)null && val.HasInputAuthority)
				{
					SayHello(Runner);
				}
			};
			PlayerLeftHook.Install();
		}

		internal static void OnPlayerLeft(int playerId)
		{
			if (!Core.Quitting)
			{
				RemovePeer(playerId);
			}
		}

		private static void RemovePeer(int id)
		{
			if (!peers.Remove(id))
			{
				return;
			}
			Delegate[] array = HillNet.PlayerLeft?.GetInvocationList() ?? Array.Empty<Delegate>();
			foreach (Delegate obj in array)
			{
				try
				{
					((Action<int>)obj)(id);
				}
				catch (Exception ex)
				{
					Core.Log.Error(ex.ToString());
				}
			}
		}

		public static void SendToHost(string channel, object msg)
		{
			NetworkRunner runner = Runner;
			if ((Object)(object)runner != (Object)null)
			{
				Send(runner, null, Wrap(channel, msg));
			}
		}

		public static void SendTo(PlayerRef p, string channel, object msg)
		{
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			NetworkRunner runner = Runner;
			if ((Object)(object)runner != (Object)null)
			{
				Send(runner, p, Wrap(channel, msg));
			}
		}

		public static void Broadcast(string channel, object msg, int exceptPlayerId = int.MinValue)
		{
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0078: Unknown result type (might be due to invalid IL or missing references)
			NetworkRunner runner = Runner;
			if ((Object)(object)runner == (Object)null || !runner.IsServer || peers.Count == 0)
			{
				return;
			}
			Envelope envelope = null;
			foreach (var (num2, peer2) in peers)
			{
				if (num2 != exceptPlayerId && peer2.Channels.Contains(channel) && runner.IsPlayerValid(peer2.Ref))
				{
					if (envelope == null)
					{
						envelope = Wrap(channel, msg);
					}
					Send(runner, peer2.Ref, envelope);
				}
			}
		}

		private static Envelope Wrap(string channel, object msg)
		{
			return new Envelope
			{
				T = "msg",
				C = channel,
				J = JsonSerializer.Serialize(msg, msg.GetType())
			};
		}

		private static void Send(NetworkRunner r, PlayerRef? to, Envelope env)
		{
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			//IL_002c: Unknown result type (might be due to invalid IL or missing references)
			//IL_004f: 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_003f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0040: Unknown result type (might be due to invalid IL or missing references)
			if (Core.Quitting)
			{
				return;
			}
			using SpanBuffer spanBuffer = new SpanBuffer(Encoding.UTF8.GetBytes(JsonSerializer.Serialize(env)));
			ReliableKey val = ReliableKey.FromInts(1330923587, 1, 0, 0);
			if (to.HasValue)
			{
				PlayerRef valueOrDefault = to.GetValueOrDefault();
				r.SendReliableDataToPlayer(valueOrDefault, val, spanBuffer.Span);
			}
			else
			{
				r.SendReliableDataToServer(val, spanBuffer.Span);
			}
		}

		internal static void OnReceive(NetworkRunner runner, PlayerRef from, int version, byte[] data)
		{
			//IL_01cf: 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_00e3: Unknown result type (might be due to invalid IL or missing references)
			//IL_0170: Unknown result type (might be due to invalid IL or missing references)
			//IL_02c7: Unknown result type (might be due to invalid IL or missing references)
			if (Core.Quitting)
			{
				return;
			}
			if (version != 1)
			{
				Core.Log.Warning($"Ignoring mod message from player {((PlayerRef)(ref from)).PlayerId}: different JoofOTHFramework version");
				return;
			}
			CheckSession(runner);
			Envelope envelope;
			try
			{
				envelope = JsonSerializer.Deserialize<Envelope>(Encoding.UTF8.GetString(data));
			}
			catch (Exception ex)
			{
				Core.Log.Warning("Bad mod message: " + ex.Message);
				return;
			}
			if (envelope == null)
			{
				return;
			}
			switch (envelope.T)
			{
			case "hello":
			{
				if (!runner.IsServer)
				{
					break;
				}
				peers[((PlayerRef)(ref from)).PlayerId] = new Peer
				{
					Ref = from,
					Channels = new HashSet<string>(envelope.Channels ?? new List<string>())
				};
				Core.Log.Msg($"Player {((PlayerRef)(ref from)).PlayerId} has: {string.Join(", ", peers[((PlayerRef)(ref from)).PlayerId].Channels)}");
				Send(runner, from, new Envelope
				{
					T = "welcome",
					Channels = channels.Keys.ToList()
				});
				Delegate[] array = HillNet.PlayerReady?.GetInvocationList() ?? Array.Empty<Delegate>();
				foreach (Delegate obj in array)
				{
					try
					{
						((Action<PlayerRef>)obj)(from);
					}
					catch (Exception ex2)
					{
						Core.Log.Error(ex2.ToString());
					}
				}
				break;
			}
			case "welcome":
			{
				if (runner.IsServer)
				{
					break;
				}
				hostChannels = new HashSet<string>(envelope.Channels ?? new List<string>());
				Core.Log.Msg("Host has: " + string.Join(", ", hostChannels));
				Delegate[] array = HillNet.HostReady?.GetInvocationList() ?? Array.Empty<Delegate>();
				foreach (Delegate obj2 in array)
				{
					try
					{
						((Action)obj2)();
					}
					catch (Exception ex3)
					{
						Core.Log.Error(ex3.ToString());
					}
				}
				break;
			}
			case "msg":
			{
				if (envelope.C != null && envelope.J != null && channels.TryGetValue(envelope.C, out var value))
				{
					value.Handler(runner, from, envelope.J);
				}
				break;
			}
			}
		}
	}
	internal static class NetReceiveHook
	{
		private struct NativeKey
		{
			public int K0;

			public int K1;

			public int K2;

			public int K3;
		}

		private struct NativeSpan
		{
			public IntPtr W0;

			public long W1;
		}

		[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
		private delegate void d_OnReliableDataReceived(IntPtr self, IntPtr runner, int player, NativeKey key, NativeSpan data, IntPtr method);

		private static d_OnReliableDataReceived original;

		private static bool pointerFirst = true;

		internal static void Install()
		{
			if (original == null)
			{
				(int pointer, int length) tuple = SpanLayout(Il2CppClassPointerStore<ReadOnlySpan<byte>>.NativeClassPtr);
				int item = tuple.pointer;
				int item2 = tuple.length;
				pointerFirst = item < item2;
				original = Patches.Native<d_OnReliableDataReceived>(Patches.NativePointer(Patches.Method(typeof(OverlandNetworkRunner), "OnReliableDataReceived")), OnReliableDataReceived);
				Core.Log.Msg("Hooked network receive (span pointer " + (pointerFirst ? "first" : "second") + ")");
			}
		}

		internal static (int pointer, int length) SpanLayout(IntPtr spanClass)
		{
			int num = -1;
			int num2 = -1;
			IntPtr zero = IntPtr.Zero;
			IntPtr intPtr;
			while ((intPtr = IL2CPP.il2cpp_class_get_fields(spanClass, ref zero)) != IntPtr.Zero)
			{
				string text = Marshal.PtrToStringAnsi(IL2CPP.il2cpp_field_get_name(intPtr));
				int num3 = (int)IL2CPP.il2cpp_field_get_offset(intPtr);
				switch (text)
				{
				case "_length":
					num2 = num3;
					break;
				case "_pointer":
				case "_reference":
					num = num3;
					break;
				}
			}
			if (num < 0 || num2 < 0)
			{
				throw new Exception($"Unexpected ReadOnlySpan layout (ptr {num}, len {num2})");
			}
			return (pointer: num, length: num2);
		}

		private static void OnReliableDataReceived(IntPtr self, IntPtr runner, int player, NativeKey key, NativeSpan data, IntPtr method)
		{
			//IL_005d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0064: Unknown result type (might be due to invalid IL or missing references)
			//IL_0072: Unknown result type (might be due to invalid IL or missing references)
			//IL_007f: Expected O, but got Unknown
			try
			{
				if (key.K0 == 1330923587)
				{
					IntPtr source = (pointerFirst ? data.W0 : ((IntPtr)data.W1));
					int num = (int)(pointerFirst ? data.W1 : ((long)data.W0));
					byte[] array = new byte[num];
					if (num > 0)
					{
						Marshal.Copy(source, array, 0, num);
					}
					HillNet.OnReceive(new NetworkRunner(runner), new PlayerRef
					{
						Raw = player
					}, key.K1, array);
					return;
				}
			}
			catch (Exception ex)
			{
				Core.Log.Error(ex.ToString());
				if (key.K0 == 1330923587)
				{
					return;
				}
			}
			original(self, runner, player, key, data, method);
		}
	}
	internal static class PlayerLeftHook
	{
		private static bool installed;

		internal static void Install()
		{
			if (!installed)
			{
				installed = true;
				Patches.Apply(Patches.Method(typeof(OverlandNetworkRunner), "Fusion_INetworkRunnerCallbacks_OnPlayerLeft"), typeof(PlayerLeftHook));
			}
		}

		private static void Postfix(PlayerRef player)
		{
			try
			{
				HillNet.OnPlayerLeft(((PlayerRef)(ref player)).PlayerId);
			}
			catch (Exception ex)
			{
				Core.Log.Error(ex.ToString());
			}
		}
	}
	public static class Core
	{
		[CompilerGenerated]
		private static class <>O
		{
			public static LemonAction <0>__OnDefiniteQuit;
		}

		internal static readonly Instance Log = new Instance("JoofOTHFramework");

		private static MelonPreferences_Entry<int> quitWatchdogSeconds;

		public static bool Quitting { get; private set; }

		public static event Action DiagnosticsRequested;

		[ModuleInitializer]
		internal static void Init()
		{
			//IL_003a: Unknown result type (might be due to invalid IL or missing references)
			//IL_003f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0045: Expected O, but got Unknown
			quitWatchdogSeconds = MelonPreferences.CreateCategory("JoofOTHFramework").CreateEntry<int>("QuitWatchdogSeconds", 30, (string)null, "The game can hang on exit under Proton after everything is saved. If it is still running this many seconds after quitting, end it. 0 = never.", false, false, (ValueValidator)null, (string)null);
			MelonEvent onApplicationDefiniteQuit = MelonEvents.OnApplicationDefiniteQuit;
			object obj = <>O.<0>__OnDefiniteQuit;
			if (obj == null)
			{
				LemonAction val = OnDefiniteQuit;
				<>O.<0>__OnDefiniteQuit = val;
				obj = (object)val;
			}
			((MelonEventBase<LemonAction>)(object)onApplicationDefiniteQuit).Subscribe((LemonAction)obj, 0, false);
		}

		public static void RequestDiagnostics()
		{
			Delegate[] array = Core.DiagnosticsRequested?.GetInvocationList() ?? Array.Empty<Delegate>();
			foreach (Delegate obj in array)
			{
				try
				{
					((Action)obj)();
				}
				catch (Exception ex)
				{
					Log.Error(ex.ToString());
				}
			}
		}

		private static void OnDefiniteQuit()
		{
			Quitting = true;
			Patches.DetachNative();
			StartQuitWatchdog(quitWatchdogSeconds?.Value ?? 0);
		}

		private static void StartQuitWatchdog(int seconds)
		{
			if (seconds > 0)
			{
				Thread thread = new Thread((ThreadStart)delegate
				{
					Thread.Sleep(TimeSpan.FromSeconds(seconds));
					Log.Warning($"Still running {seconds} s after quitting; ending the process (QuitWatchdogSeconds)");
					Process.GetCurrentProcess().Kill();
				});
				thread.IsBackground = true;
				thread.Name = "JoofOTHFramework quit watchdog";
				thread.Start();
			}
		}
	}
	public static class Patches
	{
		private static readonly Harmony harmony = new Harmony("JoofOTHFramework");

		private static readonly List<object> keepAlive = new List<object>();

		private static readonly List<Action> detachers = new List<Action>();

		internal static void Apply(MethodBase target, Type patches)
		{
			//IL_002c: 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)
			MethodInfo method = patches.GetMethod("Prefix", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
			MethodInfo method2 = patches.GetMethod("Postfix", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
			harmony.Patch(target, (method == null) ? ((HarmonyMethod)null) : new HarmonyMethod(method), (method2 == null) ? ((HarmonyMethod)null) : new HarmonyMethod(method2), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
		}

		internal static void Apply(MethodBase target, HarmonyMethod prefix, HarmonyMethod postfix)
		{
			harmony.Patch(target, prefix, postfix, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
		}

		internal static T Native<T>(IntPtr target, T detour) where T : Delegate
		{
			if (Core.Quitting)
			{
				return Marshal.GetDelegateForFunctionPointer<T>(target);
			}
			NativeHook<T> hook = new NativeHook<T>(target, Marshal.GetFunctionPointerForDelegate(detour));
			hook.Attach();
			detachers.Add(delegate
			{
				if (hook.IsHooked)
				{
					hook.Detach();
				}
			});
			keepAlive.Add(detour);
			keepAlive.Add(hook);
			return hook.Trampoline;
		}

		internal static void DetachNative()
		{
			foreach (Action detacher in detachers)
			{
				try
				{
					detacher();
				}
				catch (Exception ex)
				{
					Core.Log.Error("Detaching a hook: " + ex.Message);
				}
			}
			detachers.Clear();
		}

		public static MethodInfo Method(Type type, string name, Type[] args = null)
		{
			return ((args != null) ? type.GetMethod(name, args) : type.GetMethod(name)) ?? throw new MissingMethodException(type.FullName, name);
		}

		internal static IntPtr NativePointer(MethodBase method)
		{
			return Marshal.ReadIntPtr((IntPtr)Il2CppInteropUtils.GetIl2CppMethodInfoPointerFieldForGeneratedMethod(method).GetValue(null));
		}
	}
	public static class Tracking
	{
		public static readonly Tracked<VehicleBase> Cars = new Tracked<VehicleBase>((IntPtr p) => new VehicleBase(p), delegate(Tracked<VehicleBase> t)
		{
			Lifecycle.After(typeof(VehicleBase), "Spawned", t.Add);
		});

		public static readonly Tracked<VehicleWinchSystem> Winches = new Tracked<VehicleWinchSystem>((IntPtr p) => new VehicleWinchSystem(p), delegate(Tracked<VehicleWinchSystem> t)
		{
			Lifecycle.After(typeof(VehicleWinchSystem), "Spawned", t.Add);
			Lifecycle.Despawned(typeof(VehicleWinchSystem), t.Remove);
			Lifecycle.After(typeof(VehicleWinchSystem), "OnDestroy", t.Remove);
		});

		public static readonly Tracked<AnimalAI_Simple> Animals = new Tracked<AnimalAI_Simple>((IntPtr p) => new AnimalAI_Simple(p), delegate(Tracked<AnimalAI_Simple> t)
		{
			Lifecycle.After(typeof(AnimalAI_Simple), "Awake", t.Add);
			Lifecycle.After(typeof(AnimalAI_Simple), "OnDestroy", t.Remove);
		});

		private static Action<int> playerMoved;

		public static event Action<int> PlayerMoved
		{
			add
			{
				Teleports.Install();
				playerMoved = (Action<int>)Delegate.Combine(playerMoved, value);
			}
			remove
			{
				playerMoved = (Action<int>)Delegate.Remove(playerMoved, value);
			}
		}

		internal static void RaisePlayerMoved(int playerId)
		{
			if (playerMoved == null || Core.Quitting)
			{
				return;
			}
			Delegate[] invocationList = playerMoved.GetInvocationList();
			foreach (Delegate obj in invocationList)
			{
				try
				{
					((Action<int>)obj)(playerId);
				}
				catch (Exception ex)
				{
					Core.Log.Error(ex.ToString());
				}
			}
		}
	}
	internal static class Teleports
	{
		private static class JackPatch
		{
			private static void Postfix(PlayerRef playerRef)
			{
				try
				{
					Moved(((PlayerRef)(ref playerRef)).PlayerId);
				}
				catch (Exception ex)
				{
					Core.Log.Error(ex.ToString());
				}
			}
		}

		private static bool installed;

		private static readonly Dictionary<int, int> lastFrame = new Dictionary<int, int>();

		internal static void Install()
		{
			if (!installed)
			{
				installed = true;
				Action<PlayerRef> val = DelegateSupport.ConvertDelegate<Action<PlayerRef>>((Delegate)(Action<PlayerRef>)delegate(PlayerRef p)
				{
					Moved(((PlayerRef)(ref p)).PlayerId);
				});
				Action<PlayerRef> playerTeleported = OverlandSessionPlayers.PlayerTeleported;
				OverlandSessionPlayers.PlayerTeleported = (((Delegate)(object)playerTeleported == (Delegate)null) ? val : ((Il2CppObjectBase)Delegate.Combine((Delegate)(object)playerTeleported, (Delegate)(object)val)).Cast<Action<PlayerRef>>());
				Patches.Apply(Patches.Method(typeof(MapNetworkManager), "RPC_PortableJackTeleport", new Type[3]
				{
					typeof(PlayerRef),
					typeof(Vector3),
					typeof(Quaternion)
				}), typeof(JackPatch));
				Core.Log.Msg("Hooked teleports");
			}
		}

		private static void Moved(int playerId)
		{
			if (!Core.Quitting)
			{
				int frameCount = Time.frameCount;
				if (!lastFrame.TryGetValue(playerId, out var value) || value != frameCount)
				{
					lastFrame[playerId] = frameCount;
					Tracking.RaisePlayerMoved(playerId);
				}
			}
		}
	}
	public sealed class Tracked<T> where T : Object
	{
		private readonly Func<IntPtr, T> wrap;

		private readonly Action<Tracked<T>> install;

		private readonly List<T> items = new List<T>();

		private readonly HashSet<IntPtr> pointers = new HashSet<IntPtr>();

		private Action<T> added;

		private Action<T> removed;

		private bool installed;

		public IReadOnlyList<T> Items
		{
			get
			{
				Install();
				Prune();
				return items;
			}
		}

		public event Action<T> Added
		{
			add
			{
				Install();
				Prune();
				T[] array = items.ToArray();
				foreach (T o in array)
				{
					Safe(value, o);
				}
				added = (Action<T>)Delegate.Combine(added, value);
			}
			remove
			{
				added = (Action<T>)Delegate.Remove(added, value);
			}
		}

		public event Action<T> Removed
		{
			add
			{
				Install();
				removed = (Action<T>)Delegate.Combine(removed, value);
			}
			remove
			{
				removed = (Action<T>)Delegate.Remove(removed, value);
			}
		}

		internal Tracked(Func<IntPtr, T> wrap, Action<Tracked<T>> install)
		{
			this.wrap = wrap;
			this.install = install;
		}

		private void Install()
		{
			if (!installed)
			{
				installed = true;
				install(this);
			}
		}

		internal void Add(IntPtr p)
		{
			if (pointers.Add(p))
			{
				T val = wrap(p);
				items.Add(val);
				Raise(added, val);
			}
		}

		internal void Remove(IntPtr p)
		{
			if (!pointers.Remove(p))
			{
				return;
			}
			for (int num = items.Count - 1; num >= 0; num--)
			{
				if (!(((Il2CppObjectBase)(object)items[num]).Pointer != p))
				{
					T o = items[num];
					items.RemoveAt(num);
					Raise(removed, o);
					break;
				}
			}
		}

		private void Prune()
		{
			for (int num = items.Count - 1; num >= 0; num--)
			{
				if (!((Object)(object)items[num] != (Object)null))
				{
					T val = items[num];
					pointers.Remove(((Il2CppObjectBase)(object)val).Pointer);
					items.RemoveAt(num);
					Raise(removed, val);
				}
			}
		}

		private static void Raise(Action<T> handlers, T o)
		{
			if (handlers != null)
			{
				Delegate[] invocationList = handlers.GetInvocationList();
				for (int i = 0; i < invocationList.Length; i++)
				{
					Safe((Action<T>)invocationList[i], o);
				}
			}
		}

		private static void Safe(Action<T> handler, T o)
		{
			try
			{
				handler(o);
			}
			catch (Exception ex)
			{
				Core.Log.Error(ex.ToString());
			}
		}
	}
	internal static class Lifecycle
	{
		private sealed class Hook
		{
			public readonly List<(IntPtr Class, Action<IntPtr> Run)> Handlers = new List<(IntPtr, Action<IntPtr>)>();
		}

		private static readonly Dictionary<IntPtr, Hook> hooks = new Dictionary<IntPtr, Hook>();

		private static readonly Dictionary<MethodBase, IntPtr> natives = new Dictionary<MethodBase, IntPtr>();

		internal static void After(Type type, string method, Action<IntPtr> handler)
		{
			//IL_001e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0029: Expected O, but got Unknown
			Add(type, Patches.Method(type, method, Type.EmptyTypes), handler, new HarmonyMethod(typeof(Lifecycle), "AfterPostfix", (Type[])null), null);
		}

		internal static void Despawned(Type type, Action<IntPtr> handler)
		{
			//IL_003e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0048: Expected O, but got Unknown
			Add(type, Patches.Method(type, "Despawned", new Type[2]
			{
				typeof(NetworkRunner),
				typeof(bool)
			}), handler, null, new HarmonyMethod(typeof(Lifecycle), "BeforePrefix", (Type[])null));
		}

		private static void Add(Type type, MethodInfo method, Action<IntPtr> handler, HarmonyMethod postfix, HarmonyMethod prefix)
		{
			IntPtr nativeClassPointer = Il2CppClassPointerStore.GetNativeClassPointer(type);
			if (nativeClassPointer == IntPtr.Zero)
			{
				throw new Exception("No IL2CPP class for " + type.FullName);
			}
			IntPtr intPtr = Patches.NativePointer(method);
			if (!hooks.TryGetValue(intPtr, out var value))
			{
				value = (hooks[intPtr] = new Hook());
				natives[method] = intPtr;
				Patches.Apply(method, prefix, postfix);
			}
			value.Handlers.Add((nativeClassPointer, handler));
		}

		private static void AfterPostfix(MethodBase __originalMethod, Il2CppObjectBase __instance)
		{
			Dispatch(__originalMethod, __instance);
		}

		private static void BeforePrefix(MethodBase __originalMethod, Il2CppObjectBase __instance)
		{
			Dispatch(__originalMethod, __instance);
		}

		private static void Dispatch(MethodBase method, Il2CppObjectBase instance)
		{
			if (Core.Quitting || instance == null || !natives.TryGetValue(method, out var value) || !hooks.TryGetValue(value, out var value2))
			{
				return;
			}
			IntPtr pointer = instance.Pointer;
			if (pointer == IntPtr.Zero)
			{
				return;
			}
			IntPtr intPtr = IL2CPP.il2cpp_object_get_class(pointer);
			foreach (var (intPtr2, action) in value2.Handlers)
			{
				if (IL2CPP.il2cpp_class_is_assignable_from(intPtr2, intPtr))
				{
					try
					{
						action(pointer);
					}
					catch (Exception ex)
					{
						Core.Log.Error(ex.ToString());
					}
				}
			}
		}
	}
	public static class WinchHooks
	{
		public delegate int AnchorsHandler(VehicleWinchSystem winch, Transform winchPoint, bool filterByCamera, Vector3 cameraForward);

		private static class TickPatch
		{
			private static void Prefix(VehicleWinchSystem __instance)
			{
				Run(beforeTick, __instance);
			}

			private static void Postfix(VehicleWinchSystem __instance)
			{
				Run(afterTick, __instance);
			}
		}

		private static class GatherPatch
		{
			private static void Postfix(VehicleWinchSystem __instance, Transform winchPoint, bool filterByCameraForwardDirection, Vector3 cameraForward)
			{
				//IL_0003: Unknown result type (might be due to invalid IL or missing references)
				AddAnchors(__instance, winchPoint, filterByCameraForwardDirection, cameraForward);
			}
		}

		private static class UpdatePatch
		{
			private static void Postfix(VehicleWinchSystem __instance, Transform winchPoint, bool filterByCameraForwardDirection, Vector3 cameraForward, ref int __result)
			{
				//IL_0008: Unknown result type (might be due to invalid IL or missing references)
				__result += AddAnchors(__instance, winchPoint, filterByCameraForwardDirection, cameraForward);
			}
		}

		private static Action<VehicleWinchSystem> beforeTick;

		private static Action<VehicleWinchSystem> afterTick;

		private static AnchorsHandler anchorsGathered;

		private static bool tickInstalled;

		private static bool anchorsInstalled;

		public static event Action<VehicleWinchSystem> BeforeTick
		{
			add
			{
				InstallTick();
				beforeTick = (Action<VehicleWinchSystem>)Delegate.Combine(beforeTick, value);
			}
			remove
			{
				beforeTick = (Action<VehicleWinchSystem>)Delegate.Remove(beforeTick, value);
			}
		}

		public static event Action<VehicleWinchSystem> AfterTick
		{
			add
			{
				InstallTick();
				afterTick = (Action<VehicleWinchSystem>)Delegate.Combine(afterTick, value);
			}
			remove
			{
				afterTick = (Action<VehicleWinchSystem>)Delegate.Remove(afterTick, value);
			}
		}

		public static event AnchorsHandler AnchorsGathered
		{
			add
			{
				InstallAnchors();
				anchorsGathered = (AnchorsHandler)Delegate.Combine(anchorsGathered, value);
			}
			remove
			{
				anchorsGathered = (AnchorsHandler)Delegate.Remove(anchorsGathered, value);
			}
		}

		private static void InstallTick()
		{
			if (!tickInstalled)
			{
				tickInstalled = true;
				Patches.Apply(Patches.Method(typeof(VehicleWinchSystem), "FixedUpdateNetwork"), typeof(TickPatch));
				Core.Log.Msg("Hooked winch tick");
			}
		}

		private static void InstallAnchors()
		{
			if (!anchorsInstalled)
			{
				anchorsInstalled = true;
				Patches.Apply(Patches.Method(typeof(VehicleWinchSystem), "GatherPotentialAnchorPoints"), typeof(GatherPatch));
				Patches.Apply(Patches.Method(typeof(VehicleWinchSystem), "UpdatePotentialAnchorPoints"), typeof(UpdatePatch));
				Core.Log.Msg("Hooked winch anchor search");
			}
		}

		private static void Run(Action<VehicleWinchSystem> handlers, VehicleWinchSystem w)
		{
			if (handlers == null || Core.Quitting)
			{
				return;
			}
			Delegate[] invocationList = handlers.GetInvocationList();
			foreach (Delegate obj in invocationList)
			{
				try
				{
					((Action<VehicleWinchSystem>)obj)(w);
				}
				catch (Exception ex)
				{
					Core.Log.Error(ex.ToString());
				}
			}
		}

		private static int AddAnchors(VehicleWinchSystem w, Transform winchPoint, bool filter, Vector3 cameraForward)
		{
			//IL_0038: Unknown result type (might be due to invalid IL or missing references)
			AnchorsHandler anchorsHandler = anchorsGathered;
			if (anchorsHandler == null || (Object)(object)winchPoint == (Object)null || Core.Quitting)
			{
				return 0;
			}
			int num = 0;
			Delegate[] invocationList = anchorsHandler.GetInvocationList();
			foreach (Delegate obj in invocationList)
			{
				try
				{
					num += ((AnchorsHandler)obj)(w, winchPoint, filter, cameraForward);
				}
				catch (Exception ex)
				{
					Core.Log.Error(ex.ToString());
				}
			}
			return num;
		}
	}
}