Decompiled source of LobbyPlus v1.0.0

LobbyPlus.dll

Decompiled 2 hours ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Text;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Configuration;
using BepInEx.Logging;
using ExitGames.Client.Photon;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using Photon.Pun;
using Photon.Realtime;
using Steamworks;
using Steamworks.Data;
using UnityEngine;
using UnityEngine.SceneManagement;

[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("LobbyPlus")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0")]
[assembly: AssemblyProduct("LobbyPlus")]
[assembly: AssemblyTitle("LobbyPlus")]
[assembly: AssemblyVersion("1.0.0.0")]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace LobbyPlus
{
	internal static class GameAccess
	{
		private static readonly FieldRef<SteamLobbyManager, Lobby> currentLobby = Ref<SteamLobbyManager, Lobby>("currentLobby");

		private static readonly FieldRef<GameManager, bool> connectRandom = Ref<GameManager, bool>("connectRandom");

		private static readonly FieldRef<RunManager, bool> restarting = Ref<RunManager, bool>("restarting");

		private static readonly FieldRef<RunManager, Level> debugLevel = Ref<RunManager, Level>("debugLevel");

		private static readonly FieldRef<RunManager, RunManagerPUN> runManagerPun = Ref<RunManager, RunManagerPUN>("runManagerPUN");

		private static readonly FieldRef<RunManagerPUN, PhotonView> runManagerPunView = Ref<RunManagerPUN, PhotonView>("photonView");

		private static readonly FieldRef<PlayerAvatar, bool> avatarSpawned = Ref<PlayerAvatar, bool>("spawned");

		private static readonly FieldRef<PlayerAvatar, bool> avatarLevelAnimationCompleted = Ref<PlayerAvatar, bool>("levelAnimationCompleted");

		private static readonly FieldRef<PlayerAvatar, bool> avatarOutroDone = Ref<PlayerAvatar, bool>("outroDone");

		private static readonly FieldRef<LoadingUI, bool> uiLevelAnimationCompleted = Ref<LoadingUI, bool>("levelAnimationCompleted");

		private static readonly FieldRef<PlayerAvatar, PlayerDeathHead> avatarDeathHead = Ref<PlayerAvatar, PlayerDeathHead>("playerDeathHead");

		private static readonly FieldRef<PlayerAvatar, PlayerTumble> avatarTumble = Ref<PlayerAvatar, PlayerTumble>("tumble");

		private static readonly FieldRef<AssetManager, Vector3> physDisabledPosition = Ref<AssetManager, Vector3>("physDisabledPosition");

		private static readonly FieldInfo roomCloseConfirmed = Field(typeof(PhotonNetwork), "persistentObjectsRoomClosed");

		private static readonly MethodInfo persistSetter = Setter(typeof(PhotonView), "PersistAcrossSceneReset");

		internal static bool CanCheckHeadAndTumble
		{
			get
			{
				if (avatarDeathHead != null)
				{
					return avatarTumble != null;
				}
				return false;
			}
		}

		internal static bool CanSetPersistent => persistSetter != null;

		internal static bool CanMarkOutroDone => avatarOutroDone != null;

		internal static bool? RoomCloseConfirmed
		{
			get
			{
				if (roomCloseConfirmed == null)
				{
					return null;
				}
				return (bool)roomCloseConfirmed.GetValue(null);
			}
		}

		internal static PlayerDeathHead DeathHead(PlayerAvatar avatar)
		{
			if (!((Object)(object)avatar != (Object)null) || avatarDeathHead == null)
			{
				return null;
			}
			return avatarDeathHead.Invoke(avatar);
		}

		internal static void SetDeathHead(PlayerAvatar avatar, PlayerDeathHead head)
		{
			if ((Object)(object)avatar != (Object)null && avatarDeathHead != null)
			{
				avatarDeathHead.Invoke(avatar) = head;
			}
		}

		internal static PlayerTumble Tumble(PlayerAvatar avatar)
		{
			if (!((Object)(object)avatar != (Object)null) || avatarTumble == null)
			{
				return null;
			}
			return avatarTumble.Invoke(avatar);
		}

		internal static void SetTumble(PlayerAvatar avatar, PlayerTumble tumble)
		{
			if ((Object)(object)avatar != (Object)null && avatarTumble != null)
			{
				avatarTumble.Invoke(avatar) = tumble;
			}
		}

		internal static Vector3 ParkingSpot()
		{
			//IL_0025: Unknown result type (might be due to invalid IL or missing references)
			//IL_0036: Unknown result type (might be due to invalid IL or missing references)
			AssetManager instance = AssetManager.instance;
			if (!((Object)(object)instance != (Object)null) || physDisabledPosition == null)
			{
				return new Vector3(0f, 3000f, 0f);
			}
			return physDisabledPosition.Invoke(instance);
		}

		internal static void SetPersistent(PhotonView view, bool persistent)
		{
			if ((Object)(object)view != (Object)null && persistSetter != null)
			{
				persistSetter.Invoke(view, new object[1] { persistent });
			}
		}

		private static MethodInfo Setter(Type type, string property)
		{
			MethodInfo methodInfo = AccessTools.PropertySetter(type, property);
			if (methodInfo == null)
			{
				Plugin.Log.LogError((object)("Couldn't find " + type.Name + "." + property + " (game update?). Late joiners may get stuck loading."));
			}
			return methodInfo;
		}

		internal static Lobby CurrentLobby(SteamLobbyManager manager)
		{
			//IL_0012: 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_0025: Unknown result type (might be due to invalid IL or missing references)
			if (!((Object)(object)manager != (Object)null) || currentLobby == null)
			{
				return default(Lobby);
			}
			return currentLobby.Invoke(manager);
		}

		internal static bool IsPublicSession(GameManager manager)
		{
			if ((Object)(object)manager != (Object)null && connectRandom != null)
			{
				return connectRandom.Invoke(manager);
			}
			return false;
		}

		internal static bool IsRestarting(RunManager manager)
		{
			if ((Object)(object)manager != (Object)null && restarting != null)
			{
				return restarting.Invoke(manager);
			}
			return false;
		}

		internal static bool SetDebugLevel(RunManager manager, Level level)
		{
			if ((Object)(object)manager == (Object)null || debugLevel == null)
			{
				return false;
			}
			debugLevel.Invoke(manager) = level;
			return true;
		}

		internal static PhotonView RunManagerView(RunManager manager)
		{
			if ((Object)(object)manager == (Object)null || runManagerPun == null || runManagerPunView == null)
			{
				return null;
			}
			RunManagerPUN val = runManagerPun.Invoke(manager);
			if (!((Object)(object)val != (Object)null))
			{
				return null;
			}
			return runManagerPunView.Invoke(val);
		}

		internal static bool IsSpawned(PlayerAvatar avatar)
		{
			if (!((Object)(object)avatar == (Object)null) && avatarSpawned != null)
			{
				return avatarSpawned.Invoke(avatar);
			}
			return true;
		}

		internal static bool AvatarLevelAnimationDone(PlayerAvatar avatar)
		{
			if ((Object)(object)avatar != (Object)null && avatarLevelAnimationCompleted != null)
			{
				return avatarLevelAnimationCompleted.Invoke(avatar);
			}
			return false;
		}

		internal static bool MarkAvatarLevelAnimationDone(PlayerAvatar avatar)
		{
			if ((Object)(object)avatar == (Object)null || avatarLevelAnimationCompleted == null || avatarLevelAnimationCompleted.Invoke(avatar))
			{
				return false;
			}
			avatarLevelAnimationCompleted.Invoke(avatar) = true;
			return true;
		}

		internal static bool MarkOutroDone(PlayerAvatar avatar)
		{
			if ((Object)(object)avatar == (Object)null || avatarOutroDone == null || avatarOutroDone.Invoke(avatar))
			{
				return false;
			}
			avatarOutroDone.Invoke(avatar) = true;
			return true;
		}

		internal static bool LoadingScreenDone(LoadingUI ui)
		{
			if (!((Object)(object)ui == (Object)null) && uiLevelAnimationCompleted != null)
			{
				return uiLevelAnimationCompleted.Invoke(ui);
			}
			return true;
		}

		private static FieldRef<T, F> Ref<T, F>(string name) where T : class
		{
			try
			{
				return AccessTools.FieldRefAccess<T, F>(name);
			}
			catch (Exception ex)
			{
				Plugin.Log.LogError((object)("Couldn't find " + typeof(T).Name + "." + name + " (game update?). The feature that needs it is turned off. " + ex.Message));
				return null;
			}
		}

		private static FieldInfo Field(Type type, string name)
		{
			FieldInfo fieldInfo = AccessTools.Field(type, name);
			if (fieldInfo == null)
			{
				Plugin.Log.LogError((object)("Couldn't find " + type.Name + "." + name + " (game update?). Late join will stay closed."));
			}
			return fieldInfo;
		}
	}
	internal static class LateJoin
	{
		private static bool openedByUs;

		private static bool cleanupPending;

		private static bool blockedThisLevel;

		private static float clientStuckTimer;

		private static PhotonView taggedRunView;

		private static readonly HashSet<int> lateJoiners = new HashSet<int>();

		private static readonly HashSet<int> outroSkipped = new HashSet<int>();

		private static LevelGenerator lateJoinersLevel;

		private static bool shopReloadQueued;

		internal static string BlockReason { get; private set; }

		private static bool HostActive
		{
			get
			{
				if (Plugin.LateJoinEnabled.Value && (Object)(object)GameManager.instance != (Object)null && GameManager.Multiplayer() && PhotonNetwork.InRoom)
				{
					return PhotonNetwork.IsMasterClient;
				}
				return false;
			}
		}

		internal static bool IsTruck(Level level)
		{
			if ((Object)(object)level != (Object)null && (Object)(object)RunManager.instance != (Object)null)
			{
				return (Object)(object)level == (Object)(object)RunManager.instance.levelLobby;
			}
			return false;
		}

		internal static bool IsShop(Level level)
		{
			if ((Object)(object)level != (Object)null && (Object)(object)RunManager.instance != (Object)null && RunManager.instance.levelShop != null)
			{
				return RunManager.instance.levelShop.Contains(level);
			}
			return false;
		}

		internal static bool IsJoinableLevel(Level level)
		{
			if (!IsTruck(level) || !Plugin.LateJoinInTruck.Value)
			{
				if (IsShop(level))
				{
					return Plugin.LateJoinInShop.Value;
				}
				return false;
			}
			return true;
		}

		internal static string Where(Level level)
		{
			if ((Object)(object)level == (Object)null || (Object)(object)RunManager.instance == (Object)null)
			{
				return "loading";
			}
			if ((Object)(object)level == (Object)(object)RunManager.instance.levelLobbyMenu)
			{
				return "lobby menu";
			}
			if (IsTruck(level))
			{
				return "truck";
			}
			if (IsShop(level))
			{
				return "shop";
			}
			if (SemiFunc.IsLevelArena(level))
			{
				return "arena";
			}
			return "level";
		}

		internal static void HostTick()
		{
			//IL_0082: Unknown result type (might be due to invalid IL or missing references)
			//IL_0088: Invalid comparison between Unknown and I4
			if (!HostActive)
			{
				openedByUs = false;
				return;
			}
			RunManager instance = RunManager.instance;
			LevelGenerator instance2 = LevelGenerator.Instance;
			GameDirector instance3 = GameDirector.instance;
			Room currentRoom = PhotonNetwork.CurrentRoom;
			TrackLevel(instance2);
			if ((Object)(object)instance != (Object)null && (Object)(object)instance3 != (Object)null && GameAccess.IsRestarting(instance))
			{
				SkipOutroWaitForLoadingJoiners(instance3);
			}
			else if (!((Object)(object)instance == (Object)null) && !((Object)(object)instance2 == (Object)null) && !((Object)(object)instance3 == (Object)null) && currentRoom != null && IsJoinableLevel(instance.levelCurrent) && instance2.Generated && (int)instance3.currentState == 2 && !blockedThisLevel && !currentRoom.IsOpen)
			{
				OpenJoining(instance.levelCurrent);
			}
		}

		private static void TrackLevel(LevelGenerator generator)
		{
			if ((Object)(object)generator != (Object)(object)lateJoinersLevel)
			{
				lateJoinersLevel = generator;
				lateJoiners.Clear();
				outroSkipped.Clear();
				shopReloadQueued = false;
			}
		}

		private static void SkipOutroWaitForLoadingJoiners(GameDirector director)
		{
			if (lateJoiners.Count == 0)
			{
				return;
			}
			foreach (PlayerAvatar player in director.PlayerList)
			{
				Player val = (((Object)(object)player != (Object)null && (Object)(object)player.photonView != (Object)null) ? player.photonView.Owner : null);
				if (val != null && lateJoiners.Contains(val.ActorNumber) && !GameAccess.AvatarLevelAnimationDone(player) && GameAccess.MarkOutroDone(player) && outroSkipped.Add(val.ActorNumber))
				{
					Plugin.Log.LogInfo((object)(val.NickName + " is still loading, so the level change doesn't wait for them."));
				}
			}
		}

		private static void OpenJoining(Level level)
		{
			PhotonNetwork.SetRoomOpen(true);
			if (PlayerLimit.IsPublicSession)
			{
				PhotonNetwork.CurrentRoom.IsVisible = true;
			}
			else if ((Object)(object)SteamLobbyManager.instance != (Object)null)
			{
				SteamLobbyManager.instance.UnlockLobby(false);
			}
			openedByUs = true;
			Plugin.Log.LogInfo((object)("Joining is open: friends can join while you're in the " + Where(level) + "."));
		}

		private static void CloseJoining(string why)
		{
			Room currentRoom = PhotonNetwork.CurrentRoom;
			if (currentRoom != null && (currentRoom.IsOpen || openedByUs))
			{
				PhotonNetwork.SetRoomOpen(false);
				currentRoom.IsVisible = false;
				if ((Object)(object)SteamLobbyManager.instance != (Object)null)
				{
					SteamLobbyManager.instance.LockLobby();
				}
				openedByUs = false;
				Plugin.Log.LogInfo((object)("Joining is closed (" + why + ")."));
			}
		}

		internal static void BeforeLevelChange(RunManager run)
		{
			if (HostActive && !GameAccess.IsRestarting(run))
			{
				CloseJoining("level change");
				ClearOldBufferedMessages(run);
				blockedThisLevel = false;
				BlockReason = null;
				cleanupPending = false;
				PhotonView val = GameAccess.RunManagerView(run);
				if ((Object)(object)val != (Object)null && GameAccess.CanSetPersistent)
				{
					GameAccess.SetPersistent(val, persistent: true);
					taggedRunView = val;
				}
			}
		}

		internal static void AfterLevelChange(RunManager run)
		{
			if ((Object)(object)taggedRunView != (Object)null)
			{
				GameAccess.SetPersistent(taggedRunView, persistent: false);
				if ((Object)(object)run != (Object)null && ((Object)(object)run.levelCurrent == (Object)(object)run.levelLobbyMenu || (Object)(object)run.levelCurrent == (Object)(object)run.levelMainMenu) && PhotonNetwork.InRoom && PhotonNetwork.IsMasterClient)
				{
					PhotonNetwork.RemoveBufferedRPCs(taggedRunView.ViewID, "UpdateLevelRPC", (int[])null);
					PhotonNetwork.RemoveBufferedRPCs(taggedRunView.ViewID, "AllPlayersDeadRPC", (int[])null);
				}
				taggedRunView = null;
			}
			if (HostActive && GameAccess.IsRestarting(run) && IsJoinableLevel(run.levelCurrent))
			{
				cleanupPending = true;
			}
		}

		private static void ClearOldBufferedMessages(RunManager run)
		{
			//IL_003a: Unknown result type (might be due to invalid IL or missing references)
			//IL_003f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0042: Unknown result type (might be due to invalid IL or missing references)
			//IL_0047: Unknown result type (might be due to invalid IL or missing references)
			//IL_0081: Unknown result type (might be due to invalid IL or missing references)
			//IL_0086: Unknown result type (might be due to invalid IL or missing references)
			PhotonView val = GameAccess.RunManagerView(run);
			if ((Object)(object)val != (Object)null)
			{
				PhotonNetwork.RemoveBufferedRPCs(val.ViewID, "UpdateLevelRPC", (int[])null);
				PhotonNetwork.RemoveBufferedRPCs(val.ViewID, "AllPlayersDeadRPC", (int[])null);
			}
			List<int> list = new List<int>();
			ValueIterator<int, PhotonView> enumerator = PhotonNetwork.PhotonViewCollection.GetEnumerator();
			try
			{
				while (enumerator.MoveNext())
				{
					PhotonView current = enumerator.Current;
					if ((Object)(object)current != (Object)null && current.ViewID > 0 && (Object)(object)current != (Object)(object)val && !current.isRuntimeInstantiated)
					{
						Scene scene = ((Component)current).gameObject.scene;
						if (((Scene)(ref scene)).buildIndex != -1)
						{
							list.Add(current.ViewID);
						}
					}
				}
			}
			finally
			{
				((IDisposable)enumerator/*cast due to .constrained prefix*/).Dispose();
			}
			foreach (int item in list)
			{
				PhotonNetwork.RemoveBufferedRPCs(item, (string)null, (int[])null);
			}
		}

		internal static void BeforeLoad(string sceneName)
		{
			if (!cleanupPending)
			{
				return;
			}
			cleanupPending = false;
			if (HostActive && !(sceneName != "Reload"))
			{
				if (GameAccess.RoomCloseConfirmed != true)
				{
					blockedThisLevel = true;
					BlockReason = "the server didn't confirm the room was closed in time, so old level data couldn't be cleared";
					Plugin.Log.LogWarning((object)("Late join paused for this level: " + BlockReason + ". It will try again next level."));
				}
				else if ((Object)(object)NetworkManager.instance == (Object)null)
				{
					blockedThisLevel = true;
					BlockReason = "the game's network manager wasn't found";
					Plugin.Log.LogWarning((object)("Late join paused for this level: " + BlockReason + "."));
				}
				else
				{
					NetworkManager.instance.DestroyRunObjects();
					Plugin.Log.LogInfo((object)"Cleared old level objects so late joiners only load the truck or shop.");
				}
			}
		}

		internal static void OnPlayerAvatarStart(PlayerAvatar avatar)
		{
			if (!HostActive || (Object)(object)avatar == (Object)null || (Object)(object)avatar.photonView == (Object)null || avatar.photonView.IsMine)
			{
				return;
			}
			LevelGenerator instance = LevelGenerator.Instance;
			RunManager instance2 = RunManager.instance;
			if ((Object)(object)instance == (Object)null || !instance.Generated || (Object)(object)instance2 == (Object)null)
			{
				return;
			}
			TrackLevel(instance);
			if (avatar.photonView.Owner != null)
			{
				lateJoiners.Add(avatar.photonView.Owner.ActorNumber);
			}
			if ((Object)(object)LobbyPlusController.Instance == (Object)null || GameAccess.IsRestarting(instance2))
			{
				return;
			}
			if (IsShop(instance2.levelCurrent) && Plugin.LateJoinInShop.Value)
			{
				if (!shopReloadQueued)
				{
					shopReloadQueued = true;
					((MonoBehaviour)LobbyPlusController.Instance).StartCoroutine(ReloadShopForJoiner(avatar));
				}
			}
			else if (IsTruck(instance2.levelCurrent) && Plugin.LateJoinInTruck.Value)
			{
				((MonoBehaviour)LobbyPlusController.Instance).StartCoroutine(PlaceLateJoiner(avatar));
			}
		}

		private static IEnumerator ReloadShopForJoiner(PlayerAvatar avatar)
		{
			string name = (((Object)(object)avatar != (Object)null && (Object)(object)avatar.photonView != (Object)null && avatar.photonView.Owner != null) ? avatar.photonView.Owner.NickName : "a player");
			yield return (object)new WaitForSecondsRealtime(1f);
			RunManager instance = RunManager.instance;
			if (!HostActive || (Object)(object)instance == (Object)null || GameAccess.IsRestarting(instance) || !IsShop(instance.levelCurrent) || (Object)(object)LevelGenerator.Instance == (Object)null || !LevelGenerator.Instance.Generated)
			{
				shopReloadQueued = false;
				yield break;
			}
			if (!GameAccess.CanMarkOutroDone)
			{
				Plugin.Log.LogWarning((object)(name + " joined in the shop, but the shop can't be reloaded for them (game update?). They'll be stuck loading until they press Escape."));
				yield break;
			}
			Plugin.Log.LogInfo((object)(name + " joined in the shop. Reloading the shop for everyone so they can load in with you (it restocks)."));
			Level levelCurrent = instance.levelCurrent;
			bool flag = GameAccess.SetDebugLevel(instance, levelCurrent);
			try
			{
				instance.ChangeLevel(false, false, (ChangeLevelType)5);
			}
			finally
			{
				if (flag)
				{
					GameAccess.SetDebugLevel(instance, null);
				}
			}
		}

		private static IEnumerator PlaceLateJoiner(PlayerAvatar avatar)
		{
			string name = ((avatar.photonView.Owner != null) ? avatar.photonView.Owner.NickName : "a player");
			yield return (object)new WaitForSecondsRealtime(1.5f);
			if ((Object)(object)avatar == (Object)null || !HostActive || (Object)(object)LevelGenerator.Instance == (Object)null || !LevelGenerator.Instance.Generated)
			{
				yield break;
			}
			if (GameAccess.IsSpawned(avatar))
			{
				Plugin.Log.LogInfo((object)(name + " joined mid-run in the " + Where(RunManager.instance.levelCurrent) + " (the game placed them itself)."));
				yield break;
			}
			SpawnPoint[] source = Object.FindObjectsByType<SpawnPoint>((FindObjectsSortMode)0);
			List<SpawnPoint> list = source.Where((SpawnPoint p) => (Object)(object)p != (Object)null && !p.debug).ToList();
			if (list.Count == 0)
			{
				list = source.Where((SpawnPoint p) => (Object)(object)p != (Object)null).ToList();
			}
			if (list.Count == 0)
			{
				Plugin.Log.LogWarning((object)("Couldn't place " + name + ": this level has no spawn points."));
				yield break;
			}
			SpawnPoint val = list[Random.Range(0, list.Count)];
			avatar.Spawn(((Component)val).transform.position, ((Component)val).transform.rotation, false);
			GiveHeadAndTumble(avatar, name);
			Plugin.Log.LogInfo((object)(name + " joined mid-run and was placed in the " + Where(RunManager.instance.levelCurrent) + "."));
		}

		private static void GiveHeadAndTumble(PlayerAvatar avatar, string name)
		{
			//IL_0058: Unknown result type (might be due to invalid IL or missing references)
			//IL_005d: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a9: Unknown result type (might be due to invalid IL or missing references)
			LevelGenerator instance = LevelGenerator.Instance;
			if ((Object)(object)instance == (Object)null || !GameAccess.CanCheckHeadAndTumble)
			{
				Plugin.Log.LogWarning((object)("Couldn't give " + name + " a death head and tumble; dying or being knocked over may not work for them this level."));
				return;
			}
			if ((Object)(object)GameAccess.DeathHead(avatar) == (Object)null && (Object)(object)instance.PlayerDeathHeadPrefab != (Object)null)
			{
				PlayerDeathHead component = PhotonNetwork.Instantiate(((Object)instance.PlayerDeathHeadPrefab).name, GameAccess.ParkingSpot(), Quaternion.identity, (byte)0, (object[])null).GetComponent<PlayerDeathHead>();
				component.playerAvatar = avatar;
				GameAccess.SetDeathHead(avatar, component);
			}
			if ((Object)(object)GameAccess.Tumble(avatar) == (Object)null && (Object)(object)instance.PlayerTumblePrefab != (Object)null)
			{
				PlayerTumble component2 = PhotonNetwork.Instantiate(((Object)instance.PlayerTumblePrefab).name, GameAccess.ParkingSpot(), Quaternion.identity, (byte)0, (object[])null).GetComponent<PlayerTumble>();
				component2.playerAvatar = avatar;
				GameAccess.SetTumble(avatar, component2);
			}
		}

		internal static void ClientTick()
		{
			//IL_00a5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ab: Invalid comparison between Unknown and I4
			if (!Plugin.LateJoinEnabled.Value || (Object)(object)GameManager.instance == (Object)null || !GameManager.Multiplayer() || !PhotonNetwork.InRoom || PhotonNetwork.IsMasterClient)
			{
				clientStuckTimer = 0f;
				return;
			}
			RunManager instance = RunManager.instance;
			GameDirector instance2 = GameDirector.instance;
			LoadingUI instance3 = LoadingUI.instance;
			PlayerAvatar val = (((Object)(object)PlayerController.instance != (Object)null) ? PlayerController.instance.playerAvatarScript : null);
			if (!((Object)(object)instance != (Object)null) || !((Object)(object)instance2 != (Object)null) || !((Object)(object)instance3 != (Object)null) || !((Object)(object)val != (Object)null) || (!IsShop(instance.levelCurrent) && !IsTruck(instance.levelCurrent)) || (int)instance2.currentState != 1 || !GameAccess.AvatarLevelAnimationDone(val) || GameAccess.LoadingScreenDone(instance3))
			{
				clientStuckTimer = 0f;
				return;
			}
			clientStuckTimer += Time.unscaledDeltaTime;
			if (clientStuckTimer < 3f)
			{
				return;
			}
			clientStuckTimer = 0f;
			int num = 0;
			foreach (PlayerAvatar player in instance2.PlayerList)
			{
				if ((Object)(object)player != (Object)null && (Object)(object)player != (Object)(object)val && GameAccess.MarkAvatarLevelAnimationDone(player))
				{
					num++;
				}
			}
			if (num > 0)
			{
				Plugin.Log.LogInfo((object)$"Joined mid-run: marked {num} player(s) as already in the {Where(instance.levelCurrent)} so the loading screen can finish.");
			}
		}
	}
	[HarmonyPatch]
	internal static class LateJoinPatches
	{
		[HarmonyPrefix]
		[HarmonyPatch(typeof(RunManager), "ChangeLevel")]
		private static void ChangeLevelPrefix(RunManager __instance)
		{
			LateJoin.BeforeLevelChange(__instance);
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(RunManager), "ChangeLevel")]
		private static void ChangeLevelPostfix(RunManager __instance)
		{
			LateJoin.AfterLevelChange(__instance);
		}

		[HarmonyPrefix]
		[HarmonyPatch(typeof(PhotonNetwork), "LoadLevel", new Type[] { typeof(string) })]
		private static void LoadLevelPrefix(string levelName)
		{
			LateJoin.BeforeLoad(levelName);
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(PlayerAvatar), "Start")]
		private static void PlayerAvatarStartPostfix(PlayerAvatar __instance)
		{
			LateJoin.OnPlayerAvatarStart(__instance);
		}
	}
	internal static class LobbyInfoOverlay
	{
		private const string Green = "#7CFC7C";

		private const string Yellow = "#FFD54A";

		private const string Red = "#FF6B6B";

		private const string Grey = "#B8B8B8";

		private const float HudHeightFraction = 0.17f;

		private static GUIStyle boxStyle;

		private static GUIStyle textStyle;

		private static int styledFontSize;

		private static readonly List<string> lines = new List<string>();

		internal static void Draw()
		{
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			//IL_000b: Invalid comparison between Unknown and I4
			if ((int)Event.current.type != 7 || !Plugin.ShowLobbyInfo.Value || (Object)(object)GameManager.instance == (Object)null || !GameManager.Multiplayer() || !PhotonNetwork.InRoom || (Object)(object)RunManager.instance == (Object)null)
			{
				return;
			}
			Room currentRoom = PhotonNetwork.CurrentRoom;
			if (currentRoom != null)
			{
				Level levelCurrent = RunManager.instance.levelCurrent;
				if (SemiFunc.RunIsLobbyMenu() || LateJoin.IsTruck(levelCurrent) || LateJoin.IsShop(levelCurrent) || Plugin.ShowDuringLevels.Value)
				{
					BuildLines(currentRoom, levelCurrent);
					Render();
				}
			}
		}

		private static void BuildLines(Room room, Level level)
		{
			lines.Clear();
			bool isMasterClient = PhotonNetwork.IsMasterClient;
			int steamLimit = PlayerLimit.SteamLimit;
			lines.Add("<b>LobbyPlus</b>");
			lines.Add($"Players: <b>{room.PlayerCount} / {room.MaxPlayers}</b>");
			if (steamLimit > 0)
			{
				if (steamLimit < room.MaxPlayers)
				{
					lines.Add(Color("#FF6B6B", $"Steam lobby limit: <b>{steamLimit}</b>. Player {steamLimit + 1} can't join!"));
					lines.Add(Color("#FF6B6B", isMasterClient ? "Go back to the main menu and host again." : "Ask the host to host again."));
				}
				else
				{
					lines.Add(Color("#7CFC7C", $"Steam lobby limit: {steamLimit}"));
				}
			}
			if (isMasterClient)
			{
				int num = PlayerLimit.Desired(PlayerLimit.IsPublicSession);
				if (room.MaxPlayers < num)
				{
					lines.Add(Color("#FFD54A", $"Your setting is {num}; host again to use it."));
				}
			}
			lines.Add(JoinLine(room, level));
			if (Plugin.MorePlayersSimpleLoaded)
			{
				lines.Add(Color("#FF6B6B", "MorePlayersSimple is also installed. Turn it off:"));
				lines.Add(Color("#FF6B6B", "LobbyPlus replaces it."));
			}
		}

		private static string JoinLine(Room room, Level level)
		{
			string text = LateJoin.Where(level);
			if (room.IsOpen)
			{
				return Color("#7CFC7C", "Joining: <b>OPEN</b> (" + text + ")");
			}
			if (SemiFunc.RunIsLobbyMenu())
			{
				return Color("#FFD54A", "Joining: opening...");
			}
			if (LateJoin.IsTruck(level) || LateJoin.IsShop(level))
			{
				if (!Plugin.LateJoinEnabled.Value || !LateJoin.IsJoinableLevel(level))
				{
					return Color("#B8B8B8", "Joining: closed (late join is off for the " + text + ")");
				}
				if (LateJoin.BlockReason != null)
				{
					return Color("#FFD54A", "Joining: paused this level (see log)");
				}
				return Color("#FFD54A", "Joining: opening once everyone has loaded...");
			}
			return Color("#B8B8B8", "Joining: closed (" + text + ")");
		}

		private static string Color(string hex, string text)
		{
			return "<color=" + hex + ">" + text + "</color>";
		}

		private static void Render()
		{
			//IL_005c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0066: Expected O, but got Unknown
			//IL_0061: Unknown result type (might be due to invalid IL or missing references)
			//IL_0066: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a3: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f1: Unknown result type (might be due to invalid IL or missing references)
			int num = Mathf.Clamp(Screen.height / 48, 12, 30);
			if (boxStyle == null || styledFontSize != num)
			{
				CreateStyles(num);
			}
			float num2 = 0f;
			float num3 = 0f;
			Vector2[] array = (Vector2[])(object)new Vector2[lines.Count];
			for (int i = 0; i < lines.Count; i++)
			{
				array[i] = textStyle.CalcSize(new GUIContent(lines[i]));
				num2 = Mathf.Max(num2, array[i].x);
				num3 += array[i].y;
			}
			float num4 = (float)num * 0.6f;
			float num5 = num;
			float y = (SemiFunc.RunIsLobbyMenu() ? num5 : Mathf.Max(num5, (float)Screen.height * 0.17f));
			Rect val = default(Rect);
			((Rect)(ref val))..ctor(0f, 0f, num2 + num4 * 2f, num3 + num4 * 2f);
			switch (Plugin.LobbyInfoCorner.Value)
			{
			case InfoCorner.TopRight:
				((Rect)(ref val)).x = (float)Screen.width - ((Rect)(ref val)).width - num5;
				((Rect)(ref val)).y = num5;
				break;
			case InfoCorner.BottomLeft:
				((Rect)(ref val)).x = num5;
				((Rect)(ref val)).y = (float)Screen.height - ((Rect)(ref val)).height - num5;
				break;
			case InfoCorner.BottomRight:
				((Rect)(ref val)).x = (float)Screen.width - ((Rect)(ref val)).width - num5;
				((Rect)(ref val)).y = (float)Screen.height - ((Rect)(ref val)).height - num5;
				break;
			default:
				((Rect)(ref val)).x = num5;
				((Rect)(ref val)).y = y;
				break;
			}
			GUI.Box(val, GUIContent.none, boxStyle);
			float num6 = ((Rect)(ref val)).y + num4;
			for (int j = 0; j < lines.Count; j++)
			{
				GUI.Label(new Rect(((Rect)(ref val)).x + num4, num6, array[j].x + 2f, array[j].y), lines[j], textStyle);
				num6 += array[j].y;
			}
		}

		private static void CreateStyles(int fontSize)
		{
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0016: Expected O, but got Unknown
			//IL_002d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0047: Unknown result type (might be due to invalid IL or missing references)
			//IL_0051: Expected O, but got Unknown
			//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_0077: Unknown result type (might be due to invalid IL or missing references)
			//IL_007e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0085: Unknown result type (might be due to invalid IL or missing references)
			//IL_0091: Expected O, but got Unknown
			//IL_009b: Unknown result type (might be due to invalid IL or missing references)
			styledFontSize = fontSize;
			Texture2D val = new Texture2D(1, 1)
			{
				hideFlags = (HideFlags)61
			};
			val.SetPixel(0, 0, new Color(0f, 0f, 0f, 0.62f));
			val.Apply();
			boxStyle = new GUIStyle(GUI.skin.box);
			boxStyle.normal.background = val;
			textStyle = new GUIStyle(GUI.skin.label)
			{
				fontSize = fontSize,
				richText = true,
				wordWrap = false,
				alignment = (TextAnchor)0
			};
			textStyle.normal.textColor = Color.white;
		}
	}
	internal static class PlayerLimit
	{
		private static float nextCheck;

		private static ulong checkedLobbyId;

		private static bool fixAttempted;

		internal static int SteamLimit { get; private set; } = -1;

		internal static bool IsPublicSession => GameAccess.IsPublicSession(GameManager.instance);

		internal static int Desired(bool publicLobby)
		{
			int num = (((Object)(object)GameManager.instance != (Object)null) ? GameManager.instance.maxPlayersPhoton : 20);
			return Mathf.Clamp(publicLobby ? Plugin.PublicMaxPlayers.Value : Plugin.PrivateMaxPlayers.Value, 1, Mathf.Max(1, num));
		}

		internal static void Apply(bool publicLobby, string when)
		{
			GameManager instance = GameManager.instance;
			if (!((Object)(object)instance == (Object)null))
			{
				int num = Desired(publicLobby);
				if (instance.maxPlayers != num)
				{
					instance.SetMaxPlayers(num);
					Plugin.Log.LogInfo((object)string.Format("Player limit set to {0} for a {1} lobby ({2}).", num, publicLobby ? "public" : "private", when));
				}
			}
		}

		internal static void Tick()
		{
			//IL_0022: Unknown result type (might be due to invalid IL or missing references)
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			//IL_002a: Unknown result type (might be due to invalid IL or missing references)
			//IL_002f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0055: 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_0089: Unknown result type (might be due to invalid IL or missing references)
			if (Time.unscaledTime < nextCheck)
			{
				return;
			}
			nextCheck = Time.unscaledTime + 1f;
			Lobby val = GameAccess.CurrentLobby(SteamLobbyManager.instance);
			SteamId id = ((Lobby)(ref val)).Id;
			if (!((SteamId)(ref id)).IsValid)
			{
				SteamLimit = -1;
				return;
			}
			SteamLimit = ((Lobby)(ref val)).MaxMembers;
			if (!SteamClient.IsValid || !((Lobby)(ref val)).IsOwnedBy(SteamClient.SteamId) || !PhotonNetwork.IsMasterClient)
			{
				return;
			}
			int num = Desired(IsPublicSession);
			if (((Lobby)(ref val)).Id.Value != checkedLobbyId)
			{
				checkedLobbyId = ((Lobby)(ref val)).Id.Value;
				fixAttempted = false;
				if (SteamLimit >= num)
				{
					Plugin.Log.LogInfo((object)$"Steam lobby limit is {SteamLimit}, as it should be.");
				}
			}
			if (SteamLimit < num && !fixAttempted)
			{
				fixAttempted = true;
				Plugin.Log.LogWarning((object)$"Steam lobby limit is {SteamLimit} but should be {num}. Trying to raise it; if it stays low, leave and host again.");
				((Lobby)(ref val)).MaxMembers = num;
			}
		}
	}
	[HarmonyPatch]
	internal static class PlayerLimitPatches
	{
		[HarmonyPostfix]
		[HarmonyPatch(typeof(GameManager), "Awake")]
		private static void GameManagerAwake(GameManager __instance)
		{
			if ((Object)(object)GameManager.instance == (Object)(object)__instance)
			{
				__instance.maxPlayers = PlayerLimit.Desired(publicLobby: false);
			}
		}

		[HarmonyPrefix]
		[HarmonyPatch(typeof(SteamLobbyManager), "HostLobby")]
		private static void HostLobby(bool _open)
		{
			PlayerLimit.Apply(_open, "before creating the Steam lobby");
		}

		[HarmonyPrefix]
		[HarmonyPatch(typeof(NetworkConnect), "OnConnectedToMaster")]
		private static void OnConnectedToMaster()
		{
			PlayerLimit.Apply(PlayerLimit.IsPublicSession, "before creating the game room");
		}
	}
	public enum InfoCorner
	{
		TopLeft,
		TopRight,
		BottomLeft,
		BottomRight
	}
	[BepInPlugin("LobbyPlus", "LobbyPlus", "1.0.0")]
	public sealed class Plugin : BaseUnityPlugin
	{
		public const string Guid = "LobbyPlus";

		public const string Name = "LobbyPlus";

		public const string Version = "1.0.0";

		internal const string MorePlayersSimpleGuid = "dyxc666.MorePlayersSimple";

		internal static ManualLogSource Log;

		internal static ConfigEntry<int> PrivateMaxPlayers;

		internal static ConfigEntry<int> PublicMaxPlayers;

		internal static ConfigEntry<bool> LateJoinEnabled;

		internal static ConfigEntry<bool> LateJoinInTruck;

		internal static ConfigEntry<bool> LateJoinInShop;

		internal static ConfigEntry<bool> ShowLobbyInfo;

		internal static ConfigEntry<bool> ShowDuringLevels;

		internal static ConfigEntry<InfoCorner> LobbyInfoCorner;

		internal static ConfigEntry<int> KeepSessionLogs;

		internal static ConfigEntry<KeyCode> LogMarkerKey;

		private static bool? morePlayersSimpleLoaded;

		internal static bool MorePlayersSimpleLoaded
		{
			get
			{
				if (!morePlayersSimpleLoaded.HasValue && Chainloader.PluginInfos != null)
				{
					morePlayersSimpleLoaded = Chainloader.PluginInfos.ContainsKey("dyxc666.MorePlayersSimple");
					if (morePlayersSimpleLoaded == true)
					{
						Log.LogWarning((object)"MorePlayersSimple is also installed. LobbyPlus replaces it; turn MorePlayersSimple off so only one mod controls the player limit.");
					}
				}
				return morePlayersSimpleLoaded == true;
			}
		}

		private void Awake()
		{
			//IL_001b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0020: Unknown result type (might be due to invalid IL or missing references)
			//IL_0030: Expected O, but got Unknown
			//IL_003f: Expected O, but got Unknown
			//IL_0044: Unknown result type (might be due to invalid IL or missing references)
			//IL_0049: Unknown result type (might be due to invalid IL or missing references)
			//IL_004f: Expected O, but got Unknown
			//IL_004f: Unknown result type (might be due to invalid IL or missing references)
			Log = ((BaseUnityPlugin)this).Logger;
			BindConfig();
			SessionLog.Start();
			Harmony val = new Harmony("LobbyPlus");
			PatchClass(val, typeof(PlayerLimitPatches));
			PatchClass(val, typeof(LateJoinPatches));
			GameObject val2 = new GameObject("LobbyPlus");
			Object.DontDestroyOnLoad((Object)val2);
			((Object)val2).hideFlags = (HideFlags)61;
			val2.AddComponent<LobbyPlusController>();
			Log.LogInfo((object)(string.Format("{0} {1} loaded. Private lobby limit {2}, public lobby limit {3}, ", "LobbyPlus", "1.0.0", PrivateMaxPlayers.Value, PublicMaxPlayers.Value) + "late join " + (LateJoinEnabled.Value ? $"on (truck: {LateJoinInTruck.Value}, shop: {LateJoinInShop.Value})" : "off") + "."));
		}

		private static void PatchClass(Harmony harmony, Type patchClass)
		{
			try
			{
				harmony.CreateClassProcessor(patchClass).Patch();
			}
			catch (Exception arg)
			{
				Log.LogError((object)$"Couldn't apply {patchClass.Name} (a game update may have changed the code it patches): {arg}");
			}
		}

		private void BindConfig()
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Expected O, but got Unknown
			//IL_0057: Unknown result type (might be due to invalid IL or missing references)
			//IL_0061: Expected O, but got Unknown
			//IL_014a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0154: Expected O, but got Unknown
			PrivateMaxPlayers = ((BaseUnityPlugin)this).Config.Bind<int>("Player Limit", "Private Lobby Max Players", 20, new ConfigDescription("Most players allowed in a private (invite) lobby. Applied when a lobby is created, so host again after changing it.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(1, 20), Array.Empty<object>()));
			PublicMaxPlayers = ((BaseUnityPlugin)this).Config.Bind<int>("Player Limit", "Public Lobby Max Players", 20, new ConfigDescription("Most players allowed in a public (server list) lobby. Applied when a lobby is created, so host again after changing it.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(1, 20), Array.Empty<object>()));
			LateJoinEnabled = ((BaseUnityPlugin)this).Config.Bind<bool>("Late Join", "Enabled", true, "Let friends join a run that's already started, while the crew is in the truck or the shop. Only the host's setting matters for opening the lobby.");
			LateJoinInTruck = ((BaseUnityPlugin)this).Config.Bind<bool>("Late Join", "Allow In Truck", true, "Allow joining while the crew is in the truck between levels.");
			LateJoinInShop = ((BaseUnityPlugin)this).Config.Bind<bool>("Late Join", "Allow In Shop", true, "Allow joining while the crew is in the shop. When someone joins there, the shop reloads for everyone so they can load in: it restocks, and items not yet bought (on the checkout too) are gone. Turn it off to only allow joining in the truck.");
			ShowLobbyInfo = ((BaseUnityPlugin)this).Config.Bind<bool>("Lobby Info", "Show Lobby Info", true, "Show a small box with the player count, the real Steam lobby limit and whether friends can join right now.");
			ShowDuringLevels = ((BaseUnityPlugin)this).Config.Bind<bool>("Lobby Info", "Show During Levels", false, "Also show the box while you're out in a level. Off by default so it only shows in the lobby menu, truck and shop.");
			LobbyInfoCorner = ((BaseUnityPlugin)this).Config.Bind<InfoCorner>("Lobby Info", "Corner", InfoCorner.TopLeft, "Which corner of the screen the box goes in.");
			KeepSessionLogs = ((BaseUnityPlugin)this).Config.Bind<int>("Session Logs", "Keep Logs", 10, new ConfigDescription("Keep a log of each game session (everything the game and mods log, with times) in BepInEx\\LobbyPlus\\logs, and keep this many. BepInEx's own LogOutput.log is replaced every time the game starts. 0 turns it off. Applies the next time the game starts.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 50), Array.Empty<object>()));
			LogMarkerKey = ((BaseUnityPlugin)this).Config.Bind<KeyCode>("Session Logs", "Marker Key", (KeyCode)291, "Press this when something goes wrong: it marks the moment in your session log and in the logs of everyone else in the game who has LobbyPlus.");
		}
	}
	internal sealed class LobbyPlusController : MonoBehaviour
	{
		internal static LobbyPlusController Instance;

		private void Awake()
		{
			Instance = this;
			PhotonNetwork.NetworkingClient.EventReceived += OnEvent;
		}

		private void OnDestroy()
		{
			PhotonNetwork.NetworkingClient.EventReceived -= OnEvent;
		}

		private static void OnEvent(EventData photonEvent)
		{
			try
			{
				SessionLog.OnEvent(photonEvent);
			}
			catch (Exception arg)
			{
				Plugin.Log.LogError((object)$"Network message error: {arg}");
			}
		}

		private void Update()
		{
			try
			{
				PlayerLimit.Tick();
				LateJoin.HostTick();
				LateJoin.ClientTick();
			}
			catch (Exception arg)
			{
				Plugin.Log.LogError((object)$"Update error: {arg}");
			}
			try
			{
				SessionLog.Tick();
			}
			catch (Exception arg2)
			{
				Plugin.Log.LogError((object)$"Session log error: {arg2}");
			}
		}

		private void OnGUI()
		{
			try
			{
				LobbyInfoOverlay.Draw();
			}
			catch (Exception arg)
			{
				Plugin.Log.LogError((object)$"Lobby info error: {arg}");
				Plugin.ShowLobbyInfo.Value = false;
			}
			try
			{
				SessionLog.DrawToast();
			}
			catch (Exception arg2)
			{
				Plugin.Log.LogError((object)$"Marker note error: {arg2}");
			}
		}
	}
	internal sealed class SessionLog : ILogListener, IDisposable
	{
		private const long MaxBytes = 41943040L;

		private const byte MarkerEvent = 192;

		private const string Tag = "LobbyPlus";

		private static SessionLog instance;

		private readonly object gate = new object();

		private readonly StreamWriter writer;

		private long bytes;

		private bool full;

		private string lastKey;

		private int repeats;

		private bool needsFlush;

		private static bool modsListed;

		private static bool wasInRoom;

		private static int lastMasterActor = -1;

		private static GUIStyle toastStyle;

		private static LevelGenerator lastReadyLevel;

		private static float nextFlush;

		private static int markerCount;

		internal static string Folder => Path.Combine(Paths.BepInExRootPath, "LobbyPlus", "logs");

		internal static string FileName { get; private set; }

		internal static string Toast { get; private set; }

		internal static float ToastUntil { get; private set; }

		private SessionLog(string path)
		{
			writer = new StreamWriter(new FileStream(path, FileMode.CreateNew, FileAccess.Write, FileShare.ReadWrite), new UTF8Encoding(encoderShouldEmitUTF8Identifier: false));
		}

		internal static void Start()
		{
			int value = Plugin.KeepSessionLogs.Value;
			if (value <= 0)
			{
				return;
			}
			try
			{
				Directory.CreateDirectory(Folder);
				DeleteOld(value - 1);
				string text = DateTime.Now.ToString("yyyy-MM-dd_HH-mm-ss");
				string path = Path.Combine(Folder, "session_" + text + ".log");
				if (File.Exists(path))
				{
					path = Path.Combine(Folder, $"session_{text}_{Process.GetCurrentProcess().Id}.log");
				}
				instance = new SessionLog(path);
				FileName = Path.GetFileName(path);
				instance.WriteHeader();
				instance.CopyStartupLog();
				Logger.Listeners.Add((ILogListener)(object)instance);
				Application.quitting += Stop;
				Plugin.Log.LogInfo((object)$"Session log: BepInEx\\LobbyPlus\\logs\\{FileName} (keeps the last {value}).");
			}
			catch (Exception ex)
			{
				instance = null;
				Plugin.Log.LogWarning((object)("Couldn't start the session log: " + ex.Message));
			}
		}

		private static void Stop()
		{
			SessionLog sessionLog = instance;
			if (sessionLog != null)
			{
				sessionLog.WriteRaw(Now() + " Game closed.");
				Logger.Listeners.Remove((ILogListener)(object)sessionLog);
				sessionLog.Dispose();
				instance = null;
			}
		}

		private static void DeleteOld(int keep)
		{
			foreach (FileInfo item in (from f in new DirectoryInfo(Folder).GetFiles("session_*.log")
				orderby f.LastWriteTimeUtc descending
				select f).ToList().Skip(Math.Max(0, keep)))
			{
				try
				{
					item.Delete();
				}
				catch (IOException)
				{
				}
				catch (UnauthorizedAccessException)
				{
				}
			}
		}

		private void WriteHeader()
		{
			//IL_00a7: Unknown result type (might be due to invalid IL or missing references)
			DateTime now = DateTime.Now;
			TimeSpan utcOffset = TimeZoneInfo.Local.GetUtcOffset(now);
			WriteRaw("R.E.P.O. session log, kept by LobbyPlus 1.0.0");
			WriteRaw(string.Format("Started {0:yyyy-MM-dd HH:mm:ss} (local time, UTC{1}{2:hh\\:mm}). Times below are HH:mm:ss.", now, (utcOffset < TimeSpan.Zero) ? "-" : "+", utcOffset));
			WriteRaw($"Game {Application.version}, Unity {Application.unityVersion}, BepInEx {typeof(Paths).Assembly.GetName().Version}, profile \"{ProfileName()}\"");
			WriteRaw($"Marker key: {Plugin.LogMarkerKey.Value} (press it when something goes wrong; it marks the moment in everyone's log)");
			WriteRaw("");
		}

		private static string ProfileName()
		{
			try
			{
				return new DirectoryInfo(Paths.BepInExRootPath).Parent?.Name ?? "?";
			}
			catch
			{
				return "?";
			}
		}

		private void CopyStartupLog()
		{
			string text = Guid.NewGuid().ToString("N");
			Plugin.Log.LogInfo((object)("Session log " + text));
			try
			{
				foreach (DiskLogListener item in Logger.Listeners.OfType<DiskLogListener>())
				{
					item.LogWriter?.Flush();
				}
				string[] files = Directory.GetFiles(Paths.BepInExRootPath, "LogOutput*.log");
				for (int i = 0; i < files.Length; i++)
				{
					string text2;
					using (FileStream stream = new FileStream(files[i], FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete))
					{
						using StreamReader streamReader = new StreamReader(stream);
						text2 = streamReader.ReadToEnd();
					}
					int num = text2.IndexOf(text, StringComparison.Ordinal);
					if (num >= 0)
					{
						int val = text2.LastIndexOf('\n', num);
						WriteRaw("---------- Startup (before LobbyPlus loaded, copied from LogOutput.log, no times) ----------");
						WriteRaw(text2.Substring(0, Math.Max(0, val)).TrimEnd());
						WriteRaw("---------- End of startup ----------");
						WriteRaw("");
						return;
					}
				}
				WriteRaw("(Startup log not found; BepInEx's file log may be turned off.)");
			}
			catch (Exception ex)
			{
				WriteRaw("(Couldn't copy the startup log: " + ex.Message + ")");
			}
		}

		public void LogEvent(object sender, LogEventArgs eventArgs)
		{
			//IL_001d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_0043: Unknown result type (might be due to invalid IL or missing references)
			//IL_00dd: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e3: Unknown result type (might be due to invalid IL or missing references)
			ILogSource source = eventArgs.Source;
			string text = ((source != null) ? source.SourceName : null) ?? "?";
			if ((eventArgs.Level & 0x20) != 0 && text != "LobbyPlus" && text != "ImprovedShop")
			{
				return;
			}
			string text2 = LevelName(eventArgs.Level);
			string text3 = eventArgs.Data?.ToString() ?? "";
			string text4 = text2 + text + text3;
			lock (gate)
			{
				if (text4 == lastKey)
				{
					repeats++;
					return;
				}
				FlushRepeats();
				lastKey = text4;
				Write($"{Now()} [{text2,-7}:{text}] {text3}");
				if ((eventArgs.Level & 3) != 0)
				{
					writer.Flush();
				}
			}
		}

		private void FlushRepeats()
		{
			if (repeats > 0)
			{
				Write(string.Format("{0}          (the line above repeated {1} more time{2})", Now(), repeats, (repeats == 1) ? "" : "s"));
				repeats = 0;
			}
		}

		private void Write(string line)
		{
			if (!full)
			{
				bytes += line.Length + 2;
				if (bytes > 41943040)
				{
					full = true;
					writer.WriteLine($"{Now()} (Session log is {40L} MB; stopped writing. BepInEx's LogOutput.log goes on.)");
					writer.Flush();
				}
				else
				{
					writer.WriteLine(line);
					needsFlush = true;
				}
			}
		}

		private void WriteRaw(string line)
		{
			lock (gate)
			{
				writer.WriteLine(line);
				needsFlush = true;
			}
		}

		public void Dispose()
		{
			lock (gate)
			{
				try
				{
					FlushRepeats();
					writer.Flush();
					writer.Dispose();
				}
				catch (ObjectDisposedException)
				{
				}
			}
		}

		private static string Now()
		{
			return DateTime.Now.ToString("HH:mm:ss.fff");
		}

		private unsafe static string LevelName(LogLevel level)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0002: 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_000d: 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_0018: Unknown result type (might be due to invalid IL or missing references)
			//IL_0021: Unknown result type (might be due to invalid IL or missing references)
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			//IL_002c: Unknown result type (might be due to invalid IL or missing references)
			//IL_002f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0038: Unknown result type (might be due to invalid IL or missing references)
			//IL_003b: Unknown result type (might be due to invalid IL or missing references)
			if ((level & 1) != 0)
			{
				return "Fatal";
			}
			if ((level & 2) != 0)
			{
				return "Error";
			}
			if ((level & 4) != 0)
			{
				return "Warning";
			}
			if ((level & 8) != 0)
			{
				return "Message";
			}
			if ((level & 0x10) != 0)
			{
				return "Info";
			}
			if ((level & 0x20) != 0)
			{
				return "Debug";
			}
			return ((object)(*(LogLevel*)(&level))/*cast due to .constrained prefix*/).ToString();
		}

		internal static void Tick()
		{
			//IL_0033: Unknown result type (might be due to invalid IL or missing references)
			if (instance == null)
			{
				return;
			}
			if (!modsListed && Chainloader.PluginInfos != null && Time.frameCount > 2)
			{
				modsListed = true;
				ListMods();
			}
			WatchSession();
			if (Input.GetKeyDown(Plugin.LogMarkerKey.Value) && SemiFunc.NoTextInputsActive())
			{
				PlaceMarker();
			}
			if (!(Time.unscaledTime >= nextFlush))
			{
				return;
			}
			nextFlush = Time.unscaledTime + 1f;
			SessionLog sessionLog = instance;
			lock (sessionLog.gate)
			{
				sessionLog.FlushRepeats();
				if (sessionLog.needsFlush)
				{
					sessionLog.writer.Flush();
					sessionLog.needsFlush = false;
				}
			}
		}

		private static void ListMods()
		{
			List<string> list = new List<string> { $"Mods loaded ({Chainloader.PluginInfos.Count}):" };
			foreach (PluginInfo item in Chainloader.PluginInfos.Values.OrderBy<PluginInfo, string>((PluginInfo i) => i.Metadata.Name, StringComparer.OrdinalIgnoreCase))
			{
				list.Add($"  {item.Metadata.Name} {item.Metadata.Version} ({item.Metadata.GUID})");
			}
			Plugin.Log.LogInfo((object)string.Join(Environment.NewLine, list));
		}

		private static void WatchSession()
		{
			//IL_00e1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f2: Unknown result type (might be due to invalid IL or missing references)
			//IL_0102: Unknown result type (might be due to invalid IL or missing references)
			bool inRoom = PhotonNetwork.InRoom;
			bool flag = inRoom && PhotonNetwork.IsMasterClient;
			if (inRoom && !wasInRoom)
			{
				string text = (((Object)(object)RunManager.instance != (Object)null) ? LateJoin.Where(RunManager.instance.levelCurrent) : "?");
				Plugin.Log.LogInfo((object)("=== Joined a game as " + (flag ? "the host" : "a player") + " (server region " + PhotonNetwork.CloudRegion + ", game is in the " + text + "). Players: " + PlayerNames() + " ==="));
				lastMasterActor = ((PhotonNetwork.MasterClient != null) ? PhotonNetwork.MasterClient.ActorNumber : (-1));
			}
			else if (!inRoom && wasInRoom)
			{
				DisconnectCause val = (DisconnectCause)((PhotonNetwork.NetworkingClient != null) ? ((int)PhotonNetwork.NetworkingClient.DisconnectedCause) : 0);
				Plugin.Log.LogInfo((object)("=== Left the game" + (((int)val != 0) ? $" (disconnect reason: {val})" : "") + " ==="));
				lastMasterActor = -1;
				lastReadyLevel = null;
			}
			else if (inRoom && PhotonNetwork.MasterClient != null && PhotonNetwork.MasterClient.ActorNumber != lastMasterActor)
			{
				lastMasterActor = PhotonNetwork.MasterClient.ActorNumber;
				Plugin.Log.LogWarning((object)("=== The host changed: " + (flag ? "you are" : (PhotonNetwork.MasterClient.NickName + " is")) + " the host now (the old host left) ==="));
			}
			wasInRoom = inRoom;
			LevelGenerator val2 = LevelGenerator.Instance;
			if ((Object)(object)val2 != (Object)null && val2.Generated && (Object)(object)val2 != (Object)(object)lastReadyLevel && (Object)(object)RunManager.instance != (Object)null && (Object)(object)RunManager.instance.levelCurrent != (Object)null)
			{
				lastReadyLevel = val2;
				Level levelCurrent = RunManager.instance.levelCurrent;
				if ((Object)(object)levelCurrent != (Object)(object)RunManager.instance.levelSplashScreen && (Object)(object)levelCurrent != (Object)(object)RunManager.instance.levelMainMenu)
				{
					string text2 = (inRoom ? $"{PhotonNetwork.CurrentRoom.PlayerCount} player(s): {PlayerNames()}, ping {PhotonNetwork.GetPing()} ms" : "not in a game");
					Plugin.Log.LogInfo((object)("=== Level ready: " + ((Object)levelCurrent).name + " (" + LateJoin.Where(levelCurrent) + ", " + (flag ? "you're the host" : "you're a player") + "). " + text2 + " ==="));
				}
			}
		}

		private static string PlayerNames()
		{
			Room currentRoom = PhotonNetwork.CurrentRoom;
			if (currentRoom == null)
			{
				return "-";
			}
			return string.Join(", ", from p in currentRoom.Players.Values
				orderby p.ActorNumber
				select p.NickName + (p.IsMasterClient ? " (host)" : "") + (p.IsLocal ? " (you)" : ""));
		}

		private static void PlaceMarker()
		{
			//IL_006e: 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_00d8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00da: 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_00e9: Expected O, but got Unknown
			markerCount++;
			object obj;
			if (!((Object)(object)RunManager.instance != (Object)null))
			{
				obj = "?";
			}
			else
			{
				Level levelCurrent = RunManager.instance.levelCurrent;
				obj = ((levelCurrent != null) ? ((Object)levelCurrent).name : null) + " (" + LateJoin.Where(RunManager.instance.levelCurrent) + ")";
			}
			string arg = (string)obj;
			Plugin.Log.LogMessage((object)$"########## MARKER {markerCount}: you pressed {Plugin.LogMarkerKey.Value} here. Level: {arg} ##########");
			Toast = $"Marked in your log (#{markerCount}). Everyone's log has it too.";
			ToastUntil = Time.unscaledTime + 3f;
			if (PhotonNetwork.InRoom)
			{
				PhotonNetwork.RaiseEvent((byte)192, (object)new object[2] { "LobbyPlus", markerCount }, new RaiseEventOptions
				{
					Receivers = (ReceiverGroup)0
				}, SendOptions.SendReliable);
			}
		}

		internal static void OnEvent(EventData photonEvent)
		{
			if (photonEvent.Code == 192 && instance != null && photonEvent.CustomData is object[] array && array.Length >= 2 && array[0] is string text && !(text != "LobbyPlus") && array[1] is int num)
			{
				Room currentRoom = PhotonNetwork.CurrentRoom;
				Player val = ((currentRoom != null) ? currentRoom.GetPlayer(photonEvent.Sender, false) : null);
				string text2 = ((val != null) ? val.NickName : $"player {photonEvent.Sender}");
				Plugin.Log.LogMessage((object)$"########## MARKER from {text2} (their #{num}): they pressed the marker key here ##########");
				Toast = text2 + " marked this moment in everyone's log.";
				ToastUntil = Time.unscaledTime + 3f;
			}
		}

		internal static void DrawToast()
		{
			//IL_0042: Unknown result type (might be due to invalid IL or missing references)
			//IL_0047: Unknown result type (might be due to invalid IL or missing references)
			//IL_004e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0055: Unknown result type (might be due to invalid IL or missing references)
			//IL_0061: Expected O, but got Unknown
			//IL_00bc: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00db: Unknown result type (might be due to invalid IL or missing references)
			//IL_0103: 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_011d: Unknown result type (might be due to invalid IL or missing references)
			if (Toast != null && !(Time.unscaledTime > ToastUntil))
			{
				int num = Mathf.Max(14, Screen.height / 45);
				if (toastStyle == null || toastStyle.fontSize != num)
				{
					toastStyle = new GUIStyle(GUI.skin.label)
					{
						fontSize = num,
						alignment = (TextAnchor)4,
						wordWrap = true
					};
				}
				Rect val = default(Rect);
				((Rect)(ref val))..ctor((float)Screen.width * 0.2f, (float)Screen.height * 0.8f, (float)Screen.width * 0.6f, (float)num * 2.5f);
				Rect val2 = new Rect(((Rect)(ref val)).x + 2f, ((Rect)(ref val)).y + 2f, ((Rect)(ref val)).width, ((Rect)(ref val)).height);
				Color color = GUI.color;
				GUI.color = new Color(0f, 0f, 0f, 0.8f);
				GUI.Label(val2, Toast, toastStyle);
				GUI.color = new Color(1f, 0.85f, 0.3f);
				GUI.Label(val, Toast, toastStyle);
				GUI.color = color;
			}
		}
	}
}