Decompiled source of XenoriaAfterLife v1.0.2

BepInEx\plugins\XenoriaAfterLife\XenoriaAfterLife.dll

Decompiled 2 weeks ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using ExitGames.Client.Photon;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using Photon.Pun;
using Photon.Realtime;
using REPOLib.Modules;
using RepoOmniPossession;
using TMPro;
using UnityEngine;
using UnityEngine.AI;
using UnityEngine.SceneManagement;
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("XenoriaAfterLife")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.2.0")]
[assembly: AssemblyInformationalVersion("1.0.2")]
[assembly: AssemblyProduct("XenoriaAfterLife")]
[assembly: AssemblyTitle("XenoriaAfterLife")]
[assembly: AssemblyVersion("1.0.2.0")]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace XenoriaAfterLife
{
	internal sealed class AfterLifeManager : MonoBehaviour
	{
		private enum MessageType : byte
		{
			Reset,
			Begin,
			End
		}

		private NetworkedEvent _networkEvent;

		private readonly CountdownUI _countdown = new CountdownUI();

		private bool _roundConsumed;

		private bool _startInProgress;

		private int _activeActor = -1;

		private int _activeEnemyViewId = -1;

		private int _activeEnemyIndex = -1;

		private string _activeMonsterKey;

		private double _activeEndTime;

		private int _originalMasterActor = -1;

		private GameObject _activeEnemyObject;

		private GameObject _activeEnemyRoot;

		private Vector3 _lastEnemyPosition;

		private bool _ending;

		private SpectateCamera _disabledSpectateCamera;

		private bool _spectateCameraWasEnabled;

		private Camera _possessionCamera;

		private Transform _possessionCameraOriginalParent;

		private Vector3 _possessionCameraOriginalLocalPosition;

		private Quaternion _possessionCameraOriginalLocalRotation;

		private float _possessionFarClipPlane = 90f;

		private float _possessionFieldOfView = 70f;

		private static readonly FieldInfo SpectatePreviousFarClipField = AccessTools.Field(typeof(SpectateCamera), "previousFarClipPlane");

		private static readonly MethodInfo SpectateUpdateStateMethod = AccessTools.Method(typeof(SpectateCamera), "UpdateState", (Type[])null, (Type[])null);

		private readonly Dictionary<int, Dictionary<Renderer, bool>> _hiddenHeadRenderers = new Dictionary<int, Dictionary<Renderer, bool>>();

		internal static AfterLifeManager Instance { get; private set; }

		internal bool HasActivePossession
		{
			get
			{
				if (_activeActor > 0)
				{
					return _activeEnemyViewId > 0;
				}
				return false;
			}
		}

		internal bool IsLocalPlayerPossessed
		{
			get
			{
				if (HasActivePossession && PhotonNetwork.LocalPlayer != null)
				{
					return PhotonNetwork.LocalPlayer.ActorNumber == _activeActor;
				}
				return false;
			}
		}

		internal int ActiveActor => _activeActor;

		internal int ActiveEnemyIndex => _activeEnemyIndex;

		private void Awake()
		{
			//IL_0018: Unknown result type (might be due to invalid IL or missing references)
			//IL_0022: Expected O, but got Unknown
			Instance = this;
			_networkEvent = new NetworkedEvent("XenoriaAfterLife.State", (Action<EventData>)OnNetworkEvent);
			SceneManager.sceneLoaded += OnSceneLoaded;
		}

		private void OnDestroy()
		{
			SceneManager.sceneLoaded -= OnSceneLoaded;
			StopLocalPossession();
			if ((Object)(object)Instance == (Object)(object)this)
			{
				Instance = null;
			}
		}

		private void OnSceneLoaded(Scene scene, LoadSceneMode mode)
		{
			ResetLocalState();
			if (PhotonNetwork.IsMasterClient)
			{
				Raise(new object[1] { (byte)0 });
			}
		}

		private void Update()
		{
			//IL_0052: Unknown result type (might be due to invalid IL or missing references)
			//IL_0057: Unknown result type (might be due to invalid IL or missing references)
			if (!Plugin.Enabled.Value)
			{
				return;
			}
			if (IsLocalPlayerPossessed)
			{
				UpdateLocalPossession();
			}
			if (PhotonNetwork.IsMasterClient && HasActivePossession && !_ending)
			{
				ResolveActiveEnemy();
				if (Object.op_Implicit((Object)(object)_activeEnemyRoot))
				{
					_lastEnemyPosition = _activeEnemyRoot.transform.position;
				}
				bool num = PhotonNetwork.CurrentRoom != null && PhotonNetwork.CurrentRoom.Players.ContainsKey(_activeActor);
				bool flag = Object.op_Implicit((Object)(object)RunManager.instance) && SemiFunc.RunIsLevel();
				bool flag2 = PhotonNetwork.Time >= _activeEndTime;
				bool flag3 = IsActiveEnemyDead();
				if (!num)
				{
					((MonoBehaviour)this).StartCoroutine(EndPossession(forceMonsterDeath: true, restoreDeadPlayer: false));
				}
				else if (!flag)
				{
					((MonoBehaviour)this).StartCoroutine(EndPossession(forceMonsterDeath: false, restoreDeadPlayer: true));
				}
				else if (flag2)
				{
					((MonoBehaviour)this).StartCoroutine(EndPossession(forceMonsterDeath: true, restoreDeadPlayer: true));
				}
				else if (flag3)
				{
					((MonoBehaviour)this).StartCoroutine(EndPossession(forceMonsterDeath: false, restoreDeadPlayer: true));
				}
			}
		}

		internal void TryHandleFirstDeath(PlayerAvatar avatar)
		{
			if (Plugin.Enabled.Value && PhotonNetwork.IsMasterClient && !_roundConsumed && !_startInProgress && !HasActivePossession && Object.op_Implicit((Object)(object)avatar) && GameAccess.IsDead(avatar) && Object.op_Implicit((Object)(object)RunManager.instance) && SemiFunc.RunIsLevel() && PhotonNetwork.CurrentRoom != null && PhotonNetwork.CurrentRoom.PlayerCount >= Plugin.MinimumPlayers.Value)
			{
				PhotonView photonView = avatar.photonView;
				int num = ((photonView != null) ? photonView.OwnerActorNr : (-1));
				if (num > 0)
				{
					_roundConsumed = true;
					_startInProgress = true;
					((MonoBehaviour)this).StartCoroutine(BeginPossession(avatar, num));
				}
			}
		}

		internal bool IsPossessedAvatar(PlayerAvatar avatar)
		{
			if (Object.op_Implicit((Object)(object)avatar) && Object.op_Implicit((Object)(object)avatar.photonView))
			{
				return avatar.photonView.OwnerActorNr == _activeActor;
			}
			return false;
		}

		internal bool IsActiveEnemyComponent(Component component)
		{
			if (!HasActivePossession || !Object.op_Implicit((Object)(object)component))
			{
				return false;
			}
			ResolveActiveEnemy();
			if (!Object.op_Implicit((Object)(object)_activeEnemyRoot))
			{
				return false;
			}
			if (!((Object)(object)component.gameObject == (Object)(object)_activeEnemyRoot))
			{
				return component.transform.IsChildOf(_activeEnemyRoot.transform);
			}
			return true;
		}

		internal bool IsAuthorizedPossessedSender(PhotonMessageInfo info)
		{
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			if (HasActivePossession && info.Sender != null)
			{
				return info.Sender.ActorNumber == _activeActor;
			}
			return false;
		}

		private IEnumerator BeginPossession(PlayerAvatar avatar, int actor)
		{
			yield return (object)new WaitForSecondsRealtime(1.25f);
			if (!Object.op_Implicit((Object)(object)avatar) || !GameAccess.IsDead(avatar) || !SemiFunc.RunIsLevel())
			{
				_startInProgress = false;
				yield break;
			}
			List<MonsterSpawnCandidate> availableVanillaCandidates = MonsterCatalog.GetAvailableVanillaCandidates();
			if (availableVanillaCandidates.Count == 0)
			{
				Plugin.Log.LogError((object)"No verified vanilla monster prefab is currently available; possession was cancelled.");
				_startInProgress = false;
				yield break;
			}
			Vector3 val = FindRemoteSpawnPosition(((Component)avatar).transform.position);
			MonsterSpawnCandidate candidate = availableVanillaCandidates[Random.Range(0, availableVanillaCandidates.Count)];
			GameObject root = null;
			try
			{
				root = PhotonNetwork.InstantiateRoomObject(((PrefabRef<GameObject>)(object)candidate.Prefab).ResourcePath, val, Quaternion.identity, (byte)0, (object[])null);
			}
			catch (Exception ex)
			{
				Plugin.Log.LogError((object)("Failed to spawn possession monster: " + ex));
			}
			if (!Object.op_Implicit((Object)(object)root))
			{
				_startInProgress = false;
				yield break;
			}
			GameObject enemyObject = null;
			float timeout = 5f;
			while (timeout > 0f && !Object.op_Implicit((Object)(object)enemyObject))
			{
				enemyObject = candidate.Definition.FindEnemyObject(root);
				timeout -= Time.unscaledDeltaTime;
				yield return null;
			}
			if (!Object.op_Implicit((Object)(object)enemyObject))
			{
				Plugin.Log.LogError((object)("Spawned monster has no supported controller component: " + candidate.Definition.Key));
				PhotonNetwork.Destroy(root);
				_startInProgress = false;
				yield break;
			}
			PhotonView val2 = enemyObject.GetComponent<PhotonView>() ?? enemyObject.GetComponentInParent<PhotonView>();
			if (!Object.op_Implicit((Object)(object)val2))
			{
				Plugin.Log.LogError((object)("Spawned monster has no PhotonView: " + candidate.Definition.Key));
				PhotonNetwork.Destroy(root);
				_startInProgress = false;
				yield break;
			}
			EnemyParent val3 = root.GetComponent<EnemyParent>() ?? root.GetComponentInChildren<EnemyParent>(true);
			if (Object.op_Implicit((Object)(object)val3))
			{
				val3.SpawnedTimerPause(Plugin.MonsterLifetime.Value + 30f);
			}
			Player masterClient = PhotonNetwork.MasterClient;
			int num = ((masterClient != null) ? masterClient.ActorNumber : PhotonNetwork.LocalPlayer.ActorNumber);
			double num2 = PhotonNetwork.Time + (double)Plugin.MonsterLifetime.Value;
			Raise(new object[6]
			{
				(byte)1,
				actor,
				val2.ViewID,
				candidate.Definition.Key,
				num2,
				num
			});
			if (actor != num)
			{
				Room currentRoom = PhotonNetwork.CurrentRoom;
				Player val4 = ((currentRoom != null) ? currentRoom.GetPlayer(actor, false) : null);
				if (val4 == null || !PhotonNetwork.SetMasterClient(val4))
				{
					Plugin.Log.LogError((object)"Could not hand gameplay authority to the possessed player.");
				}
			}
			Plugin.Log.LogInfo((object)($"Player {actor} became {candidate.Definition.DisplayName} for " + $"{Plugin.MonsterLifetime.Value:0} seconds."));
			_startInProgress = false;
		}

		private IEnumerator EndPossession(bool forceMonsterDeath, bool restoreDeadPlayer)
		{
			if (!_ending && HasActivePossession)
			{
				_ending = true;
				ResolveActiveEnemy();
				Vector3 deathPosition = (Object.op_Implicit((Object)(object)_activeEnemyRoot) ? _activeEnemyRoot.transform.position : _lastEnemyPosition);
				if (forceMonsterDeath)
				{
					ForceKillActiveEnemy();
					yield return (object)new WaitForSecondsRealtime(0.15f);
				}
				RestoreOriginalMasterClient();
				Raise(new object[6]
				{
					(byte)2,
					_activeActor,
					restoreDeadPlayer,
					deathPosition.x,
					deathPosition.y,
					deathPosition.z
				});
				_ending = false;
			}
		}

		private void OnNetworkEvent(EventData eventData)
		{
			//IL_00a4: Unknown result type (might be due to invalid IL or missing references)
			if (!(eventData.CustomData is object[] array) || array.Length == 0)
			{
				return;
			}
			switch ((MessageType)Convert.ToByte(array[0]))
			{
			case MessageType.Reset:
				ResetLocalState();
				break;
			case MessageType.Begin:
				if (array.Length >= 5)
				{
					ApplyBegin(Convert.ToInt32(array[1]), Convert.ToInt32(array[2]), Convert.ToString(array[3]), Convert.ToDouble(array[4]), (array.Length >= 6) ? Convert.ToInt32(array[5]) : (-1));
				}
				break;
			case MessageType.End:
				if (array.Length >= 6)
				{
					ApplyEnd(Convert.ToInt32(array[1]), Convert.ToBoolean(array[2]), new Vector3(Convert.ToSingle(array[3]), Convert.ToSingle(array[4]), Convert.ToSingle(array[5])));
				}
				break;
			}
		}

		private void ApplyBegin(int actor, int enemyViewId, string monsterKey, double endTime, int originalMasterActor)
		{
			_roundConsumed = true;
			_activeActor = actor;
			_activeEnemyViewId = enemyViewId;
			_activeMonsterKey = monsterKey;
			_activeEndTime = endTime;
			int originalMasterActor2;
			if (originalMasterActor <= 0)
			{
				Player masterClient = PhotonNetwork.MasterClient;
				originalMasterActor2 = ((masterClient != null) ? masterClient.ActorNumber : (-1));
			}
			else
			{
				originalMasterActor2 = originalMasterActor;
			}
			_originalMasterActor = originalMasterActor2;
			_ending = false;
			ResolveActiveEnemy();
			HideDeathHead(actor);
			SetEnemyAuthorityForThisClient();
			if (IsLocalPlayerPossessed)
			{
				((MonoBehaviour)this).StartCoroutine(StartLocalPossessionWhenReady());
			}
		}

		private void ApplyEnd(int actor, bool restoreDeadPlayer, Vector3 deathPosition)
		{
			//IL_0021: Unknown result type (might be due to invalid IL or missing references)
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			if (actor == _activeActor)
			{
				StopLocalPossession();
				if (restoreDeadPlayer)
				{
					RestoreDeathHead(actor, deathPosition);
				}
				else
				{
					RestoreDeathHead(actor, deathPosition, visible: false);
				}
				ClearActiveState();
			}
		}

		private IEnumerator StartLocalPossessionWhenReady()
		{
			float timeout = 8f;
			while (timeout > 0f && !Object.op_Implicit((Object)(object)_activeEnemyObject))
			{
				ResolveActiveEnemy();
				timeout -= Time.unscaledDeltaTime;
				yield return null;
			}
			if (SemiFunc.IsMultiplayer())
			{
				float authorityTimeout = 8f;
				while (authorityTimeout > 0f && (PhotonNetwork.MasterClient == null || PhotonNetwork.MasterClient.ActorNumber != _activeActor))
				{
					authorityTimeout -= Time.unscaledDeltaTime;
					yield return null;
				}
				if (PhotonNetwork.MasterClient == null || PhotonNetwork.MasterClient.ActorNumber != _activeActor)
				{
					Plugin.Log.LogError((object)"Possession input was not started because gameplay authority did not arrive.");
					yield break;
				}
				SetEnemyAuthorityForThisClient();
			}
			MonsterDefinition monsterDefinition = MonsterCatalog.Get(_activeMonsterKey);
			if (!Object.op_Implicit((Object)(object)_activeEnemyObject) || monsterDefinition == null)
			{
				Plugin.Log.LogError((object)"Local possession could not start because the enemy or controller is unavailable.");
				yield break;
			}
			try
			{
				Camera gameplayCamera = (Object.op_Implicit((Object)(object)GameDirector.instance) ? GameDirector.instance.MainCamera : Camera.main);
				CaptureGameplayCamera(gameplayCamera);
				if (Object.op_Implicit((Object)(object)SpectateCamera.instance))
				{
					_disabledSpectateCamera = SpectateCamera.instance;
					_spectateCameraWasEnabled = ((Behaviour)_disabledSpectateCamera).enabled;
					((Behaviour)_disabledSpectateCamera).enabled = false;
				}
				PrepareGameplayCamera();
				IPossessedController val = (IPossessedController)Activator.CreateInstance(monsterDefinition.ControllerType);
				OmniPossessionManager.EnterPossession(_activeEnemyObject, val);
				EnsureDependencyUsesGameplayCamera();
				PrepareGameplayCamera();
				_countdown.Show();
			}
			catch (Exception ex)
			{
				Plugin.Log.LogError((object)("Local possession controller failed: " + ex));
			}
		}

		private void UpdateLocalPossession()
		{
			float seconds = Mathf.Max(0f, (float)(_activeEndTime - PhotonNetwork.Time));
			_countdown.UpdateTime(seconds);
			KeepDeathHeadHidden(_activeActor);
			PrepareGameplayCamera();
			if (!PhotonNetwork.IsMasterClient && OmniPossessionManager.IsPossessed && OmniPossessionManager.CurrentController != null)
			{
				try
				{
					OmniPossessionManager.CurrentController.HandleInputAndMovement();
				}
				catch (Exception ex)
				{
					Plugin.Debug("Remote controller update failed: " + ex.Message);
				}
			}
		}

		private void StopLocalPossession()
		{
			_countdown.Hide();
			if (OmniPossessionManager.IsPossessed)
			{
				try
				{
					OmniPossessionManager.ExitPossession();
				}
				catch (Exception ex)
				{
					Plugin.Debug("Possession cleanup failed: " + ex.Message);
				}
			}
			if (Object.op_Implicit((Object)(object)_disabledSpectateCamera))
			{
				try
				{
					SpectateUpdateStateMethod?.Invoke(_disabledSpectateCamera, new object[1] { (object)(State)1 });
				}
				catch (Exception ex2)
				{
					Plugin.Debug("Spectate camera state restore failed: " + ex2.Message);
				}
				((Behaviour)_disabledSpectateCamera).enabled = _spectateCameraWasEnabled;
				_disabledSpectateCamera = null;
			}
			_possessionCamera = null;
			_possessionCameraOriginalParent = null;
		}

		private void CaptureGameplayCamera(Camera gameplayCamera)
		{
			//IL_002f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0034: Unknown result type (might be due to invalid IL or missing references)
			//IL_003b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0040: Unknown result type (might be due to invalid IL or missing references)
			_possessionCamera = gameplayCamera;
			if (!Object.op_Implicit((Object)(object)_possessionCamera))
			{
				return;
			}
			Transform transform = ((Component)_possessionCamera).transform;
			_possessionCameraOriginalParent = transform.parent;
			_possessionCameraOriginalLocalPosition = transform.localPosition;
			_possessionCameraOriginalLocalRotation = transform.localRotation;
			float num = 0f;
			if (Object.op_Implicit((Object)(object)SpectateCamera.instance) && SpectatePreviousFarClipField != null)
			{
				try
				{
					num = Convert.ToSingle(SpectatePreviousFarClipField.GetValue(SpectateCamera.instance));
				}
				catch
				{
					num = 0f;
				}
			}
			if (num > 1f)
			{
				_possessionFarClipPlane = num;
			}
			else if (_possessionCamera.farClipPlane > 1f)
			{
				_possessionFarClipPlane = _possessionCamera.farClipPlane;
			}
			if (Object.op_Implicit((Object)(object)CameraZoom.Instance) && CameraZoom.Instance.playerZoomDefault > 1f)
			{
				_possessionFieldOfView = CameraZoom.Instance.playerZoomDefault;
			}
			else if (_possessionCamera.fieldOfView > 1f)
			{
				_possessionFieldOfView = _possessionCamera.fieldOfView;
			}
		}

		private void EnsureDependencyUsesGameplayCamera()
		{
			//IL_006b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0070: Unknown result type (might be due to invalid IL or missing references)
			//IL_0076: Unknown result type (might be due to invalid IL or missing references)
			//IL_007b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0040: Unknown result type (might be due to invalid IL or missing references)
			//IL_004a: Unknown result type (might be due to invalid IL or missing references)
			if (Object.op_Implicit((Object)(object)_possessionCamera) && !((Object)(object)OmniPossessionManager.MainCamera == (Object)(object)_possessionCamera))
			{
				Camera mainCamera = OmniPossessionManager.MainCamera;
				if (Object.op_Implicit((Object)(object)mainCamera))
				{
					Transform transform = ((Component)mainCamera).transform;
					transform.SetParent(OmniPossessionManager.OriginalCamParent);
					transform.localPosition = OmniPossessionManager.OriginalCamLocalPos;
					transform.localRotation = OmniPossessionManager.OriginalCamLocalRot;
				}
				OmniPossessionManager.MainCamera = _possessionCamera;
				OmniPossessionManager.OriginalCamParent = _possessionCameraOriginalParent;
				OmniPossessionManager.OriginalCamLocalPos = _possessionCameraOriginalLocalPosition;
				OmniPossessionManager.OriginalCamLocalRot = _possessionCameraOriginalLocalRotation;
				((Component)_possessionCamera).transform.SetParent((Transform)null);
				if (Object.op_Implicit((Object)(object)OmniPossessionManager.CurrentAudioListener))
				{
					((Component)OmniPossessionManager.CurrentAudioListener).transform.SetParent(((Component)_possessionCamera).transform, false);
				}
			}
		}

		private void PrepareGameplayCamera()
		{
			Camera val = (Object.op_Implicit((Object)(object)OmniPossessionManager.MainCamera) ? OmniPossessionManager.MainCamera : _possessionCamera);
			if (!Object.op_Implicit((Object)(object)val))
			{
				return;
			}
			_possessionCamera = val;
			((Behaviour)val).enabled = true;
			val.nearClipPlane = 0.01f;
			val.farClipPlane = Mathf.Max(_possessionFarClipPlane, 10f);
			val.fieldOfView = _possessionFieldOfView;
			Camera[] componentsInChildren = ((Component)val).GetComponentsInChildren<Camera>(true);
			foreach (Camera val2 in componentsInChildren)
			{
				if (Object.op_Implicit((Object)(object)val2) && (Object)(object)val2 != (Object)(object)val)
				{
					val2.fieldOfView = _possessionFieldOfView;
				}
			}
			RenderSettings.fog = true;
			RenderSettings.fogStartDistance = 0f;
			if (Object.op_Implicit((Object)(object)PostProcessing.Instance))
			{
				PostProcessing.Instance.SpectateReset();
			}
			if (Object.op_Implicit((Object)(object)AudioManager.instance) && Object.op_Implicit((Object)(object)AudioManager.instance.AudioListener))
			{
				AudioManager.instance.AudioListener.TargetPositionTransform = ((Component)val).transform;
			}
		}

		private void ResetLocalState()
		{
			//IL_002d: Unknown result type (might be due to invalid IL or missing references)
			RestoreOriginalMasterClient();
			((MonoBehaviour)this).StopAllCoroutines();
			StopLocalPossession();
			int[] array = _hiddenHeadRenderers.Keys.ToArray();
			foreach (int actor in array)
			{
				RestoreDeathHead(actor, Vector3.zero, visible: true, teleport: false);
			}
			_hiddenHeadRenderers.Clear();
			_roundConsumed = false;
			_startInProgress = false;
			_ending = false;
			ClearActiveState();
		}

		private void ClearActiveState()
		{
			_activeActor = -1;
			_activeEnemyViewId = -1;
			_activeEnemyIndex = -1;
			_activeMonsterKey = null;
			_activeEndTime = 0.0;
			_originalMasterActor = -1;
			_activeEnemyObject = null;
			_activeEnemyRoot = null;
		}

		private void Raise(object[] payload)
		{
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			_networkEvent.RaiseEvent((object)payload, NetworkingEvents.RaiseAll, SendOptions.SendReliable);
		}

		private void ResolveActiveEnemy()
		{
			if (!HasActivePossession)
			{
				return;
			}
			if (!Object.op_Implicit((Object)(object)_activeEnemyObject))
			{
				PhotonView val = PhotonView.Find(_activeEnemyViewId);
				_activeEnemyObject = (Object.op_Implicit((Object)(object)val) ? ((Component)val).gameObject : null);
			}
			if (Object.op_Implicit((Object)(object)_activeEnemyObject) && !Object.op_Implicit((Object)(object)_activeEnemyRoot))
			{
				EnemyParent componentInParent = _activeEnemyObject.GetComponentInParent<EnemyParent>(true);
				_activeEnemyRoot = (Object.op_Implicit((Object)(object)componentInParent) ? ((Component)componentInParent).gameObject : ((Component)_activeEnemyObject.transform.root).gameObject);
			}
			if (Object.op_Implicit((Object)(object)_activeEnemyObject) && _activeEnemyIndex < 0)
			{
				Enemy val2 = _activeEnemyObject.GetComponent<Enemy>() ?? _activeEnemyObject.GetComponentInParent<Enemy>() ?? _activeEnemyObject.GetComponentInChildren<Enemy>(true);
				if (Object.op_Implicit((Object)(object)val2))
				{
					_activeEnemyIndex = SemiFunc.EnemyGetIndex(val2);
				}
			}
		}

		private void SetEnemyAuthorityForThisClient()
		{
			ResolveActiveEnemy();
			if (Object.op_Implicit((Object)(object)_activeEnemyRoot))
			{
				bool isLocalPlayerPossessed = IsLocalPlayerPossessed;
				Enemy[] componentsInChildren = _activeEnemyRoot.GetComponentsInChildren<Enemy>(true);
				foreach (Enemy obj in componentsInChildren)
				{
					AccessTools.Field(typeof(Enemy), "MasterClient")?.SetValue(obj, isLocalPlayerPossessed);
				}
			}
		}

		private void RestoreOriginalMasterClient()
		{
			if (!SemiFunc.IsMultiplayer() || !PhotonNetwork.InRoom || !PhotonNetwork.IsMasterClient || _originalMasterActor <= 0 || PhotonNetwork.LocalPlayer == null || PhotonNetwork.LocalPlayer.ActorNumber == _originalMasterActor)
			{
				return;
			}
			Room currentRoom = PhotonNetwork.CurrentRoom;
			Player val = ((currentRoom != null) ? currentRoom.GetPlayer(_originalMasterActor, false) : null);
			if (val == null && PhotonNetwork.CurrentRoom != null)
			{
				val = (from player in PhotonNetwork.CurrentRoom.Players.Values
					where player != null && player.ActorNumber != _activeActor
					orderby player.ActorNumber
					select player).FirstOrDefault();
			}
			if (val != null && !PhotonNetwork.SetMasterClient(val))
			{
				Plugin.Log.LogWarning((object)"Could not immediately restore the original gameplay authority.");
			}
		}

		private bool IsActiveEnemyDead()
		{
			ResolveActiveEnemy();
			if (!Object.op_Implicit((Object)(object)_activeEnemyRoot) || !_activeEnemyRoot.activeInHierarchy)
			{
				return true;
			}
			EnemyHealth componentInChildren = _activeEnemyRoot.GetComponentInChildren<EnemyHealth>(true);
			if (!Object.op_Implicit((Object)(object)componentInChildren))
			{
				return false;
			}
			FieldInfo fieldInfo = AccessTools.Field(typeof(EnemyHealth), "dead");
			FieldInfo fieldInfo2 = AccessTools.Field(typeof(EnemyHealth), "healthCurrent");
			bool num = fieldInfo != null && Convert.ToBoolean(fieldInfo.GetValue(componentInChildren));
			int num2 = ((fieldInfo2 == null) ? 1 : Convert.ToInt32(fieldInfo2.GetValue(componentInChildren)));
			if (!num)
			{
				return num2 <= 0;
			}
			return true;
		}

		private void ForceKillActiveEnemy()
		{
			//IL_0059: Unknown result type (might be due to invalid IL or missing references)
			ResolveActiveEnemy();
			if (!Object.op_Implicit((Object)(object)_activeEnemyRoot))
			{
				return;
			}
			EnemyHealth componentInChildren = _activeEnemyRoot.GetComponentInChildren<EnemyHealth>(true);
			if (Object.op_Implicit((Object)(object)componentInChildren))
			{
				try
				{
					AccessTools.Field(typeof(EnemyHealth), "damageResistance")?.SetValue(componentInChildren, 0f);
					componentInChildren.Hurt(1000000, Vector3.up);
					return;
				}
				catch (Exception ex)
				{
					Plugin.Debug("Normal forced enemy death failed: " + ex.Message);
				}
			}
			if (Object.op_Implicit((Object)(object)_activeEnemyRoot))
			{
				PhotonNetwork.Destroy(_activeEnemyRoot);
			}
		}

		private Vector3 FindRemoteSpawnPosition(Vector3 fallback)
		{
			//IL_00aa: 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_00d3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ee: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f3: Unknown result type (might be due to invalid IL or missing references)
			//IL_0192: Unknown result type (might be due to invalid IL or missing references)
			//IL_0170: Unknown result type (might be due to invalid IL or missing references)
			//IL_0175: Unknown result type (might be due to invalid IL or missing references)
			List<PlayerAvatar> list = (from player in SemiFunc.PlayerGetAll()
				where Object.op_Implicit((Object)(object)player) && !GameAccess.IsDead(player) && !GameAccess.IsDisabled(player)
				select player).ToList();
			List<LevelPoint> obj = ((Object.op_Implicit((Object)(object)LevelGenerator.Instance) && LevelGenerator.Instance.LevelPathPoints != null) ? LevelGenerator.Instance.LevelPathPoints.Where((LevelPoint point) => Object.op_Implicit((Object)(object)point)).ToList() : (from point in Object.FindObjectsOfType<LevelPoint>()
				where Object.op_Implicit((Object)(object)point)
				select point).ToList());
			Vector3 result = fallback;
			float num = float.MinValue;
			bool flag = false;
			NavMeshHit val = default(NavMeshHit);
			foreach (LevelPoint item in obj)
			{
				if (NavMesh.SamplePosition(((Component)item).transform.position, ref val, 4f, -1))
				{
					Vector3 candidate = ((NavMeshHit)(ref val)).position;
					float num2 = ((list.Count == 0) ? 1000f : list.Min((PlayerAvatar player) => Vector3.Distance(candidate, ((Component)player).transform.position)));
					bool flag2 = list.All((PlayerAvatar player) => !HasDirectLineOfSight(player, candidate));
					bool flag3 = num2 >= Plugin.MinimumSpawnDistance.Value && flag2;
					float num3 = num2 + (flag2 ? 1000f : 0f);
					if ((flag3 && !flag) || (flag3 == flag && num3 > num))
					{
						flag = flag3;
						num = num3;
						result = candidate;
					}
				}
			}
			return result;
		}

		private static bool HasDirectLineOfSight(PlayerAvatar player, Vector3 candidate)
		{
			//IL_002f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0034: Unknown result type (might be due to invalid IL or missing references)
			//IL_0039: Unknown result type (might be due to invalid IL or missing references)
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			//IL_0018: Unknown result type (might be due to invalid IL or missing references)
			//IL_001d: 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_003f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0040: Unknown result type (might be due to invalid IL or missing references)
			//IL_0045: 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_004b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0050: Unknown result type (might be due to invalid IL or missing references)
			//IL_0063: 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)
			Vector3 val = (Object.op_Implicit((Object)(object)player.playerAvatarVisuals) ? (((Component)player.playerAvatarVisuals).transform.position + Vector3.up) : (((Component)player).transform.position + Vector3.up));
			Vector3 val2 = candidate + Vector3.up - val;
			float magnitude = ((Vector3)(ref val2)).magnitude;
			if (magnitude <= 0.1f)
			{
				return true;
			}
			return !Physics.Raycast(val, ((Vector3)(ref val2)).normalized, magnitude, LayerMask.GetMask(new string[2] { "Default", "RoomVolume" }), (QueryTriggerInteraction)1);
		}

		private void HideDeathHead(int actor)
		{
			PlayerAvatar obj = FindAvatar(actor);
			PlayerDeathHead val = GameAccess.DeathHead(obj);
			if (!Object.op_Implicit((Object)(object)obj) || !Object.op_Implicit((Object)(object)val))
			{
				return;
			}
			Renderer[] componentsInChildren = ((Component)val).GetComponentsInChildren<Renderer>(true);
			Dictionary<Renderer, bool> dictionary = new Dictionary<Renderer, bool>();
			Renderer[] array = componentsInChildren;
			foreach (Renderer val2 in array)
			{
				if (Object.op_Implicit((Object)(object)val2))
				{
					dictionary[val2] = val2.enabled;
					val2.enabled = false;
				}
			}
			_hiddenHeadRenderers[actor] = dictionary;
			KeepDeathHeadHidden(actor);
		}

		private void KeepDeathHeadHidden(int actor)
		{
			PlayerAvatar obj = FindAvatar(actor);
			PlayerDeathHead val = GameAccess.DeathHead(obj);
			if (!Object.op_Implicit((Object)(object)obj) || !Object.op_Implicit((Object)(object)val))
			{
				return;
			}
			PhysGrabObject obj2 = GameAccess.HeadGrabObject(val);
			if (obj2 != null)
			{
				obj2.OverrideGrabDisable(1f);
			}
			if (!_hiddenHeadRenderers.TryGetValue(actor, out var value))
			{
				return;
			}
			foreach (Renderer key in value.Keys)
			{
				if (Object.op_Implicit((Object)(object)key))
				{
					key.enabled = false;
				}
			}
		}

		private void RestoreDeathHead(int actor, Vector3 position, bool visible = true, bool teleport = true)
		{
			//IL_0038: 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_0043: 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_004d: Unknown result type (might be due to invalid IL or missing references)
			PlayerAvatar obj = FindAvatar(actor);
			PlayerDeathHead val = GameAccess.DeathHead(obj);
			if (!Object.op_Implicit((Object)(object)obj) || !Object.op_Implicit((Object)(object)val))
			{
				return;
			}
			PhysGrabObject val2 = GameAccess.HeadGrabObject(val);
			if (teleport && PhotonNetwork.IsMasterClient && Object.op_Implicit((Object)(object)val2))
			{
				val2.Teleport(position + Vector3.up * 0.35f, Quaternion.identity);
			}
			if (!_hiddenHeadRenderers.TryGetValue(actor, out var value))
			{
				return;
			}
			foreach (KeyValuePair<Renderer, bool> item in value)
			{
				if (Object.op_Implicit((Object)(object)item.Key))
				{
					item.Key.enabled = visible && item.Value;
				}
			}
			_hiddenHeadRenderers.Remove(actor);
		}

		private static PlayerAvatar FindAvatar(int actor)
		{
			return ((IEnumerable<PlayerAvatar>)SemiFunc.PlayerGetAll()).FirstOrDefault((Func<PlayerAvatar, bool>)((PlayerAvatar avatar) => Object.op_Implicit((Object)(object)avatar) && Object.op_Implicit((Object)(object)avatar.photonView) && avatar.photonView.OwnerActorNr == actor));
		}
	}
	internal sealed class CountdownUI
	{
		private GameObject _root;

		private TextMeshProUGUI _text;

		internal void Show()
		{
			EnsureCreated();
			_root.SetActive(true);
		}

		internal void Hide()
		{
			if (Object.op_Implicit((Object)(object)_root))
			{
				_root.SetActive(false);
			}
		}

		internal void UpdateTime(float seconds)
		{
			//IL_0084: Unknown result type (might be due to invalid IL or missing references)
			//IL_0069: 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)
			EnsureCreated();
			int num = Mathf.Max(0, Mathf.CeilToInt(seconds));
			int num2 = num / 60;
			int num3 = num % 60;
			((TMP_Text)_text).text = $"SZÖRNY IDŐ: {num2:00}:{num3:00}";
			((Graphic)_text).color = (Color)((num <= 10) ? new Color(1f, 0.15f, 0.15f, 1f) : ((num <= 60) ? new Color(1f, 0.82f, 0.1f, 1f) : Color.white));
		}

		private void EnsureCreated()
		{
			//IL_0014: Unknown result type (might be due to invalid IL or missing references)
			//IL_001e: Expected O, but got Unknown
			//IL_006f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0094: Unknown result type (might be due to invalid IL or missing references)
			//IL_009a: Expected O, but got Unknown
			//IL_012f: Unknown result type (might be due to invalid IL or missing references)
			//IL_014f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0164: Unknown result type (might be due to invalid IL or missing references)
			//IL_0179: Unknown result type (might be due to invalid IL or missing references)
			//IL_018e: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a2: Unknown result type (might be due to invalid IL or missing references)
			if (!Object.op_Implicit((Object)(object)_root))
			{
				_root = new GameObject("XenoriaAfterLife Countdown");
				((Object)_root).hideFlags = (HideFlags)61;
				Object.DontDestroyOnLoad((Object)(object)_root);
				Canvas obj = _root.AddComponent<Canvas>();
				obj.renderMode = (RenderMode)0;
				obj.sortingOrder = 1200;
				CanvasScaler obj2 = _root.AddComponent<CanvasScaler>();
				obj2.uiScaleMode = (ScaleMode)1;
				obj2.referenceResolution = new Vector2(1920f, 1080f);
				obj2.matchWidthOrHeight = 1f;
				_root.AddComponent<GraphicRaycaster>();
				GameObject val = new GameObject("Countdown Text");
				val.transform.SetParent(_root.transform, false);
				_text = val.AddComponent<TextMeshProUGUI>();
				((TMP_Text)_text).font = TMP_Settings.defaultFontAsset;
				((TMP_Text)_text).fontSize = 72f;
				((TMP_Text)_text).fontStyle = (FontStyles)1;
				((TMP_Text)_text).alignment = (TextAlignmentOptions)258;
				((TMP_Text)_text).enableWordWrapping = false;
				((Graphic)_text).raycastTarget = false;
				((TMP_Text)_text).outlineWidth = 0.22f;
				((TMP_Text)_text).outlineColor = new Color32((byte)0, (byte)0, (byte)0, (byte)230);
				RectTransform rectTransform = ((TMP_Text)_text).rectTransform;
				rectTransform.anchorMin = new Vector2(0.1f, 1f);
				rectTransform.anchorMax = new Vector2(0.9f, 1f);
				rectTransform.pivot = new Vector2(0.5f, 1f);
				rectTransform.anchoredPosition = new Vector2(0f, -28f);
				rectTransform.sizeDelta = new Vector2(0f, 110f);
			}
		}
	}
	internal static class GameAccess
	{
		private static readonly FieldInfo DeadSetField = AccessTools.Field(typeof(PlayerAvatar), "deadSet");

		private static readonly FieldInfo DisabledField = AccessTools.Field(typeof(PlayerAvatar), "isDisabled");

		private static readonly FieldInfo DeathHeadField = AccessTools.Field(typeof(PlayerAvatar), "playerDeathHead");

		private static readonly FieldInfo HeadGrabObjectField = AccessTools.Field(typeof(PlayerDeathHead), "physGrabObject");

		internal static bool IsDead(PlayerAvatar avatar)
		{
			if (Object.op_Implicit((Object)(object)avatar) && DeadSetField != null)
			{
				return Convert.ToBoolean(DeadSetField.GetValue(avatar));
			}
			return false;
		}

		internal static bool IsDisabled(PlayerAvatar avatar)
		{
			if (Object.op_Implicit((Object)(object)avatar) && DisabledField != null)
			{
				return Convert.ToBoolean(DisabledField.GetValue(avatar));
			}
			return false;
		}

		internal static PlayerDeathHead DeathHead(PlayerAvatar avatar)
		{
			if (!Object.op_Implicit((Object)(object)avatar) || !(DeathHeadField != null))
			{
				return null;
			}
			object? value = DeathHeadField.GetValue(avatar);
			return (PlayerDeathHead)((value is PlayerDeathHead) ? value : null);
		}

		internal static PhysGrabObject HeadGrabObject(PlayerDeathHead head)
		{
			if (!Object.op_Implicit((Object)(object)head) || !(HeadGrabObjectField != null))
			{
				return null;
			}
			object? value = HeadGrabObjectField.GetValue(head);
			return (PhysGrabObject)((value is PhysGrabObject) ? value : null);
		}
	}
	internal sealed class MonsterDefinition
	{
		public string Key { get; }

		public string DisplayName { get; }

		public Type EnemyComponentType { get; }

		public Type ControllerType { get; }

		public MonsterDefinition(string key, string displayName, Type enemyComponentType, Type controllerType)
		{
			Key = key;
			DisplayName = displayName;
			EnemyComponentType = enemyComponentType;
			ControllerType = controllerType;
		}

		public GameObject FindEnemyObject(GameObject root)
		{
			if (!Object.op_Implicit((Object)(object)root))
			{
				return null;
			}
			Component componentInChildren = root.GetComponentInChildren(EnemyComponentType, true);
			if (!Object.op_Implicit((Object)(object)componentInChildren))
			{
				return null;
			}
			return componentInChildren.gameObject;
		}
	}
	internal sealed class MonsterSpawnCandidate
	{
		public MonsterDefinition Definition { get; }

		public PrefabRef Prefab { get; }

		public MonsterSpawnCandidate(MonsterDefinition definition, PrefabRef prefab)
		{
			Definition = definition;
			Prefab = prefab;
		}
	}
	internal static class MonsterCatalog
	{
		internal static readonly IReadOnlyList<MonsterDefinition> Definitions = new List<MonsterDefinition>
		{
			new MonsterDefinition("duck", "Duck", typeof(EnemyDuck), typeof(DuckController)),
			new MonsterDefinition("elsa", "Elsa", typeof(EnemyElsa), typeof(ElsaController)),
			new MonsterDefinition("slow_walker", "Slow Walker", typeof(EnemySlowWalker), typeof(SlowWalkerController)),
			new MonsterDefinition("hunter", "Hunter", typeof(EnemyHunter), typeof(HunterController)),
			new MonsterDefinition("bomb_thrower", "Bomb Thrower", typeof(EnemyBombThrower), typeof(BombThrowerController)),
			new MonsterDefinition("bang", "Bang", typeof(EnemyBang), typeof(BangController)),
			new MonsterDefinition("beamer", "Beamer", typeof(EnemyBeamer), typeof(BeamerController)),
			new MonsterDefinition("floater", "Floater", typeof(EnemyFloater), typeof(FloaterController)),
			new MonsterDefinition("bowtie", "Bowtie", typeof(EnemyBowtie), typeof(BowtieController)),
			new MonsterDefinition("birthday_boy", "Birthday Boy", typeof(EnemyBirthdayBoy), typeof(BirthdayBoyController)),
			new MonsterDefinition("animal", "Animal", typeof(EnemyAnimal), typeof(AnimalController)),
			new MonsterDefinition("head", "Head", typeof(EnemyHeadController), typeof(HeadController)),
			new MonsterDefinition("gnome", "Gnome", typeof(EnemyGnome), typeof(GnomeController)),
			new MonsterDefinition("head_grabber", "Head Grabber", typeof(EnemyHeadGrabber), typeof(HeadGrabberController)),
			new MonsterDefinition("heart_hugger", "Heart Hugger", typeof(EnemyHeartHugger), typeof(HeartHuggerController)),
			new MonsterDefinition("hidden", "Hidden", typeof(EnemyHidden), typeof(HiddenController)),
			new MonsterDefinition("robe", "Robe", typeof(EnemyRobe), typeof(RobeController)),
			new MonsterDefinition("runner", "Runner", typeof(EnemyRunner), typeof(RunnerController)),
			new MonsterDefinition("shadow", "Shadow", typeof(EnemyShadow), typeof(ShadowController)),
			new MonsterDefinition("spinny", "Spinny", typeof(EnemySpinny), typeof(SpinnyController)),
			new MonsterDefinition("slow_mouth", "Slow Mouth", typeof(EnemySlowMouth), typeof(SlowMouthController)),
			new MonsterDefinition("tick", "Tick", typeof(EnemyTick), typeof(TickController)),
			new MonsterDefinition("tricycle", "Tricycle", typeof(EnemyTricycle), typeof(TricycleController)),
			new MonsterDefinition("tumbler", "Tumbler", typeof(EnemyTumbler), typeof(TumblerController)),
			new MonsterDefinition("upscream", "Upscream", typeof(EnemyUpscream), typeof(UpscreamController)),
			new MonsterDefinition("valuable_thrower", "Valuable Thrower", typeof(EnemyValuableThrower), typeof(ValuableThrowerController)),
			new MonsterDefinition("oogly", "Oogly", typeof(EnemyOogly), typeof(OoglyController)),
			new MonsterDefinition("snatcher", "Snatcher", typeof(EnemySnatcher), typeof(SnatcherController))
		};

		private static readonly Dictionary<string, MonsterDefinition> ByKey = BuildKeyMap();

		internal static MonsterDefinition Get(string key)
		{
			if (key == null || !ByKey.TryGetValue(key, out var value))
			{
				return null;
			}
			return value;
		}

		internal static List<MonsterSpawnCandidate> GetAvailableVanillaCandidates()
		{
			List<MonsterSpawnCandidate> list = new List<MonsterSpawnCandidate>();
			EnemyDirector instance = EnemyDirector.instance;
			if (!Object.op_Implicit((Object)(object)instance))
			{
				return list;
			}
			HashSet<string> hashSet = new HashSet<string>(StringComparer.Ordinal);
			List<EnemySetup> list2 = new List<EnemySetup>();
			list2.AddRange(instance.enemiesDifficulty1);
			list2.AddRange(instance.enemiesDifficulty2);
			list2.AddRange(instance.enemiesDifficulty3);
			foreach (EnemySetup item in list2)
			{
				if (!Object.op_Implicit((Object)(object)item) || item.spawnObjects == null)
				{
					continue;
				}
				foreach (PrefabRef spawnObject in item.spawnObjects)
				{
					if (spawnObject == null || string.IsNullOrWhiteSpace(((PrefabRef<GameObject>)(object)spawnObject).ResourcePath) || !hashSet.Add(((PrefabRef<GameObject>)(object)spawnObject).ResourcePath))
					{
						continue;
					}
					GameObject prefab = ((PrefabRef<GameObject>)(object)spawnObject).Prefab;
					if (!Object.op_Implicit((Object)(object)prefab))
					{
						continue;
					}
					foreach (MonsterDefinition definition in Definitions)
					{
						Component componentInChildren = prefab.GetComponentInChildren(definition.EnemyComponentType, true);
						if (Object.op_Implicit((Object)(object)componentInChildren) && !(((object)componentInChildren).GetType() != definition.EnemyComponentType))
						{
							list.Add(new MonsterSpawnCandidate(definition, spawnObject));
							break;
						}
					}
				}
			}
			return list;
		}

		private static Dictionary<string, MonsterDefinition> BuildKeyMap()
		{
			Dictionary<string, MonsterDefinition> dictionary = new Dictionary<string, MonsterDefinition>(StringComparer.OrdinalIgnoreCase);
			foreach (MonsterDefinition definition in Definitions)
			{
				dictionary[definition.Key] = definition;
			}
			return dictionary;
		}
	}
	[HarmonyPatch(typeof(PlayerAvatar), "PlayerDeathRPC")]
	internal static class FirstDeathPatch
	{
		private static void Postfix(PlayerAvatar __instance)
		{
			if (GameAccess.IsDead(__instance))
			{
				AfterLifeManager.Instance?.TryHandleFirstDeath(__instance);
			}
		}
	}
	[HarmonyPatch]
	internal static class PossessedPlayerReviveBlockPatch
	{
		private static IEnumerable<MethodBase> TargetMethods()
		{
			yield return AccessTools.Method(typeof(PlayerAvatar), "Revive", (Type[])null, (Type[])null);
			yield return AccessTools.Method(typeof(PlayerAvatar), "ReviveRPC", (Type[])null, (Type[])null);
		}

		private static bool Prefix(PlayerAvatar __instance)
		{
			AfterLifeManager instance = AfterLifeManager.Instance;
			if (!((Object)(object)instance == (Object)null))
			{
				return !instance.IsPossessedAvatar(__instance);
			}
			return true;
		}
	}
	[HarmonyPatch]
	internal static class DisableOmniDebugMenuPatch
	{
		private static IEnumerable<MethodBase> TargetMethods()
		{
			Type typeFromHandle = typeof(OmniUIManager);
			MethodInfo methodInfo = AccessTools.Method(typeFromHandle, "Update", (Type[])null, (Type[])null);
			MethodInfo onGui = AccessTools.Method(typeFromHandle, "OnGUI", (Type[])null, (Type[])null);
			if (methodInfo != null)
			{
				yield return methodInfo;
			}
			if (onGui != null)
			{
				yield return onGui;
			}
		}

		private static bool Prefix()
		{
			if (Plugin.DisableManualPossessionMenu != null)
			{
				return !Plugin.DisableManualPossessionMenu.Value;
			}
			return true;
		}
	}
	[HarmonyPatch(typeof(OmniPossessionManager), "get_HasEffectiveControl")]
	internal static class OmniEffectiveControlPatch
	{
		private static void Postfix(ref bool __result)
		{
			if (!__result)
			{
				AfterLifeManager instance = AfterLifeManager.Instance;
				if (instance != null && instance.IsLocalPlayerPossessed)
				{
					__result = true;
				}
			}
		}
	}
	[HarmonyPatch]
	internal static class RemotePossessedEnemyAiPatch
	{
		private static IEnumerable<MethodBase> TargetMethods()
		{
			HashSet<MethodBase> hashSet = new HashSet<MethodBase>();
			foreach (MonsterDefinition definition in MonsterCatalog.Definitions)
			{
				string[] array = new string[2] { "Update", "FixedUpdate" };
				foreach (string name in array)
				{
					MethodInfo method = definition.EnemyComponentType.GetMethod(name, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
					if (method != null)
					{
						hashSet.Add(method);
					}
				}
			}
			return hashSet;
		}

		private static bool Prefix(MonoBehaviour __instance)
		{
			AfterLifeManager instance = AfterLifeManager.Instance;
			if ((Object)(object)instance == (Object)null || !instance.IsActiveEnemyComponent((Component)(object)__instance))
			{
				return true;
			}
			if (PhotonNetwork.IsMasterClient && PhotonNetwork.LocalPlayer != null)
			{
				return instance.ActiveActor == PhotonNetwork.LocalPlayer.ActorNumber;
			}
			return true;
		}
	}
	internal static class PossessedAttackScope
	{
		[ThreadStatic]
		private static int _depth;

		internal static bool Active => _depth > 0;

		internal static void Enter()
		{
			_depth++;
		}

		internal static void Exit()
		{
			if (_depth > 0)
			{
				_depth--;
			}
		}
	}
	[HarmonyPatch]
	internal static class PossessedControllerAttackScopePatch
	{
		private static IEnumerable<MethodBase> TargetMethods()
		{
			return (from definition in MonsterCatalog.Definitions
				select AccessTools.Method(definition.ControllerType, "HandleInputAndMovement", (Type[])null, (Type[])null) into method
				where method != null
				select method).Distinct();
		}

		private static void Prefix(out bool __state)
		{
			__state = AfterLifeManager.Instance?.IsLocalPlayerPossessed ?? false;
			if (__state)
			{
				PossessedAttackScope.Enter();
			}
		}

		private static Exception Finalizer(Exception __exception, bool __state)
		{
			if (__state)
			{
				PossessedAttackScope.Exit();
			}
			return __exception;
		}
	}
	[HarmonyPatch(typeof(EnemyHealth), "Hurt")]
	internal static class PossessedCannotDamageAiEnemiesPatch
	{
		private static bool Prefix()
		{
			return !PossessedAttackScope.Active;
		}
	}
	internal static class PossessedRpcScope
	{
		[ThreadStatic]
		private static int _depth;

		internal static bool Active => _depth > 0;

		internal static void Enter()
		{
			_depth++;
		}

		internal static void Exit()
		{
			if (_depth > 0)
			{
				_depth--;
			}
		}
	}
	[HarmonyPatch]
	internal static class PossessedEnemyPunRpcScopePatch
	{
		private static IEnumerable<MethodBase> TargetMethods()
		{
			Type[] source;
			try
			{
				source = typeof(PlayerAvatar).Assembly.GetTypes();
			}
			catch (ReflectionTypeLoadException ex)
			{
				source = ex.Types.Where((Type type) => type != null).ToArray();
			}
			return from method in source.SelectMany((Type type) => type.GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic))
				where method.GetCustomAttributes(typeof(PunRPC), inherit: true).Length != 0
				select method;
		}

		private static void Prefix(object __instance, object[] __args, out bool __state)
		{
			//IL_003f: Unknown result type (might be due to invalid IL or missing references)
			__state = false;
			Component val = (Component)((__instance is Component) ? __instance : null);
			if (val != null && !((Object)(object)AfterLifeManager.Instance == (Object)null) && AfterLifeManager.Instance.IsActiveEnemyComponent(val))
			{
				PhotonMessageInfo? val2 = FindInfo(__args);
				if (val2.HasValue && AfterLifeManager.Instance.IsAuthorizedPossessedSender(val2.Value))
				{
					PossessedRpcScope.Enter();
					__state = true;
				}
			}
		}

		private static Exception Finalizer(Exception __exception, bool __state)
		{
			if (__state)
			{
				PossessedRpcScope.Exit();
			}
			return __exception;
		}

		internal static PhotonMessageInfo? FindInfo(object[] args)
		{
			//IL_0020: Unknown result type (might be due to invalid IL or missing references)
			//IL_0025: Unknown result type (might be due to invalid IL or missing references)
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			if (args == null)
			{
				return null;
			}
			foreach (object obj in args)
			{
				if (obj is PhotonMessageInfo)
				{
					return (PhotonMessageInfo)obj;
				}
			}
			return null;
		}
	}
	[HarmonyPatch]
	internal static class PossessedPlayerDamageRpcScopePatch
	{
		private static MethodBase TargetMethod()
		{
			return AccessTools.Method(typeof(PlayerHealth), "HurtOtherRPC", (Type[])null, (Type[])null);
		}

		private static void Prefix(int enemyIndex, PhotonMessageInfo _info, out bool __state)
		{
			//IL_0020: Unknown result type (might be due to invalid IL or missing references)
			__state = false;
			AfterLifeManager instance = AfterLifeManager.Instance;
			if (!((Object)(object)instance == (Object)null) && enemyIndex >= 0 && enemyIndex == instance.ActiveEnemyIndex && instance.IsAuthorizedPossessedSender(_info))
			{
				PossessedRpcScope.Enter();
				__state = true;
			}
		}

		private static Exception Finalizer(Exception __exception, bool __state)
		{
			if (__state)
			{
				PossessedRpcScope.Exit();
			}
			return __exception;
		}
	}
	[HarmonyPatch]
	internal static class PossessedRpcAuthorizationPatch
	{
		private static IEnumerable<MethodBase> TargetMethods()
		{
			yield return AccessTools.Method(typeof(SemiFunc), "MasterOnlyRPC", (Type[])null, (Type[])null);
			yield return AccessTools.Method(typeof(SemiFunc), "MasterAndOwnerOnlyRPC", (Type[])null, (Type[])null);
		}

		private static void Postfix(ref bool __result)
		{
			if (!__result && PossessedRpcScope.Active)
			{
				__result = true;
			}
		}
	}
	[BepInPlugin("hu.xenon.xenoriaafterlife", "XenoriaAfterLife", "1.0.2")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	public sealed class Plugin : BaseUnityPlugin
	{
		public const string PluginGuid = "hu.xenon.xenoriaafterlife";

		public const string PluginName = "XenoriaAfterLife";

		public const string PluginVersion = "1.0.2";

		private Harmony _harmony;

		internal static Plugin Instance { get; private set; }

		internal static ManualLogSource Log { get; private set; }

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

		internal static ConfigEntry<float> MonsterLifetime { get; private set; }

		internal static ConfigEntry<int> MinimumPlayers { get; private set; }

		internal static ConfigEntry<float> MinimumSpawnDistance { get; private set; }

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

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

		private void Awake()
		{
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0069: Expected O, but got Unknown
			//IL_0091: Unknown result type (might be due to invalid IL or missing references)
			//IL_009b: Expected O, but got Unknown
			//IL_00ce: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d8: Expected O, but got Unknown
			//IL_0123: Unknown result type (might be due to invalid IL or missing references)
			//IL_012d: Expected O, but got Unknown
			//IL_0157: Unknown result type (might be due to invalid IL or missing references)
			//IL_015c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0164: Unknown result type (might be due to invalid IL or missing references)
			//IL_016a: Expected O, but got Unknown
			Instance = this;
			Log = ((BaseUnityPlugin)this).Logger;
			Enabled = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "Enabled", true, "Enable the first-death monster event on gameplay levels.");
			MonsterLifetime = ((BaseUnityPlugin)this).Config.Bind<float>("General", "Monster lifetime seconds", 180f, new ConfigDescription("How long the first dead player may remain a monster.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(10f, 1800f), Array.Empty<object>()));
			MinimumPlayers = ((BaseUnityPlugin)this).Config.Bind<int>("General", "Minimum players", 2, new ConfigDescription("Minimum connected player count required when the first death occurs.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(2, 32), Array.Empty<object>()));
			MinimumSpawnDistance = ((BaseUnityPlugin)this).Config.Bind<float>("Spawn", "Minimum distance from living players", 30f, new ConfigDescription("Preferred minimum spawn distance in metres.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(10f, 100f), Array.Empty<object>()));
			DisableManualPossessionMenu = ((BaseUnityPlugin)this).Config.Bind<bool>("Compatibility", "Disable manual possession menu", true, "Prevents the dependency's F1/F5 debug possession controls from bypassing XenoriaAfterLife.");
			DebugLogging = ((BaseUnityPlugin)this).Config.Bind<bool>("Debug", "Verbose logging", false, "Write additional state and networking information to the BepInEx log.");
			_harmony = new Harmony("hu.xenon.xenoriaafterlife");
			_harmony.PatchAll(typeof(Plugin).Assembly);
			TimerReviveCompatibility.Install(_harmony);
			GameObject val = new GameObject("XenoriaAfterLife Manager")
			{
				hideFlags = (HideFlags)61
			};
			Object.DontDestroyOnLoad((Object)val);
			val.AddComponent<AfterLifeManager>();
			((BaseUnityPlugin)this).Logger.LogInfo((object)("XenoriaAfterLife 1.0.2 loaded. TimerRevive compatibility: " + (TimerReviveCompatibility.Installed ? "active" : "not installed")));
		}

		private void OnDestroy()
		{
			if (_harmony != null)
			{
				_harmony.UnpatchSelf();
			}
		}

		internal static void Debug(string message)
		{
			if (DebugLogging != null && DebugLogging.Value)
			{
				Log.LogInfo((object)message);
			}
		}
	}
	internal static class TimerReviveCompatibility
	{
		private static Type _timerUpdateType;

		private static Type _pluginType;

		private static FieldInfo _reviveStatesField;

		private static FieldInfo _timerResetLocalField;

		private static FieldInfo _waitTimerLocalField;

		private static FieldInfo _reviveTimerLocalField;

		private static FieldInfo _canvasField;

		internal static bool Installed { get; private set; }

		internal static void Install(Harmony harmony)
		{
			//IL_00d2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00df: Expected O, but got Unknown
			try
			{
				_timerUpdateType = AccessTools.TypeByName("TimerRevive.TimerUpdate");
				_pluginType = AccessTools.TypeByName("TimerRevive.TimerRevive");
				MethodInfo methodInfo = ((_timerUpdateType == null) ? null : AccessTools.Method(_timerUpdateType, "Postfix", (Type[])null, (Type[])null));
				if (!(methodInfo == null) && !(_pluginType == null))
				{
					_reviveStatesField = AccessTools.Field(_timerUpdateType, "reviveStates");
					_timerResetLocalField = AccessTools.Field(_timerUpdateType, "timerReset_local");
					_waitTimerLocalField = AccessTools.Field(_timerUpdateType, "waitTimer_local");
					_reviveTimerLocalField = AccessTools.Field(_timerUpdateType, "reviveTimer_local");
					_canvasField = AccessTools.Field(_pluginType, "canvas");
					harmony.Patch((MethodBase)methodInfo, (HarmonyMethod)null, new HarmonyMethod(typeof(TimerReviveCompatibility), "AfterTimerReviveUpdate", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
					Installed = true;
				}
			}
			catch (Exception ex)
			{
				Plugin.Log.LogWarning((object)("TimerRevive compatibility could not be installed: " + ex.Message));
			}
		}

		private static void AfterTimerReviveUpdate()
		{
			AfterLifeManager instance = AfterLifeManager.Instance;
			if ((Object)(object)instance == (Object)null || !instance.HasActivePossession)
			{
				return;
			}
			try
			{
				if (PhotonNetwork.IsMasterClient && _reviveStatesField?.GetValue(null) is IDictionary dictionary)
				{
					foreach (DictionaryEntry item in dictionary)
					{
						object key = item.Key;
						PlayerAvatar val = (PlayerAvatar)((key is PlayerAvatar) ? key : null);
						if (val != null && instance.IsPossessedAvatar(val) && item.Value != null)
						{
							Type type = item.Value.GetType();
							AccessTools.Field(type, "timerReset")?.SetValue(item.Value, false);
							AccessTools.Field(type, "isdead")?.SetValue(item.Value, false);
							AccessTools.Field(type, "waitTimer")?.SetValue(item.Value, 5f);
						}
					}
				}
				if (instance.IsLocalPlayerPossessed)
				{
					_timerResetLocalField?.SetValue(null, false);
					_waitTimerLocalField?.SetValue(null, 5f);
					_reviveTimerLocalField?.SetValue(null, 0f);
					object? obj = _canvasField?.GetValue(null);
					Canvas val2 = (Canvas)((obj is Canvas) ? obj : null);
					if (val2 != null)
					{
						((Behaviour)val2).enabled = false;
					}
				}
			}
			catch (Exception ex)
			{
				Plugin.Debug("TimerRevive state hold failed: " + ex.Message);
			}
		}
	}
}