Decompiled source of CompanyGhosts v1.0.0

CompanyGhosts.dll

Decompiled an hour ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security.Cryptography;
using System.Text;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using GameNetcodeStuff;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using Unity.Collections;
using Unity.Netcode;
using UnityEngine;
using UnityEngine.Rendering.HighDefinition;
using UnityEngine.UI;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("CompanyGhosts")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0")]
[assembly: AssemblyProduct("CompanyGhosts")]
[assembly: AssemblyTitle("CompanyGhosts")]
[assembly: AssemblyVersion("1.0.0.0")]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.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 CompanyGhosts
{
	[BepInPlugin("CompanyGhosts", "CompanyGhosts", "1.0.0")]
	[HarmonyPatch]
	public class Plugin : BaseUnityPlugin
	{
		[HarmonyPatch]
		private static class GhostsDoing
		{
			internal static bool Active;

			private static readonly FieldInfo ThrownBy = AccessTools.Field(typeof(StunGrenadeItem), "playerThrownBy");

			private static IEnumerable<MethodBase> TargetMethods()
			{
				return new MethodInfo[3]
				{
					AccessTools.Method(typeof(ShotgunItem), "ShootGun", (Type[])null, (Type[])null),
					AccessTools.Method(typeof(StunGrenadeItem), "ExplodeStunGrenade", (Type[])null, (Type[])null),
					AccessTools.Method(typeof(VehicleController), "DestroyCar", (Type[])null, (Type[])null)
				};
			}

			private static void Prefix(object __instance)
			{
				//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_0044: Expected O, but got Unknown
				ShotgunItem val = (ShotgunItem)((__instance is ShotgunItem) ? __instance : null);
				PlayerControllerB player;
				if (val == null)
				{
					StunGrenadeItem val2 = (StunGrenadeItem)((__instance is StunGrenadeItem) ? __instance : null);
					if (val2 == null)
					{
						player = ((VehicleController)(((__instance is VehicleController) ? __instance : null)?)).currentDriver;
					}
					else
					{
						PlayerControllerB val3 = (PlayerControllerB)ThrownBy.GetValue(val2);
						object obj = (object)val3;
						if ((int)val3 == 0)
						{
							obj = ((GrabbableObject)val2).playerHeldBy;
						}
						player = (PlayerControllerB)obj;
					}
				}
				else
				{
					player = ((GrabbableObject)val).playerHeldBy;
				}
				Active = Ghost.Is(player);
			}

			private static void Finalizer()
			{
				Active = false;
			}
		}

		internal static ManualLogSource Log;

		internal static ConfigEntry<float> ReturnDelay;

		internal static ConfigEntry<bool> CountAsDead;

		internal static ConfigEntry<bool> LeftBehind;

		internal static ConfigEntry<bool> NoPenalties;

		internal static ConfigEntry<int> Opacity;

		private static GameObject? _lobbyKey;

		private void Awake()
		{
			//IL_0039: Unknown result type (might be due to invalid IL or missing references)
			//IL_0043: Expected O, but got Unknown
			//IL_006c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0076: Expected O, but got Unknown
			//IL_010f: Unknown result type (might be due to invalid IL or missing references)
			Log = ((BaseUnityPlugin)this).Logger;
			ReturnDelay = ((BaseUnityPlugin)this).Config.Bind<float>("General", "Return delay", 3f, new ConfigDescription("Seconds between dying at the Company and coming back on the ship as a ghost.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 60f), Array.Empty<object>()));
			Opacity = ((BaseUnityPlugin)this).Config.Bind<int>("General", "Ghost opacity", 60, new ConfigDescription("How visible ghosts are, from 0 (invisible) to 100 (as solid as the living).", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 100), Array.Empty<object>()));
			CountAsDead = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "Ghosts count as dead", true, "Ghosts still count as dead, so they count towards the death penalty and the ship leaves if everyone still alive dies.");
			LeftBehind = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "Ghosts are left behind", true, "When the ship takes off, the ship and everything on it turns intangible to ghosts, so they stay at the Company and are lost. Off: ghosts always leave with the ship.");
			NoPenalties = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "No penalties at the Company", true, "Nobody is fined for dying or being lost at the Company, ghost or not.");
			Rules.UseOwn();
			((BaseUnityPlugin)this).Config.SettingChanged += delegate
			{
				Rules.Changed();
			};
			new Harmony("CompanyGhosts").PatchAll();
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(PlayerControllerB), "ConnectClientToPlayerObject")]
		private static void InLobby()
		{
			Rules.Connected();
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(GameNetworkManager), "Start")]
		private static void RequireInLobby()
		{
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			//IL_0020: Expected O, but got Unknown
			try
			{
				if ((Object)(object)_lobbyKey == (Object)null)
				{
					GameObject val = new GameObject("CompanyGhosts")
					{
						hideFlags = (HideFlags)61
					};
					val.SetActive(false);
					using MD5 mD = MD5.Create();
					AccessTools.Field(typeof(NetworkObject), "GlobalObjectIdHash").SetValue(val.AddComponent<NetworkObject>(), BitConverter.ToUInt32(mD.ComputeHash(Encoding.UTF8.GetBytes("CompanyGhosts")), 0));
					_lobbyKey = val;
				}
				if (!NetworkManager.Singleton.NetworkConfig.Prefabs.Contains(_lobbyKey))
				{
					NetworkManager.Singleton.AddNetworkPrefab(_lobbyKey);
				}
			}
			catch (Exception arg)
			{
				Log.LogError((object)$"Couldn't require the mod in lobbies, so players without it can join: {arg}");
			}
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(PlayerControllerB), "KillPlayerClientRpc")]
		private static void OnDeath(int playerId)
		{
			PlayerControllerB val = StartOfRound.Instance.allPlayerScripts[playerId];
			Ghost ghost = default(Ghost);
			if (val.isPlayerDead && Ghost.AtTheCompany() && !((Component)val).TryGetComponent<Ghost>(ref ghost))
			{
				((Component)val).gameObject.AddComponent<Ghost>();
			}
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(PlayerControllerB), "AllowPlayerDeath")]
		private static void Invulnerable(PlayerControllerB __instance, ref bool __result)
		{
			if (Ghost.Protects(__instance))
			{
				__result = false;
			}
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(PlayerControllerB), "KillPlayer")]
		private static void Unkillable(PlayerControllerB __instance)
		{
			if (((NetworkBehaviour)__instance).IsOwner && Ghost.Protects(__instance))
			{
				__instance.ResetFallGravity();
				StartOfRound.Instance.ForcePlayerIntoShip();
			}
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(StartOfRound), "ShipLeave")]
		private static void TakingOff(StartOfRound __instance)
		{
			if (!Rules.LeftBehind)
			{
				return;
			}
			PlayerControllerB[] allPlayerScripts = __instance.allPlayerScripts;
			Ghost ghost = default(Ghost);
			for (int i = 0; i < allPlayerScripts.Length; i++)
			{
				if (((Component)allPlayerScripts[i]).TryGetComponent<Ghost>(ref ghost) && ghost.Risen)
				{
					ghost.Abandon();
				}
			}
		}

		[HarmonyPrefix]
		[HarmonyPatch(typeof(ElevatorAnimationEvents), "ElevatorFullyRunning")]
		private static void TakenOff()
		{
			//IL_0038: 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_0047: 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)
			PlayerControllerB localPlayerController = StartOfRound.Instance.localPlayerController;
			Ghost ghost = default(Ghost);
			if (!((Object)(object)localPlayerController == (Object)null) && !localPlayerController.isPlayerDead && ((Component)localPlayerController).TryGetComponent<Ghost>(ref ghost) && ghost.Risen)
			{
				if (ghost.Abandoned)
				{
					localPlayerController.KillPlayer(Vector3.zero, false, ghost.DiedOf, 0, default(Vector3), false);
				}
				else if (!localPlayerController.isInElevator)
				{
					localPlayerController.ResetFallGravity();
					StartOfRound.Instance.ForcePlayerIntoShip();
				}
			}
		}

		[HarmonyPrefix]
		[HarmonyPatch(typeof(OutOfBoundsTrigger), "OnTriggerEnter")]
		private static bool OutOfBounds(OutOfBoundsTrigger __instance, Collider other)
		{
			//IL_0050: Unknown result type (might be due to invalid IL or missing references)
			if (__instance.disableWhenRoundStarts && !StartOfRound.Instance.inShipPhase)
			{
				return true;
			}
			PlayerControllerB val = default(PlayerControllerB);
			if (!((Component)other).TryGetComponent<PlayerControllerB>(ref val) || (Object)(object)val != (Object)(object)StartOfRound.Instance.localPlayerController)
			{
				return true;
			}
			Ghost ghost = default(Ghost);
			if (!((Component)val).TryGetComponent<Ghost>(ref ghost) || !ghost.Abandoned)
			{
				return true;
			}
			val.ResetFallGravity();
			val.TeleportPlayer(ghost.LeftAt, false, 0f, false, true);
			return false;
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(EnemyAI), "PlayerIsTargetable")]
		private static void Untargetable(PlayerControllerB playerScript, ref bool __result)
		{
			if (Ghost.Is(playerScript))
			{
				__result = false;
			}
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(PumaAI), "PlayerIsTargetable")]
		private static void UntargetableToPumas(PlayerControllerB playerScript, ref bool __result)
		{
			Untargetable(playerScript, ref __result);
		}

		[HarmonyTranspiler]
		[HarmonyPatch(typeof(Turret), "CheckForPlayersInLineOfSight")]
		private static IEnumerable<CodeInstruction> TurretsSeePast(IEnumerable<CodeInstruction> code)
		{
			return SeePast(code, "turrets ignoring ghosts", typeof(Ray), typeof(RaycastHit).MakeByRefType(), typeof(float), typeof(int), typeof(QueryTriggerInteraction));
		}

		[HarmonyTranspiler]
		[HarmonyPatch(typeof(SpikeRoofTrap), "Update")]
		private static IEnumerable<CodeInstruction> TrapsSeePast(IEnumerable<CodeInstruction> code)
		{
			return SeePast(code, "spike traps ignoring ghosts", typeof(Vector3), typeof(Vector3), typeof(RaycastHit).MakeByRefType(), typeof(float), typeof(int), typeof(QueryTriggerInteraction));
		}

		private static IEnumerable<CodeInstruction> SeePast(IEnumerable<CodeInstruction> code, string feature, params Type[] raycast)
		{
			//IL_0002: 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_0037: Expected O, but got Unknown
			CodeMatcher val = new CodeMatcher(code, (ILGenerator)null).MatchForward(false, (CodeMatch[])(object)new CodeMatch[1]
			{
				new CodeMatch((OpCode?)OpCodes.Call, (object)AccessTools.Method(typeof(Physics), "Raycast", raycast, (Type[])null), (string)null)
			});
			if (val.IsInvalid)
			{
				return Unchanged(val, feature);
			}
			return val.SetOperandAndAdvance((object)AccessTools.Method(typeof(Ghost), "RaycastPast", raycast, (Type[])null)).InstructionEnumeration();
		}

		private static IEnumerable<CodeInstruction> Unchanged(CodeMatcher matcher, string feature)
		{
			Log.LogWarning((object)("Couldn't apply " + feature + ", so it's off. The game or another mod may have changed that code."));
			return matcher.InstructionEnumeration();
		}

		[HarmonyPrefix]
		[HarmonyPatch(typeof(Landmine), "OnTriggerEnter")]
		private static bool SteppedOn(Collider other)
		{
			return !Ghost.Is(((Component)other).GetComponent<PlayerControllerB>());
		}

		[HarmonyPrefix]
		[HarmonyPatch(typeof(Landmine), "OnTriggerExit")]
		private static bool SteppedOff(Collider other)
		{
			return !Ghost.Is(((Component)other).GetComponent<PlayerControllerB>());
		}

		[HarmonyPrefix]
		[HarmonyPatch(typeof(CompanyMonsterCollisionDetect), "OnTriggerEnter")]
		private static bool OutOfReach(Collider other)
		{
			return !Ghost.Is(((Component)other).GetComponent<PlayerControllerB>());
		}

		[HarmonyPrefix]
		[HarmonyPatch(typeof(PlayerControllerB), "IHittable.Hit")]
		private static bool HarmlessToPlayers(PlayerControllerB playerWhoHit, ref bool __result)
		{
			if (!Ghost.Is(playerWhoHit))
			{
				return true;
			}
			__result = false;
			return false;
		}

		[HarmonyPrefix]
		[HarmonyPatch(typeof(EnemyAI), "HitEnemyOnLocalClient")]
		private static bool HarmlessToCreatures(PlayerControllerB playerWhoHit)
		{
			if (!GhostsDoing.Active)
			{
				return !Ghost.Is(playerWhoHit);
			}
			return false;
		}

		[HarmonyPrefix]
		[HarmonyPatch(typeof(PlayerControllerB), "DamagePlayer")]
		private static bool Unharmed()
		{
			return !GhostsDoing.Active;
		}

		[HarmonyPrefix]
		[HarmonyPatch(typeof(PlayerControllerB), "KillPlayer")]
		private static bool Spared()
		{
			return !GhostsDoing.Active;
		}

		[HarmonyPrefix]
		[HarmonyPatch(typeof(VehicleCollisionTrigger), "OnTriggerEnter")]
		private static bool RunOver(VehicleCollisionTrigger __instance)
		{
			return !Ghost.Is(__instance.mainScript.currentDriver);
		}

		[HarmonyPrefix]
		[HarmonyPatch(typeof(HUDManager), "ApplyPenalty")]
		[HarmonyPriority(800)]
		private static void Fine(ref int playersDead, ref int bodiesInsured)
		{
			if (Rules.NoPenalties && Ghost.IsCompany(StartOfRound.Instance.currentLevel))
			{
				playersDead = 0;
				bodiesInsured = 0;
			}
		}

		[HarmonyTranspiler]
		[HarmonyPatch(typeof(PlayerControllerB), "Update")]
		private static IEnumerable<CodeInstruction> NoShoving(IEnumerable<CodeInstruction> code)
		{
			//IL_0002: 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_002b: Expected O, but got Unknown
			//IL_0039: Unknown result type (might be due to invalid IL or missing references)
			//IL_003f: Expected O, but got Unknown
			//IL_0060: Unknown result type (might be due to invalid IL or missing references)
			//IL_0066: Expected O, but got Unknown
			//IL_0074: Unknown result type (might be due to invalid IL or missing references)
			//IL_007a: Expected O, but got Unknown
			//IL_009b: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a1: Expected O, but got Unknown
			//IL_00fd: Unknown result type (might be due to invalid IL or missing references)
			//IL_0103: Expected O, but got Unknown
			//IL_012c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0132: Expected O, but got Unknown
			CodeMatcher val = new CodeMatcher(code, (ILGenerator)null).MatchForward(true, (CodeMatch[])(object)new CodeMatch[6]
			{
				new CodeMatch((OpCode?)OpCodes.Ldc_R4, (object)0.75f, (string)null),
				new CodeMatch((OpCode?)OpCodes.Ldarg_0, (object)null, (string)null),
				new CodeMatch((OpCode?)OpCodes.Ldfld, (object)AccessTools.Field(typeof(PlayerControllerB), "nearByPlayers"), (string)null),
				new CodeMatch((OpCode?)OpCodes.Call, (object)null, (string)null),
				new CodeMatch((OpCode?)OpCodes.Ldfld, (object)AccessTools.Field(typeof(StartOfRound), "playersMask"), (string)null),
				new CodeMatch((OpCode?)OpCodes.Call, (object)AccessTools.Method(typeof(Physics), "OverlapSphereNonAlloc", new Type[4]
				{
					typeof(Vector3),
					typeof(float),
					typeof(Collider[]),
					typeof(int)
				}, (Type[])null), (string)null)
			});
			if (val.IsInvalid)
			{
				return Unchanged(val, "walking through ghosts");
			}
			return val.Insert((CodeInstruction[])(object)new CodeInstruction[1]
			{
				new CodeInstruction(OpCodes.Ldarg_0, (object)null)
			}).Advance(1).SetOperandAndAdvance((object)AccessTools.Method(typeof(Plugin), "Shovers", (Type[])null, (Type[])null))
				.InstructionEnumeration();
		}

		private static int Shovers(Vector3 position, float radius, Collider[] results, int mask, PlayerControllerB self)
		{
			//IL_0007: 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)
			if (!Ghost.Any)
			{
				return Physics.OverlapSphereNonAlloc(position, radius, results, mask);
			}
			if (Ghost.Is(self))
			{
				return 0;
			}
			int num = Physics.OverlapSphereNonAlloc(position, radius, results, mask);
			int result = 0;
			for (int i = 0; i < num; i++)
			{
				if (!Ghost.Is(((Component)results[i]).GetComponent<PlayerControllerB>()))
				{
					results[result++] = results[i];
				}
			}
			return result;
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(UnlockableSuit), "SwitchSuitForPlayer")]
		private static void SuitChanged(PlayerControllerB player)
		{
			Ghost ghost = default(Ghost);
			if (((Component)player).TryGetComponent<Ghost>(ref ghost) && ghost.Risen)
			{
				ghost.Fade();
			}
		}

		[HarmonyPrefix]
		[HarmonyPatch(typeof(StartOfRound), "ReviveDeadPlayers")]
		private static void DayEnding(StartOfRound __instance, out bool __state)
		{
			PlayerControllerB localPlayerController = __instance.localPlayerController;
			__state = __instance.allPlayersDead && Ghost.Is(localPlayerController) && !localPlayerController.isPlayerDead;
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(StartOfRound), "ReviveDeadPlayers")]
		private static void DayOver(StartOfRound __instance, bool __state)
		{
			if (__state)
			{
				HUDManager.Instance.gameOverAnimator.SetTrigger("revive");
				__instance.SetSpectateCameraToGameOverMode(false, __instance.localPlayerController);
			}
			PlayerControllerB[] allPlayerScripts = __instance.allPlayerScripts;
			Ghost ghost = default(Ghost);
			for (int i = 0; i < allPlayerScripts.Length; i++)
			{
				if (((Component)allPlayerScripts[i]).TryGetComponent<Ghost>(ref ghost))
				{
					ghost.Lay();
				}
			}
		}

		[HarmonyPrefix]
		[HarmonyPatch(typeof(StartOfRound), "OnPlayerDC")]
		private static void Disconnected(StartOfRound __instance, int playerObjectNumber)
		{
			Ghost ghost = default(Ghost);
			if (((Component)__instance.allPlayerScripts[playerObjectNumber]).TryGetComponent<Ghost>(ref ghost))
			{
				if (ghost.Risen)
				{
					ghost.CountAlive();
				}
				ghost.Lay();
			}
		}
	}
	internal static class Rules
	{
		[Serializable]
		[CompilerGenerated]
		private sealed class <>c
		{
			public static readonly <>c <>9 = new <>c();

			public static HandleNamedMessageDelegate <>9__6_0;

			public static HandleNamedMessageDelegate <>9__6_1;

			public static Func<ulong, bool> <>9__7_0;

			internal void <Connected>b__6_0(ulong guest, FastBufferReader _)
			{
				Send(new ulong[1] { guest });
			}

			internal void <Connected>b__6_1(ulong _, FastBufferReader rules)
			{
				//IL_0000: Unknown result type (might be due to invalid IL or missing references)
				Receive(rules);
			}

			internal bool <Changed>b__7_0(ulong id)
			{
				return id != 0;
			}
		}

		private const string Message = "CompanyGhosts.Rules";

		internal static float ReturnDelay;

		internal static bool CountAsDead;

		internal static bool LeftBehind;

		internal static bool NoPenalties;

		internal static void UseOwn()
		{
			ReturnDelay = Plugin.ReturnDelay.Value;
			CountAsDead = Plugin.CountAsDead.Value;
			LeftBehind = Plugin.LeftBehind.Value;
			NoPenalties = Plugin.NoPenalties.Value;
		}

		internal unsafe static void Connected()
		{
			//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_006d: Expected O, but got Unknown
			//IL_0032: 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_003d: Expected O, but got Unknown
			//IL_0089: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager singleton = NetworkManager.Singleton;
			if (singleton.IsServer)
			{
				UseOwn();
				CustomMessagingManager customMessagingManager = singleton.CustomMessagingManager;
				object obj = <>c.<>9__6_0;
				if (obj == null)
				{
					HandleNamedMessageDelegate val = delegate(ulong guest, FastBufferReader _)
					{
						Send(new ulong[1] { guest });
					};
					<>c.<>9__6_0 = val;
					obj = (object)val;
				}
				customMessagingManager.RegisterNamedMessageHandler("CompanyGhosts.Rules", (HandleNamedMessageDelegate)obj);
				return;
			}
			CustomMessagingManager customMessagingManager2 = singleton.CustomMessagingManager;
			object obj2 = <>c.<>9__6_1;
			if (obj2 == null)
			{
				HandleNamedMessageDelegate val2 = delegate(ulong _, FastBufferReader rules)
				{
					//IL_0000: Unknown result type (might be due to invalid IL or missing references)
					Receive(rules);
				};
				<>c.<>9__6_1 = val2;
				obj2 = (object)val2;
			}
			customMessagingManager2.RegisterNamedMessageHandler("CompanyGhosts.Rules", (HandleNamedMessageDelegate)obj2);
			FastBufferWriter val3 = default(FastBufferWriter);
			((FastBufferWriter)(ref val3))..ctor(0, (Allocator)2, -1);
			try
			{
				singleton.CustomMessagingManager.SendNamedMessage("CompanyGhosts.Rules", 0uL, val3, (NetworkDelivery)3);
			}
			finally
			{
				((IDisposable)(*(FastBufferWriter*)(&val3))/*cast due to .constrained prefix*/).Dispose();
			}
		}

		internal static void Changed()
		{
			NetworkManager singleton = NetworkManager.Singleton;
			if ((Object)(object)singleton != (Object)null && singleton.IsListening && !singleton.IsServer)
			{
				return;
			}
			UseOwn();
			if ((Object)(object)singleton != (Object)null && singleton.IsServer)
			{
				Send(singleton.ConnectedClientsIds.Where((ulong id) => id != 0).ToArray());
			}
		}

		private unsafe static void Send(ulong[] guests)
		{
			//IL_0018: Unknown result type (might be due to invalid IL or missing references)
			//IL_001e: Unknown result type (might be due to invalid IL or missing references)
			//IL_002d: 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_0042: 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_0057: Unknown result type (might be due to invalid IL or missing references)
			//IL_005d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0073: Unknown result type (might be due to invalid IL or missing references)
			if (guests.Length == 0)
			{
				return;
			}
			FastBufferWriter val = default(FastBufferWriter);
			((FastBufferWriter)(ref val))..ctor(7, (Allocator)2, -1);
			try
			{
				((FastBufferWriter)(ref val)).WriteValueSafe<float>(ref ReturnDelay, default(ForPrimitives));
				((FastBufferWriter)(ref val)).WriteValueSafe<bool>(ref CountAsDead, default(ForPrimitives));
				((FastBufferWriter)(ref val)).WriteValueSafe<bool>(ref LeftBehind, default(ForPrimitives));
				((FastBufferWriter)(ref val)).WriteValueSafe<bool>(ref NoPenalties, default(ForPrimitives));
				NetworkManager.Singleton.CustomMessagingManager.SendNamedMessage("CompanyGhosts.Rules", (IReadOnlyList<ulong>)guests, val, (NetworkDelivery)3);
			}
			finally
			{
				((IDisposable)(*(FastBufferWriter*)(&val))/*cast due to .constrained prefix*/).Dispose();
			}
		}

		private static void Receive(FastBufferReader rules)
		{
			//IL_0009: 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_001e: 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_0033: 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_0048: Unknown result type (might be due to invalid IL or missing references)
			//IL_004e: Unknown result type (might be due to invalid IL or missing references)
			((FastBufferReader)(ref rules)).ReadValueSafe<float>(ref ReturnDelay, default(ForPrimitives));
			((FastBufferReader)(ref rules)).ReadValueSafe<bool>(ref CountAsDead, default(ForPrimitives));
			((FastBufferReader)(ref rules)).ReadValueSafe<bool>(ref LeftBehind, default(ForPrimitives));
			((FastBufferReader)(ref rules)).ReadValueSafe<bool>(ref NoPenalties, default(ForPrimitives));
		}
	}
	internal class Ghost : MonoBehaviour
	{
		private static Func<StartOfRound, int, bool, Vector3>? _spawnPosition;

		private PlayerControllerB _player;

		private readonly Dictionary<Material, Material> _faded = new Dictionary<Material, Material>();

		private readonly Dictionary<Material, Material> _original = new Dictionary<Material, Material>();

		private readonly HashSet<Renderer> _hidden = new HashSet<Renderer>();

		private bool _countedAlive;

		private Collider[]? _ship;

		private bool _risen;

		private static int _risenCount;

		private static float Opacity => (float)Plugin.Opacity.Value / 100f;

		private static Func<StartOfRound, int, bool, Vector3> SpawnPosition => _spawnPosition ?? (_spawnPosition = AccessTools.MethodDelegate<Func<StartOfRound, int, bool, Vector3>>(AccessTools.Method(typeof(StartOfRound), "GetPlayerSpawnPosition", (Type[])null, (Type[])null), (object)null, true));

		internal bool Abandoned { get; private set; }

		internal CauseOfDeath DiedOf { get; private set; }

		internal Vector3 LeftAt { get; private set; }

		internal bool Risen
		{
			get
			{
				return _risen;
			}
			private set
			{
				if (value != _risen)
				{
					_risen = value;
					_risenCount += (value ? 1 : (-1));
				}
			}
		}

		internal static bool Any => _risenCount > 0;

		internal static bool AtTheCompany()
		{
			StartOfRound instance = StartOfRound.Instance;
			if (IsCompany(instance.currentLevel) && !instance.inShipPhase)
			{
				return !instance.shipIsLeaving;
			}
			return false;
		}

		internal static bool IsCompany(SelectableLevel level)
		{
			if (!level.planetHasTime)
			{
				return !level.spawnEnemiesAndScrap;
			}
			return false;
		}

		internal static bool Is(PlayerControllerB? player)
		{
			Ghost ghost = default(Ghost);
			if (Any && (Object)(object)player != (Object)null && ((Component)player).TryGetComponent<Ghost>(ref ghost))
			{
				return ghost.Risen;
			}
			return false;
		}

		internal static bool Protects(PlayerControllerB player)
		{
			Ghost ghost = default(Ghost);
			if (((Component)player).TryGetComponent<Ghost>(ref ghost) && ghost.Risen)
			{
				return !ghost.Abandoned;
			}
			return false;
		}

		internal static bool RaycastPast(Ray ray, out RaycastHit hit, float distance, int mask, QueryTriggerInteraction triggers)
		{
			//IL_0002: 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_0011: Unknown result type (might be due to invalid IL or missing references)
			return RaycastPast(((Ray)(ref ray)).origin, ((Ray)(ref ray)).direction, out hit, distance, mask, triggers);
		}

		internal static bool RaycastPast(Vector3 origin, Vector3 direction, out RaycastHit hit, float distance, int mask, QueryTriggerInteraction triggers)
		{
			//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_0012: Unknown result type (might be due to invalid IL or missing references)
			//IL_0021: 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_0028: 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_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_005d: 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_0067: Unknown result type (might be due to invalid IL or missing references)
			bool flag = Physics.Raycast(origin, direction, ref hit, distance, mask, triggers);
			if (!flag || !IsGhost(hit))
			{
				return flag;
			}
			hit = default(RaycastHit);
			RaycastHit[] array = Physics.RaycastAll(origin, direction, distance, mask, triggers);
			for (int i = 0; i < array.Length; i++)
			{
				RaycastHit val = array[i];
				if (((Object)(object)((RaycastHit)(ref hit)).collider == (Object)null || ((RaycastHit)(ref val)).distance < ((RaycastHit)(ref hit)).distance) && !IsGhost(val))
				{
					hit = val;
				}
			}
			return (Object)(object)((RaycastHit)(ref hit)).collider != (Object)null;
		}

		private static bool IsGhost(RaycastHit hit)
		{
			if (Any)
			{
				return Is(((Component)((RaycastHit)(ref hit)).collider).GetComponentInParent<PlayerControllerB>());
			}
			return false;
		}

		internal void CountAlive()
		{
			if (!_countedAlive)
			{
				StartOfRound instance = StartOfRound.Instance;
				instance.livingPlayers++;
				_countedAlive = true;
			}
		}

		internal void Abandon()
		{
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			Abandoned = true;
			LeftAt = StartOfRound.Instance.outsideShipSpawnPosition.position;
			CountAlive();
			_ship = (from c in ((Component)StartOfRound.Instance.elevatorTransform).GetComponentsInChildren<Collider>(true).Concat(Object.FindObjectsByType<AutoParentToShip>((FindObjectsSortMode)0).SelectMany((AutoParentToShip f) => ((Component)f).GetComponentsInChildren<Collider>(true)))
				where (Object)(object)((Component)c).GetComponentInParent<PlayerControllerB>() == (Object)null
				select c).ToArray();
			Intangible(intangible: true);
			if (((NetworkBehaviour)_player).IsOwner)
			{
				_player.SetAllItemsInElevator(false, false);
			}
		}

		private void Update()
		{
			if (!Abandoned)
			{
				return;
			}
			Collider[] ship = _ship;
			foreach (Collider val in ship)
			{
				if (!((Object)(object)val == (Object)null))
				{
					if (((Collider)_player.thisController).enabled && !Physics.GetIgnoreCollision((Collider)(object)_player.thisController, val))
					{
						Intangible(intangible: true);
					}
					break;
				}
			}
			if (((NetworkBehaviour)_player).IsOwner)
			{
				_player.isInElevator = false;
				_player.isInHangarShipRoom = false;
			}
		}

		private void Intangible(bool intangible)
		{
			Collider[] componentsInChildren = ((Component)_player).GetComponentsInChildren<Collider>(true);
			Collider[] ship = _ship;
			foreach (Collider val in ship)
			{
				Collider[] array = componentsInChildren;
				foreach (Collider val2 in array)
				{
					if ((Object)(object)val != (Object)null && (Object)(object)val2 != (Object)null)
					{
						Physics.IgnoreCollision(val2, val, intangible);
					}
				}
			}
		}

		private void Awake()
		{
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			_player = ((Component)this).GetComponent<PlayerControllerB>();
			DiedOf = _player.causeOfDeath;
			((MonoBehaviour)this).Invoke("Rise", Rules.ReturnDelay);
		}

		private void Rise()
		{
			if (!_player.isPlayerDead || !AtTheCompany())
			{
				Object.Destroy((Object)(object)this);
				return;
			}
			Revive();
			if (!Rules.CountAsDead)
			{
				CountAlive();
			}
			Risen = true;
			Fade();
		}

		private void Revive()
		{
			//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_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_005c: 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_006f: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fb: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d9: Unknown result type (might be due to invalid IL or missing references)
			//IL_01de: Unknown result type (might be due to invalid IL or missing references)
			StartOfRound instance = StartOfRound.Instance;
			PlayerControllerB player = _player;
			int num = (int)player.playerClientId;
			Vector3 val = SpawnPosition(instance, num, arg3: false);
			player.ResetPlayerBloodObjects(true);
			player.isClimbingLadder = false;
			player.clampLooking = false;
			player.inVehicleAnimation = false;
			Vector3 localEulerAngles = ((Component)player.gameplayCamera).transform.localEulerAngles;
			((Component)player.gameplayCamera).transform.localEulerAngles = new Vector3(localEulerAngles.x, 0f, localEulerAngles.z);
			player.overridePoisonValue = false;
			player.disableMoveInput = false;
			player.ResetZAndXRotation();
			((Collider)player.thisController).enabled = true;
			player.health = 100;
			player.hasBeenCriticallyInjured = false;
			player.disableLookInput = false;
			player.disableInteract = false;
			((Behaviour)player.nightVisionRadar).enabled = false;
			player.isPlayerDead = false;
			player.enemyWaitingForBodyRagdoll = null;
			player.isPlayerControlled = true;
			player.isInElevator = true;
			player.isInHangarShipRoom = true;
			player.isInsideFactory = false;
			player.parentedToElevatorLastFrame = false;
			player.overrideGameOverSpectatePivot = null;
			player.TeleportPlayer(val, false, 0f, false, true);
			player.setPositionOfDeadPlayer = false;
			player.DisablePlayerModel(((Component)this).gameObject, true, true);
			((Behaviour)player.helmetLight).enabled = false;
			player.Crouch(false);
			player.criticallyInjured = false;
			if ((Object)(object)player.playerBodyAnimator != (Object)null)
			{
				player.playerBodyAnimator.SetBool("Limp", false);
			}
			player.bleedingHeavily = false;
			player.activatingItem = false;
			player.twoHanded = false;
			player.inShockingMinigame = false;
			player.inSpecialInteractAnimation = false;
			player.freeRotationInInteractAnimation = false;
			player.disableSyncInAnimation = false;
			player.inAnimationWithEnemy = null;
			player.holdingWalkieTalkie = false;
			player.speakingToWalkieTalkie = false;
			player.isSinking = false;
			player.isUnderwater = false;
			player.sinkingValue = 0f;
			player.statusEffectAudio.Stop();
			player.DisableJetpackControlsLocally();
			player.mapRadarDotAnimator.SetBool("dead", false);
			player.externalForceAutoFade = Vector3.zero;
			player.carryWeight = 1f;
			player.voiceMuffledByEnemy = false;
			SoundManager.Instance.playerVoicePitchTargets[num] = 1f;
			SoundManager.Instance.SetPlayerPitch(1f, num);
			PlayerVoiceIngameSettings currentVoiceChatIngameSettings = player.currentVoiceChatIngameSettings;
			OccludeAudio val2 = default(OccludeAudio);
			if ((Object)(object)currentVoiceChatIngameSettings != (Object)null && (Object)(object)currentVoiceChatIngameSettings.voiceAudio != (Object)null && ((Component)currentVoiceChatIngameSettings.voiceAudio).TryGetComponent<OccludeAudio>(ref val2))
			{
				val2.overridingLowPass = false;
			}
			if (((NetworkBehaviour)player).IsOwner)
			{
				instance.SetPlayerObjectExtrapolate(false);
				instance.SetSpectateCameraToGameOverMode(false, player);
				instance.SendChangedWeightEvent();
				player.hasBegunSpectating = false;
				player.spectatedPlayerScript = null;
				player.hinderedMultiplier = 1f;
				player.isMovementHindered = 0;
				player.sourcesCausingSinking = 0;
				player.reverbPreset = instance.shipReverb;
				HUDManager instance2 = HUDManager.Instance;
				instance2.SetCracksOnVisor(100f);
				instance2.gasHelmetAnimator.SetBool("gasEmitting", false);
				instance2.RemoveSpectateUI();
				instance2.gameOverAnimator.SetTrigger("revive");
				instance2.spitOnCameraAlpha = 1f;
				instance2.cadaverFilter = 0f;
				((Behaviour)instance2.audioListenerLowPass).enabled = false;
				instance2.UpdateHealthUI(100, false);
				instance2.HideHUD(false);
				SoundManager.Instance.earsRingingTimer = 0f;
				SoundManager.Instance.alternateEarsRinging = false;
			}
			instance.UpdatePlayerVoiceEffects();
		}

		internal void Fade()
		{
			foreach (Renderer item in OnBody<Renderer>(((Component)_player.thisPlayerModel).transform.parent))
			{
				if (Opacity <= 0f)
				{
					if (!item.forceRenderingOff && _hidden.Add(item))
					{
						item.forceRenderingOff = true;
					}
					continue;
				}
				if (_hidden.Remove(item))
				{
					item.forceRenderingOff = false;
				}
				Material[] sharedMaterials = item.sharedMaterials;
				for (int i = 0; i < sharedMaterials.Length; i++)
				{
					if ((Object)(object)sharedMaterials[i] != (Object)null)
					{
						sharedMaterials[i] = Faded(sharedMaterials[i]);
					}
				}
				item.sharedMaterials = sharedMaterials;
			}
			foreach (Graphic item2 in OnBody<Graphic>(((Component)_player).transform))
			{
				item2.canvasRenderer.SetAlpha(Opacity);
			}
		}

		private Material Faded(Material material)
		{
			//IL_0031: Unknown result type (might be due to invalid IL or missing references)
			//IL_0036: Unknown result type (might be due to invalid IL or missing references)
			//IL_004d: Expected O, but got Unknown
			//IL_0092: 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_00ae: Unknown result type (might be due to invalid IL or missing references)
			if (_original.ContainsKey(material))
			{
				return material;
			}
			if (_faded.TryGetValue(material, out Material value))
			{
				return value;
			}
			if (Opacity >= 1f)
			{
				return material;
			}
			value = new Material(material)
			{
				name = ((Object)material).name + " (Ghost)"
			};
			value.SetFloat("_SurfaceType", 1f);
			value.SetFloat("_TransparentDepthPrepassEnable", 1f);
			if (!HDMaterial.ValidateMaterial(value) || !value.HasProperty("_BaseColor"))
			{
				Object.Destroy((Object)(object)value);
				value = material;
			}
			else
			{
				Color color = value.GetColor("_BaseColor");
				color.a *= Opacity;
				value.SetColor("_BaseColor", color);
				_original[value] = material;
			}
			_faded[material] = value;
			return value;
		}

		internal void Lay()
		{
			Risen = false;
			Abandoned = false;
			if (_ship != null)
			{
				Intangible(intangible: false);
			}
			foreach (Graphic item in OnBody<Graphic>(((Component)_player).transform))
			{
				item.canvasRenderer.SetAlpha(1f);
			}
			foreach (Renderer item2 in _hidden)
			{
				if ((Object)(object)item2 != (Object)null)
				{
					item2.forceRenderingOff = false;
				}
			}
			foreach (Renderer item3 in OnBody<Renderer>(((Component)_player.thisPlayerModel).transform.parent))
			{
				Material[] sharedMaterials = item3.sharedMaterials;
				for (int i = 0; i < sharedMaterials.Length; i++)
				{
					if ((Object)(object)sharedMaterials[i] != (Object)null && _original.TryGetValue(sharedMaterials[i], out Material value))
					{
						sharedMaterials[i] = value;
					}
				}
				item3.sharedMaterials = sharedMaterials;
			}
			Object.Destroy((Object)(object)this);
		}

		private void OnDestroy()
		{
			Risen = false;
			foreach (Material key in _original.Keys)
			{
				Object.Destroy((Object)(object)key);
			}
		}

		private IEnumerable<T> OnBody<T>(Transform root) where T : Component
		{
			Transform camera = ((Component)_player.gameplayCamera).transform;
			T[] componentsInChildren = ((Component)root).GetComponentsInChildren<T>(true);
			foreach (T val in componentsInChildren)
			{
				if (!((Component)val).transform.IsChildOf(camera))
				{
					yield return val;
				}
			}
		}
	}
	public static class MyPluginInfo
	{
		public const string PLUGIN_GUID = "CompanyGhosts";

		public const string PLUGIN_NAME = "CompanyGhosts";

		public const string PLUGIN_VERSION = "1.0.0";
	}
}