Decompiled source of KeepItemsOnTeleport v1.0.2

KeepItemsOnTeleport.dll

Decompiled 2 weeks ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using GameNetcodeStuff;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using Unity.Collections;
using Unity.Netcode;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("KeepItemsOnTeleport")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.2.0")]
[assembly: AssemblyInformationalVersion("1.0.2+81ea212d4f3d3e19a8c6800206e00d1645bd373a")]
[assembly: AssemblyProduct("KeepItemsOnTeleport")]
[assembly: AssemblyTitle("KeepItemsOnTeleport")]
[assembly: AssemblyMetadata("AI_Assisted_Creation", "true")]
[assembly: AssemblyMetadata("AI_Model_Vendor", "AI coding agent")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.0.2.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

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

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

		public NullableContextAttribute(byte P_0)
		{
			Flag = P_0;
		}
	}
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace KeepItemsOnTeleport
{
	internal static class HostModGate
	{
		[CompilerGenerated]
		private static class <>O
		{
			public static HandleNamedMessageDelegate <0>__OnMessage;

			public static Action<ulong> <1>__OnClientConnected;
		}

		public const string MessageName = "MrGlim.KeepItemsOnTeleport";

		private const byte OpHostHello = 0;

		private const byte OpClientSyncRequest = 1;

		private static bool _registered;

		private static bool _clientConnectedHooked;

		private static bool _requestedSync;

		private static bool _clientHostEnabled;

		private static bool _clientKeepNormal = true;

		private static bool _clientKeepInverse = true;

		public static bool HostHasMod
		{
			get
			{
				EnsureRegistered();
				NetworkManager singleton = NetworkManager.Singleton;
				if ((Object)(object)singleton == (Object)null)
				{
					return true;
				}
				if (singleton.IsServer || singleton.IsHost)
				{
					if (Plugin.Enabled != null)
					{
						return Plugin.Enabled.Value;
					}
					return false;
				}
				return _clientHostEnabled;
			}
		}

		public static bool FeaturesActive => HostHasMod;

		public static bool KeepOnNormal
		{
			get
			{
				EnsureRegistered();
				NetworkManager singleton = NetworkManager.Singleton;
				if ((Object)(object)singleton == (Object)null || singleton.IsServer || singleton.IsHost)
				{
					if (Plugin.KeepOnNormalTeleporter != null)
					{
						return Plugin.KeepOnNormalTeleporter.Value;
					}
					return false;
				}
				return _clientKeepNormal;
			}
		}

		public static bool KeepOnInverse
		{
			get
			{
				EnsureRegistered();
				NetworkManager singleton = NetworkManager.Singleton;
				if ((Object)(object)singleton == (Object)null || singleton.IsServer || singleton.IsHost)
				{
					if (Plugin.KeepOnInverseTeleporter != null)
					{
						return Plugin.KeepOnInverseTeleporter.Value;
					}
					return false;
				}
				return _clientKeepInverse;
			}
		}

		public static void Reset()
		{
			_registered = false;
			_clientConnectedHooked = false;
			_requestedSync = false;
			_clientHostEnabled = false;
			_clientKeepNormal = true;
			_clientKeepInverse = true;
		}

		public static void EnsureRegistered()
		{
			//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_0049: Expected O, but got Unknown
			NetworkManager singleton = NetworkManager.Singleton;
			if ((Object)(object)singleton == (Object)null)
			{
				_registered = false;
				_clientConnectedHooked = false;
				return;
			}
			if (!_registered)
			{
				CustomMessagingManager customMessagingManager = singleton.CustomMessagingManager;
				object obj = <>O.<0>__OnMessage;
				if (obj == null)
				{
					HandleNamedMessageDelegate val = OnMessage;
					<>O.<0>__OnMessage = val;
					obj = (object)val;
				}
				customMessagingManager.RegisterNamedMessageHandler("MrGlim.KeepItemsOnTeleport", (HandleNamedMessageDelegate)obj);
				_registered = true;
				Plugin.Log.LogInfo((object)"MrGlim.KeepItemsOnTeleport net handler registered.");
			}
			if (singleton.IsServer && !_clientConnectedHooked)
			{
				singleton.OnClientConnectedCallback += OnClientConnected;
				_clientConnectedHooked = true;
			}
			if (!singleton.IsServer && singleton.IsConnectedClient && !_requestedSync)
			{
				_requestedSync = true;
				RequestSync();
			}
		}

		private static void OnClientConnected(ulong clientId)
		{
			NetworkManager singleton = NetworkManager.Singleton;
			if (!((Object)(object)singleton == (Object)null) && singleton.IsServer && clientId != singleton.LocalClientId)
			{
				SendHello(clientId);
			}
		}

		private static void RequestSync()
		{
			//IL_002b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0031: Unknown result type (might be due to invalid IL or missing references)
			//IL_0044: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager singleton = NetworkManager.Singleton;
			if (!((Object)(object)singleton == (Object)null) && !singleton.IsServer)
			{
				FastBufferWriter val = default(FastBufferWriter);
				((FastBufferWriter)(ref val))..ctor(16, (Allocator)2, -1);
				byte b = 1;
				((FastBufferWriter)(ref val)).WriteValueSafe<byte>(ref b, default(ForPrimitives));
				singleton.CustomMessagingManager.SendNamedMessage("MrGlim.KeepItemsOnTeleport", 0uL, val, (NetworkDelivery)2);
				((FastBufferWriter)(ref val)).Dispose();
			}
		}

		private static void SendHello(ulong clientId)
		{
			//IL_006b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0071: 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_0084: Unknown result type (might be due to invalid IL or missing references)
			//IL_0091: Unknown result type (might be due to invalid IL or missing references)
			//IL_0097: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00aa: 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)
			NetworkManager singleton = NetworkManager.Singleton;
			if (!((Object)(object)singleton == (Object)null) && singleton.IsServer)
			{
				bool flag = Plugin.Enabled != null && Plugin.Enabled.Value;
				bool flag2 = Plugin.KeepOnNormalTeleporter != null && Plugin.KeepOnNormalTeleporter.Value;
				bool flag3 = Plugin.KeepOnInverseTeleporter != null && Plugin.KeepOnInverseTeleporter.Value;
				FastBufferWriter val = default(FastBufferWriter);
				((FastBufferWriter)(ref val))..ctor(32, (Allocator)2, -1);
				byte b = 0;
				((FastBufferWriter)(ref val)).WriteValueSafe<byte>(ref b, default(ForPrimitives));
				((FastBufferWriter)(ref val)).WriteValueSafe<bool>(ref flag, default(ForPrimitives));
				((FastBufferWriter)(ref val)).WriteValueSafe<bool>(ref flag2, default(ForPrimitives));
				((FastBufferWriter)(ref val)).WriteValueSafe<bool>(ref flag3, default(ForPrimitives));
				singleton.CustomMessagingManager.SendNamedMessage("MrGlim.KeepItemsOnTeleport", clientId, val, (NetworkDelivery)2);
				((FastBufferWriter)(ref val)).Dispose();
			}
		}

		private static void OnMessage(ulong sender, FastBufferReader reader)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: 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: 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_0058: 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_006b: Unknown result type (might be due to invalid IL or missing references)
			byte b = default(byte);
			((FastBufferReader)(ref reader)).ReadValueSafe<byte>(ref b, default(ForPrimitives));
			NetworkManager singleton = NetworkManager.Singleton;
			switch (b)
			{
			case 1:
				if ((Object)(object)singleton != (Object)null && singleton.IsServer)
				{
					SendHello(sender);
				}
				break;
			case 0:
			{
				bool flag = default(bool);
				((FastBufferReader)(ref reader)).ReadValueSafe<bool>(ref flag, default(ForPrimitives));
				bool flag2 = default(bool);
				((FastBufferReader)(ref reader)).ReadValueSafe<bool>(ref flag2, default(ForPrimitives));
				bool flag3 = default(bool);
				((FastBufferReader)(ref reader)).ReadValueSafe<bool>(ref flag3, default(ForPrimitives));
				if ((Object)(object)singleton != (Object)null && !singleton.IsServer)
				{
					_clientHostEnabled = flag;
					_clientKeepNormal = flag2;
					_clientKeepInverse = flag3;
					Plugin.Log.LogInfo((object)$"Host hello: enabled={flag} keepNormal={flag2} keepInverse={flag3}");
				}
				break;
			}
			}
		}
	}
	[HarmonyPatch(typeof(GameNetworkManager), "Disconnect")]
	internal static class HostModGateDisconnectPatch
	{
		public static void Prefix()
		{
			HostModGate.Reset();
			Plugin.Log.LogInfo((object)"KeepItemsOnTeleport gate reset on disconnect.");
		}
	}
	[HarmonyPatch(typeof(ShipTeleporter))]
	internal static class ShipTeleporterPatches
	{
		[HarmonyPatch("PressTeleportButtonClientRpc")]
		[HarmonyPostfix]
		private static void PressTeleportButtonClientRpcPostfix(ShipTeleporter __instance)
		{
			if (!((Object)(object)__instance == (Object)null) && !__instance.isInverseTeleporter)
			{
				PlayerControllerB val = StartOfRound.Instance?.mapScreen?.targetedPlayer;
				if (!((Object)(object)val == (Object)null))
				{
					TeleportSession.Mark(val.playerClientId, isInverse: false);
				}
			}
		}

		[HarmonyPatch("TeleportPlayerOutWithInverseTeleporter")]
		[HarmonyPrefix]
		private static void InverseTeleportPrefix(int playerObj)
		{
			StartOfRound instance = StartOfRound.Instance;
			if (!((Object)(object)instance == (Object)null) && playerObj >= 0 && playerObj < instance.allPlayerScripts.Length)
			{
				PlayerControllerB val = instance.allPlayerScripts[playerObj];
				if (!((Object)(object)val == (Object)null))
				{
					TeleportSession.Mark(val.playerClientId, isInverse: true);
				}
			}
		}
	}
	[HarmonyPatch(typeof(PlayerControllerB))]
	internal static class DropHeldItemsPatches
	{
		[HarmonyPatch("DropAllHeldItems")]
		[HarmonyPrefix]
		[HarmonyPriority(0)]
		private static bool DropAllHeldItemsPrefix(PlayerControllerB __instance, bool disconnecting)
		{
			return !ShouldKeepItems(__instance, disconnecting, "DropAllHeldItems");
		}

		[HarmonyPatch("DropAllHeldItemsAndSync")]
		[HarmonyPrefix]
		[HarmonyPriority(0)]
		private static bool DropAllHeldItemsAndSyncPrefix(PlayerControllerB __instance)
		{
			return !ShouldKeepItems(__instance, disconnecting: false, "DropAllHeldItemsAndSync");
		}

		[HarmonyPatch("DropAllHeldItemsAndSyncNonexact")]
		[HarmonyPrefix]
		[HarmonyPriority(0)]
		private static bool DropAllHeldItemsAndSyncNonexactPrefix(PlayerControllerB __instance)
		{
			return !ShouldKeepItems(__instance, disconnecting: false, "DropAllHeldItemsAndSyncNonexact");
		}

		[HarmonyPatch("DropAllHeldItemsRpc")]
		[HarmonyPrefix]
		private static void DropAllHeldItemsRpcPrefix()
		{
			TeleportSession.ApplyingRemoteDrop = true;
		}

		[HarmonyPatch("DropAllHeldItemsRpc")]
		[HarmonyPostfix]
		private static void DropAllHeldItemsRpcPostfix()
		{
			TeleportSession.ApplyingRemoteDrop = false;
		}

		[HarmonyPatch("DropAllHeldItemsNonexactRpc")]
		[HarmonyPrefix]
		private static void DropAllHeldItemsNonexactRpcPrefix()
		{
			TeleportSession.ApplyingRemoteDrop = true;
		}

		[HarmonyPatch("DropAllHeldItemsNonexactRpc")]
		[HarmonyPostfix]
		private static void DropAllHeldItemsNonexactRpcPostfix()
		{
			TeleportSession.ApplyingRemoteDrop = false;
		}

		[HarmonyPatch("TeleportPlayer")]
		[HarmonyPostfix]
		private static void TeleportPlayerPostfix(PlayerControllerB __instance)
		{
			if ((Object)(object)__instance != (Object)null)
			{
				TeleportSession.Clear(__instance.playerClientId);
			}
		}

		private static bool ShouldKeepItems(PlayerControllerB player, bool disconnecting, string source)
		{
			if (TeleportSession.ApplyingRemoteDrop)
			{
				return false;
			}
			if (!HostModGate.FeaturesActive)
			{
				return false;
			}
			if ((Object)(object)player == (Object)null)
			{
				return false;
			}
			if (disconnecting || player.isPlayerDead)
			{
				return false;
			}
			if (!TeleportSession.TryGet(player.playerClientId, out var isInverse))
			{
				return false;
			}
			if (!(isInverse ? HostModGate.KeepOnInverse : HostModGate.KeepOnNormal))
			{
				TeleportSession.Clear(player.playerClientId);
				return false;
			}
			TeleportSession.Clear(player.playerClientId);
			Plugin.V($"Kept items on teleport ({source}) player={player.playerClientId} inverse={isInverse}");
			return true;
		}
	}
	[HarmonyPatch(typeof(StartOfRound), "Start")]
	internal static class HostModGateStartPatch
	{
		private static void Postfix()
		{
			HostModGate.EnsureRegistered();
		}
	}
	[BepInPlugin("com.benhough.lethal.KeepItemsOnTeleport", "KeepItemsOnTeleport", "1.0.2")]
	public class Plugin : BaseUnityPlugin
	{
		public const string ModGuid = "com.benhough.lethal.KeepItemsOnTeleport";

		public const string ModName = "KeepItemsOnTeleport";

		public const string ModVersion = "1.0.2";

		private readonly Harmony _harmony = new Harmony("com.benhough.lethal.KeepItemsOnTeleport");

		internal static Plugin Instance { get; private set; }

		internal static ManualLogSource Log { get; private set; }

		internal static ConfigEntry<bool> Enabled { get; private set; }

		internal static ConfigEntry<bool> KeepOnNormalTeleporter { get; private set; }

		internal static ConfigEntry<bool> KeepOnInverseTeleporter { get; private set; }

		internal static ConfigEntry<bool> Verbose { get; private set; }

		private void Awake()
		{
			Instance = this;
			Log = ((BaseUnityPlugin)this).Logger;
			Enabled = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "Enabled", true, "Master toggle — keep inventory when ship-teleported.");
			KeepOnNormalTeleporter = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "KeepOnNormalTeleporter", true, "Keep items when beamed back to the ship (normal teleporter).");
			KeepOnInverseTeleporter = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "KeepOnInverseTeleporter", true, "Keep items when beamed into the facility (inverse teleporter).");
			Verbose = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "VerboseLogging", false, "Log when a teleport drop is skipped.");
			try
			{
				_harmony.PatchAll(typeof(Plugin).Assembly);
				Log.LogInfo((object)"KeepItemsOnTeleport v1.0.2 loaded.");
			}
			catch (Exception arg)
			{
				Log.LogError((object)$"Harmony patch failed: {arg}");
			}
		}

		internal static void V(string msg)
		{
			if (Verbose != null && Verbose.Value)
			{
				Log.LogInfo((object)msg);
			}
		}
	}
	internal static class PluginInfo
	{
		public const string PLUGIN_GUID = "com.benhough.lethal.KeepItemsOnTeleport";

		public const string PLUGIN_NAME = "KeepItemsOnTeleport";

		public const string PLUGIN_VERSION = "1.0.2";
	}
	internal static class TeleportSession
	{
		private static readonly Dictionary<ulong, bool> InverseByPlayer = new Dictionary<ulong, bool>();

		internal static bool ApplyingRemoteDrop;

		internal static void Mark(ulong playerClientId, bool isInverse)
		{
			InverseByPlayer[playerClientId] = isInverse;
			Plugin.V($"Marked teleport player={playerClientId} inverse={isInverse}");
		}

		internal static bool TryGet(ulong playerClientId, out bool isInverse)
		{
			return InverseByPlayer.TryGetValue(playerClientId, out isInverse);
		}

		internal static void Clear(ulong playerClientId)
		{
			if (InverseByPlayer.Remove(playerClientId))
			{
				Plugin.V($"Cleared teleport mark player={playerClientId}");
			}
		}
	}
}