Decompiled source of Poltergeist Possession v1.0.0

BepInEx/plugins/PoltergeistPossession/PoltergeistPossession.dll

Decompiled an hour ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using System.Text;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using GameNetcodeStuff;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using Poltergeist;
using TMPro;
using Unity.Collections;
using Unity.Netcode;
using UnityEngine;
using UnityEngine.AI;
using UnityEngine.InputSystem;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: IgnoresAccessChecksTo("Assembly-CSharp")]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("PoltergeistPossession")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0")]
[assembly: AssemblyProduct("PoltergeistPossession")]
[assembly: AssemblyTitle("PoltergeistPossession")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.0.0.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace PoltergeistPossession
{
	internal class EnemyProfile
	{
		private class Bracken : EnemyProfile
		{
			public override float CameraHeight => 2.4f;

			public override float WalkSpeed(EnemyAI e)
			{
				return 6f;
			}

			public override float RunSpeed(EnemyAI e)
			{
				if (e.currentBehaviourStateIndex != 2)
				{
					return 9f;
				}
				return 12f;
			}

			public override bool CanMove(EnemyAI e)
			{
				//IL_0001: Unknown result type (might be due to invalid IL or missing references)
				return !((FlowermanAI)e).inKillAnimation;
			}

			public override string PrimaryName(EnemyAI e)
			{
				//IL_0001: Unknown result type (might be due to invalid IL or missing references)
				if (!((FlowermanAI)e).carryingPlayerBody)
				{
					return "Anger";
				}
				return "Drop body";
			}

			public override void OnPrimary(EnemyAI e)
			{
				//IL_0001: Unknown result type (might be due to invalid IL or missing references)
				//IL_0007: Expected O, but got Unknown
				FlowermanAI val = (FlowermanAI)e;
				if (!val.inKillAnimation)
				{
					if (val.carryingPlayerBody)
					{
						val.DropPlayerBodyServerRpc();
					}
					else if (((EnemyAI)val).currentBehaviourStateIndex != 2)
					{
						val.EnterAngerModeServerRpc(10f);
					}
				}
			}
		}

		private class Jester : EnemyProfile
		{
			private const float CrankTime = 8f;

			public override float CameraHeight => 2.4f;

			public override float WalkSpeed(EnemyAI e)
			{
				if (e.currentBehaviourStateIndex != 2)
				{
					return 5f;
				}
				return 9f;
			}

			public override float RunSpeed(EnemyAI e)
			{
				if (e.currentBehaviourStateIndex != 2)
				{
					return 5f;
				}
				return 14f;
			}

			public override bool CanMove(EnemyAI e)
			{
				//IL_000a: Unknown result type (might be due to invalid IL or missing references)
				if (e.currentBehaviourStateIndex != 1)
				{
					return !((JesterAI)e).inKillAnimation;
				}
				return false;
			}

			public override bool CanRotate(EnemyAI e)
			{
				//IL_0001: Unknown result type (might be due to invalid IL or missing references)
				return !((JesterAI)e).inKillAnimation;
			}

			public override string PrimaryName(EnemyAI e)
			{
				return e.currentBehaviourStateIndex switch
				{
					0 => "Wind crank", 
					1 => "Pop out now", 
					_ => "Back in the box", 
				};
			}

			public override void OnPrimary(EnemyAI e)
			{
				//IL_0001: Unknown result type (might be due to invalid IL or missing references)
				//IL_0007: Expected O, but got Unknown
				JesterAI val = (JesterAI)e;
				if (!val.inKillAnimation)
				{
					switch (((EnemyAI)val).currentBehaviourStateIndex)
					{
					case 0:
						((EnemyAI)val).SwitchToBehaviourState(1);
						break;
					case 1:
						((EnemyAI)val).SwitchToBehaviourState(2);
						break;
					default:
						((EnemyAI)val).SwitchToBehaviourState(0);
						break;
					}
				}
			}

			public override void OnTick(EnemyAI e)
			{
				//IL_0001: Unknown result type (might be due to invalid IL or missing references)
				//IL_0007: Expected O, but got Unknown
				JesterAI val = (JesterAI)e;
				if (((EnemyAI)val).currentBehaviourStateIndex == 1 && val.popUpTimer > 8f)
				{
					val.popUpTimer = 8f;
				}
				if (((EnemyAI)val).currentBehaviourStateIndex == 2)
				{
					val.noPlayersToChaseTimer = 5f;
				}
			}
		}

		private class CoilHead : EnemyProfile
		{
			private float nextStateCheck;

			public override float CameraHeight => 2.8f;

			public override float WalkSpeed(EnemyAI e)
			{
				return 8f;
			}

			public override float RunSpeed(EnemyAI e)
			{
				return 14f;
			}

			public override bool CanMove(EnemyAI e)
			{
				//IL_0001: Unknown result type (might be due to invalid IL or missing references)
				//IL_0007: Expected O, but got Unknown
				SpringManAI val = (SpringManAI)e;
				if (!val.stoppingMovement)
				{
					return !val.inCooldownAnimation;
				}
				return false;
			}

			public override void OnStart(EnemyAI e)
			{
				nextStateCheck = 0f;
			}

			public override void OnTick(EnemyAI e)
			{
				//IL_0001: Unknown result type (might be due to invalid IL or missing references)
				//IL_0007: Expected O, but got Unknown
				SpringManAI val = (SpringManAI)e;
				if (!(Time.time < nextStateCheck))
				{
					nextStateCheck = Time.time + 1f;
					if (((EnemyAI)val).currentBehaviourStateIndex != 1 && !val.inCooldownAnimation && !val.setOnCooldown)
					{
						((EnemyAI)val).SwitchToBehaviourState(1);
					}
				}
			}
		}

		private class EyelessDog : EnemyProfile
		{
			public override float CameraHeight => 3f;

			public override float CameraDistance => 4.5f;

			public override float WalkSpeed(EnemyAI e)
			{
				return 4.5f;
			}

			public override float RunSpeed(EnemyAI e)
			{
				return 13f;
			}

			public override bool CanMove(EnemyAI e)
			{
				//IL_0001: Unknown result type (might be due to invalid IL or missing references)
				if (!((MouthDogAI)e).inKillAnimation)
				{
					return e.currentBehaviourStateIndex != 3;
				}
				return false;
			}

			public override string PrimaryName(EnemyAI e)
			{
				if (e.currentBehaviourStateIndex != 3)
				{
					return "Lunge";
				}
				return null;
			}

			public override void OnPrimary(EnemyAI e)
			{
				//IL_0001: Unknown result type (might be due to invalid IL or missing references)
				//IL_0007: Expected O, but got Unknown
				MouthDogAI val = (MouthDogAI)e;
				if (!val.inKillAnimation && !val.inLunge && ((EnemyAI)val).currentBehaviourStateIndex != 3)
				{
					val.inLunge = true;
					val.EnterLunge();
				}
			}

			public override bool ForcedVelocity(EnemyAI e, out Vector3 velocity)
			{
				//IL_0001: Unknown result type (might be due to invalid IL or missing references)
				//IL_0007: Expected O, but got Unknown
				//IL_0059: Unknown result type (might be due to invalid IL or missing references)
				//IL_005e: Unknown result type (might be due to invalid IL or missing references)
				//IL_002d: Unknown result type (might be due to invalid IL or missing references)
				//IL_004c: Unknown result type (might be due to invalid IL or missing references)
				//IL_0051: Unknown result type (might be due to invalid IL or missing references)
				MouthDogAI val = (MouthDogAI)e;
				if (((EnemyAI)val).currentBehaviourStateIndex == 3 && !val.inKillAnimation && (Object)(object)((EnemyAI)val).agent != (Object)null)
				{
					velocity = ((Component)val).transform.forward * Mathf.Clamp(((EnemyAI)val).agent.speed, 0f, 13f);
					return true;
				}
				velocity = Vector3.zero;
				return false;
			}
		}

		private class Thumper : EnemyProfile
		{
			private float nextScreech;

			public override float CameraHeight => 2.6f;

			public override float CameraDistance => 4f;

			public override float WalkSpeed(EnemyAI e)
			{
				return 6f;
			}

			public override float RunSpeed(EnemyAI e)
			{
				return 14f;
			}

			public override string PrimaryName(EnemyAI e)
			{
				return "Screech";
			}

			public override void OnPrimary(EnemyAI e)
			{
				//IL_0020: Unknown result type (might be due to invalid IL or missing references)
				if (!(Time.time < nextScreech))
				{
					nextScreech = Time.time + 1.5f;
					((CrawlerAI)e).MakeScreechNoiseServerRpc();
				}
			}
		}

		private class Nutcracker : EnemyProfile
		{
			public override float CameraHeight => 2.8f;

			public override float WalkSpeed(EnemyAI e)
			{
				return 5.5f;
			}

			public override float RunSpeed(EnemyAI e)
			{
				return 7f;
			}

			public override string PrimaryName(EnemyAI e)
			{
				//IL_0001: Unknown result type (might be due to invalid IL or missing references)
				if (!((Object)(object)((NutcrackerEnemyAI)e).gun != (Object)null))
				{
					return null;
				}
				return "Fire shotgun";
			}

			private static bool Ready(NutcrackerEnemyAI nut)
			{
				if ((Object)(object)nut.gun != (Object)null && !nut.reloadingGun && !nut.aimingGun)
				{
					return nut.timeSinceFiringGun >= 0.75f;
				}
				return false;
			}

			public override void OnPrimary(EnemyAI e)
			{
				//IL_0001: Unknown result type (might be due to invalid IL or missing references)
				//IL_0007: Expected O, but got Unknown
				NutcrackerEnemyAI val = (NutcrackerEnemyAI)e;
				if (Ready(val) && val.gun.shellsLoaded > 0)
				{
					val.timeSinceFiringGun = 0f;
					val.FireGunServerRpc();
				}
			}

			public override void OnTick(EnemyAI e)
			{
				//IL_0001: Unknown result type (might be due to invalid IL or missing references)
				//IL_0007: Expected O, but got Unknown
				NutcrackerEnemyAI val = (NutcrackerEnemyAI)e;
				if (Ready(val) && val.gun.shellsLoaded <= 0)
				{
					val.reloadingGun = true;
					val.ReloadGunServerRpc();
				}
			}
		}

		private class HoardingBug : EnemyProfile
		{
			private bool angry;

			public override float CameraHeight => 1.8f;

			public override float WalkSpeed(EnemyAI e)
			{
				return 6f;
			}

			public override float RunSpeed(EnemyAI e)
			{
				if (!angry)
				{
					return 9f;
				}
				return 12f;
			}

			public override string PrimaryName(EnemyAI e)
			{
				if (!angry)
				{
					return "Get angry";
				}
				return "Calm down";
			}

			public override void OnStart(EnemyAI e)
			{
				angry = false;
			}

			public override void OnPrimary(EnemyAI e)
			{
				//IL_0001: Unknown result type (might be due to invalid IL or missing references)
				//IL_0007: Expected O, but got Unknown
				//IL_0025: Unknown result type (might be due to invalid IL or missing references)
				HoarderBugAI val = (HoarderBugAI)e;
				angry = !angry;
				if (angry)
				{
					val.angryAtPlayer = ClosestLivingPlayer(((Component)val).transform.position);
					val.angryTimer = 15f;
					if (((EnemyAI)val).currentBehaviourStateIndex != 2)
					{
						((EnemyAI)val).SwitchToBehaviourState(2);
					}
				}
				else
				{
					val.angryTimer = 0f;
				}
			}

			public override void OnTick(EnemyAI e)
			{
				//IL_0009: Unknown result type (might be due to invalid IL or missing references)
				if (angry)
				{
					((HoarderBugAI)e).angryTimer = 15f;
				}
			}

			public override void OnEnd(EnemyAI e)
			{
				//IL_0009: Unknown result type (might be due to invalid IL or missing references)
				if (angry)
				{
					((HoarderBugAI)e).angryTimer = 3f;
				}
			}
		}

		private class SporeLizard : EnemyProfile
		{
			private float nextAction;

			public override float WalkSpeed(EnemyAI e)
			{
				return 4f;
			}

			public override float RunSpeed(EnemyAI e)
			{
				return 8f;
			}

			public override string PrimaryName(EnemyAI e)
			{
				return "Stomp";
			}

			public override string SecondaryName(EnemyAI e)
			{
				return "Smoke";
			}

			private bool Ready(PufferAI puffer)
			{
				if (puffer.inPuffingAnimation || Time.time < nextAction)
				{
					return false;
				}
				nextAction = Time.time + 1f;
				return true;
			}

			public override void OnPrimary(EnemyAI e)
			{
				//IL_0001: Unknown result type (might be due to invalid IL or missing references)
				//IL_0007: Expected O, but got Unknown
				PufferAI val = (PufferAI)e;
				if (Ready(val))
				{
					val.StompServerRpc();
				}
			}

			public override void OnSecondary(EnemyAI e)
			{
				//IL_0001: Unknown result type (might be due to invalid IL or missing references)
				//IL_0007: Expected O, but got Unknown
				PufferAI val = (PufferAI)e;
				if (Ready(val))
				{
					val.ShakeTailServerRpc();
				}
			}
		}

		private class SnareFlea : EnemyProfile
		{
			public override float CameraHeight => 1.6f;

			public override float WalkSpeed(EnemyAI e)
			{
				return 5.5f;
			}

			public override float RunSpeed(EnemyAI e)
			{
				return 7.5f;
			}

			private static bool Busy(CentipedeAI flea)
			{
				if (!((Object)(object)flea.clingingToPlayer != (Object)null) && !flea.clingingToCeiling && !flea.clingingToDeadBody)
				{
					return ((EnemyAI)flea).inSpecialAnimation;
				}
				return true;
			}

			public override bool CanMove(EnemyAI e)
			{
				//IL_0001: Unknown result type (might be due to invalid IL or missing references)
				//IL_000b: Expected O, but got Unknown
				return !Busy((CentipedeAI)e);
			}

			public override string PrimaryName(EnemyAI e)
			{
				//IL_000a: Unknown result type (might be due to invalid IL or missing references)
				if (e.currentBehaviourStateIndex != 2)
				{
					if (!((CentipedeAI)e).clingingToCeiling)
					{
						return "Attack mode";
					}
					return "Drop down";
				}
				return null;
			}

			public override string SecondaryName(EnemyAI e)
			{
				//IL_0001: Unknown result type (might be due to invalid IL or missing references)
				//IL_000b: Expected O, but got Unknown
				if (!Busy((CentipedeAI)e))
				{
					return "Hide on ceiling";
				}
				return null;
			}

			public override void OnPrimary(EnemyAI e)
			{
				//IL_0001: Unknown result type (might be due to invalid IL or missing references)
				//IL_0007: Expected O, but got Unknown
				CentipedeAI val = (CentipedeAI)e;
				if (!((Object)(object)val.clingingToPlayer != (Object)null) && ((EnemyAI)val).currentBehaviourStateIndex != 2)
				{
					((EnemyAI)val).SwitchToBehaviourState(2);
				}
			}

			public override void OnSecondary(EnemyAI e)
			{
				//IL_0001: Unknown result type (might be due to invalid IL or missing references)
				//IL_0007: Expected O, but got Unknown
				CentipedeAI val = (CentipedeAI)e;
				if (!Busy(val))
				{
					val.RaycastToCeiling();
				}
			}
		}

		private class Butler : EnemyProfile
		{
			private bool knife;

			private float nextStateCheck;

			public override float CameraHeight => 2.4f;

			public override float WalkSpeed(EnemyAI e)
			{
				return 3.5f;
			}

			public override float RunSpeed(EnemyAI e)
			{
				return 8f;
			}

			public override bool CanMove(EnemyAI e)
			{
				return !e.inSpecialAnimation;
			}

			public override string PrimaryName(EnemyAI e)
			{
				if (!knife)
				{
					return "Draw knife";
				}
				return "Put knife away";
			}

			public override void OnStart(EnemyAI e)
			{
				knife = e.currentBehaviourStateIndex == 2;
			}

			public override void OnPrimary(EnemyAI e)
			{
				if (!e.inSpecialAnimation)
				{
					knife = !knife;
					e.SwitchToBehaviourState(knife ? 2 : 0);
					nextStateCheck = Time.time + 1f;
				}
			}

			public override void OnTick(EnemyAI e)
			{
				if (knife && !e.inSpecialAnimation && !(Time.time < nextStateCheck))
				{
					nextStateCheck = Time.time + 1f;
					if (e.currentBehaviourStateIndex != 2)
					{
						e.SwitchToBehaviourState(2);
					}
				}
			}
		}

		private class Masked : EnemyProfile
		{
			private bool handsOut;

			private bool crouching;

			public override float CameraHeight => 2.4f;

			public override float WalkSpeed(EnemyAI e)
			{
				return 3.8f;
			}

			public override float RunSpeed(EnemyAI e)
			{
				return 7.3f;
			}

			public override bool CanMove(EnemyAI e)
			{
				//IL_0001: Unknown result type (might be due to invalid IL or missing references)
				return !((MaskedPlayerEnemy)e).inKillAnimation;
			}

			public override string PrimaryName(EnemyAI e)
			{
				if (!handsOut)
				{
					return "Raise arms";
				}
				return "Lower arms";
			}

			public override string SecondaryName(EnemyAI e)
			{
				if (!crouching)
				{
					return "Crouch";
				}
				return "Stand";
			}

			public override void OnStart(EnemyAI e)
			{
				handsOut = false;
				crouching = false;
			}

			public override void OnPrimary(EnemyAI e)
			{
				//IL_0010: Unknown result type (might be due to invalid IL or missing references)
				handsOut = !handsOut;
				((MaskedPlayerEnemy)e).SetHandsOutServerRpc(handsOut);
			}

			public override void OnSecondary(EnemyAI e)
			{
				//IL_0010: Unknown result type (might be due to invalid IL or missing references)
				crouching = !crouching;
				((MaskedPlayerEnemy)e).SetCrouchingServerRpc(crouching);
			}

			public override void OnEnd(EnemyAI e)
			{
				//IL_0001: Unknown result type (might be due to invalid IL or missing references)
				//IL_0007: Expected O, but got Unknown
				MaskedPlayerEnemy val = (MaskedPlayerEnemy)e;
				if (handsOut)
				{
					val.SetHandsOutServerRpc(false);
				}
				if (crouching)
				{
					val.SetCrouchingServerRpc(false);
				}
			}
		}

		private class ForestGiant : EnemyProfile
		{
			public override float CameraHeight => 7f;

			public override float CameraDistance => 9f;

			public override float WalkSpeed(EnemyAI e)
			{
				return 5f;
			}

			public override float RunSpeed(EnemyAI e)
			{
				return 8f;
			}

			public override bool CanMove(EnemyAI e)
			{
				//IL_0001: Unknown result type (might be due to invalid IL or missing references)
				return !((ForestGiantAI)e).inEatingPlayerAnimation;
			}
		}

		private class Spider : EnemyProfile
		{
			public override float CameraHeight => 2f;

			public override float CameraDistance => 4f;

			public override float WalkSpeed(EnemyAI e)
			{
				return 4.5f;
			}

			public override float RunSpeed(EnemyAI e)
			{
				return 6.5f;
			}
		}

		private class Hygrodere : EnemyProfile
		{
			public override float CameraHeight => 2f;

			public override float CameraDistance => 4f;

			public override float WalkSpeed(EnemyAI e)
			{
				return 2f;
			}

			public override float RunSpeed(EnemyAI e)
			{
				return 3.5f;
			}
		}

		private class BaboonHawk : EnemyProfile
		{
			public override float CameraHeight => 2.6f;

			public override float WalkSpeed(EnemyAI e)
			{
				return 7f;
			}

			public override float RunSpeed(EnemyAI e)
			{
				return 11f;
			}

			public override bool CanMove(EnemyAI e)
			{
				//IL_0001: Unknown result type (might be due to invalid IL or missing references)
				return !((BaboonBirdAI)e).doingKillAnimation;
			}
		}

		private class Maneater : EnemyProfile
		{
			public override float CameraHeight => 2.4f;

			public override float WalkSpeed(EnemyAI e)
			{
				return 5f;
			}

			public override float RunSpeed(EnemyAI e)
			{
				return 9f;
			}

			public override string CannotPossessReason(EnemyAI e)
			{
				if (e.currentBehaviourStateIndex != 0)
				{
					return null;
				}
				return "It's only a baby";
			}

			public override bool CanMove(EnemyAI e)
			{
				//IL_0011: Unknown result type (might be due to invalid IL or missing references)
				if (e.currentBehaviourStateIndex != 0 && !e.inSpecialAnimation)
				{
					return !((CaveDwellerAI)e).inKillAnimation;
				}
				return false;
			}
		}

		public virtual float CameraHeight => 2.2f;

		public virtual float CameraDistance => 3.5f;

		public virtual float WalkSpeed(EnemyAI e)
		{
			return 5f;
		}

		public virtual float RunSpeed(EnemyAI e)
		{
			return 8f;
		}

		public virtual string PrimaryName(EnemyAI e)
		{
			return null;
		}

		public virtual string SecondaryName(EnemyAI e)
		{
			return null;
		}

		public virtual string CannotPossessReason(EnemyAI e)
		{
			return null;
		}

		public virtual bool CanMove(EnemyAI e)
		{
			return true;
		}

		public virtual bool CanRotate(EnemyAI e)
		{
			return CanMove(e);
		}

		public virtual bool ForcedVelocity(EnemyAI e, out Vector3 velocity)
		{
			//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)
			velocity = Vector3.zero;
			return false;
		}

		public virtual void OnStart(EnemyAI e)
		{
		}

		public virtual void OnTick(EnemyAI e)
		{
		}

		public virtual void OnPrimary(EnemyAI e)
		{
		}

		public virtual void OnSecondary(EnemyAI e)
		{
		}

		public virtual void OnEnd(EnemyAI e)
		{
		}

		public static EnemyProfile For(EnemyAI enemy)
		{
			if (!(enemy is FlowermanAI))
			{
				if (!(enemy is JesterAI))
				{
					if (!(enemy is SpringManAI))
					{
						if (!(enemy is MouthDogAI))
						{
							if (!(enemy is CrawlerAI))
							{
								if (!(enemy is NutcrackerEnemyAI))
								{
									if (!(enemy is HoarderBugAI))
									{
										if (!(enemy is PufferAI))
										{
											if (!(enemy is CentipedeAI))
											{
												if (!(enemy is ButlerEnemyAI))
												{
													if (!(enemy is MaskedPlayerEnemy))
													{
														if (!(enemy is ForestGiantAI))
														{
															if (!(enemy is SandSpiderAI))
															{
																if (!(enemy is BlobAI))
																{
																	if (!(enemy is BaboonBirdAI))
																	{
																		if (enemy is CaveDwellerAI)
																		{
																			return new Maneater();
																		}
																		return new EnemyProfile();
																	}
																	return new BaboonHawk();
																}
																return new Hygrodere();
															}
															return new Spider();
														}
														return new ForestGiant();
													}
													return new Masked();
												}
												return new Butler();
											}
											return new SnareFlea();
										}
										return new SporeLizard();
									}
									return new HoardingBug();
								}
								return new Nutcracker();
							}
							return new Thumper();
						}
						return new EyelessDog();
					}
					return new CoilHead();
				}
				return new Jester();
			}
			return new Bracken();
		}

		protected static PlayerControllerB ClosestLivingPlayer(Vector3 position)
		{
			//IL_004e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0053: Unknown result type (might be due to invalid IL or missing references)
			//IL_0054: Unknown result type (might be due to invalid IL or missing references)
			//IL_0059: Unknown result type (might be due to invalid IL or missing references)
			StartOfRound instance = StartOfRound.Instance;
			if ((Object)(object)instance == (Object)null)
			{
				return null;
			}
			PlayerControllerB result = null;
			float num = float.MaxValue;
			PlayerControllerB[] allPlayerScripts = instance.allPlayerScripts;
			foreach (PlayerControllerB val in allPlayerScripts)
			{
				if (!((Object)(object)val == (Object)null) && val.isPlayerControlled && !val.isPlayerDead)
				{
					Vector3 val2 = ((Component)val).transform.position - position;
					float sqrMagnitude = ((Vector3)(ref val2)).sqrMagnitude;
					if (sqrMagnitude < num)
					{
						num = sqrMagnitude;
						result = val;
					}
				}
			}
			return result;
		}
	}
	[HarmonyPatch(typeof(SpectatorCamController))]
	internal static class GhostCamPatches
	{
		private static readonly FieldRef<SpectatorCamController, float> PowerRef = AccessTools.FieldRefAccess<SpectatorCamController, float>("power");

		[HarmonyPrefix]
		[HarmonyPatch("LateUpdate")]
		private static void BeforeCamUpdate(SpectatorCamController __instance, out float __state)
		{
			__state = PowerRef.Invoke(__instance);
		}

		[HarmonyPostfix]
		[HarmonyPatch("LateUpdate")]
		private static void AfterCamUpdate(SpectatorCamController __instance, float __state)
		{
			if ((Object)(object)PossessionController.Instance != (Object)null)
			{
				PossessionController.Instance.AfterGhostCamUpdate(__instance, __state);
			}
		}

		[HarmonyPrefix]
		[HarmonyPatch("DoInteract")]
		private static bool OnInteract()
		{
			if ((Object)(object)PossessionController.Instance == (Object)null)
			{
				return true;
			}
			return !PossessionController.Instance.HandleInteractPressed();
		}

		[HarmonyPrefix]
		[HarmonyPatch("SwitchLight")]
		private static bool OnSwitchLight()
		{
			if (!((Object)(object)PossessionController.Instance == (Object)null))
			{
				return !PossessionController.Instance.IsPossessing;
			}
			return true;
		}
	}
	[HarmonyPatch]
	internal static class GamePatches
	{
		[HarmonyPrefix]
		[HarmonyPatch(typeof(EnemyAI), "ChangeOwnershipOfEnemy")]
		private static bool KeepPossessedOwnership(EnemyAI __instance, ulong newOwnerClientId)
		{
			if (!PossessionNet.TryGetPossessor(__instance, out var playerIndex))
			{
				return true;
			}
			PlayerControllerB player = PossessionNet.GetPlayer(playerIndex);
			if (!((Object)(object)player == (Object)null))
			{
				return player.actualClientId == newOwnerClientId;
			}
			return true;
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(StartOfRound), "UpdatePlayerVoiceEffects")]
		private static void AfterVoiceEffects()
		{
			VoiceRouter.Apply(setVolume: true);
		}
	}
	[BepInPlugin("poltergeist.addon.possession", "Poltergeist-Possession", "1.0.0")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	public class Plugin : BaseUnityPlugin
	{
		public const string GUID = "poltergeist.addon.possession";

		public const string NAME = "Poltergeist-Possession";

		public const string VERSION = "1.0.0";

		internal static ManualLogSource Log;

		internal static PossessionConfig Cfg;

		private void Awake()
		{
			//IL_0020: Unknown result type (might be due to invalid IL or missing references)
			//IL_003e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0043: Unknown result type (might be due to invalid IL or missing references)
			//IL_0049: Expected O, but got Unknown
			//IL_0049: Unknown result type (might be due to invalid IL or missing references)
			Log = ((BaseUnityPlugin)this).Logger;
			Cfg = new PossessionConfig(((BaseUnityPlugin)this).Config);
			new Harmony("poltergeist.addon.possession").PatchAll(typeof(Plugin).Assembly);
			GameObject val = new GameObject("PoltergeistPossessionController");
			Object.DontDestroyOnLoad((Object)val);
			((Object)val).hideFlags = (HideFlags)61;
			val.AddComponent<PossessionController>();
			Log.LogInfo((object)"Poltergeist-Possession 1.0.0 loaded");
		}

		internal static void Debug(string msg)
		{
			if (Cfg != null && Cfg.DebugLogs.Value)
			{
				Log.LogInfo((object)msg);
			}
		}
	}
	public class PossessionConfig
	{
		public const string DefaultBlacklist = "DressGirlAI,SandWormAI,RadMechAI,RedLocustBees,DocileLocustBeesAI,ButlerBeesEnemyAI,DoublewingAI,FlowerSnakeEnemy,LassoManAI";

		public ConfigEntry<float> DrainPerSecond;

		public ConfigEntry<float> MinPowerToPossess;

		public ConfigEntry<float> PossessRange;

		public ConfigEntry<float> MoveSpeedMultiplier;

		public ConfigEntry<bool> AllowAbilities;

		public ConfigEntry<bool> VoiceThroughMonster;

		public ConfigEntry<string> Blacklist;

		public ConfigEntry<float> CameraDistance;

		public ConfigEntry<bool> DebugLogs;

		public PossessionConfig(ConfigFile cfg)
		{
			//IL_0030: Unknown result type (might be due to invalid IL or missing references)
			//IL_003a: Expected O, but got Unknown
			//IL_0069: Unknown result type (might be due to invalid IL or missing references)
			//IL_0073: Expected O, but got Unknown
			//IL_00a2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ac: Expected O, but got Unknown
			//IL_00db: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e5: Expected O, but got Unknown
			//IL_016c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0176: Expected O, but got Unknown
			DrainPerSecond = cfg.Bind<float>("Host", "DrainPerSecond", 1f, new ConfigDescription("Poltergeist power consumed per second while possessing a monster. Power does not regenerate while possessing.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 100f), Array.Empty<object>()));
			MinPowerToPossess = cfg.Bind<float>("Host", "MinPowerToPossess", 5f, new ConfigDescription("Power a ghost needs to have before it can start a possession.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 1000f), Array.Empty<object>()));
			PossessRange = cfg.Bind<float>("Host", "PossessRange", 3f, new ConfigDescription("How close (in metres) the ghost has to be to a monster to possess it.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.5f, 30f), Array.Empty<object>()));
			MoveSpeedMultiplier = cfg.Bind<float>("Host", "MoveSpeedMultiplier", 1f, new ConfigDescription("Multiplier on how fast possessed monsters move.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.1f, 5f), Array.Empty<object>()));
			AllowAbilities = cfg.Bind<bool>("Host", "AllowAbilities", true, "If false, ghosts can only move and talk through monsters; the attack buttons do nothing. Monsters still hurt players they touch.");
			VoiceThroughMonster = cfg.Bind<bool>("Host", "VoiceThroughMonster", true, "If true, living players hear the possessing ghost's voice coming from the monster.");
			Blacklist = cfg.Bind<string>("Host", "Blacklist", "DressGirlAI,SandWormAI,RadMechAI,RedLocustBees,DocileLocustBeesAI,ButlerBeesEnemyAI,DoublewingAI,FlowerSnakeEnemy,LassoManAI", "Comma separated monsters that can not be possessed. Accepts the internal class name (e.g. FlowermanAI) or the in-game enemy name (e.g. Flowerman).");
			CameraDistance = cfg.Bind<float>("Client", "CameraDistance", 1f, new ConfigDescription("Multiplier on how far the camera sits behind a possessed monster.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.3f, 4f), Array.Empty<object>()));
			DebugLogs = cfg.Bind<bool>("Client", "DebugLogs", false, "Print extra information to the log.");
		}
	}
	public class NetSettings
	{
		public float Drain = 1f;

		public float MinPower = 5f;

		public float Range = 3f;

		public float Speed = 1f;

		public bool Abilities = true;

		public bool Voice = true;

		public string Blacklist = "DressGirlAI,SandWormAI,RadMechAI,RedLocustBees,DocileLocustBeesAI,ButlerBeesEnemyAI,DoublewingAI,FlowerSnakeEnemy,LassoManAI";

		private HashSet<string> blacklistSet;

		public static NetSettings Active = new NetSettings();

		public static NetSettings FromConfig()
		{
			PossessionConfig cfg = Plugin.Cfg;
			return new NetSettings
			{
				Drain = cfg.DrainPerSecond.Value,
				MinPower = cfg.MinPowerToPossess.Value,
				Range = cfg.PossessRange.Value,
				Speed = cfg.MoveSpeedMultiplier.Value,
				Abilities = cfg.AllowAbilities.Value,
				Voice = cfg.VoiceThroughMonster.Value,
				Blacklist = (cfg.Blacklist.Value ?? "")
			};
		}

		public bool IsBlacklisted(EnemyAI enemy)
		{
			if (blacklistSet == null)
			{
				blacklistSet = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
				string[] array = (Blacklist ?? "").Split(',');
				for (int i = 0; i < array.Length; i++)
				{
					string text = array[i].Trim();
					if (text.Length > 0)
					{
						blacklistSet.Add(text);
					}
				}
			}
			if (blacklistSet.Contains(((object)enemy).GetType().Name))
			{
				return true;
			}
			if ((Object)(object)enemy.enemyType != (Object)null && enemy.enemyType.enemyName != null)
			{
				return blacklistSet.Contains(enemy.enemyType.enemyName.Trim());
			}
			return false;
		}

		public byte[] Serialize()
		{
			using MemoryStream memoryStream = new MemoryStream();
			using BinaryWriter binaryWriter = new BinaryWriter(memoryStream);
			binaryWriter.Write(Drain);
			binaryWriter.Write(MinPower);
			binaryWriter.Write(Range);
			binaryWriter.Write(Speed);
			binaryWriter.Write(Abilities);
			binaryWriter.Write(Voice);
			binaryWriter.Write(Blacklist ?? "");
			binaryWriter.Flush();
			return memoryStream.ToArray();
		}

		public static NetSettings Deserialize(byte[] data)
		{
			using MemoryStream input = new MemoryStream(data);
			using BinaryReader binaryReader = new BinaryReader(input);
			return new NetSettings
			{
				Drain = binaryReader.ReadSingle(),
				MinPower = binaryReader.ReadSingle(),
				Range = binaryReader.ReadSingle(),
				Speed = binaryReader.ReadSingle(),
				Abilities = binaryReader.ReadBoolean(),
				Voice = binaryReader.ReadBoolean(),
				Blacklist = binaryReader.ReadString()
			};
		}
	}
	public class PossessionController : MonoBehaviour
	{
		private enum Phase
		{
			Idle,
			Pending,
			Active
		}

		private static readonly FieldRef<SpectatorCamController, float> PowerRef = AccessTools.FieldRefAccess<SpectatorCamController, float>("power");

		private static readonly FieldRef<SpectatorCamController, float> MaxPowerRef = AccessTools.FieldRefAccess<SpectatorCamController, float>("maxPower");

		private Phase phase;

		private EnemyAI enemy;

		private EnemyProfile profile;

		private string enemyName = "";

		private float pendingDeadline;

		private bool hasControl;

		private bool savedState;

		private float ownerWait;

		private float nextOwnerRequest;

		private bool savedUpdateRotation;

		private float savedPositionThreshold;

		private float nextPositionSync;

		private float yaw;

		private float pitch;

		private EnemyAI candidate;

		private EnemyProfile candidateProfile;

		private string candidateBlocked;

		private float nextScan;

		private readonly Dictionary<EnemyAI, Collider[]> colliderCache = new Dictionary<EnemyAI, Collider[]>();

		private bool abilityErrorLogged;

		public static PossessionController Instance { get; private set; }

		public bool IsPossessing => phase == Phase.Active;

		public bool IsBusy => phase != Phase.Idle;

		private static PlayerControllerB LocalPlayer
		{
			get
			{
				if (!((Object)(object)StartOfRound.Instance != (Object)null))
				{
					return null;
				}
				return StartOfRound.Instance.localPlayerController;
			}
		}

		private static bool GhostCamActive
		{
			get
			{
				SpectatorCamController instance = SpectatorCamController.instance;
				if ((Object)(object)instance != (Object)null && ((Behaviour)instance).enabled)
				{
					return !Patches.vanillaMode;
				}
				return false;
			}
		}

		private void Awake()
		{
			Instance = this;
		}

		private static bool InputPaused(PlayerControllerB player)
		{
			if (!((Object)(object)player == (Object)null) && !player.isTypingChat)
			{
				if ((Object)(object)player.quickMenuManager != (Object)null)
				{
					return player.quickMenuManager.isMenuOpen;
				}
				return false;
			}
			return true;
		}

		private static string NameOf(EnemyAI e)
		{
			if ((Object)(object)e != (Object)null && (Object)(object)e.enemyType != (Object)null && !string.IsNullOrEmpty(e.enemyType.enemyName))
			{
				return e.enemyType.enemyName;
			}
			return "monster";
		}

		public bool HandleInteractPressed()
		{
			if (InputPaused(LocalPlayer) || !PossessionNet.Ready)
			{
				return false;
			}
			if (phase != Phase.Idle)
			{
				Release();
				return true;
			}
			if (!GhostCamActive || (Object)(object)candidate == (Object)null)
			{
				return false;
			}
			SpectatorCamController instance = SpectatorCamController.instance;
			if (candidateBlocked != null)
			{
				HUDManager.Instance.DisplayTip("Can't possess", candidateBlocked, true, false, "LC_Tip1");
				return true;
			}
			if (instance.Power < NetSettings.Active.MinPower)
			{
				HUDManager.Instance.DisplayTip("Can't possess", "Not enough power (" + NetSettings.Active.MinPower.ToString("F0") + " needed).", true, false, "LC_Tip1");
				return true;
			}
			enemy = candidate;
			enemyName = NameOf(enemy);
			phase = Phase.Pending;
			pendingDeadline = Time.unscaledTime + 3f;
			PossessionNet.ClientRequest(enemy);
			return true;
		}

		internal void OnConfirmed(EnemyAI confirmed)
		{
			//IL_00af: Unknown result type (might be due to invalid IL or missing references)
			//IL_009d: Unknown result type (might be due to invalid IL or missing references)
			if (phase != Phase.Pending || (Object)(object)confirmed == (Object)null)
			{
				if (phase != Phase.Active)
				{
					PossessionNet.ClientRelease();
				}
				return;
			}
			enemy = confirmed;
			enemyName = NameOf(enemy);
			profile = EnemyProfile.For(enemy);
			phase = Phase.Active;
			hasControl = false;
			savedState = false;
			ownerWait = 0f;
			nextOwnerRequest = Time.unscaledTime + 1f;
			abilityErrorLogged = false;
			SpectatorCamController instance = SpectatorCamController.instance;
			yaw = (((Object)(object)instance != (Object)null) ? ((Component)instance).transform.eulerAngles.y : ((Component)enemy).transform.eulerAngles.y);
			pitch = 15f;
			candidate = null;
			Plugin.Debug("Possessing " + ((Object)enemy).name);
		}

		internal void OnDenied(string reason)
		{
			if (phase == Phase.Pending)
			{
				phase = Phase.Idle;
				enemy = null;
			}
			if ((Object)(object)HUDManager.Instance != (Object)null)
			{
				HUDManager.Instance.DisplayTip("Can't possess", reason, true, false, "LC_Tip1");
			}
		}

		internal void OnServerEnded(ulong? enemyId = null)
		{
			if (phase != Phase.Idle && (!enemyId.HasValue || !((Object)(object)enemy != (Object)null) || !((NetworkBehaviour)enemy).IsSpawned || ((NetworkBehaviour)enemy).NetworkObjectId == enemyId.Value))
			{
				CleanupLocal();
			}
		}

		public void Release(string tip = null)
		{
			if (phase != Phase.Idle)
			{
				CleanupLocal();
				PossessionNet.ClientRelease();
				if (tip != null && (Object)(object)HUDManager.Instance != (Object)null)
				{
					HUDManager.Instance.DisplayTip("Possession ended", tip, false, false, "LC_Tip1");
				}
			}
		}

		private void CleanupLocal()
		{
			EnemyAI val = enemy;
			bool flag = savedState;
			EnemyProfile enemyProfile = profile;
			phase = Phase.Idle;
			enemy = null;
			profile = null;
			hasControl = false;
			savedState = false;
			nextScan = 0f;
			if ((Object)(object)val == (Object)null || !flag)
			{
				return;
			}
			try
			{
				if (!val.isEnemyDead && ((NetworkBehaviour)val).IsSpawned && ((NetworkBehaviour)val).IsOwner)
				{
					enemyProfile.OnEnd(val);
				}
			}
			catch (Exception ex)
			{
				Plugin.Log.LogWarning((object)("Error while leaving " + ((Object)val).name + ": " + ex.Message));
			}
			if ((Object)(object)val.agent != (Object)null)
			{
				val.agent.updateRotation = savedUpdateRotation;
			}
			val.updatePositionThreshold = savedPositionThreshold;
			val.updateDestinationInterval = 0f;
			if (((NetworkBehaviour)val).IsSpawned && ((NetworkBehaviour)val).IsOwner && !val.isEnemyDead)
			{
				val.SyncPositionToClients();
			}
		}

		private void Update()
		{
			PossessionNet.Tick();
			if (phase == Phase.Idle)
			{
				return;
			}
			if ((Object)(object)enemy == (Object)null || !((NetworkBehaviour)enemy).IsSpawned || enemy.isEnemyDead)
			{
				Release((phase == Phase.Active) ? ("The " + enemyName + " is no more.") : null);
				return;
			}
			if (!GhostCamActive)
			{
				Release();
				return;
			}
			if (phase == Phase.Pending)
			{
				if (Time.unscaledTime > pendingDeadline)
				{
					Release("The host did not answer. Does everyone have Poltergeist-Possession installed?");
				}
				return;
			}
			if (!((NetworkBehaviour)enemy).IsOwner)
			{
				hasControl = false;
				ownerWait += Time.unscaledDeltaTime;
				if (ownerWait > 5f)
				{
					Release("Lost control of the " + enemyName + ".");
				}
				else if (Time.unscaledTime >= nextOwnerRequest)
				{
					nextOwnerRequest = Time.unscaledTime + 0.75f;
					enemy.ChangeEnemyOwnerServerRpc(NetworkManager.Singleton.LocalClientId);
				}
				return;
			}
			ownerWait = 0f;
			if (!hasControl)
			{
				TakeControl();
			}
			bool paused = InputPaused(LocalPlayer);
			SuppressAI();
			RunAbilities(paused);
			MoveEnemy(paused);
			if (Time.unscaledTime >= nextPositionSync)
			{
				nextPositionSync = Time.unscaledTime + 0.08f;
				enemy.SyncPositionToClients();
			}
		}

		private void TakeControl()
		{
			hasControl = true;
			nextPositionSync = 0f;
			if (savedState)
			{
				return;
			}
			savedState = true;
			NavMeshAgent agent = enemy.agent;
			savedUpdateRotation = (Object)(object)agent == (Object)null || agent.updateRotation;
			savedPositionThreshold = enemy.updatePositionThreshold;
			enemy.updatePositionThreshold = Mathf.Min(savedPositionThreshold, 0.2f);
			if (enemy.currentSearch != null && enemy.currentSearch.inProgress)
			{
				enemy.StopSearch(enemy.currentSearch, true);
			}
			try
			{
				profile.OnStart(enemy);
			}
			catch (Exception ex)
			{
				Plugin.Log.LogWarning((object)("Error while entering " + ((Object)enemy).name + ": " + ex.Message));
			}
		}

		private void SuppressAI()
		{
			enemy.updateDestinationInterval = 1f;
			enemy.movingTowardsTargetPlayer = false;
			enemy.moveTowardsDestination = false;
			NavMeshAgent agent = enemy.agent;
			if ((Object)(object)agent != (Object)null && ((Behaviour)agent).enabled && agent.isOnNavMesh)
			{
				agent.updateRotation = false;
				if (agent.hasPath)
				{
					agent.ResetPath();
				}
			}
		}

		private void RunAbilities(bool paused)
		{
			try
			{
				profile.OnTick(enemy);
				if (!paused && NetSettings.Active.Abilities && !(enemy.stunNormalizedTimer > 0f))
				{
					Mouse current = Mouse.current;
					Gamepad current2 = Gamepad.current;
					bool num = (current != null && current.leftButton.wasPressedThisFrame) || (current2 != null && current2.rightTrigger.wasPressedThisFrame);
					bool flag = (current != null && current.rightButton.wasPressedThisFrame) || (current2 != null && current2.leftTrigger.wasPressedThisFrame);
					if (num && profile.PrimaryName(enemy) != null)
					{
						profile.OnPrimary(enemy);
					}
					if (flag && profile.SecondaryName(enemy) != null)
					{
						profile.OnSecondary(enemy);
					}
				}
			}
			catch (Exception ex)
			{
				if (!abilityErrorLogged)
				{
					abilityErrorLogged = true;
					Plugin.Log.LogWarning((object)("Ability error on " + ((Object)enemy).name + ": " + ex));
				}
			}
		}

		private void MoveEnemy(bool paused)
		{
			//IL_006e: 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_00a6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ab: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d6: Unknown result type (might be due to invalid IL or missing references)
			//IL_0111: Unknown result type (might be due to invalid IL or missing references)
			//IL_0116: Unknown result type (might be due to invalid IL or missing references)
			//IL_0190: Unknown result type (might be due to invalid IL or missing references)
			//IL_0195: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a1: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a8: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ad: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b2: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b5: Unknown result type (might be due to invalid IL or missing references)
			//IL_01bc: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c3: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c9: Unknown result type (might be due to invalid IL or missing references)
			NavMeshAgent agent = enemy.agent;
			bool flag = (Object)(object)agent != (Object)null && ((Behaviour)agent).enabled && agent.isOnNavMesh;
			bool flag2 = !enemy.inSpecialAnimation && enemy.stunNormalizedTimer <= 0f;
			float deltaTime = Time.deltaTime;
			if (flag2 && flag && profile.ForcedVelocity(enemy, out var velocity))
			{
				agent.Move(velocity * deltaTime);
			}
			else
			{
				if (paused || !flag2)
				{
					return;
				}
				if (profile.CanRotate(enemy))
				{
					Quaternion val = Quaternion.Euler(0f, yaw, 0f);
					((Component)enemy).transform.rotation = Quaternion.Slerp(((Component)enemy).transform.rotation, val, Mathf.Clamp01(12f * deltaTime));
				}
				if (flag && profile.CanMove(enemy))
				{
					Vector2 val2 = IngamePlayerSettings.Instance.playerInput.actions.FindAction("Move", false).ReadValue<Vector2>();
					if (!(((Vector2)(ref val2)).sqrMagnitude < 0.01f))
					{
						float num = ((IngamePlayerSettings.Instance.playerInput.actions.FindAction("Sprint", false).ReadValue<float>() > 0.3f) ? profile.RunSpeed(enemy) : profile.WalkSpeed(enemy)) * NetSettings.Active.Speed;
						Vector3 val3 = Quaternion.Euler(0f, yaw, 0f) * new Vector3(val2.x, 0f, val2.y);
						agent.Move(Vector3.ClampMagnitude(val3, 1f) * num * deltaTime);
					}
				}
			}
		}

		private void LateUpdate()
		{
			VoiceRouter.Apply(setVolume: false);
		}

		internal void AfterGhostCamUpdate(SpectatorCamController cam, float powerBefore)
		{
			PlayerControllerB localPlayer = LocalPlayer;
			if ((Object)(object)localPlayer == (Object)null || Patches.vanillaMode)
			{
				return;
			}
			if (phase == Phase.Active && (Object)(object)enemy != (Object)null)
			{
				DrainPower(cam, powerBefore);
				if (phase == Phase.Active)
				{
					UpdateCamera(cam, localPlayer);
					ShowActiveHud(localPlayer);
				}
			}
			else if (phase == Phase.Pending)
			{
				((TMP_Text)localPlayer.cursorTip).text = "Possessing...";
			}
			else
			{
				if (InputPaused(localPlayer))
				{
					return;
				}
				ScanForCandidate(cam);
				if (!((Object)(object)candidate == (Object)null))
				{
					string text = NameOf(candidate);
					if (candidateBlocked != null)
					{
						((TMP_Text)localPlayer.cursorTip).text = "Can't possess " + text + " (" + candidateBlocked + ")";
					}
					else if (cam.Power < NetSettings.Active.MinPower)
					{
						((TMP_Text)localPlayer.cursorTip).text = "Possess " + text + " : Not Enough Power (" + NetSettings.Active.MinPower.ToString("F0") + ")";
					}
					else
					{
						((TMP_Text)localPlayer.cursorTip).text = "Possess " + text + " : [" + PoltergeistCustomInputs.GetInteractString() + "] (" + NetSettings.Active.Drain.ToString("0.#") + "/sec)";
					}
				}
			}
		}

		private void DrainPower(SpectatorCamController cam, float powerBefore)
		{
			float num = Mathf.Max(0f, powerBefore - NetSettings.Active.Drain * Time.deltaTime);
			PowerRef.Invoke(cam) = num;
			((TMP_Text)HUDManager.Instance.spectatingPlayerText).text = "Power: " + num.ToString("F0") + " / " + MaxPowerRef.Invoke(cam).ToString("F0");
			if (num <= 0f && NetSettings.Active.Drain > 0f)
			{
				Release("You ran out of power.");
			}
		}

		private void UpdateCamera(SpectatorCamController cam, PlayerControllerB player)
		{
			//IL_00ae: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bf: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00de: Unknown result type (might be due to invalid IL or missing references)
			//IL_00df: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ea: Unknown result type (might be due to invalid IL or missing references)
			//IL_0107: Unknown result type (might be due to invalid IL or missing references)
			//IL_010d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0029: Unknown result type (might be due to invalid IL or missing references)
			//IL_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_0141: Unknown result type (might be due to invalid IL or missing references)
			//IL_0142: Unknown result type (might be due to invalid IL or missing references)
			//IL_0144: Unknown result type (might be due to invalid IL or missing references)
			//IL_0149: Unknown result type (might be due to invalid IL or missing references)
			//IL_014e: Unknown result type (might be due to invalid IL or missing references)
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0081: Unknown result type (might be due to invalid IL or missing references)
			if (!InputPaused(player))
			{
				MovementActions movement = player.playerActions.Movement;
				Vector2 val = ((MovementActions)(ref movement)).Look.ReadValue<Vector2>() * 0.008f * (float)IngamePlayerSettings.Instance.settings.lookSensitivity;
				if (!IngamePlayerSettings.Instance.settings.invertYAxis)
				{
					val.y *= -1f;
				}
				yaw += val.x;
				pitch = Mathf.Clamp(pitch + val.y, -60f, 80f);
			}
			Quaternion val2 = Quaternion.Euler(pitch, yaw, 0f);
			Vector3 val3 = ((Component)enemy).transform.position + Vector3.up * profile.CameraHeight;
			Vector3 val4 = val2 * Vector3.back;
			float num = profile.CameraDistance * Plugin.Cfg.CameraDistance.Value;
			RaycastHit val5 = default(RaycastHit);
			if (Physics.SphereCast(val3, 0.25f, val4, ref val5, num, StartOfRound.Instance.collidersAndRoomMask, (QueryTriggerInteraction)1))
			{
				num = Mathf.Max(((RaycastHit)(ref val5)).distance - 0.05f, 0.3f);
			}
			((Component)cam).transform.SetPositionAndRotation(val3 + val4 * num, val2);
		}

		private void ShowActiveHud(PlayerControllerB player)
		{
			string text = "Possessing " + enemyName + " : Release [" + PoltergeistCustomInputs.GetInteractString() + "]";
			if (!hasControl)
			{
				text += "\nTaking control...";
			}
			else if (NetSettings.Active.Abilities)
			{
				string text2 = profile.PrimaryName(enemy);
				string text3 = profile.SecondaryName(enemy);
				if (text2 != null || text3 != null)
				{
					text += "\n";
					if (text2 != null)
					{
						text = text + text2 + " [LMB]";
					}
					if (text2 != null && text3 != null)
					{
						text += "   ";
					}
					if (text3 != null)
					{
						text = text + text3 + " [RMB]";
					}
				}
			}
			((TMP_Text)player.cursorTip).text = text;
		}

		private void ScanForCandidate(SpectatorCamController cam)
		{
			//IL_00a0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a5: Unknown result type (might be due to invalid IL or missing references)
			//IL_010c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0111: Unknown result type (might be due to invalid IL or missing references)
			//IL_0112: Unknown result type (might be due to invalid IL or missing references)
			//IL_0117: Unknown result type (might be due to invalid IL or missing references)
			//IL_0131: Unknown result type (might be due to invalid IL or missing references)
			if (Time.unscaledTime < nextScan)
			{
				if ((Object)(object)candidate != (Object)null && (candidate.isEnemyDead || !((NetworkBehaviour)candidate).IsSpawned))
				{
					candidate = null;
				}
				return;
			}
			nextScan = Time.unscaledTime + 0.15f;
			candidate = null;
			candidateBlocked = null;
			RoundManager instance = RoundManager.Instance;
			if ((Object)(object)instance == (Object)null || instance.SpawnedEnemies == null || !PossessionNet.Ready)
			{
				return;
			}
			if (instance.SpawnedEnemies.Count == 0)
			{
				colliderCache.Clear();
				return;
			}
			NetSettings active = NetSettings.Active;
			Vector3 position = ((Component)cam).transform.position;
			float num = active.Range;
			float num2 = (active.Range + 15f) * (active.Range + 15f);
			foreach (EnemyAI spawnedEnemy in instance.SpawnedEnemies)
			{
				if ((Object)(object)spawnedEnemy == (Object)null || spawnedEnemy.isEnemyDead || !((NetworkBehaviour)spawnedEnemy).IsSpawned || !spawnedEnemy.ventAnimationFinished)
				{
					continue;
				}
				Vector3 val = ((Component)spawnedEnemy).transform.position - position;
				if (!(((Vector3)(ref val)).sqrMagnitude > num2) && !active.IsBlacklisted(spawnedEnemy))
				{
					float num3 = DistanceTo(spawnedEnemy, position);
					if (num3 < num)
					{
						num = num3;
						candidate = spawnedEnemy;
					}
				}
			}
			if (!((Object)(object)candidate == (Object)null))
			{
				candidateProfile = EnemyProfile.For(candidate);
				if (PossessionNet.TryGetPossessor(candidate, out var _))
				{
					candidateBlocked = "already possessed";
				}
				else
				{
					candidateBlocked = candidateProfile.CannotPossessReason(candidate);
				}
			}
		}

		private float DistanceTo(EnemyAI e, Vector3 point)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_000b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0096: Unknown result type (might be due to invalid IL or missing references)
			//IL_009b: Unknown result type (might be due to invalid IL or missing references)
			//IL_009f: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a5: Unknown result type (might be due to invalid IL or missing references)
			float num = Vector3.Distance(((Component)e).transform.position, point);
			if (!colliderCache.TryGetValue(e, out var value))
			{
				EnemyAICollisionDetect[] componentsInChildren = ((Component)e).GetComponentsInChildren<EnemyAICollisionDetect>();
				List<Collider> list = new List<Collider>();
				EnemyAICollisionDetect[] array = componentsInChildren;
				for (int i = 0; i < array.Length; i++)
				{
					Collider component = ((Component)array[i]).GetComponent<Collider>();
					if ((Object)(object)component != (Object)null)
					{
						list.Add(component);
					}
				}
				value = list.ToArray();
				colliderCache[e] = value;
			}
			Collider[] array2 = value;
			foreach (Collider val in array2)
			{
				if (!((Object)(object)val == (Object)null) && val.enabled)
				{
					Bounds bounds = val.bounds;
					float num2 = Vector3.Distance(((Bounds)(ref bounds)).ClosestPoint(point), point);
					if (num2 < num)
					{
						num = num2;
					}
				}
			}
			return num;
		}
	}
	internal static class PossessionNet
	{
		internal class Entry
		{
			public int PlayerIndex;

			public ulong EnemyId;

			private EnemyAI enemy;

			public EnemyAI Enemy
			{
				get
				{
					if ((Object)(object)enemy == (Object)null)
					{
						enemy = FindEnemy(EnemyId);
					}
					return enemy;
				}
			}
		}

		[CompilerGenerated]
		private static class <>O
		{
			public static HandleNamedMessageDelegate <0>__OnRequest;

			public static HandleNamedMessageDelegate <1>__OnRelease;

			public static HandleNamedMessageDelegate <2>__OnHello;

			public static HandleNamedMessageDelegate <3>__OnState;

			public static HandleNamedMessageDelegate <4>__OnDeny;

			public static HandleNamedMessageDelegate <5>__OnSettings;
		}

		private const string MsgRequest = "PoltPossession.Request";

		private const string MsgRelease = "PoltPossession.Release";

		private const string MsgHello = "PoltPossession.Hello";

		private const string MsgState = "PoltPossession.State";

		private const string MsgDeny = "PoltPossession.Deny";

		private const string MsgSettings = "PoltPossession.Settings";

		internal static readonly Dictionary<int, Entry> Possessions = new Dictionary<int, Entry>();

		private static CustomMessagingManager registered;

		private static float nextWatchdog;

		private static readonly List<int> scratch = new List<int>();

		internal static bool Ready => registered != null;

		private static bool IsServer
		{
			get
			{
				if ((Object)(object)NetworkManager.Singleton != (Object)null)
				{
					return NetworkManager.Singleton.IsServer;
				}
				return false;
			}
		}

		internal static void Tick()
		{
			//IL_0080: Unknown result type (might be due to invalid IL or missing references)
			//IL_0085: Unknown result type (might be due to invalid IL or missing references)
			//IL_008b: Expected O, but got Unknown
			//IL_00a6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ab: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b1: Expected O, but got Unknown
			//IL_00cc: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d7: Expected O, but got Unknown
			//IL_00f2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fd: Expected O, but got Unknown
			//IL_0118: Unknown result type (might be due to invalid IL or missing references)
			//IL_011d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0123: Expected O, but got Unknown
			//IL_013e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0143: Unknown result type (might be due to invalid IL or missing references)
			//IL_0149: Expected O, but got Unknown
			NetworkManager singleton = NetworkManager.Singleton;
			if ((Object)(object)singleton == (Object)null || !singleton.IsListening || (Object)(object)StartOfRound.Instance == (Object)null)
			{
				if (registered != null || Possessions.Count > 0)
				{
					Reset();
				}
				return;
			}
			CustomMessagingManager customMessagingManager = singleton.CustomMessagingManager;
			if (customMessagingManager == null)
			{
				return;
			}
			if (customMessagingManager != registered)
			{
				if (!singleton.IsServer && !singleton.IsConnectedClient)
				{
					return;
				}
				Reset();
				object obj = <>O.<0>__OnRequest;
				if (obj == null)
				{
					HandleNamedMessageDelegate val = OnRequest;
					<>O.<0>__OnRequest = val;
					obj = (object)val;
				}
				customMessagingManager.RegisterNamedMessageHandler("PoltPossession.Request", (HandleNamedMessageDelegate)obj);
				object obj2 = <>O.<1>__OnRelease;
				if (obj2 == null)
				{
					HandleNamedMessageDelegate val2 = OnRelease;
					<>O.<1>__OnRelease = val2;
					obj2 = (object)val2;
				}
				customMessagingManager.RegisterNamedMessageHandler("PoltPossession.Release", (HandleNamedMessageDelegate)obj2);
				object obj3 = <>O.<2>__OnHello;
				if (obj3 == null)
				{
					HandleNamedMessageDelegate val3 = OnHello;
					<>O.<2>__OnHello = val3;
					obj3 = (object)val3;
				}
				customMessagingManager.RegisterNamedMessageHandler("PoltPossession.Hello", (HandleNamedMessageDelegate)obj3);
				object obj4 = <>O.<3>__OnState;
				if (obj4 == null)
				{
					HandleNamedMessageDelegate val4 = OnState;
					<>O.<3>__OnState = val4;
					obj4 = (object)val4;
				}
				customMessagingManager.RegisterNamedMessageHandler("PoltPossession.State", (HandleNamedMessageDelegate)obj4);
				object obj5 = <>O.<4>__OnDeny;
				if (obj5 == null)
				{
					HandleNamedMessageDelegate val5 = OnDeny;
					<>O.<4>__OnDeny = val5;
					obj5 = (object)val5;
				}
				customMessagingManager.RegisterNamedMessageHandler("PoltPossession.Deny", (HandleNamedMessageDelegate)obj5);
				object obj6 = <>O.<5>__OnSettings;
				if (obj6 == null)
				{
					HandleNamedMessageDelegate val6 = OnSettings;
					<>O.<5>__OnSettings = val6;
					obj6 = (object)val6;
				}
				customMessagingManager.RegisterNamedMessageHandler("PoltPossession.Settings", (HandleNamedMessageDelegate)obj6);
				registered = customMessagingManager;
				NetSettings.Active = NetSettings.FromConfig();
				if (!singleton.IsServer)
				{
					Send("PoltPossession.Hello", 0uL, new byte[1]);
				}
				Plugin.Debug("Registered possession messages (server: " + singleton.IsServer + ")");
			}
			if (singleton.IsServer && Time.unscaledTime >= nextWatchdog)
			{
				nextWatchdog = Time.unscaledTime + 0.25f;
				ServerWatchdog();
			}
		}

		private static void Reset()
		{
			registered = null;
			Possessions.Clear();
			if ((Object)(object)PossessionController.Instance != (Object)null)
			{
				PossessionController.Instance.OnServerEnded();
			}
		}

		internal static EnemyAI FindEnemy(ulong networkObjectId)
		{
			NetworkManager singleton = NetworkManager.Singleton;
			if ((Object)(object)singleton == (Object)null || singleton.SpawnManager == null)
			{
				return null;
			}
			if (!singleton.SpawnManager.SpawnedObjects.TryGetValue(networkObjectId, out var value) || (Object)(object)value == (Object)null)
			{
				return null;
			}
			EnemyAI val = ((Component)value).GetComponent<EnemyAI>();
			if ((Object)(object)val == (Object)null)
			{
				val = ((Component)value).GetComponentInChildren<EnemyAI>();
			}
			return val;
		}

		internal static PlayerControllerB GetPlayer(int index)
		{
			StartOfRound instance = StartOfRound.Instance;
			if ((Object)(object)instance == (Object)null || instance.allPlayerScripts == null || index < 0 || index >= instance.allPlayerScripts.Length)
			{
				return null;
			}
			return instance.allPlayerScripts[index];
		}

		internal static bool TryGetPossessor(EnemyAI enemy, out int playerIndex)
		{
			foreach (KeyValuePair<int, Entry> possession in Possessions)
			{
				if ((Object)(object)possession.Value.Enemy == (Object)(object)enemy)
				{
					playerIndex = possession.Key;
					return true;
				}
			}
			playerIndex = -1;
			return false;
		}

		private unsafe static void Send(string name, ulong clientId, byte[] data)
		{
			//IL_0046: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager singleton = NetworkManager.Singleton;
			if ((Object)(object)singleton == (Object)null || singleton.CustomMessagingManager == null)
			{
				return;
			}
			FastBufferWriter val = default(FastBufferWriter);
			((FastBufferWriter)(ref val))..ctor(data.Length + 8, (Allocator)2, -1);
			try
			{
				for (int i = 0; i < data.Length; i++)
				{
					((FastBufferWriter)(ref val)).WriteByteSafe(data[i]);
				}
				singleton.CustomMessagingManager.SendNamedMessage(name, clientId, val, (NetworkDelivery)3);
			}
			finally
			{
				((IDisposable)(*(FastBufferWriter*)(&val))/*cast due to .constrained prefix*/).Dispose();
			}
		}

		private static void SendToOtherClients(string name, byte[] data)
		{
			NetworkManager singleton = NetworkManager.Singleton;
			foreach (ulong connectedClientsId in singleton.ConnectedClientsIds)
			{
				if (connectedClientsId != singleton.LocalClientId)
				{
					Send(name, connectedClientsId, data);
				}
			}
		}

		private static byte[] ReadAll(FastBufferReader reader)
		{
			int num = ((FastBufferReader)(ref reader)).Length - ((FastBufferReader)(ref reader)).Position;
			byte[] array = new byte[Math.Max(num, 0)];
			for (int i = 0; i < num; i++)
			{
				((FastBufferReader)(ref reader)).ReadByteSafe(ref array[i]);
			}
			return array;
		}

		private static byte[] PackState(int playerIndex, ulong enemyId, bool active)
		{
			using MemoryStream memoryStream = new MemoryStream();
			using BinaryWriter binaryWriter = new BinaryWriter(memoryStream);
			binaryWriter.Write(playerIndex);
			binaryWriter.Write(enemyId);
			binaryWriter.Write(active);
			binaryWriter.Flush();
			return memoryStream.ToArray();
		}

		internal static void ClientRequest(EnemyAI enemy)
		{
			NetworkManager singleton = NetworkManager.Singleton;
			if (!((Object)(object)singleton == (Object)null) && Ready && !((Object)(object)enemy == (Object)null))
			{
				if (singleton.IsServer)
				{
					ServerHandleRequest(singleton.LocalClientId, ((NetworkBehaviour)enemy).NetworkObjectId);
				}
				else
				{
					Send("PoltPossession.Request", 0uL, BitConverter.GetBytes(((NetworkBehaviour)enemy).NetworkObjectId));
				}
			}
		}

		internal static void ClientRelease()
		{
			NetworkManager singleton = NetworkManager.Singleton;
			if (!((Object)(object)singleton == (Object)null) && Ready)
			{
				if (singleton.IsServer)
				{
					ServerHandleRelease(singleton.LocalClientId);
				}
				else
				{
					Send("PoltPossession.Release", 0uL, new byte[1]);
				}
			}
		}

		private static void OnRequest(ulong sender, FastBufferReader reader)
		{
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			if (IsServer)
			{
				byte[] array = ReadAll(reader);
				if (array.Length >= 8)
				{
					ServerHandleRequest(sender, BitConverter.ToUInt64(array, 0));
				}
			}
		}

		private static void OnRelease(ulong sender, FastBufferReader reader)
		{
			if (IsServer)
			{
				ServerHandleRelease(sender);
			}
		}

		private static void OnHello(ulong sender, FastBufferReader reader)
		{
			if (!IsServer)
			{
				return;
			}
			Send("PoltPossession.Settings", sender, NetSettings.Active.Serialize());
			foreach (KeyValuePair<int, Entry> possession in Possessions)
			{
				Send("PoltPossession.State", sender, PackState(possession.Key, possession.Value.EnemyId, active: true));
			}
		}

		private static void ServerHandleRequest(ulong clientId, ulong enemyId)
		{
			StartOfRound instance = StartOfRound.Instance;
			if ((Object)(object)instance == (Object)null || !instance.ClientPlayerList.TryGetValue(clientId, out var value))
			{
				return;
			}
			PlayerControllerB player = GetPlayer(value);
			EnemyAI val = FindEnemy(enemyId);
			string text = null;
			int playerIndex;
			if ((Object)(object)player == (Object)null || !player.isPlayerDead)
			{
				text = "Only ghosts can possess monsters.";
			}
			else if ((Object)(object)val == (Object)null || !((NetworkBehaviour)val).IsSpawned || val.isEnemyDead)
			{
				text = "That monster is gone.";
			}
			else if (NetSettings.Active.IsBlacklisted(val))
			{
				text = "That monster can't be possessed.";
			}
			else if (TryGetPossessor(val, out playerIndex) && playerIndex != value)
			{
				text = "Another ghost is already in there.";
			}
			if (text != null)
			{
				ServerDeny(clientId, text);
				return;
			}
			if (Possessions.ContainsKey(value))
			{
				ServerEnd(value);
			}
			Plugin.Debug("Player " + value + " possesses " + ((Object)val).name);
			if (((NetworkBehaviour)val).OwnerClientId != clientId)
			{
				val.ChangeEnemyOwnerServerRpc(clientId);
			}
			SendToOtherClients("PoltPossession.State", PackState(value, enemyId, active: true));
			ApplyState(value, enemyId, active: true);
		}

		private static void ServerHandleRelease(ulong clientId)
		{
			StartOfRound instance = StartOfRound.Instance;
			if (!((Object)(object)instance == (Object)null) && instance.ClientPlayerList.TryGetValue(clientId, out var value) && Possessions.ContainsKey(value))
			{
				ServerEnd(value);
			}
		}

		private static void ServerDeny(ulong clientId, string reason)
		{
			NetworkManager singleton = NetworkManager.Singleton;
			if (clientId == singleton.LocalClientId)
			{
				PossessionController.Instance.OnDenied(reason);
			}
			else
			{
				Send("PoltPossession.Deny", clientId, Encoding.UTF8.GetBytes(reason));
			}
		}

		private static void ServerEnd(int playerIndex)
		{
			if (Possessions.TryGetValue(playerIndex, out var value))
			{
				Plugin.Debug("Ending possession of player " + playerIndex);
				SendToOtherClients("PoltPossession.State", PackState(playerIndex, value.EnemyId, active: false));
				ApplyState(playerIndex, value.EnemyId, active: false);
				EnemyAI enemy = value.Enemy;
				if ((Object)(object)enemy != (Object)null && ((NetworkBehaviour)enemy).IsSpawned && !enemy.isEnemyDead && ((NetworkBehaviour)enemy).OwnerClientId != 0L)
				{
					enemy.ChangeEnemyOwnerServerRpc(0uL);
				}
			}
		}

		private static void ServerWatchdog()
		{
			if (Possessions.Count == 0)
			{
				return;
			}
			scratch.Clear();
			foreach (KeyValuePair<int, Entry> possession in Possessions)
			{
				PlayerControllerB player = GetPlayer(possession.Key);
				EnemyAI enemy = possession.Value.Enemy;
				if ((Object)(object)player == (Object)null || !player.isPlayerDead || (Object)(object)enemy == (Object)null || !((NetworkBehaviour)enemy).IsSpawned || enemy.isEnemyDead)
				{
					scratch.Add(possession.Key);
				}
			}
			foreach (int item in scratch)
			{
				ServerEnd(item);
			}
		}

		private static void OnState(ulong sender, FastBufferReader reader)
		{
			//IL_000b: Unknown result type (might be due to invalid IL or missing references)
			if (sender == 0L && !IsServer)
			{
				byte[] array = ReadAll(reader);
				if (array.Length >= 13)
				{
					ApplyState(BitConverter.ToInt32(array, 0), BitConverter.ToUInt64(array, 4), array[12] != 0);
				}
			}
		}

		private static void OnDeny(ulong sender, FastBufferReader reader)
		{
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			if (sender == 0L && !IsServer)
			{
				PossessionController.Instance.OnDenied(Encoding.UTF8.GetString(ReadAll(reader)));
			}
		}

		private static void OnSettings(ulong sender, FastBufferReader reader)
		{
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			if (sender != 0L || IsServer)
			{
				return;
			}
			try
			{
				NetSettings.Active = NetSettings.Deserialize(ReadAll(reader));
				Plugin.Debug("Received possession settings from the host");
			}
			catch (Exception ex)
			{
				Plugin.Log.LogWarning((object)("Could not read the host's possession settings: " + ex.Message));
			}
		}

		private static void ApplyState(int playerIndex, ulong enemyId, bool active)
		{
			Entry value;
			if (active)
			{
				Possessions[playerIndex] = new Entry
				{
					PlayerIndex = playerIndex,
					EnemyId = enemyId
				};
			}
			else if (Possessions.TryGetValue(playerIndex, out value) && value.EnemyId == enemyId)
			{
				Possessions.Remove(playerIndex);
			}
			StartOfRound instance = StartOfRound.Instance;
			PlayerControllerB val = (((Object)(object)instance != (Object)null) ? instance.localPlayerController : null);
			if ((Object)(object)val != (Object)null && (int)val.playerClientId == playerIndex && (Object)(object)PossessionController.Instance != (Object)null)
			{
				if (active)
				{
					PossessionController.Instance.OnConfirmed(FindEnemy(enemyId));
				}
				else if (!Possessions.ContainsKey(playerIndex))
				{
					PossessionController.Instance.OnServerEnded(enemyId);
				}
			}
			VoiceRouter.Refresh();
		}
	}
	internal static class VoiceRouter
	{
		private static FieldInfo voiceStateField;

		private static PropertyInfo volumeProperty;

		private static bool reflectionFailed;

		internal static void Apply(bool setVolume)
		{
			//IL_0126: Unknown result type (might be due to invalid IL or missing references)
			if (PossessionNet.Possessions.Count == 0 || !NetSettings.Active.Voice)
			{
				return;
			}
			StartOfRound instance = StartOfRound.Instance;
			if ((Object)(object)instance == (Object)null)
			{
				return;
			}
			PlayerControllerB localPlayerController = instance.localPlayerController;
			if ((Object)(object)localPlayerController == (Object)null || localPlayerController.isPlayerDead)
			{
				return;
			}
			foreach (KeyValuePair<int, PossessionNet.Entry> possession in PossessionNet.Possessions)
			{
				PlayerControllerB player = PossessionNet.GetPlayer(possession.Key);
				EnemyAI enemy = possession.Value.Enemy;
				if ((Object)(object)player == (Object)null || (Object)(object)player == (Object)(object)localPlayerController || !player.isPlayerDead || (Object)(object)enemy == (Object)null || enemy.isEnemyDead)
				{
					continue;
				}
				AudioSource currentVoiceChatAudioSource = player.currentVoiceChatAudioSource;
				if (!((Object)(object)currentVoiceChatAudioSource == (Object)null))
				{
					currentVoiceChatAudioSource.spatialBlend = 1f;
					if ((Object)(object)player.currentVoiceChatIngameSettings != (Object)null)
					{
						player.currentVoiceChatIngameSettings.set2D = false;
					}
					if (setVolume)
					{
						SetVoiceVolume(player, 1f);
					}
					Transform val = (((Object)(object)enemy.eye != (Object)null) ? enemy.eye : ((Component)enemy).transform);
					((Component)currentVoiceChatAudioSource).transform.position = val.position;
				}
			}
		}

		internal static void Refresh()
		{
			try
			{
				if ((Object)(object)StartOfRound.Instance != (Object)null)
				{
					StartOfRound.Instance.UpdatePlayerVoiceEffects();
				}
			}
			catch (Exception ex)
			{
				Plugin.Debug("Voice refresh failed: " + ex.Message);
			}
		}

		private static void SetVoiceVolume(PlayerControllerB player, float volume)
		{
			if (reflectionFailed)
			{
				return;
			}
			try
			{
				if (voiceStateField == null)
				{
					voiceStateField = typeof(PlayerControllerB).GetField("voicePlayerState", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
				}
				object value = voiceStateField.GetValue(player);
				if (value != null)
				{
					if (volumeProperty == null)
					{
						volumeProperty = value.GetType().GetProperty("Volume", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
					}
					volumeProperty.SetValue(value, volume, null);
				}
			}
			catch (Exception ex)
			{
				reflectionFailed = true;
				Plugin.Log.LogWarning((object)("Could not un-mute a possessing ghost, voice through monsters is disabled: " + ex.Message));
			}
		}
	}
}
namespace System.Runtime.CompilerServices
{
	[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)]
	internal sealed class IgnoresAccessChecksToAttribute : Attribute
	{
		public string AssemblyName { get; }

		public IgnoresAccessChecksToAttribute(string assemblyName)
		{
			AssemblyName = assemblyName;
		}
	}
}