BepInEx\plugins\P2P\P2P.dll

Decompiled a day ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using BepInEx;
using BepInEx.Configuration;
using ExitGames.Client.Photon;
using FriendlyFoe.Platform;
using HarmonyLib;
using InControl;
using Landfall.Network;
using Microsoft.CodeAnalysis;
using Photon.Pun;
using Photon.Realtime;
using RoundsBugfixes.Plugin;
using RoundsP2P.Core;
using RoundsP2P.Core.Tunnel;
using Steamworks;
using TMPro;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.Events;
using UnityEngine.Localization;
using UnityEngine.Localization.Settings;
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("P2P")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0+c9b03c0ff381adab9c0ba8924ab03e2818cd50b0")]
[assembly: AssemblyProduct("P2P")]
[assembly: AssemblyTitle("P2P")]
[assembly: AssemblyVersion("1.0.0.0")]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

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

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

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

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
internal static class PluginVersion
{
	internal const string Value = "1.0.0";
}
namespace RoundsP2P.Plugin
{
	internal sealed class MatchHud : IDisposable
	{
		private RoundCounter? _counter;

		private RectTransform? _root;

		private TextMeshProUGUI? _team0;

		private TextMeshProUGUI? _team1;

		private TextMeshProUGUI? _ping;

		private int _shownTeam0 = -1;

		private int _shownTeam1 = -1;

		private int? _shownPing;

		internal void Refresh(RoundCounter counter, int team0Wins, int team1Wins, int? peerPingMs)
		{
			//IL_01a3: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a8: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b4: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b9: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d5: Unknown result type (might be due to invalid IL or missing references)
			//IL_01dc: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f6: Unknown result type (might be due to invalid IL or missing references)
			//IL_0210: Unknown result type (might be due to invalid IL or missing references)
			//IL_0233: Unknown result type (might be due to invalid IL or missing references)
			//IL_023a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0264: Unknown result type (might be due to invalid IL or missing references)
			//IL_0276: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ad: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c1: Expected O, but got Unknown
			//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_00f4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fb: Unknown result type (might be due to invalid IL or missing references)
			//IL_0108: Unknown result type (might be due to invalid IL or missing references)
			//IL_0118: Unknown result type (might be due to invalid IL or missing references)
			Transform p1Parent = counter.p1Parent;
			Transform p2Parent = counter.p2Parent;
			if (!((Behaviour)counter).isActiveAndEnabled || (Object)(object)p1Parent == (Object)null || (Object)(object)p2Parent == (Object)null)
			{
				Hide();
				return;
			}
			if ((Object)(object)_counter != (Object)(object)counter || (Object)(object)_root == (Object)null)
			{
				Dispose();
				Transform transform = ((Component)counter).transform;
				object obj = ((transform is RectTransform) ? transform : null);
				if (obj == null)
				{
					Canvas componentInParent = ((Component)counter).GetComponentInParent<Canvas>();
					Transform obj2 = ((componentInParent != null) ? ((Component)componentInParent).transform : null);
					obj = ((obj2 is RectTransform) ? obj2 : null);
				}
				RectTransform val = (RectTransform)obj;
				if ((Object)(object)val == (Object)null)
				{
					return;
				}
				_root = (RectTransform)new GameObject("RoundsP2P.MatchHud", new Type[2]
				{
					typeof(RectTransform),
					typeof(LayoutElement)
				}).transform;
				((Component)_root).GetComponent<LayoutElement>().ignoreLayout = true;
				((Transform)_root).SetParent((Transform)(object)val, false);
				RectTransform? root = _root;
				Vector2 anchorMin = (_root.anchorMax = val.pivot);
				root.anchorMin = anchorMin;
				_root.anchoredPosition = Vector2.zero;
				_root.sizeDelta = Vector2.zero;
				_team0 = CreateLabel(_root, "Team0MatchWins");
				_team1 = CreateLabel(_root, "Team1MatchWins");
				_ping = CreateLabel(_root, "PeerPing");
				((TMP_Text)_ping).text = "Ping —";
				_counter = counter;
			}
			RectTransform root2 = _root;
			TextMeshProUGUI team = _team0;
			TextMeshProUGUI team2 = _team1;
			TextMeshProUGUI ping = _ping;
			float height;
			Vector2 rowEnd = GetRowEnd(p1Parent, root2, counter.p1Platform, out height);
			float height2;
			Vector2 rowEnd2 = GetRowEnd(p2Parent, root2, counter.p2Platform, out height2);
			float num = Mathf.Clamp(Mathf.Max(height, height2), 16f, 48f);
			float num2 = Mathf.Max(rowEnd.x, rowEnd2.x) + num * 0.35f;
			Place(team, num2, rowEnd.y, num * 2.5f, num);
			Place(team2, num2, rowEnd2.y, num * 2.5f, num);
			Place(ping, num2 + num * 2.8f, (rowEnd.y + rowEnd2.y) * 0.5f, num * 6f, num * 0.82f);
			((Graphic)team).color = PlayerSkinBank.GetPlayerSkinColors(0).winText;
			((Graphic)team2).color = PlayerSkinBank.GetPlayerSkinColors(1).winText;
			if (_shownTeam0 != team0Wins)
			{
				((TMP_Text)team).text = team0Wins.ToString(CultureInfo.InvariantCulture);
				_shownTeam0 = team0Wins;
			}
			if (_shownTeam1 != team1Wins)
			{
				((TMP_Text)team2).text = team1Wins.ToString(CultureInfo.InvariantCulture);
				_shownTeam1 = team1Wins;
			}
			if (_shownPing != peerPingMs)
			{
				((TMP_Text)ping).text = ((!peerPingMs.HasValue) ? "Ping —" : ("Ping " + peerPingMs.GetValueOrDefault().ToString(CultureInfo.InvariantCulture) + " ms"));
				_shownPing = peerPingMs;
			}
			if (!((Component)root2).gameObject.activeSelf)
			{
				((Component)root2).gameObject.SetActive(true);
			}
		}

		private static TextMeshProUGUI CreateLabel(RectTransform root, string name)
		{
			//IL_0021: Unknown result type (might be due to invalid IL or missing references)
			//IL_0056: Unknown result type (might be due to invalid IL or missing references)
			//IL_005c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0072: Unknown result type (might be due to invalid IL or missing references)
			TextMeshProUGUI component = new GameObject(name, new Type[2]
			{
				typeof(RectTransform),
				typeof(TextMeshProUGUI)
			}).GetComponent<TextMeshProUGUI>();
			((TMP_Text)component).transform.SetParent((Transform)(object)root, false);
			RectTransform rectTransform = ((TMP_Text)component).rectTransform;
			RectTransform rectTransform2 = ((TMP_Text)component).rectTransform;
			Vector2 val = default(Vector2);
			((Vector2)(ref val))..ctor(0.5f, 0.5f);
			rectTransform2.anchorMax = val;
			rectTransform.anchorMin = val;
			((TMP_Text)component).rectTransform.pivot = new Vector2(0f, 0.5f);
			((TMP_Text)component).alignment = (TextAlignmentOptions)4097;
			((TMP_Text)component).font = TMP_Settings.defaultFontAsset;
			((TMP_Text)component).enableWordWrapping = false;
			((Graphic)component).raycastTarget = false;
			return component;
		}

		private static void Place(TextMeshProUGUI label, float x, float y, float width, float size)
		{
			//IL_0008: 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)
			((TMP_Text)label).rectTransform.anchoredPosition = new Vector2(x, y);
			((TMP_Text)label).rectTransform.sizeDelta = new Vector2(width, size * 1.25f);
			((TMP_Text)label).fontSize = size;
		}

		private static Vector2 GetRowEnd(Transform row, RectTransform root, Image platform, out float height)
		{
			//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_0027: 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_0030: Unknown result type (might be due to invalid IL or missing references)
			//IL_003a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0010: 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_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)
			//IL_0052: Unknown result type (might be due to invalid IL or missing references)
			//IL_0053: Unknown result type (might be due to invalid IL or missing references)
			//IL_0063: 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_006e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0073: Unknown result type (might be due to invalid IL or missing references)
			//IL_0089: Unknown result type (might be due to invalid IL or missing references)
			//IL_008f: Expected O, but got Unknown
			//IL_00ad: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bd: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cc: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ec: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f1: 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_0108: 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_010f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0180: Unknown result type (might be due to invalid IL or missing references)
			//IL_013b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0142: Unknown result type (might be due to invalid IL or missing references)
			//IL_0119: Unknown result type (might be due to invalid IL or missing references)
			//IL_0121: Unknown result type (might be due to invalid IL or missing references)
			//IL_0128: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ef: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a5: Unknown result type (might be due to invalid IL or missing references)
			//IL_01aa: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b5: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ba: Unknown result type (might be due to invalid IL or missing references)
			//IL_01be: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c8: Unknown result type (might be due to invalid IL or missing references)
			//IL_01cd: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d2: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d7: Unknown result type (might be due to invalid IL or missing references)
			float num = float.NegativeInfinity;
			RectTransform val = (RectTransform)(object)((row is RectTransform) ? row : null);
			? val2;
			Rect rect;
			if (val == null)
			{
				val2 = Vector2.zero;
			}
			else
			{
				rect = val.rect;
				float xMax = ((Rect)(ref rect)).xMax;
				rect = val.rect;
				val2 = new Vector2(xMax, ((Rect)(ref rect)).center.y);
			}
			Vector2 val3 = (Vector2)val2;
			Vector3 val4 = ((Transform)root).InverseTransformPoint(row.TransformPoint(Vector2.op_Implicit(val3)));
			float num2 = val4.y;
			height = 0f;
			Matrix4x4 val5 = ((Transform)root).worldToLocalMatrix * row.localToWorldMatrix;
			foreach (Transform item in row)
			{
				object obj = (object)item;
				RectTransform val6 = (RectTransform)((obj is RectTransform) ? obj : null);
				if (val6 != null && ((Component)val6).gameObject.activeSelf)
				{
					Matrix4x4 val7 = val5 * Matrix4x4.TRS(((Transform)val6).localPosition, ((Transform)val6).localRotation, Vector3.one);
					Rect rect2 = val6.rect;
					Vector3 val8 = ((Matrix4x4)(ref val7)).MultiplyPoint3x4(new Vector3(((Rect)(ref rect2)).xMin, ((Rect)(ref rect2)).yMin));
					Vector3 val9 = ((Matrix4x4)(ref val7)).MultiplyPoint3x4(new Vector3(((Rect)(ref rect2)).xMax, ((Rect)(ref rect2)).yMax));
					if (val9.x > num)
					{
						num = val9.x;
						num2 = (val8.y + val9.y) * 0.5f;
					}
					height = Mathf.Max(height, Mathf.Abs(val9.y - val8.y));
				}
			}
			if (float.IsNegativeInfinity(num))
			{
				num = val4.x;
			}
			if ((Object)(object)platform != (Object)null && ((Behaviour)platform).isActiveAndEnabled)
			{
				RectTransform rectTransform = ((Graphic)platform).rectTransform;
				rect = rectTransform.rect;
				float xMax2 = ((Rect)(ref rect)).xMax;
				rect = rectTransform.rect;
				float x = ((Transform)root).InverseTransformPoint(((Transform)rectTransform).TransformPoint(Vector2.op_Implicit(new Vector2(xMax2, ((Rect)(ref rect)).center.y)))).x;
				num = Mathf.Max(num, x);
			}
			return new Vector2(num, num2);
		}

		internal void Hide()
		{
			if ((Object)(object)_root != (Object)null && ((Component)_root).gameObject.activeSelf)
			{
				((Component)_root).gameObject.SetActive(false);
			}
		}

		public void Dispose()
		{
			if ((Object)(object)_root != (Object)null)
			{
				Hide();
				Object.Destroy((Object)(object)((Component)_root).gameObject);
			}
			_root = null;
			_counter = null;
			_team0 = (_team1 = (_ping = null));
			_shownTeam0 = (_shownTeam1 = -1);
			_shownPing = null;
		}
	}
	internal sealed class NativeSteamMenu : IDisposable
	{
		private sealed class PlayerRow
		{
			internal readonly GameObject Root;

			internal readonly TextMeshProUGUI NameLabel;

			internal readonly TextMeshProUGUI ScoreLabel;

			internal readonly GameObject Ready;

			internal PlayerRow(GameObject root, TextMeshProUGUI nameLabel, TextMeshProUGUI scoreLabel, GameObject ready)
			{
				Root = root;
				NameLabel = nameLabel;
				ScoreLabel = scoreLabel;
				Ready = ready;
			}

			internal void Refresh((string? Name, int Wins, bool Ready) player)
			{
				Root.SetActive(player.Name != null);
				if (player.Name != null)
				{
					if (((TMP_Text)NameLabel).text != player.Name)
					{
						((TMP_Text)NameLabel).text = player.Name;
					}
					string text = player.Wins.ToString();
					if (((TMP_Text)ScoreLabel).text != text)
					{
						((TMP_Text)ScoreLabel).text = text;
						((Component)ScoreLabel).GetComponent<LayoutElement>().minWidth = ((TMP_Text)ScoreLabel).preferredWidth;
					}
					Ready.SetActive(player.Ready);
				}
			}
		}

		[Serializable]
		[CompilerGenerated]
		private sealed class <>c
		{
			public static readonly <>c <>9 = new <>c();

			public static UnityAction <>9__24_1;

			internal void <EnsurePages>b__24_1()
			{
				ListMenu.instance.CloseTopPage();
			}
		}

		private readonly Plugin _plugin;

		private ListMenuPage? _sourcePage;

		private ListMenuPage? _onlinePage;

		private ListMenuPage? _lobbyPage;

		private Button? _createButton;

		private Button? _backButton;

		private Button? _inviteButton;

		private Button? _readyButton;

		private Button? _leaveButton;

		private Button? _returnButton;

		private string? _shownReadyLabel;

		private TextMeshProUGUI? _onlineStatus;

		private TextMeshProUGUI? _lobbyStatus;

		private GameObject? _lobbyStatusRow;

		private PlayerRow? _hostRow;

		private PlayerRow? _guestRow;

		internal NativeSteamMenu(Plugin plugin)
		{
			_plugin = plugin ?? throw new ArgumentNullException("plugin");
			LocalizationSettings.SelectedLocaleChanged += OnLocaleChanged;
		}

		internal void OpenOnline()
		{
			EnsurePages();
			SkipIntro obj = Object.FindObjectOfType<SkipIntro>(true);
			if (obj != null)
			{
				obj.Skip();
			}
			MainMenuHandler.instance.Open();
			ListMenu.instance.Unfocus = false;
			Open(_plugin.HasSteamLobby ? _lobbyPage : _onlinePage);
			Refresh();
		}

		internal void ShowLobby()
		{
			EnsurePages();
			MainMenuHandler.instance.Open();
			ListMenu.instance.Unfocus = false;
			Open(_lobbyPage);
			Refresh();
		}

		internal void Refresh()
		{
			if ((Object)(object)_onlinePage == (Object)null || (Object)(object)_lobbyPage == (Object)null)
			{
				return;
			}
			string text = _plugin.SteamStatus ?? string.Empty;
			if ((Object)(object)_onlineStatus != (Object)null && ((TMP_Text)_onlineStatus).text != text)
			{
				((TMP_Text)_onlineStatus).text = text;
			}
			if ((Object)(object)_createButton != (Object)null)
			{
				((Selectable)_createButton).interactable = !_plugin.HasSteamLobby;
			}
			if (!_lobbyPage.IsOpen)
			{
				return;
			}
			_hostRow?.Refresh(_plugin.LobbyPlayer(isHost: true));
			_guestRow?.Refresh(_plugin.LobbyPlayer(isHost: false));
			if ((Object)(object)_lobbyStatus != (Object)null)
			{
				string lobbyConnectionStatus = _plugin.LobbyConnectionStatus;
				if (((TMP_Text)_lobbyStatus).text != lobbyConnectionStatus)
				{
					((TMP_Text)_lobbyStatus).text = lobbyConnectionStatus;
				}
				GameObject? lobbyStatusRow = _lobbyStatusRow;
				if (lobbyStatusRow != null)
				{
					lobbyStatusRow.SetActive(lobbyConnectionStatus.Length != 0);
				}
			}
			if ((Object)(object)_inviteButton != (Object)null)
			{
				((Selectable)_inviteButton).interactable = _plugin.CanInviteSteamFriend;
			}
			if ((Object)(object)_readyButton != (Object)null)
			{
				((Selectable)_readyButton).interactable = _plugin.CanReadyInLobby;
				RefreshReadyLabel();
			}
		}

		internal void CloseForMatch()
		{
			CloseOwnedTopPages();
		}

		internal void RefreshPause(EscapeMenuHandler menu, bool canReturn)
		{
			//IL_004b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0055: Expected O, but got Unknown
			//IL_0083: Unknown result type (might be due to invalid IL or missing references)
			//IL_008d: Expected O, but got Unknown
			if (!canReturn)
			{
				if ((Object)(object)_returnButton != (Object)null)
				{
					((Component)_returnButton).gameObject.SetActive(false);
				}
				return;
			}
			if ((Object)(object)_returnButton == (Object)null)
			{
				Button val = FindButtonTemplate((ListMenuPage)AccessTools.Field(typeof(EscapeMenuHandler), "m_pageToOpen").GetValue(menu));
				if ((Object)(object)val == (Object)null)
				{
					return;
				}
				_returnButton = CreateButton(val, ((Component)val).transform.parent, "Выйти в лобби", "Return to lobby", new UnityAction(_plugin.RequestLobbyReturn));
				((Component)_returnButton).transform.SetSiblingIndex(((Component)val).transform.GetSiblingIndex() + 1);
			}
			((Component)_returnButton).gameObject.SetActive(true);
		}

		internal bool TryClickCreateLobbyForSmoke()
		{
			if ((Object)(object)_onlinePage == (Object)null || !IsTop(_onlinePage) || (Object)(object)_createButton == (Object)null || !((Behaviour)_createButton).isActiveAndEnabled || !((Selectable)_createButton).interactable)
			{
				return false;
			}
			((UnityEvent)_createButton.onClick).Invoke();
			return true;
		}

		private void EnsurePages()
		{
			//IL_00ec: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f6: Expected O, but got Unknown
			//IL_01af: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b9: Expected O, but got Unknown
			//IL_01d7: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e1: Expected O, but got Unknown
			//IL_01fa: Unknown result type (might be due to invalid IL or missing references)
			//IL_0204: Expected O, but got Unknown
			//IL_011c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0121: Unknown result type (might be due to invalid IL or missing references)
			//IL_0127: Expected O, but got Unknown
			MainMenuHandler instance = MainMenuHandler.instance;
			if ((Object)(object)instance == (Object)null || (Object)(object)instance.MainMenu == (Object)null || (Object)(object)ListMenu.instance == (Object)null)
			{
				throw new InvalidOperationException(SteamMenuText.Translate("Главное меню ещё загружается.", "The main menu is still loading."));
			}
			if ((Object)(object)_onlinePage != (Object)null && (Object)(object)_lobbyPage != (Object)null && (Object)(object)_sourcePage == (Object)(object)instance.MainMenu)
			{
				return;
			}
			DestroyPages();
			_sourcePage = instance.MainMenu;
			Button val = FindButtonTemplate(_sourcePage);
			if ((Object)(object)val == (Object)null)
			{
				throw new InvalidOperationException(SteamMenuText.Translate("Не удалось подготовить меню онлайн-игры.", "Could not prepare the online menu."));
			}
			try
			{
				_onlinePage = CreatePage("RoundsP2P.Online", _sourcePage, out Transform grid);
				_onlineStatus = CreateStatus(val, grid, "OnlineStatus", out GameObject _);
				_createButton = CreateButton(val, grid, "Создать лобби", "Create lobby", (UnityAction)delegate
				{
					_plugin.CreateSteamLobby();
					ShowLobby();
				});
				Transform parent = grid;
				object obj = <>c.<>9__24_1;
				if (obj == null)
				{
					UnityAction val2 = delegate
					{
						ListMenu.instance.CloseTopPage();
					};
					<>c.<>9__24_1 = val2;
					obj = (object)val2;
				}
				_backButton = CreateButton(val, parent, "Назад", "Back", (UnityAction)obj);
				FinishPage(_onlinePage, _createButton);
				_lobbyPage = CreatePage("RoundsP2P.Lobby", _sourcePage, out Transform grid2);
				_hostRow = CreatePlayerRow(val, grid2, "RoundsP2P.HostPlayer");
				_guestRow = CreatePlayerRow(val, grid2, "RoundsP2P.GuestPlayer");
				_lobbyStatus = CreateStatus(val, grid2, "LobbyStatus", out _lobbyStatusRow);
				_readyButton = CreateButton(val, grid2, "Готов", "Ready", new UnityAction(_plugin.ReadyInLobby));
				_inviteButton = CreateButton(val, grid2, "Пригласить друга", "Invite friend", new UnityAction(_plugin.InviteSteamFriend));
				_leaveButton = CreateButton(val, grid2, "Покинуть лобби", "Leave lobby", (UnityAction)delegate
				{
					_plugin.LeaveSteamLobby();
					CloseOwnedTopPages();
					OpenOnline();
				});
				FinishPage(_lobbyPage, _readyButton);
			}
			catch
			{
				DestroyPages();
				throw;
			}
		}

		private static Button? FindButtonTemplate(ListMenuPage page)
		{
			Button val = null;
			Button[] componentsInChildren = ((Component)page).GetComponentsInChildren<Button>(true);
			foreach (Button val2 in componentsInChildren)
			{
				if (!((Object)(object)((Component)val2).GetComponent<ListMenuButton>() == (Object)null) && !((Object)(object)((Component)val2).GetComponentInChildren<TextMeshProUGUI>(true) == (Object)null))
				{
					if (val == null)
					{
						val = val2;
					}
					if ((Object)(object)((Component)val2).GetComponent<CheckUserPrivilegeButton>() == (Object)null && (Object)(object)((Component)val2).GetComponent<QuitButton>() == (Object)null && (Object)(object)((Component)val2).GetComponent<OptionsButton>() == (Object)null)
					{
						return val2;
					}
				}
			}
			return val;
		}

		private static ListMenuPage CreatePage(string name, ListMenuPage source, out Transform grid)
		{
			//IL_0036: Unknown result type (might be due to invalid IL or missing references)
			//IL_003c: Expected O, but got Unknown
			if (((Component)source).transform.childCount == 0)
			{
				throw new InvalidOperationException(SteamMenuText.Translate("Штатная страница меню не содержит список кнопок.", "The stock menu page is missing its button list."));
			}
			GameObject val = new GameObject(name, new Type[1] { typeof(RectTransform) });
			val.SetActive(false);
			val.transform.SetParent(((Component)source).transform.parent, false);
			CopyTransform(((Component)source).transform, val.transform);
			GameObject val2 = Object.Instantiate<GameObject>(((Component)((Component)source).transform.GetChild(0)).gameObject, val.transform, false);
			((Object)val2).name = "Grid";
			grid = val2.transform;
			while (grid.childCount > 0)
			{
				Object.DestroyImmediate((Object)(object)((Component)grid.GetChild(0)).gameObject);
			}
			StripGameActions(val2, preserveMenuStyle: false);
			VerticalLayoutGroup val3 = val2.GetComponent<VerticalLayoutGroup>();
			if ((Object)(object)val3 == (Object)null)
			{
				LayoutGroup[] components = val2.GetComponents<LayoutGroup>();
				for (int i = 0; i < components.Length; i++)
				{
					Object.DestroyImmediate((Object)(object)components[i]);
				}
				val3 = val2.AddComponent<VerticalLayoutGroup>();
				((HorizontalOrVerticalLayoutGroup)val3).spacing = 12f;
				((LayoutGroup)val3).childAlignment = (TextAnchor)0;
			}
			((HorizontalOrVerticalLayoutGroup)val3).childControlHeight = true;
			((HorizontalOrVerticalLayoutGroup)val3).childControlWidth = true;
			((HorizontalOrVerticalLayoutGroup)val3).childForceExpandHeight = false;
			((HorizontalOrVerticalLayoutGroup)val3).childForceExpandWidth = true;
			ListMenuPage obj = val.AddComponent<ListMenuPage>();
			obj.barHeight = source.barHeight;
			return obj;
		}

		private static void CopyTransform(Transform source, Transform target)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			//IL_001a: Unknown result type (might be due to invalid IL or missing references)
			//IL_003a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0046: Unknown result type (might be due to invalid IL or missing references)
			//IL_0052: Unknown result type (might be due to invalid IL or missing references)
			//IL_005e: Unknown result type (might be due to invalid IL or missing references)
			//IL_006a: Unknown result type (might be due to invalid IL or missing references)
			target.localPosition = source.localPosition;
			target.localRotation = source.localRotation;
			target.localScale = source.localScale;
			RectTransform val = (RectTransform)(object)((source is RectTransform) ? source : null);
			if (val != null)
			{
				RectTransform val2 = (RectTransform)(object)((target is RectTransform) ? target : null);
				if (val2 != null)
				{
					val2.anchorMin = val.anchorMin;
					val2.anchorMax = val.anchorMax;
					val2.pivot = val.pivot;
					val2.sizeDelta = val.sizeDelta;
					val2.anchoredPosition3D = val.anchoredPosition3D;
				}
			}
		}

		private static Button CreateButton(Button template, Transform parent, string russian, string english, UnityAction action)
		{
			//IL_002e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0038: Expected O, but got Unknown
			//IL_0048: Unknown result type (might be due to invalid IL or missing references)
			//IL_0056: 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_0085: Expected O, but got Unknown
			//IL_00c6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cb: Unknown result type (might be due to invalid IL or missing references)
			GameObject val = Object.Instantiate<GameObject>(((Component)template).gameObject, parent, false);
			((Object)val).name = "RoundsP2P." + russian;
			StripGameActions(val, preserveMenuStyle: true);
			Button component = val.GetComponent<Button>();
			component.onClick = new ButtonClickedEvent();
			((UnityEvent)component.onClick).AddListener(action);
			Navigation navigation = default(Navigation);
			((Navigation)(ref navigation)).mode = (Mode)3;
			((Selectable)component).navigation = navigation;
			Button[] componentsInChildren = val.GetComponentsInChildren<Button>(true);
			foreach (Button val2 in componentsInChildren)
			{
				if ((Object)(object)val2 != (Object)(object)component)
				{
					val2.onClick = new ButtonClickedEvent();
				}
			}
			SetLabel(val, SteamMenuText.Translate(russian, english));
			LayoutElement obj = val.GetComponent<LayoutElement>() ?? val.AddComponent<LayoutElement>();
			obj.minHeight = 80f;
			Rect rect = ((Component)template).GetComponent<RectTransform>().rect;
			obj.preferredHeight = Math.Max(80f, ((Rect)(ref rect)).height);
			obj.flexibleHeight = 0f;
			val.SetActive(true);
			return component;
		}

		private static TextMeshProUGUI CreateStatus(Button template, Transform parent, string name, out GameObject root)
		{
			//IL_007d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0084: Unknown result type (might be due to invalid IL or missing references)
			GameObject val = (root = Object.Instantiate<GameObject>(((Component)template).gameObject, parent, false));
			((Object)val).name = "RoundsP2P." + name;
			StripGameActions(val, preserveMenuStyle: true);
			Button[] componentsInChildren = val.GetComponentsInChildren<Button>(true);
			for (int i = 0; i < componentsInChildren.Length; i++)
			{
				Object.DestroyImmediate((Object)(object)componentsInChildren[i]);
			}
			ListMenuButton[] componentsInChildren2 = val.GetComponentsInChildren<ListMenuButton>(true);
			for (int i = 0; i < componentsInChildren2.Length; i++)
			{
				Object.DestroyImmediate((Object)(object)componentsInChildren2[i]);
			}
			SetLabel(val, string.Empty);
			TextMeshProUGUI componentInChildren = val.GetComponentInChildren<TextMeshProUGUI>(true);
			((TMP_Text)componentInChildren).fontStyle = (FontStyles)(((TMP_Text)componentInChildren).fontStyle & -2);
			((TMP_Text)componentInChildren).fontSize = Math.Min(((TMP_Text)componentInChildren).fontSize, 30f);
			((TMP_Text)componentInChildren).enableWordWrapping = true;
			((Graphic)componentInChildren).raycastTarget = false;
			Graphic[] componentsInChildren3 = val.GetComponentsInChildren<Graphic>(true);
			for (int i = 0; i < componentsInChildren3.Length; i++)
			{
				componentsInChildren3[i].raycastTarget = false;
			}
			LayoutElement obj = val.GetComponent<LayoutElement>() ?? val.AddComponent<LayoutElement>();
			obj.minHeight = 100f;
			obj.preferredHeight = 120f;
			obj.flexibleHeight = 0f;
			val.SetActive(true);
			return componentInChildren;
		}

		private static PlayerRow CreatePlayerRow(Button template, Transform parent, string name)
		{
			//IL_002e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0034: Expected O, but got Unknown
			//IL_00f9: Unknown result type (might be due to invalid IL or missing references)
			//IL_0100: Expected O, but got Unknown
			//IL_0145: Unknown result type (might be due to invalid IL or missing references)
			//IL_014a: Unknown result type (might be due to invalid IL or missing references)
			//IL_016b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0190: Unknown result type (might be due to invalid IL or missing references)
			GameObject val = new GameObject(name, new Type[3]
			{
				typeof(RectTransform),
				typeof(HorizontalLayoutGroup),
				typeof(LayoutElement)
			});
			val.transform.SetParent(parent, false);
			val.GetComponent<LayoutElement>().minHeight = 46f;
			HorizontalLayoutGroup component = val.GetComponent<HorizontalLayoutGroup>();
			((LayoutGroup)component).childAlignment = (TextAnchor)4;
			((HorizontalOrVerticalLayoutGroup)component).childControlWidth = true;
			((HorizontalOrVerticalLayoutGroup)component).childControlHeight = true;
			((HorizontalOrVerticalLayoutGroup)component).childForceExpandWidth = false;
			((HorizontalOrVerticalLayoutGroup)component).childForceExpandHeight = false;
			((HorizontalOrVerticalLayoutGroup)component).spacing = 12f;
			TextMeshProUGUI componentInChildren = ((Component)template).GetComponentInChildren<TextMeshProUGUI>(true);
			TextMeshProUGUI val2 = CreatePlayerLabel(val.transform, "Nickname", componentInChildren);
			((TMP_Text)val2).overflowMode = (TextOverflowModes)1;
			((Component)val2).GetComponent<LayoutElement>().minWidth = 0f;
			TextMeshProUGUI scoreLabel = CreatePlayerLabel(val.transform, "Wins", componentInChildren);
			GameObject val3 = new GameObject("Ready", new Type[3]
			{
				typeof(RectTransform),
				typeof(Image),
				typeof(LayoutElement)
			});
			val3.transform.SetParent(val.transform, false);
			LayoutElement component2 = val3.GetComponent<LayoutElement>();
			component2.minWidth = 24f;
			component2.minHeight = 24f;
			Image component3 = val3.GetComponent<Image>();
			((Graphic)component3).color = Color32.op_Implicit(new Color32((byte)40, (byte)139, (byte)76, byte.MaxValue));
			((Graphic)component3).raycastTarget = false;
			AddCheckStroke(val3.transform, new Vector2(5f, 12f), 8f, -45f);
			AddCheckStroke(val3.transform, new Vector2(10f, 7f), 13f, 45f);
			val.SetActive(false);
			return new PlayerRow(val, val2, scoreLabel, val3);
		}

		private static TextMeshProUGUI CreatePlayerLabel(Transform parent, string name, TextMeshProUGUI model)
		{
			//IL_002e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0033: Unknown result type (might be due to invalid IL or missing references)
			//IL_0069: Unknown result type (might be due to invalid IL or missing references)
			GameObject val = new GameObject(name, new Type[3]
			{
				typeof(RectTransform),
				typeof(TextMeshProUGUI),
				typeof(LayoutElement)
			});
			val.transform.SetParent(parent, false);
			TextMeshProUGUI component = val.GetComponent<TextMeshProUGUI>();
			((TMP_Text)component).font = ((TMP_Text)model).font;
			((TMP_Text)component).fontSize = Math.Min(((TMP_Text)model).fontSize, 38f);
			((Graphic)component).color = ((Graphic)model).color;
			((TMP_Text)component).alignment = (TextAlignmentOptions)4097;
			((TMP_Text)component).richText = false;
			((TMP_Text)component).enableWordWrapping = false;
			((Graphic)component).raycastTarget = false;
			return component;
		}

		private static void AddCheckStroke(Transform parent, Vector2 start, float length, float degrees)
		{
			//IL_0025: 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_0037: 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_0044: 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_004b: Unknown result type (might be due to invalid IL or missing references)
			//IL_005c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0067: Unknown result type (might be due to invalid IL or missing references)
			//IL_0074: 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)
			GameObject val = new GameObject("CheckStroke", new Type[2]
			{
				typeof(RectTransform),
				typeof(Image)
			});
			val.transform.SetParent(parent, false);
			RectTransform component = val.GetComponent<RectTransform>();
			Vector2 anchorMin = (component.anchorMax = Vector2.zero);
			component.anchorMin = anchorMin;
			component.pivot = new Vector2(0f, 0.5f);
			component.anchoredPosition = start;
			component.sizeDelta = new Vector2(length, 2.5f);
			((Transform)component).localRotation = Quaternion.Euler(0f, 0f, degrees);
			((Graphic)val.GetComponent<Image>()).raycastTarget = false;
		}

		private static void SetLabel(GameObject root, string label)
		{
			//IL_0038: Unknown result type (might be due to invalid IL or missing references)
			//IL_0042: Expected O, but got Unknown
			UILocalizedString[] componentsInChildren = root.GetComponentsInChildren<UILocalizedString>(true);
			foreach (UILocalizedString val in componentsInChildren)
			{
				((TMP_Text)val.Text).text = label;
				val.ResetReference(label);
				AccessTools.Field(typeof(UILocalizedString), "m_onStringUpdated").SetValue(val, (object?)new UnityEvent());
			}
			((TMP_Text)root.GetComponentInChildren<TextMeshProUGUI>(true)).text = label;
		}

		private void OnLocaleChanged(Locale locale)
		{
			if ((Object)(object)_createButton != (Object)null)
			{
				SetLabel(((Component)_createButton).gameObject, SteamMenuText.Translate("Создать лобби", "Create lobby"));
			}
			if ((Object)(object)_backButton != (Object)null)
			{
				SetLabel(((Component)_backButton).gameObject, SteamMenuText.Translate("Назад", "Back"));
			}
			if ((Object)(object)_inviteButton != (Object)null)
			{
				SetLabel(((Component)_inviteButton).gameObject, SteamMenuText.Translate("Пригласить друга", "Invite friend"));
			}
			if ((Object)(object)_leaveButton != (Object)null)
			{
				SetLabel(((Component)_leaveButton).gameObject, SteamMenuText.Translate("Покинуть лобби", "Leave lobby"));
			}
			if ((Object)(object)_returnButton != (Object)null)
			{
				SetLabel(((Component)_returnButton).gameObject, SteamMenuText.Translate("Выйти в лобби", "Return to lobby"));
			}
			RefreshReadyLabel();
		}

		private void RefreshReadyLabel()
		{
			if (!((Object)(object)_readyButton == (Object)null))
			{
				string text = (_plugin.LobbyReadySelected ? SteamMenuText.Translate("Не готов", "Unready") : SteamMenuText.Translate("Готов", "Ready"));
				if (!(_shownReadyLabel == text))
				{
					SetLabel(((Component)_readyButton).gameObject, text);
					_shownReadyLabel = text;
				}
			}
		}

		private static void StripGameActions(GameObject root, bool preserveMenuStyle)
		{
			MonoBehaviour[] componentsInChildren = root.GetComponentsInChildren<MonoBehaviour>(true);
			foreach (MonoBehaviour val in componentsInChildren)
			{
				if (!((Object)(object)val == (Object)null) && (!preserveMenuStyle || (!(val is ListMenuButton) && !(val is UILocalizedString))) && (val is EventTrigger || ((object)val).GetType().Assembly == typeof(MainMenuHandler).Assembly))
				{
					Object.DestroyImmediate((Object)(object)val);
				}
			}
		}

		private static void FinishPage(ListMenuPage page, Button first)
		{
			AccessTools.Field(typeof(ListMenuPage), "firstSelected").SetValue(page, ((Component)first).GetComponent<ListMenuButton>());
			AccessTools.Field(typeof(ListMenuPage), "firstActiveChild").SetValue(page, ((Component)first).transform.parent);
			((Component)page).gameObject.SetActive(true);
			page.Hide();
		}

		private static void Open(ListMenuPage page)
		{
			if (!IsTop(page))
			{
				page.Open();
			}
			else
			{
				page.Show();
			}
			ListMenu.instance.UpdateBar(page);
		}

		private static bool IsTop(ListMenuPage page)
		{
			Stack<ListMenuPage> stack = (Stack<ListMenuPage>)AccessTools.Field(typeof(ListMenu), "m_menuStack").GetValue(ListMenu.instance);
			if (stack.Count > 0)
			{
				return (Object)(object)stack.Peek() == (Object)(object)page;
			}
			return false;
		}

		private void CloseOwnedTopPages()
		{
			while (((Object)(object)_lobbyPage != (Object)null && IsTop(_lobbyPage)) || ((Object)(object)_onlinePage != (Object)null && IsTop(_onlinePage)))
			{
				ListMenu.instance.CloseTopPage();
			}
		}

		private void DestroyPages()
		{
			if ((Object)(object)ListMenu.instance != (Object)null)
			{
				CloseOwnedTopPages();
			}
			if ((Object)(object)_onlinePage != (Object)null)
			{
				Object.Destroy((Object)(object)((Component)_onlinePage).gameObject);
			}
			if ((Object)(object)_lobbyPage != (Object)null)
			{
				Object.Destroy((Object)(object)((Component)_lobbyPage).gameObject);
			}
			_sourcePage = null;
			_onlinePage = null;
			_lobbyPage = null;
			_createButton = null;
			_backButton = null;
			_inviteButton = null;
			_readyButton = null;
			_leaveButton = null;
			_shownReadyLabel = null;
			_onlineStatus = null;
			_lobbyStatus = null;
			_lobbyStatusRow = null;
			_hostRow = null;
			_guestRow = null;
		}

		internal string DumpHierarchy()
		{
			StringBuilder stringBuilder = new StringBuilder();
			MainMenuHandler instance = MainMenuHandler.instance;
			if ((Object)(object)instance == (Object)null || (Object)(object)instance.MainMenu == (Object)null)
			{
				return "Main menu not available.";
			}
			AppendHierarchy(stringBuilder, ((Component)instance.MainMenu).transform, 0);
			if ((Object)(object)_onlinePage != (Object)null)
			{
				AppendHierarchy(stringBuilder, ((Component)_onlinePage).transform, 0);
			}
			if ((Object)(object)_lobbyPage != (Object)null)
			{
				AppendHierarchy(stringBuilder, ((Component)_lobbyPage).transform, 0);
			}
			return stringBuilder.ToString();
		}

		private static void AppendHierarchy(StringBuilder output, Transform transform, int depth)
		{
			output.Append(' ', depth * 2).Append(((Object)transform).name).Append(" [");
			bool flag = true;
			Component[] components = ((Component)transform).GetComponents<Component>();
			foreach (Component val in components)
			{
				if (!((Object)(object)val == (Object)null))
				{
					if (!flag)
					{
						output.Append(", ");
					}
					output.Append(((object)val).GetType().Name);
					flag = false;
				}
			}
			output.AppendLine("]");
			for (int j = 0; j < transform.childCount; j++)
			{
				AppendHierarchy(output, transform.GetChild(j), depth + 1);
			}
		}

		public void Dispose()
		{
			LocalizationSettings.SelectedLocaleChanged -= OnLocaleChanged;
			DestroyPages();
			if ((Object)(object)_returnButton != (Object)null)
			{
				Object.Destroy((Object)(object)((Component)_returnButton).gameObject);
			}
		}
	}
	[BepInPlugin("local.rounds.p2p.prototype", "P2P", "1.0.0")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	public sealed class Plugin : BaseUnityPlugin
	{
		private enum LobbyMessage
		{
			Ready,
			Return,
			State
		}

		public const string Id = "local.rounds.p2p.prototype";

		public const string PrototypeAppId = "5d9f49ea-424d-42a1-956a-dc65752e51ae";

		public const string ProtocolVersion = "rounds-p2p-1.0-lobby-6";

		private ConfigEntry<PrototypeRole> _role;

		private ConfigEntry<string> _host;

		private ConfigEntry<string> _advertised;

		private ConfigEntry<string> _room;

		private ConfigEntry<int> _masterPort;

		private ConfigEntry<int> _gamePort;

		private ConfigEntry<double> _timeout;

		private ConfigEntry<bool> _autoConnect;

		private LuxonServerProcess? _server;

		private PhotonPortDefinition _savedPorts;

		private AuthenticationValues? _savedAuth;

		private string? _savedAppId;

		private string? _savedVersion;

		private bool _active;

		private bool _connecting;

		private bool _panel;

		private bool _seenRoom;

		private bool _disconnectPending;

		private string? _operationError;

		private Coroutine? _connectionRoutine;

		private string _status = "F8: optional direct-IPv4 diagnostics; use Online for Steam lobbies.";

		private ClientState _lastState;

		private StreamWriter? _trace;

		private readonly Stopwatch _clock = Stopwatch.StartNew();

		private readonly object _traceLock = new object();

		private Harmony? _smokeHarmony;

		private Harmony? _wireHarmony;

		private readonly MatchHud _matchHud = new MatchHud();

		private LobbyMatchScore? _matchScore;

		private bool _hudSmoke;

		private const byte MatchLobbyEvent = 171;

		private const double LobbyRetrySeconds = 0.25;

		private LobbyReadiness _lobbyReadiness;

		private LobbyReadiness? _pendingLobbyState;

		private int _lobbyReadyRevision;

		private double _nextLobbyVoteSend;

		private double _nextLobbyStateSend;

		private Coroutine? _lobbyReload;

		private bool _lobbySmoke;

		private SteamLobbySession? _steam;

		private NativeSteamMenu? _steamMenu;

		private NetworkConnectionHandler? _matchUiOwner;

		private bool _usingSteam;

		private bool _steamPlayerJoined;

		private int _savedMtu;

		private string? _steamUnavailable;

		internal static Plugin? Instance { get; private set; }

		internal bool SmokeEnabled { get; private set; }

		internal bool Active => _active;

		private bool UsesMatchLobby
		{
			get
			{
				if (_active)
				{
					if (!_usingSteam)
					{
						return _lobbySmoke;
					}
					return true;
				}
				return false;
			}
		}

		private bool HasOpponent
		{
			get
			{
				if (UsesMatchLobby && PhotonNetwork.InRoom)
				{
					return PhotonNetwork.CurrentRoom.PlayerCount == 2;
				}
				return false;
			}
		}

		private LobbyReadiness HostLobbyReadiness => (LobbyReadiness)(((??)_pendingLobbyState) ?? _lobbyReadiness);

		private bool CanReturnToLobby
		{
			get
			{
				//IL_0016: Unknown result type (might be due to invalid IL or missing references)
				//IL_001b: Unknown result type (might be due to invalid IL or missing references)
				if (HasOpponent && ((LobbyReadiness)(ref _lobbyReadiness)).MatchAllowed)
				{
					LobbyReadiness hostLobbyReadiness = HostLobbyReadiness;
					return ((LobbyReadiness)(ref hostLobbyReadiness)).MatchAllowed;
				}
				return false;
			}
		}

		internal bool CanReadyInLobby
		{
			get
			{
				//IL_0016: Unknown result type (might be due to invalid IL or missing references)
				//IL_001b: Unknown result type (might be due to invalid IL or missing references)
				if (HasOpponent && !((LobbyReadiness)(ref _lobbyReadiness)).MatchAllowed)
				{
					LobbyReadiness hostLobbyReadiness = HostLobbyReadiness;
					if (!((LobbyReadiness)(ref hostLobbyReadiness)).MatchAllowed)
					{
						return _lobbyReload == null;
					}
				}
				return false;
			}
		}

		internal bool LobbyReadySelected { get; private set; }

		internal int LobbyCycle => ((LobbyReadiness)(ref _lobbyReadiness)).Cycle;

		internal bool MatchAllowed => ((LobbyReadiness)(ref _lobbyReadiness)).MatchAllowed;

		internal string LobbyConnectionStatus
		{
			get
			{
				if (!HasOpponent)
				{
					return SteamStatus;
				}
				return string.Empty;
			}
		}

		internal string SteamStatus => _steam?.Status ?? _steamUnavailable ?? SteamMenuText.Translate("Создайте лобби, чтобы пригласить друга через Steam.", "Create a lobby to invite a friend on Steam.");

		internal bool HasSteamLobby => _steam?.HasLobby ?? false;

		internal bool CanInviteSteamFriend => _steam?.CanInvite ?? false;

		private void Awake()
		{
			//IL_01ba: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c4: Expected O, but got Unknown
			//IL_01fd: Unknown result type (might be due to invalid IL or missing references)
			//IL_020a: Expected O, but got Unknown
			//IL_0252: Unknown result type (might be due to invalid IL or missing references)
			//IL_0260: Expected O, but got Unknown
			//IL_028f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0299: Expected O, but got Unknown
			Instance = this;
			Application.runInBackground = true;
			_role = ((BaseUnityPlugin)this).Config.Bind<PrototypeRole>("Connection", "Role", (PrototypeRole)0, "Disabled, Host or Client. The default leaves stock networking alone.");
			_host = ((BaseUnityPlugin)this).Config.Bind<string>("Connection", "HostAddress", "127.0.0.1", "IPv4 of the PC running the server; host normally uses loopback.");
			_advertised = ((BaseUnityPlugin)this).Config.Bind<string>("Connection", "AdvertisedAddress", "127.0.0.1", "Host IPv4 reachable by the friend. This is NOT a bind-address/firewall restriction.");
			_room = ((BaseUnityPlugin)this).Config.Bind<string>("Connection", "RoomName", "rounds-prototype", "Same room on both PCs; ASCII letters/digits/-/_ only.");
			_masterPort = ((BaseUnityPlugin)this).Config.Bind<int>("Connection", "MasterPort", 5055, "UDP master port.");
			_gamePort = ((BaseUnityPlugin)this).Config.Bind<int>("Connection", "GamePort", 5056, "UDP game port.");
			_timeout = ((BaseUnityPlugin)this).Config.Bind<double>("Connection", "TimeoutSeconds", 30.0, "Connection/room operation timeout, 1..120 seconds.");
			_autoConnect = ((BaseUnityPlugin)this).Config.Bind<bool>("Connection", "AutoConnect", false, "Connect automatically after the stock main menu is ready.");
			SmokeEnabled = Array.IndexOf(Environment.GetCommandLineArgs(), "--rounds-p2p-smoke") >= 0;
			_lobbySmoke = SmokeEnabled && Array.IndexOf(Environment.GetCommandLineArgs(), "--rounds-p2p-lobby-smoke") >= 0;
			string path = CommandLineValue("--rounds-p2p-trace=") ?? Path.Combine(Paths.BepInExRootPath, "RoundsP2P.trace.log");
			Directory.CreateDirectory(Path.GetDirectoryName(Path.GetFullPath(path)));
			_trace = new StreamWriter(path, append: false)
			{
				AutoFlush = true
			};
			_wireHarmony = new Harmony("local.rounds.p2p.prototype.wire");
			InstallMatchHudHooks(_wireHarmony);
			_wireHarmony.Patch((MethodBase)AccessTools.Method(typeof(LoadBalancingPeer), "RoomOptionsToOpParameters", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(typeof(Plugin), "NormalizeRoomOptions", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			string[] array = new string[2] { "OnDisconnected", "OnJoinRoomFailed" };
			foreach (string text in array)
			{
				_wireHarmony.Patch((MethodBase)AccessTools.Method(typeof(NetworkConnectionHandler), text, (Type[])null, (Type[])null), new HarmonyMethod(typeof(Plugin), "UseStockFailureHandling", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			}
			InstallSteamHooks(_wireHarmony);
			InstallMatchLobbyHooks(_wireHarmony);
			if (SmokeEnabled)
			{
				_smokeHarmony = new Harmony("local.rounds.p2p.prototype.smoke");
				SmokeDriver.Install(_smokeHarmony);
				((Component)this).gameObject.AddComponent<SmokeDriver>();
			}
			WriteTrace("plugin_loaded", "unity=" + Application.unityVersion + ";smoke=" + SmokeEnabled);
			((BaseUnityPlugin)this).Logger.LogInfo((object)"Standalone prototype loaded; no RWF/UnboundLib/DuctTape dependency. F8 opens connection controls.");
		}

		private IEnumerator Start()
		{
			while ((Object)(object)NetworkConnectionHandler.instance == (Object)null || (Object)(object)MainMenuHandler.instance == (Object)null || (Object)(object)LoadingScreen.instance == (Object)null)
			{
				yield return null;
			}
			InitializeSteamFeatures();
			string text = CommandLineValue("--rounds-p2p-role=");
			if (text == null && !_autoConnect.Value)
			{
				yield break;
			}
			PrototypeRole role;
			try
			{
				role = (PrototypeRole)((text == null) ? _role.Value : ((PrototypeRole)Enum.Parse(typeof(PrototypeRole), text, ignoreCase: true)));
			}
			catch (Exception ex)
			{
				Fail(ex.Message);
				yield break;
			}
			if (SmokeEnabled && Array.IndexOf(Environment.GetCommandLineArgs(), "--rounds-p2p-cancel-retry-smoke") >= 0)
			{
				try
				{
					Begin((PrototypeRole)1);
				}
				catch (Exception ex2)
				{
					Fail(ex2.Message);
					yield break;
				}
				yield return null;
				StopSession();
				double deadline = _clock.Elapsed.TotalSeconds + 5.0;
				while (!PhotonStopped() && _clock.Elapsed.TotalSeconds < deadline)
				{
					yield return null;
				}
				if (!PhotonStopped() || _connectionRoutine != null || PhotonNetwork.NetworkingClient.AppId != _savedAppId || PhotonNetwork.AuthValues != _savedAuth)
				{
					WriteTrace("smoke_failed", "cancel_retry_did_not_restore_settings;state=" + ((object)PhotonNetwork.NetworkClientState/*cast due to .constrained prefix*/).ToString() + ";peer=" + ((object)((PhotonPeer)PhotonNetwork.NetworkingClient.LoadBalancingPeer).PeerState/*cast due to .constrained prefix*/).ToString() + ";routine_stopped=" + (_connectionRoutine == null) + ";app_restored=" + (PhotonNetwork.NetworkingClient.AppId == _savedAppId) + ";auth_restored=" + (PhotonNetwork.AuthValues == _savedAuth));
					Application.Quit(2);
					yield break;
				}
				WriteTrace("smoke_cancel_retry_complete", "pending_attempt_cancelled;settings_restored");
			}
			try
			{
				Begin(role);
			}
			catch (Exception ex3)
			{
				Fail(ex3.Message);
			}
		}

		private static bool PhotonStopped()
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Invalid comparison between Unknown and I4
			//IL_0009: Unknown result type (might be due to invalid IL or missing references)
			//IL_000f: Invalid comparison between Unknown and I4
			if ((int)PhotonNetwork.NetworkClientState != 14)
			{
				return (int)PhotonNetwork.NetworkClientState == 0;
			}
			return true;
		}

		private static string? CommandLineValue(string prefix)
		{
			string[] commandLineArgs = Environment.GetCommandLineArgs();
			foreach (string text in commandLineArgs)
			{
				if (text.StartsWith(prefix, StringComparison.Ordinal))
				{
					return text.Substring(prefix.Length);
				}
			}
			return null;
		}

		private static void NormalizeRoomOptions(Dictionary<byte, object> op, bool usePropertiesKey)
		{
			if ((Object)(object)Instance != (Object)null && Instance.Active)
			{
				PhotonWireCompatibility.NormalizeRoomOptions((IDictionary<byte, object>)op, usePropertiesKey);
			}
		}

		private static bool UseStockFailureHandling()
		{
			if (!((Object)(object)Instance == (Object)null))
			{
				return !Instance.Active;
			}
			return true;
		}

		private void OnOperationResponse(OperationResponse response)
		{
			if (_active && response.ReturnCode != 0 && (response.OperationCode == 227 || response.OperationCode == 226))
			{
				_operationError = "Room operation failed (" + response.ReturnCode + "): " + response.DebugMessage;
			}
		}

		private PrototypeOptions Options(PrototypeRole role)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bd: Expected O, but got Unknown
			return new PrototypeOptions(role, CommandLineValue("--rounds-p2p-host=") ?? _host.Value, CommandLineValue("--rounds-p2p-advertised=") ?? _advertised.Value, CommandLineValue("--rounds-p2p-room=") ?? _room.Value, int.Parse(CommandLineValue("--rounds-p2p-master-port=") ?? _masterPort.Value.ToString(CultureInfo.InvariantCulture), CultureInfo.InvariantCulture), int.Parse(CommandLineValue("--rounds-p2p-game-port=") ?? _gamePort.Value.ToString(CultureInfo.InvariantCulture), CultureInfo.InvariantCulture), _timeout.Value);
		}

		private void Begin(PrototypeRole role, PrototypeOptions? steamOptions = null)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_007d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0082: Unknown result type (might be due to invalid IL or missing references)
			//IL_0075: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f1: Expected O, but got Unknown
			//IL_0141: Unknown result type (might be due to invalid IL or missing references)
			//IL_0143: Invalid comparison between Unknown and I4
			//IL_019a: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a4: Expected O, but got Unknown
			if ((int)role == 0)
			{
				return;
			}
			if (!_active && !PhotonNetwork.IsConnected)
			{
				LoadingScreen instance = LoadingScreen.instance;
				if ((instance == null || !instance.IsLoading) && (!((Object)(object)GameManager.instance != (Object)null) || !GameManager.instance.isPlaying))
				{
					if ((Object)(object)NetworkConnectionHandler.instance == (Object)null || (Object)(object)LoadingScreen.instance == (Object)null)
					{
						throw new InvalidOperationException("Wait for the main menu to finish loading.");
					}
					PrototypeOptions val = steamOptions ?? Options(role);
					_savedPorts = PhotonNetwork.ServerPortOverrides;
					_savedAuth = PhotonNetwork.AuthValues;
					_savedAppId = PhotonNetwork.NetworkingClient.AppId;
					_savedVersion = PhotonNetwork.GameVersion;
					_savedMtu = ((PhotonPeer)PhotonNetwork.NetworkingClient.LoadBalancingPeer).MaximumTransferUnit;
					_usingSteam = steamOptions != null;
					_active = true;
					_matchScore = ((!UsesMatchLobby && !_hudSmoke) ? ((LobbyMatchScore)null) : new LobbyMatchScore());
					_seenRoom = false;
					_connecting = true;
					_operationError = null;
					PhotonNetwork.NetworkingClient.OpResponseReceived += OnOperationResponse;
					if (UsesMatchLobby)
					{
						PhotonNetwork.NetworkingClient.EventReceived += OnMatchLobbyEvent;
					}
					_panel = false;
					try
					{
						if ((int)role == 1)
						{
							string directoryName = Path.GetDirectoryName(((BaseUnityPlugin)this).Info.Location);
							string text = Path.Combine(Paths.CachePath, "RoundsP2P", Guid.NewGuid().ToString("N"));
							_server = new LuxonServerProcess(Path.Combine(directoryName, "luxon", "luxon_server.exe"), text, val, (Action<string>)delegate(string message)
							{
								((BaseUnityPlugin)this).Logger.LogInfo((object)("[Luxon] " + message));
							});
							WriteTrace("server_started", "pid=" + _server.ProcessId);
						}
						_connectionRoutine = ((MonoBehaviour)this).StartCoroutine(Connect(val));
						return;
					}
					catch (Exception ex)
					{
						Fail(ex.Message);
						return;
					}
				}
			}
			throw new InvalidOperationException("Leave the current game/connection before starting the prototype.");
		}

		private IEnumerator Connect(PrototypeOptions options)
		{
			double deadline = _clock.Elapsed.TotalSeconds + options.TimeoutSeconds;
			while (_active && _server != null && !_server.IsListening)
			{
				if (_server.HasExited)
				{
					Fail("The hosted server exited before binding its UDP ports.");
					yield break;
				}
				if (_clock.Elapsed.TotalSeconds >= deadline)
				{
					Fail("Timed out waiting for the hosted server to listen.");
					yield break;
				}
				yield return null;
			}
			if (!_active)
			{
				yield break;
			}
			if (_server != null)
			{
				WriteTrace("server_listening", "master=" + options.MasterPort + ";game=" + options.GamePort);
			}
			PhotonNetwork.ServerPortOverrides = new PhotonPortDefinition
			{
				MasterServerPort = (ushort)options.MasterPort,
				GameServerPort = (ushort)options.GamePort
			};
			PhotonNetwork.AuthValues = new AuthenticationValues(Guid.NewGuid().ToString("N"));
			if (_usingSteam)
			{
				((PhotonPeer)PhotonNetwork.NetworkingClient.LoadBalancingPeer).MaximumTransferUnit = 1000;
			}
			AppSettings val = new AppSettings
			{
				AppIdRealtime = "5d9f49ea-424d-42a1-956a-dc65752e51ae",
				AppVersion = "rounds-p2p-1.0-lobby-6",
				UseNameServer = false,
				Server = options.HostAddress,
				Port = options.MasterPort,
				Protocol = (ConnectionProtocol)0,
				EnableProtocolFallback = false,
				AuthMode = (AuthModeOption)0,
				EnableLobbyStatistics = false
			};
			_status = "Connecting to " + options.HostAddress + ":" + options.MasterPort;
			if (!PhotonNetwork.ConnectUsingSettings(val, false))
			{
				Fail("Photon rejected direct-master connection.");
				yield break;
			}
			WriteTrace("connect_started", _status);
			deadline = _clock.Elapsed.TotalSeconds + options.TimeoutSeconds;
			while (_active && (int)PhotonNetwork.NetworkClientState != 15)
			{
				if ((int)PhotonNetwork.NetworkClientState == 14)
				{
					Fail("Connection failed: " + ((object)PhotonNetwork.NetworkingClient.DisconnectedCause/*cast due to .constrained prefix*/).ToString());
					yield break;
				}
				if (_clock.Elapsed.TotalSeconds >= deadline)
				{
					Fail("Timed out connecting to the local master server.");
					yield break;
				}
				if (_server != null && _server.HasExited)
				{
					Fail("The hosted server exited during connection.");
					yield break;
				}
				yield return null;
			}
			if (!_active)
			{
				yield break;
			}
			ConfigurePrivateRoom(NetworkConnectionHandler.instance);
			if (!UsesMatchLobby)
			{
				ShowMatchLoading();
			}
			RoomOptions val2 = new RoomOptions
			{
				MaxPlayers = 2,
				IsOpen = true,
				IsVisible = false
			};
			Hashtable val3 = new Hashtable();
			((Dictionary<object, object>)val3).Add((object)NetworkConnectionHandler.ROOM_CODE, (object)options.RoomName);
			val2.CustomRoomProperties = val3;
			RoomOptions val4 = val2;
			if (!(((int)options.Role == 1) ? PhotonNetwork.CreateRoom(options.RoomName, val4, TypedLobby.Default, (string[])null) : PhotonNetwork.JoinRoom(options.RoomName, (string[])null)))
			{
				Fail("Photon rejected the create/join operation.");
				yield break;
			}
			_status = "Waiting to join room " + options.RoomName;
			deadline = _clock.Elapsed.TotalSeconds + options.TimeoutSeconds;
			while (_active && !PhotonNetwork.InRoom)
			{
				if (_operationError != null)
				{
					Fail(_operationError);
					yield break;
				}
				if (_clock.Elapsed.TotalSeconds >= deadline)
				{
					Fail("Timed out joining room; check host address, ports and room name.");
					yield break;
				}
				if ((int)PhotonNetwork.NetworkClientState == 14)
				{
					Fail("Disconnected while joining the room.");
					yield break;
				}
				yield return null;
			}
			if (_active)
			{
				_connecting = false;
				_connectionRoutine = null;
				_seenRoom = true;
				_status = (UsesMatchLobby ? "Room joined; waiting for both players to ready up." : "Room joined; waiting for the second player (press Space when the stock game asks).");
				WriteTrace("room_joined", "actor=" + PhotonNetwork.LocalPlayer.ActorNumber + ";server=" + PhotonNetwork.ServerAddress);
				if (_usingSteam)
				{
					_steam?.OnPhotonRoomReady();
				}
				else if (_lobbySmoke)
				{
					ShowSteamLobbyPage();
				}
			}
		}

		private static void ConfigurePrivateRoom(NetworkConnectionHandler handler)
		{
			FieldInfo fieldInfo = AccessTools.Field(typeof(NetworkConnectionHandler), "m_searchingType");
			fieldInfo.SetValue(handler, Enum.Parse(fieldInfo.FieldType, "HostRoom"));
		}

		private unsafe void Update()
		{
			//IL_0036: 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_003c: 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_0046: 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)
			if (Input.GetKeyDown((KeyCode)289))
			{
				_panel = !_panel;
			}
			PumpStoppedPhoton();
			UpdateSteamFeatures();
			PumpMatchLobby();
			if (_active)
			{
				ClientState networkClientState = PhotonNetwork.NetworkClientState;
				if (networkClientState != _lastState)
				{
					_lastState = networkClientState;
					WriteTrace("photon_state", ((object)(*(ClientState*)(&networkClientState))/*cast due to .constrained prefix*/).ToString() + ";server=" + PhotonNetwork.ServerAddress);
				}
				if (!_connecting && _seenRoom && !PhotonNetwork.InRoom)
				{
					_status = "Session ended; stock network settings restored.";
					StopSessionAndRestoreMenu();
				}
				else if (_server != null && _server.HasExited)
				{
					Fail("The hosted server exited.");
				}
			}
		}

		private void OnGUI()
		{
			//IL_001d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0155: Unknown result type (might be due to invalid IL or missing references)
			//IL_015a: Unknown result type (might be due to invalid IL or missing references)
			if (!_panel)
			{
				return;
			}
			GUILayout.BeginArea(new Rect(20f, 90f, 580f, 320f), GUI.skin.box);
			GUILayout.Label("ROUNDS P2P — IPv4 diagnostics 0.2 (F8)", Array.Empty<GUILayoutOption>());
			GUILayout.Label(_status, Array.Empty<GUILayoutOption>());
			if (!_active)
			{
				GUILayout.Label("Server IPv4 (client):", Array.Empty<GUILayoutOption>());
				_host.Value = GUILayout.TextField(_host.Value, Array.Empty<GUILayoutOption>());
				GUILayout.Label("Host IPv4 reachable by friend (host advertises it):", Array.Empty<GUILayoutOption>());
				_advertised.Value = GUILayout.TextField(_advertised.Value, Array.Empty<GUILayoutOption>());
				GUILayout.Label("Room name:", Array.Empty<GUILayoutOption>());
				_room.Value = GUILayout.TextField(_room.Value, Array.Empty<GUILayoutOption>());
				GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>());
				if (GUILayout.Button("Host on this PC", Array.Empty<GUILayoutOption>()))
				{
					try
					{
						Begin((PrototypeRole)1);
					}
					catch (Exception ex)
					{
						Fail(ex.Message);
					}
				}
				if (GUILayout.Button("Join host", Array.Empty<GUILayoutOption>()))
				{
					try
					{
						Begin((PrototypeRole)2);
					}
					catch (Exception ex2)
					{
						Fail(ex2.Message);
					}
				}
				GUILayout.EndHorizontal();
			}
			else
			{
				GUILayout.Label("Photon: " + ((object)PhotonNetwork.NetworkClientState/*cast due to .constrained prefix*/).ToString() + "; players: " + (PhotonNetwork.InRoom ? PhotonNetwork.CurrentRoom.PlayerCount : 0), Array.Empty<GUILayoutOption>());
				GUILayout.Label("UDP server RTT: " + PhotonNetwork.GetPing() + " ms (not peer RTT)", Array.Empty<GUILayoutOption>());
				if (GUILayout.Button("Disconnect prototype", Array.Empty<GUILayoutOption>()))
				{
					StopSessionAndRestoreMenu();
				}
			}
			GUILayout.EndArea();
		}

		private void Fail(string message)
		{
			_status = "ERROR: " + message;
			_panel = true;
			((BaseUnityPlugin)this).Logger.LogError((object)_status);
			WriteTrace("error", message);
			StopSessionAndRestoreMenu();
		}

		private void StopSession()
		{
			//IL_0126: Unknown result type (might be due to invalid IL or missing references)
			//IL_016c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0173: Invalid comparison between Unknown and I4
			//IL_0036: Unknown result type (might be due to invalid IL or missing references)
			if (!_active)
			{
				return;
			}
			_active = false;
			_matchUiOwner = null;
			_matchScore = null;
			_matchHud.Hide();
			_connecting = false;
			_lobbyReadiness = default(LobbyReadiness);
			_pendingLobbyState = null;
			_nextLobbyStateSend = 0.0;
			ResetLobbyVote();
			_steamPlayerJoined = false;
			if (_lobbyReload != null)
			{
				((MonoBehaviour)this).StopCoroutine(_lobbyReload);
				_lobbyReload = null;
			}
			PhotonNetwork.NetworkingClient.EventReceived -= OnMatchLobbyEvent;
			PhotonNetwork.NetworkingClient.OpResponseReceived -= OnOperationResponse;
			if (_connectionRoutine != null)
			{
				((MonoBehaviour)this).StopCoroutine(_connectionRoutine);
				_connectionRoutine = null;
			}
			try
			{
				try
				{
					if (PhotonNetwork.IsConnected)
					{
						PhotonNetwork.Disconnect();
					}
				}
				finally
				{
					LuxonServerProcess? server = _server;
					if (server != null)
					{
						server.Dispose();
					}
				}
			}
			catch (Exception ex)
			{
				((BaseUnityPlugin)this).Logger.LogError((object)("Prototype cleanup: " + ex.Message));
				WriteTrace("cleanup_error", ex.Message);
			}
			finally
			{
				_server = null;
				PhotonNetwork.ServerPortOverrides = _savedPorts;
				PhotonNetwork.AuthValues = _savedAuth;
				PhotonNetwork.NetworkingClient.AppId = _savedAppId;
				PhotonNetwork.GameVersion = _savedVersion;
				((PhotonPeer)PhotonNetwork.NetworkingClient.LoadBalancingPeer).MaximumTransferUnit = _savedMtu;
				_disconnectPending = (int)PhotonNetwork.NetworkClientState == 13;
				bool usingSteam = _usingSteam;
				_usingSteam = false;
				WriteTrace("session_stopped", "settings_restored");
				if (usingSteam)
				{
					_steam?.OnPhotonStopped();
				}
			}
		}

		private void PumpStoppedPhoton()
		{
			//IL_001d: 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_0051: Invalid comparison between Unknown and I4
			//IL_0025: Unknown result type (might be due to invalid IL or missing references)
			//IL_002c: Invalid comparison between Unknown and I4
			if (!_disconnectPending || _active)
			{
				return;
			}
			LoadBalancingClient networkingClient = PhotonNetwork.NetworkingClient;
			if ((int)((PhotonPeer)networkingClient.LoadBalancingPeer).PeerState == 0 && (int)networkingClient.State == 13)
			{
				for (int i = 0; i < 64; i++)
				{
					if (!((PhotonPeer)networkingClient.LoadBalancingPeer).DispatchIncomingCommands())
					{
						break;
					}
				}
			}
			_disconnectPending = (int)networkingClient.State == 13;
		}

		internal void WriteTrace(string name, string detail)
		{
			lock (_traceLock)
			{
				_trace?.WriteLine(_clock.Elapsed.TotalSeconds.ToString("F3", CultureInfo.InvariantCulture) + "\t" + name + "\t" + detail.Replace('\r', ' ').Replace('\n', ' '));
			}
		}

		private void OnApplicationQuit()
		{
			StopSession();
		}

		private void OnDestroy()
		{
			StopSession();
			_steam?.Dispose();
			_steamMenu?.Dispose();
			_matchHud.Dispose();
			Harmony? smokeHarmony = _smokeHarmony;
			if (smokeHarmony != null)
			{
				smokeHarmony.UnpatchSelf();
			}
			Harmony? wireHarmony = _wireHarmony;
			if (wireHarmony != null)
			{
				wireHarmony.UnpatchSelf();
			}
			lock (_traceLock)
			{
				_trace?.Dispose();
				_trace = null;
			}
			Instance = null;
		}

		private void InstallMatchHudHooks(Harmony harmony)
		{
			//IL_004d: Unknown result type (might be due to invalid IL or missing references)
			//IL_005b: Expected O, but got Unknown
			//IL_0084: Unknown result type (might be due to invalid IL or missing references)
			//IL_0091: Expected O, but got Unknown
			_hudSmoke = SmokeEnabled && Array.IndexOf(Environment.GetCommandLineArgs(), "--rounds-p2p-hud-smoke") >= 0;
			harmony.Patch((MethodBase)AccessTools.Method(typeof(GM_ArmsRace), "GameOver", (Type[])null, (Type[])null), new HarmonyMethod(typeof(Plugin), "RecordMatchWinner", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			harmony.Patch((MethodBase)AccessTools.Method(typeof(GM_ArmsRace), "ResetMatch", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(typeof(Plugin), "BeginScoringMatch", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
		}

		private static void RecordMatchWinner(int winningTeamID)
		{
			//IL_0039: 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_0066: Unknown result type (might be due to invalid IL or missing references)
			Plugin instance = Instance;
			if (instance?._matchScore == null || !PhotonNetwork.InRoom || PhotonNetwork.CurrentRoom.PlayerCount != 2)
			{
				return;
			}
			if (instance.UsesMatchLobby)
			{
				if (!PhotonNetwork.IsMasterClient)
				{
					return;
				}
				LobbyReadiness hostLobbyReadiness = instance.HostLobbyReadiness;
				if (!((LobbyReadiness)(ref hostLobbyReadiness)).MatchAllowed)
				{
					return;
				}
			}
			if (instance._matchScore.RecordMatchWinner(ActorForTeam(winningTeamID)))
			{
				if (instance.UsesMatchLobby)
				{
					instance.QueueLobbyState(instance.HostLobbyReadiness);
				}
				instance.WriteTrace("lobby_match_score", $"team0={instance.MatchWinsForTeam(0)};team1={instance.MatchWinsForTeam(1)}");
			}
		}

		private static void BeginScoringMatch()
		{
			Plugin? instance = Instance;
			if (instance != null)
			{
				LobbyMatchScore? matchScore = instance._matchScore;
				if (matchScore != null)
				{
					matchScore.BeginMatch();
				}
			}
		}

		private static int ActorForTeam(int teamId)
		{
			PlayerManager instance = PlayerManager.instance;
			if ((Object)(object)instance == (Object)null)
			{
				return 0;
			}
			foreach (Player player in instance.players)
			{
				if (!((Object)(object)player == (Object)null) && player.TeamID == teamId && !((Object)(object)player.data == (Object)null) && !((Object)(object)player.data.view == (Object)null))
				{
					return player.data.view.OwnerActorNr;
				}
			}
			return 0;
		}

		internal int MatchWinsForTeam(int teamId)
		{
			LobbyMatchScore? matchScore = _matchScore;
			if (matchScore == null)
			{
				return 0;
			}
			return matchScore.WinsFor(ActorForTeam(teamId));
		}

		private void LateUpdate()
		{
			UIHandler instance = UIHandler.instance;
			if (_matchScore == null || (UsesMatchLobby && !((LobbyReadiness)(ref _lobbyReadiness)).MatchAllowed) || (Object)(object)instance == (Object)null || (Object)(object)instance.roundCounterSmall == (Object)null || !((Behaviour)instance.roundCounterSmall).isActiveAndEnabled || !PhotonNetwork.InRoom)
			{
				_matchHud.Hide();
			}
			else
			{
				_matchHud.Refresh(instance.roundCounterSmall, MatchWinsForTeam(0), MatchWinsForTeam(1), _steam?.PeerPingMilliseconds);
			}
		}

		internal (string? Name, int Wins, bool Ready) LobbyPlayer(bool isHost)
		{
			GetLobbyActors(out var host, out var guest);
			int num = (isHost ? host : guest);
			if (num == 0 || !PhotonNetwork.CurrentRoom.Players.TryGetValue(num, out var value))
			{
				return default((string, int, bool));
			}
			string nickName = value.NickName;
			nickName = ((!string.IsNullOrWhiteSpace(nickName)) ? nickName.Replace('\r', ' ').Replace('\n', ' ').Trim() : (isHost ? SteamMenuText.Translate("Хост", "Host") : SteamMenuText.Translate("Гость", "Guest")));
			string item = nickName;
			LobbyMatchScore? matchScore = _matchScore;
			return (Name: item, Wins: (matchScore != null) ? matchScore.WinsFor(num) : 0, Ready: isHost ? ((LobbyReadiness)(ref _lobbyReadiness)).HostReady : ((LobbyReadiness)(ref _lobbyReadiness)).GuestReady);
		}

		private static void InstallMatchLobbyHooks(Harmony harmony)
		{
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			//IL_0035: Expected O, but got Unknown
			//IL_005d: Unknown result type (might be due to invalid IL or missing references)
			//IL_006b: Expected O, but got Unknown
			//IL_0093: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b5: Expected O, but got Unknown
			//IL_00b5: Expected O, but got Unknown
			harmony.Patch((MethodBase)AccessTools.Method(typeof(GM_ArmsRace), "GetRematchYesNo", (Type[])null, (Type[])null), new HarmonyMethod(typeof(Plugin), "ReturnOnDeclinedRematch", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			harmony.Patch((MethodBase)AccessTools.Method(typeof(EscapeMenuHandler), "ToggleEsc", (Type[])null, (Type[])null), new HarmonyMethod(typeof(Plugin), "PrepareMatchPauseMenu", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			harmony.Patch((MethodBase)AccessTools.Method(typeof(NetworkConnectionHandler), "Awake", (Type[])null, (Type[])null), new HarmonyMethod(typeof(Plugin), "SavePortsDuringLobbyReload", (Type[])null), new HarmonyMethod(typeof(Plugin), "RestorePortsAfterLobbyReload", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
		}

		private static void SavePortsDuringLobbyReload(out PhotonPortDefinition __state)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			__state = PhotonNetwork.ServerPortOverrides;
		}

		private static void RestorePortsAfterLobbyReload(NetworkConnectionHandler __instance, PhotonPortDefinition __state)
		{
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			Plugin? instance = Instance;
			if (instance != null && instance.UsesMatchLobby)
			{
				PhotonNetwork.ServerPortOverrides = __state;
				ConfigurePrivateRoom(__instance);
			}
		}

		private static bool ReturnOnDeclinedRematch(YesNo yesNo)
		{
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			//IL_0019: Invalid comparison between Unknown and I4
			Plugin instance = Instance;
			if (instance == null || !instance.HasOpponent || (int)yesNo != 1)
			{
				return true;
			}
			instance.RequestLobbyReturn();
			return false;
		}

		private static void PrepareMatchPauseMenu(EscapeMenuHandler __instance)
		{
			Plugin instance = Instance;
			instance?._steamMenu?.RefreshPause(__instance, instance.CanReturnToLobby && GameManager.instance.isPlaying);
		}

		internal void ReadyInLobby()
		{
			//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_004f: Unknown result type (might be due to invalid IL or missing references)
			if (CanReadyInLobby)
			{
				LobbyReadySelected = !LobbyReadySelected;
				_lobbyReadyRevision++;
				if (PhotonNetwork.IsMasterClient)
				{
					LobbyReadiness hostLobbyReadiness = HostLobbyReadiness;
					QueueLobbyState(((LobbyReadiness)(ref hostLobbyReadiness)).SetReady(((LobbyReadiness)(ref _lobbyReadiness)).Cycle, true, _lobbyReadyRevision, LobbyReadySelected));
				}
				else
				{
					SendGuestLobbyVote();
				}
			}
		}

		internal void RequestLobbyReturn()
		{
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			//IL_0025: Unknown result type (might be due to invalid IL or missing references)
			if (CanReturnToLobby)
			{
				if (PhotonNetwork.IsMasterClient)
				{
					LobbyReadiness hostLobbyReadiness = HostLobbyReadiness;
					QueueLobbyState(((LobbyReadiness)(ref hostLobbyReadiness)).Return(((LobbyReadiness)(ref _lobbyReadiness)).Cycle));
				}
				else if (!SendRequestToHost(new int[2]
				{
					1,
					((LobbyReadiness)(ref _lobbyReadiness)).Cycle
				}))
				{
					FailMatchLobby(SteamMenuText.Translate("Не удалось отправить команду возврата в лобби.", "The return-to-lobby request could not be sent."));
				}
			}
		}

		private void SendGuestLobbyVote()
		{
			_nextLobbyVoteSend = _clock.Elapsed.TotalSeconds + 0.25;
			if (!SendRequestToHost(new int[4]
			{
				0,
				((LobbyReadiness)(ref _lobbyReadiness)).Cycle,
				_lobbyReadyRevision,
				LobbyReadySelected ? 1 : 0
			}))
			{
				WriteTrace("lobby_ready_send_rejected", $"cycle={((LobbyReadiness)(ref _lobbyReadiness)).Cycle};revision={_lobbyReadyRevision};retry_pending");
			}
		}

		private static bool SendRequestToHost(int[] request)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: Expected O, but got Unknown
			//IL_0026: Unknown result type (might be due to invalid IL or missing references)
			RaiseEventOptions val = new RaiseEventOptions();
			val.TargetActors = new int[1] { PhotonNetwork.MasterClient.ActorNumber };
			return PhotonNetwork.RaiseEvent((byte)171, (object)request, val, SendOptions.SendReliable);
		}

		private void PumpMatchLobby()
		{
			if (!HasOpponent)
			{
				return;
			}
			double totalSeconds = _clock.Elapsed.TotalSeconds;
			if (PhotonNetwork.IsMasterClient)
			{
				if (_pendingLobbyState.HasValue && totalSeconds >= _nextLobbyStateSend)
				{
					SendPendingLobbyState();
				}
			}
			else if (!((LobbyReadiness)(ref _lobbyReadiness)).MatchAllowed && _lobbyReadyRevision > ((LobbyReadiness)(ref _lobbyReadiness)).GuestRevision && totalSeconds >= _nextLobbyVoteSend)
			{
				SendGuestLobbyVote();
			}
		}

		private void OnMatchLobbyEvent(EventData data)
		{
			//IL_009f: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e2: Unknown result type (might be due to invalid IL or missing references)
			if (data.Code != 171 || !HasOpponent || !(data.CustomData is int[] array))
			{
				return;
			}
			try
			{
				if (PhotonNetwork.IsMasterClient)
				{
					HandleGuestLobbyRequest(data.Sender, array);
				}
				else
				{
					if (data.Sender != PhotonNetwork.MasterClient.ActorNumber || array.Length != 7 || array[0] != 2)
					{
						return;
					}
					int num = array[2];
					if (num < 0 || num > 3 || array[3] < 0 || array[4] < 0)
					{
						return;
					}
					LobbyReadiness state = default(LobbyReadiness);
					((LobbyReadiness)(ref state))..ctor(array[1], (num & 1) != 0, (num & 2) != 0, array[5], array[6]);
					if (((LobbyReadiness)(ref state)).CanFollow(_lobbyReadiness))
					{
						GetLobbyActors(out var host, out var guest);
						LobbyMatchScore? matchScore = _matchScore;
						if (matchScore != null)
						{
							matchScore.SetWins(host, array[3]);
						}
						LobbyMatchScore? matchScore2 = _matchScore;
						if (matchScore2 != null)
						{
							matchScore2.SetWins(guest, array[4]);
						}
						ApplyLobbyState(state);
					}
				}
			}
			catch (Exception ex)
			{
				FailMatchLobby(ex.Message);
			}
		}

		private void HandleGuestLobbyRequest(int actor, int[] message)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_005a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0079: Unknown result type (might be due to invalid IL or missing references)
			LobbyReadiness hostLobbyReadiness = HostLobbyReadiness;
			GetLobbyActors(out var _, out var guest);
			if (actor != guest || message.Length < 2 || message[1] != ((LobbyReadiness)(ref hostLobbyReadiness)).Cycle)
			{
				return;
			}
			switch ((LobbyMessage)message[0])
			{
			case LobbyMessage.Ready:
				if (message.Length == 4 && message[2] > 0 && (message[3] == 0 || message[3] == 1))
				{
					QueueLobbyState(((LobbyReadiness)(ref hostLobbyReadiness)).SetReady(message[1], false, message[2], message[3] == 1));
				}
				break;
			case LobbyMessage.Return:
				if (message.Length == 2 && CanReturnToLobby)
				{
					QueueLobbyState(((LobbyReadiness)(ref hostLobbyReadiness)).Return(message[1]));
				}
				break;
			}
		}

		private void QueueLobbyState(LobbyReadiness state)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			_pendingLobbyState = state;
			SendPendingLobbyState();
		}

		private void SendPendingLobbyState()
		{
			//IL_0014: Unknown result type (might be due to invalid IL or missing references)
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bd: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d3: Expected O, but got Unknown
			//IL_0104: Unknown result type (might be due to invalid IL or missing references)
			if (_pendingLobbyState.HasValue)
			{
				LobbyReadiness value = _pendingLobbyState.Value;
				_nextLobbyStateSend = _clock.Elapsed.TotalSeconds + 0.25;
				GetLobbyActors(out var host, out var guest);
				int num = (((LobbyReadiness)(ref value)).HostReady ? 1 : 0) | (((LobbyReadiness)(ref value)).GuestReady ? 2 : 0);
				int[] obj = new int[7]
				{
					2,
					((LobbyReadiness)(ref value)).Cycle,
					num,
					0,
					0,
					0,
					0
				};
				LobbyMatchScore? matchScore = _matchScore;
				obj[3] = ((matchScore != null) ? matchScore.WinsFor(host) : 0);
				LobbyMatchScore? matchScore2 = _matchScore;
				obj[4] = ((matchScore2 != null) ? matchScore2.WinsFor(guest) : 0);
				obj[5] = ((LobbyReadiness)(ref value)).HostRevision;
				obj[6] = ((LobbyReadiness)(ref value)).GuestRevision;
				if (!PhotonNetwork.RaiseEvent((byte)171, (object)obj, new RaiseEventOptions
				{
					Receivers = (ReceiverGroup)0
				}, SendOptions.SendReliable))
				{
					WriteTrace("lobby_state_send_rejected", $"cycle={((LobbyReadiness)(ref value)).Cycle};retry_pending");
					return;
				}
				_pendingLobbyState = null;
				ApplyLobbyState(value);
			}
		}

		private void ResetLobbyVote()
		{
			_lobbyReadyRevision = 0;
			LobbyReadySelected = false;
			_nextLobbyVoteSend = 0.0;
		}

		private void ApplyLobbyState(LobbyReadiness state)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			//IL_0009: Unknown result type (might be due to invalid IL or missing references)
			LobbyReadiness lobbyReadiness = _lobbyReadiness;
			_lobbyReadiness = state;
			if (((LobbyReadiness)(ref state)).Cycle != ((LobbyReadiness)(ref lobbyReadiness)).Cycle)
			{
				Plugin.EnterRematchLobbyCycle(((LobbyReadiness)(ref state)).Cycle);
				ResetLobbyVote();
				_steamPlayerJoined = false;
				_matchHud.Hide();
				StopMatchForReload();
				if (PhotonNetwork.IsMasterClient)
				{
					PhotonNetwork.DestroyAll();
				}
				_lobbyReload = ((MonoBehaviour)this).StartCoroutine(ReloadIntoMatchLobby());
			}
			else if (((LobbyReadiness)(ref state)).MatchAllowed && !((LobbyReadiness)(ref lobbyReadiness)).MatchAllowed)
			{
				Plugin.EnterRematchLobbyCycle(((LobbyReadiness)(ref state)).Cycle);
				LobbyMatchScore? matchScore = _matchScore;
				if (matchScore != null)
				{
					matchScore.BeginMatch();
				}
				_steamMenu?.CloseForMatch();
				ShowMatchLoading();
				LoadingScreen.instance.StopLoading();
				WriteTrace("lobby_match_start", $"cycle={((LobbyReadiness)(ref state)).Cycle};both_ready");
			}
		}

		private static void StopMatchForReload()
		{
			GameManager.instance.battleOngoing = false;
			GM_ArmsRace instance = GM_ArmsRace.instance;
			if (instance != null)
			{
				((MonoBehaviour)instance).StopAllCoroutines();
			}
			PlayerManager instance2 = PlayerManager.instance;
			if (instance2 != null)
			{
				((MonoBehaviour)instance2).StopAllCoroutines();
			}
			CardChoice instance3 = CardChoice.instance;
			if ((Object)(object)instance3 != (Object)null)
			{
				instance3.IsPicking = false;
				((MonoBehaviour)instance3).StopAllCoroutines();
			}
			MapManager instance4 = MapManager.instance;
			if ((Object)(object)instance4 != (Object)null)
			{
				((MonoBehaviour)instance4).StopAllCoroutines();
				SceneManager.sceneLoaded -= (UnityAction<Scene, LoadSceneMode>)(object)AccessTools.Method(typeof(MapManager), "OnLevelFinishedLoading", (Type[])null, (Type[])null).CreateDelegate(typeof(UnityAction<Scene, LoadSceneMode>), instance4);
			}
		}

		private IEnumerator ReloadIntoMatchLobby()
		{
			GameManager oldGame = GameManager.instance;
			EscapeMenuHandler.isEscMenu = false;
			oldGame.GoToMenu();
			double deadline = _clock.Elapsed.TotalSeconds + _timeout.Value;
			do
			{
				yield return null;
				if (!UsesMatchLobby || !PhotonNetwork.InRoom)
				{
					yield break;
				}
				if (_clock.Elapsed.TotalSeconds >= deadline)
				{
					_lobbyReload = null;
					FailMatchLobby(SteamMenuText.Translate("Не удалось вернуться в лобби.", "The game could not return to the lobby."));
					yield break;
				}
			}
			while ((Object)(object)GameManager.instance == (Object)null || (Object)(object)GameManager.instance == (Object)(object)oldGame || (Object)(object)ListMenu.instance == (Object)null || !ListMenu.instance.IsInitialized);
			SkipIntro obj = Object.FindObjectOfType<SkipIntro>(true);
			if (obj != null)
			{
				obj.Skip();
			}
			ShowSteamLobbyPage();
			_lobbyReload = null;
			WriteTrace("lobby_returned", $"cycle={((LobbyReadiness)(ref _lobbyReadiness)).Cycle};actor={PhotonNetwork.LocalPlayer.ActorNumber};" + $"wins={LobbyPlayer(isHost: true).Wins}:{LobbyPlayer(isHost: false).Wins}");
		}

		private void FailMatchLobby(string message)
		{
			if (_usingSteam && _steam != null)
			{
				_steam.Fail(message);
			}
			else
			{
				Fail(message);
			}
		}

		private static void GetLobbyActors(out int host, out int guest)
		{
			int num;
			if (!PhotonNetwork.InRoom)
			{
				num = 0;
			}
			else
			{
				Player masterClient = PhotonNetwork.MasterClient;
				num = ((masterClient != null) ? masterClient.ActorNumber : 0);
			}
			host = num;
			guest = 0;
			if (host == 0)
			{
				return;
			}
			foreach (Player value in PhotonNetwork.CurrentRoom.Players.Values)
			{
				if (value.ActorNumber != host)
				{
					guest = value.ActorNumber;
				}
			}
		}

		private static void InstallSteamHooks(Harmony harmony)
		{
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			//IL_0035: Expected O, but got Unknown
			//IL_005d: Unknown result type (might be due to invalid IL or missing references)
			//IL_006b: Expected O, but got Unknown
			//IL_00ae: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bc: Expected O, but got Unknown
			//IL_00ee: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fc: Expected O, but got Unknown
			//IL_0124: Unknown result type (might be due to invalid IL or missing references)
			//IL_0132: Expected O, but got Unknown
			harmony.Patch((MethodBase)AccessTools.Method(typeof(MainMenuHandler), "PlayOnlineMultiplayer", (Type[])null, (Type[])null), new HarmonyMethod(typeof(Plugin), "OpenSteamOnline", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			harmony.Patch((MethodBase)AccessTools.Method(typeof(CheckUserPrivilegeButton), "TestPrivilege", (Type[])null, (Type[])null), new HarmonyMethod(typeof(Plugin), "OpenSteamOnlineFromMainMenu", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			string[] array = new string[2] { "HostPrivateRoom", "HostPrivateAndInviteFriend" };
			foreach (string text in array)
			{
				harmony.Patch((MethodBase)AccessTools.Method(typeof(NetworkConnectionHandler), text, (Type[])null, (Type[])null), new HarmonyMethod(typeof(Plugin), "CreateSteamLobbyFromStockRoom", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			}
			harmony.Patch((MethodBase)AccessTools.Method(typeof(ClientSteamLobby), "OnLobbyJoinRequest", (Type[])null, (Type[])null), new HarmonyMethod(typeof(Plugin), "HandleSteamInvite", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			harmony.Patch((MethodBase)AccessTools.Method(typeof(NetworkConnectionHandler), "RPCA_FoundGame", (Type[])null, (Type[])null), new HarmonyMethod(typeof(Plugin), "UseStockMatchLoading", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
		}

		private void InitializeSteamFeatures()
		{
			//IL_00bb: Unknown result type (might be due to invalid IL or missing references)
			_steamMenu = new NativeSteamMenu(this);
			if (!SteamManager.Initialized)
			{
				_steamUnavailable = SteamMenuText.Translate("Steam недоступен. Запустите Steam и войдите в аккаунт.", "Steam is unavailable. Start Steam and sign in.");
				return;
			}
			_steam = new SteamLobbySession(this, GameFingerprint());
			string s = null;
			string[] commandLineArgs = Environment.GetCommandLineArgs();
			for (int i = 0; i + 1 < commandLineArgs.Length; i++)
			{
				if (commandLineArgs[i] == "+connect_lobby")
				{
					s = commandLineArgs[i + 1];
				}
			}
			string text = default(string);
			SteamApps.GetLaunchCommandLine(ref text, 2048);
			Match match = Regex.Match(text ?? string.Empty, "(?:^|\\s)\\+connect_lobby\\s+(\\d+)");
			if (match.Success)
			{
				s = match.Groups[1].Value;
			}
			if (ulong.TryParse(s, out var result))
			{
				_steam.ReceiveInvite(new CSteamID(result), null);
			}
			if (Array.IndexOf(commandLineArgs, "--rounds-p2p-steam-ui-smoke") >= 0)
			{
				((MonoBehaviour)this).StartCoroutine(SteamUiSmoke());
			}
		}

		private static bool OpenSteamOnline()
		{
			if ((Object)(object)Instance == (Object)null)
			{
				return true;
			}
			try
			{
				Instance._steamMenu?.OpenOnline();
			}
			catch (Exception ex)
			{
				Instance.ShowSteamFailure(ex.Message);
			}
			return false;
		}

		private static bool OpenSteamOnlineFromMainMenu(CheckUserPrivilegeButton __instance)
		{
			ListMenuPage val = MainMenuHandler.instance?.MainMenu;
			if ((Object)(object)val == (Object)null || !((Component)__instance).transform.IsChildOf(((Component)val).transform))
			{
				return true;
			}
			Instance?.WriteTrace("steam_online_routed", "main_menu_privilege_button");
			return OpenSteamOnline();
		}

		private static bool CreateSteamLobbyFromStockRoom()
		{
			if (Instance?._steamMenu == null)
			{
				return true;
			}
			Instance.CreateSteamLobby();
			Instance._steamMenu.ShowLobby();
			return false;
		}

		private static bool HandleSteamInvite(ClientSteamLobby __instance, GameLobbyJoinRequested_t param)
		{
			//IL_0024: 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_002a: 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)
			Plugin instance = Instance;
			if (instance?._steam == null)
			{
				return true;
			}
			CSteamID lobby = param.m_steamIDLobby;
			instance._steam.ReceiveInvite(lobby, delegate
			{
				//IL_0025: Unknown result type (might be due to invalid IL or missing references)
				AccessTools.Method(typeof(ClientSteamLobby), "JoinLobby", (Type[])null, (Type[])null).Invoke(__instance, new object[1] { lobby });
			});
			return false;
		}

		private static bool UseStockMatchLoading()
		{
			Plugin? instance = Instance;
			if (instance == null)
			{
				return true;
			}
			return !instance.UsesMatchLobby;
		}

		private void ShowMatchLoading()
		{
			_matchUiOwner = NetworkConnectionHandler.instance;
			CharacterCreatorHandler instance = CharacterCreatorHandler.instance;
			if (instance != null)
			{
				instance.CloseMenus();
			}
			MainMenuHandler.instance.Close();
			TimeHandler.instance.gameStartTime = 1f;
			LoadingScreen.instance.StartLoading(true);
		}

		internal void CreateSteamLobby()
		{
			try
			{
				if (_steam == null)
				{
					throw new InvalidOperationException(SteamStatus);
				}
				_steam.Create();
			}
			catch (Exception ex)
			{
				ShowSteamFailure(ex.Message);
			}
		}

		internal void InviteSteamFriend()
		{
			try
			{
				_steam?.Invite();
			}
			catch (Exception ex)
			{
				ShowSteamFailure(ex.Message);
			}
		}

		internal void LeaveSteamLobby()
		{
			if (_steam != null)
			{
				_steam.Leave();
			}
			else
			{
				StopSteamPhoton();
			}
		}

		internal void ShowSteamFailure(string message)
		{
			_steamUnavailable = message;
			WriteTrace("steam_error", message);
			((BaseUnityPlugin)this).Logger.LogError((object)message);
			_steamMenu?.Refresh();
		}

		internal PrototypeOptions StartSteamHost(string room)
		{
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			//IL_002d: Expected O, but got Unknown
			int num = FreeUdpPort();
			int num2;
			do
			{
				num2 = FreeUdpPort();
			}
			while (num2 == num);
			PrototypeOptions val = new PrototypeOptions((PrototypeRole)1, "127.0.0.1", "127.0.0.1", room, num, num2, 40.0);
			BeginSteam(val);
			return val;
		}

		internal void StartSteamClient(int master, int game, string room)
		{
			//IL_0018: Unknown result type (might be due to invalid IL or missing references)
			//IL_0022: Expected O, but got Unknown
			BeginSteam(new PrototypeOptions((PrototypeRole)2, "127.0.0.1", "127.0.0.1", room, master, game, 40.0));
		}

		private void BeginSteam(PrototypeOptions options)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			Begin(options.Role, options);
			if (!_active)
			{
				throw new InvalidOperationException("Не удалось подготовить игровую сессию.");
			}
		}

		internal void StopSteamPhoton()
		{
			if (_usingSteam)
			{
				StopSessionAndRestoreMenu();
			}
		}

		private void StopSessionAndRestoreMenu()
		{
			NetworkConnectionHandler matchUiOwner = _matchUiOwner;
			StopSession();
			if ((Object)(object)matchUiOwner != (Object)null && (Object)(object)matchUiOwner == (Object)(object)NetworkConnectionHandler.instance)
			{
				matchUiOwner.NetworkRestart();
			}
		}

		internal void ShowSteamLobbyPage()
		{
			if (!((LobbyReadiness)(ref _lobbyReadiness)).MatchAllowed)
			{
				_steamMenu?.ShowLobby();
			}
		}

		internal void SimulateSteamFailureForSmoke()
		{
			if (!SmokeEnabled || _steam == null || !_active || (Object)(object)_matchUiOwner == (Object)null)
			{
				throw new InvalidOperationException("Steam failure smoke requires an active local match and a running Steam client.");
			}
			_usingSteam = true;
			_steam.Fail("Тестовое завершение соединения.");
		}

		private void UpdateSteamFeatures()
		{
			try
			{
				_steam?.Pump();
				_steamMenu?.Refresh();
				if (HasOpponent && ((LobbyReadiness)(ref _lobbyReadiness)).MatchAllowed && !_steamPlayerJoined && (Object)(object)GM_ArmsRace.instance != (Object)null && ((Component)GM_ArmsRace.instance).gameObject.activeInHierarchy && (Object)(object)LoadingScreen.instance != (Object)null && !LoadingScreen.instance.IsLoading)
				{
					_steamPlayerJoined = true;
					PlayerAssigner.instance.CreatePlayer((InputDevice)null, false);
					WriteTrace("steam_player_joined", "stock_player_assignment");
				}
			}
			catch (Exception ex)
			{
				if (_lobbySmoke)
				{
					Fail(ex.Message);
				}
				else
				{
					_steam?.Fail(ex.Message);
				}
			}
		}

		private static int FreeUdpPort()
		{
			using UdpClient udpClient = new UdpClient(new IPEndPoint(IPAddress.Loopback, 0));
			return ((IPEndPoint)udpClient.Client.LocalEndPoint).Port;
		}

		private static string GameFingerprint()
		{
			StringBuilder stringBuilder = new StringBuilder();
			using SHA256 sHA = SHA256.Create();
			string[] array = new string[4] { "Assembly-CSharp.dll", "Photon3Unity3D.dll", "PhotonRealtime.dll", "PhotonUnityNetworking.dll" };
			foreach (string text in array)
			{
				using FileStream inputStream = File.OpenRead(Path.Combine(Application.dataPath, "Managed", text));
				stringBuilder.Append(text).Append(':').Append(BitConverter.ToString(sHA.ComputeHash(inputStream)));
			}
			return BitConverter.ToString(sHA.ComputeHash(Encoding.ASCII.GetBytes(stringBuilder.ToString()))).Replace("-", string.Empty).ToLowerInvariant();
		}

		private IEnumerator SteamUiSmoke()
		{
			while ((Object)(object)ListMenu.instance == (Object)null || !ListMenu.instance.IsInitialized)
			{
				yield return null;
			}
			bool verifyNetworkOwnership = Array.IndexOf(Environment.GetCommandLineArgs(), "--rounds-p2p-steam-network-ownership-smoke") >= 0;
			if (verifyNetworkOwnership)
			{
				NetworkConnectionHandler stockHandler = NetworkConnectionHandler.instance;
				LoadingScreen stockLoading = LoadingScreen.instance;
				ClientState stockState = PhotonNetwork.NetworkClientState;
				stockLo

BepInEx\plugins\P2P\RoundsP2P.Core.dll

Decompiled a day ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security.Cryptography;
using System.Text;
using Microsoft.CodeAnalysis;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.0", FrameworkDisplayName = ".NET Standard 2.0")]
[assembly: AssemblyCompany("RoundsP2P.Core")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0+c9b03c0ff381adab9c0ba8924ab03e2818cd50b0")]
[assembly: AssemblyProduct("RoundsP2P.Core")]
[assembly: AssemblyTitle("RoundsP2P.Core")]
[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]
	internal sealed class IsReadOnlyAttribute : Attribute
	{
	}
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

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

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

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

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace RoundsP2P.Core
{
	public sealed class LobbyMatchScore
	{
		private readonly Dictionary<int, int> _wins = new Dictionary<int, int>();

		private bool _matchCompleted;

		public int WinsFor(int actorNumber)
		{
			if (!_wins.TryGetValue(actorNumber, out var value))
			{
				return 0;
			}
			return value;
		}

		public bool RecordMatchWinner(int actorNumber)
		{
			if (actorNumber <= 0 || _matchCompleted)
			{
				return false;
			}
			_wins[actorNumber] = WinsFor(actorNumber) + 1;
			_matchCompleted = true;
			return true;
		}

		public void BeginMatch()
		{
			_matchCompleted = false;
		}

		public void SetWins(int actorNumber, int wins)
		{
			_wins[actorNumber] = wins;
		}
	}
	public readonly struct LobbyReadiness
	{
		public int Cycle { get; }

		public bool HostReady { get; }

		public bool GuestReady { get; }

		public int HostRevision { get; }

		public int GuestRevision { get; }

		public bool MatchAllowed
		{
			get
			{
				if (HostReady)
				{
					return GuestReady;
				}
				return false;
			}
		}

		public LobbyReadiness(int cycle, bool hostReady, bool guestReady, int hostRevision = 0, int guestRevision = 0)
		{
			Cycle = cycle;
			HostReady = hostReady;
			GuestReady = guestReady;
			HostRevision = hostRevision;
			GuestRevision = guestRevision;
		}

		public LobbyReadiness SetReady(int cycle, bool isHost, int revision, bool ready)
		{
			if (cycle != Cycle || MatchAllowed || revision <= (isHost ? HostRevision : GuestRevision))
			{
				return this;
			}
			if (!isHost)
			{
				return new LobbyReadiness(Cycle, HostReady, ready, HostRevision, revision);
			}
			return new LobbyReadiness(Cycle, ready, GuestReady, revision, GuestRevision);
		}

		public LobbyReadiness Return(int cycle)
		{
			if (cycle != Cycle || !MatchAllowed)
			{
				return this;
			}
			return new LobbyReadiness(Cycle + 1, hostReady: false, guestReady: false);
		}

		public bool CanFollow(LobbyReadiness previous)
		{
			if (Cycle != previous.Cycle)
			{
				if (previous.MatchAllowed && Cycle == previous.Cycle + 1 && !HostReady && !GuestReady && HostRevision == 0)
				{
					return GuestRevision == 0;
				}
				return false;
			}
			if (previous.MatchAllowed)
			{
				if (MatchAllowed && HostRevision == previous.HostRevision)
				{
					return GuestRevision == previous.GuestRevision;
				}
				return false;
			}
			if (FollowsVote(HostRevision, HostReady, previous.HostRevision, previous.HostReady))
			{
				return FollowsVote(GuestRevision, GuestReady, previous.GuestRevision, previous.GuestReady);
			}
			return false;
		}

		private static bool FollowsVote(int revision, bool ready, int previousRevision, bool previousReady)
		{
			if (revision <= previousRevision)
			{
				if (revision == previousRevision)
				{
					return ready == previousReady;
				}
				return false;
			}
			return true;
		}
	}
	public static class LuxonConfig
	{
		public static string Render(PrototypeOptions options)
		{
			if (options == null)
			{
				throw new ArgumentNullException("options");
			}
			StringBuilder stringBuilder = new StringBuilder();
			stringBuilder.Append("Servers:\n");
			AppendServer(stringBuilder, "MasterServer", options.AdvertisedAddress, options.MasterPort);
			AppendServer(stringBuilder, "GameServer", options.AdvertisedAddress, options.GamePort);
			stringBuilder.Append("EnableIPv6: false\nHTTP:\n  enabled: false\n");
			return stringBuilder.ToString();
		}

		private static void AppendServer(StringBuilder config, string type, string address, int port)
		{
			string value = port.ToString(CultureInfo.InvariantCulture);
			config.Append("  ").Append(type).Append(":\n")
				.Append("    - port: ")
				.Append(value)
				.Append('\n')
				.Append("      external_address: ")
				.Append(address)
				.Append(':')
				.Append(value)
				.Append('\n');
		}
	}
	public sealed class LuxonServerProcess : IDisposable
	{
		public const string ExpectedSha256 = "d5b272f49b21757d36094f30f986e4f4d2f1502eec79be33ce998ea19fff3286";

		private readonly Process process;

		private readonly int masterPort;

		private readonly int gamePort;

		private readonly Stopwatch startupClock = new Stopwatch();

		private long nextProbeAtMilliseconds = 250L;

		private bool listening;

		private bool disposed;

		public bool HasExited
		{
			get
			{
				if (!disposed)
				{
					return process.HasExited;
				}
				return true;
			}
		}

		public int ProcessId { get; }

		public bool IsListening
		{
			get
			{
				if (HasExited)
				{
					return false;
				}
				long elapsedMilliseconds = startupClock.ElapsedMilliseconds;
				if (!listening && elapsedMilliseconds >= nextProbeAtMilliseconds)
				{
					nextProbeAtMilliseconds = elapsedMilliseconds + 100;
					listening = IsPortOccupied(masterPort) && IsPortOccupied(gamePort);
				}
				return listening;
			}
		}

		public LuxonServerProcess(string executablePath, string workingDirectory, PrototypeOptions options, Action<string> log)
		{
			if (options == null)
			{
				throw new ArgumentNullException("options");
			}
			if (options.Role != PrototypeRole.Host)
			{
				throw new ArgumentException("Only the host may start the local server.", "options");
			}
			if (log == null)
			{
				throw new ArgumentNullException("log");
			}
			if (string.IsNullOrWhiteSpace(executablePath))
			{
				throw new ArgumentException("An executable path is required.", "executablePath");
			}
			if (string.IsNullOrWhiteSpace(workingDirectory))
			{
				throw new ArgumentException("A dedicated working directory is required.", "workingDirectory");
			}
			string fullPath = Path.GetFullPath(executablePath);
			string fullPath2 = Path.GetFullPath(workingDirectory);
			if (File.Exists(fullPath2))
			{
				throw new ArgumentException("The working directory path points to a file.", "workingDirectory");
			}
			masterPort = options.MasterPort;
			gamePort = options.GamePort;
			using FileStream inputStream = new FileStream(fullPath, FileMode.Open, FileAccess.Read, FileShare.Read);
			string a;
			using (SHA256 sHA = SHA256.Create())
			{
				a = BitConverter.ToString(sHA.ComputeHash(inputStream)).Replace("-", string.Empty).ToLowerInvariant();
			}
			if (!string.Equals(a, "d5b272f49b21757d36094f30f986e4f4d2f1502eec79be33ce998ea19fff3286", StringComparison.Ordinal))
			{
				throw new InvalidDataException("Luxon executable SHA-256 does not match the pinned v1.5 release.");
			}
			EnsurePortsAvailable(masterPort, gamePort);
			Directory.CreateDirectory(fullPath2);
			using (FileStream stream = new FileStream(Path.Combine(fullPath2, "config.yml"), FileMode.CreateNew, FileAccess.Write, FileShare.Read))
			{
				using StreamWriter streamWriter = new StreamWriter(stream, new UTF8Encoding(encoderShouldEmitUTF8Identifier: false));
				streamWriter.Write(LuxonConfig.Render(options));
			}
			process = new Process
			{
				StartInfo = new ProcessStartInfo
				{
					FileName = fullPath,
					WorkingDirectory = fullPath2,
					UseShellExecute = false,
					CreateNoWindow = true,
					WindowStyle = ProcessWindowStyle.Hidden,
					RedirectStandardOutput = true,
					RedirectStandardError = true
				}
			};
			process.OutputDataReceived += delegate(object _, DataReceivedEventArgs args)
			{
				LogSafely(log, args.Data);
			};
			process.ErrorDataReceived += delegate(object _, DataReceivedEventArgs args)
			{
				LogSafely(log, args.Data);
			};
			bool flag = false;
			try
			{
				flag = process.Start();
				if (!flag)
				{
					throw new InvalidOperationException("Luxon process did not start.");
				}
				startupClock.Start();
				ProcessId = process.Id;
				process.BeginOutputReadLine();
				process.BeginErrorReadLine();
			}
			catch
			{
				try
				{
					if (flag)
					{
						StopOwnedProcess(process);
					}
				}
				finally
				{
					process.Dispose();
				}
				throw;
			}
		}

		public void Dispose()
		{
			if (disposed)
			{
				return;
			}
			try
			{
				StopOwnedProcess(process);
			}
			finally
			{
				disposed = true;
				process.Dispose();
			}
		}

		private static void StopOwnedProcess(Process ownedProcess)
		{
			if (!ownedProcess.HasExited)
			{
				try
				{
					ownedProcess.Kill();
				}
				catch (InvalidOperationException) when (ownedProcess.HasExited)
				{
				}
			}
			if (!ownedProcess.WaitForExit(5000))
			{
				throw new TimeoutException("The owned Luxon process did not exit within five seconds.");
			}
		}

		private static void EnsurePortsAvailable(int masterPort, int gamePort)
		{
			using Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
			using Socket socket2 = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
			socket.ExclusiveAddressUse = true;
			socket2.ExclusiveAddressUse = true;
			socket.Bind(new IPEndPoint(IPAddress.Any, masterPort));
			socket2.Bind(new IPEndPoint(IPAddress.Any, gamePort));
		}

		private static bool IsPortOccupied(int port)
		{
			using Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
			socket.ExclusiveAddressUse = true;
			try
			{
				socket.Bind(new IPEndPoint(IPAddress.Any, port));
				return false;
			}
			catch (SocketException ex) when (ex.SocketErrorCode == SocketError.AddressAlreadyInUse || ex.SocketErrorCode == SocketError.AccessDenied)
			{
				return true;
			}
		}

		private static void LogSafely(Action<string> log, string? message)
		{
			if (message == null)
			{
				return;
			}
			try
			{
				log(message);
			}
			catch
			{
			}
		}
	}
	public static class PhotonWireCompatibility
	{
		public static void NormalizeRoomOptions(IDictionary<byte, object> operation, bool usePropertiesKey)
		{
			if (operation == null)
			{
				throw new ArgumentNullException("operation");
			}
			byte key = (byte)(usePropertiesKey ? 251 : 248);
			if (operation.TryGetValue(key, out object value) && value is IDictionary<object, object> dictionary && dictionary.TryGetValue(byte.MaxValue, out var value2) && value2 is int num)
			{
				if (num < 0 || num > 255)
				{
					throw new NotSupportedException("Luxon v1.5 supports MaxPlayers values between 0 and 255.");
				}
				dictionary[byte.MaxValue] = checked((byte)num);
			}
		}
	}
	public sealed class PrototypeOptions
	{
		public PrototypeRole Role { get; }

		public string HostAddress { get; }

		public string AdvertisedAddress { get; }

		public string RoomName { get; }

		public int MasterPort { get; }

		public int GamePort { get; }

		public double TimeoutSeconds { get; }

		public PrototypeOptions(PrototypeRole role, string hostAddress, string advertisedAddress, string roomName, int masterPort = 5055, int gamePort = 5056, double timeoutSeconds = 20.0)
		{
			if (role != PrototypeRole.Disabled && role != PrototypeRole.Host && role != PrototypeRole.Client)
			{
				throw new ArgumentOutOfRangeException("role");
			}
			ValidateAddress(hostAddress, "hostAddress");
			ValidateAddress(advertisedAddress, "advertisedAddress");
			ValidateRoomName(roomName);
			ValidatePort(masterPort, "masterPort");
			ValidatePort(gamePort, "gamePort");
			if (masterPort == gamePort)
			{
				throw new ArgumentException("Master and game servers need different UDP ports.", "gamePort");
			}
			if (double.IsNaN(timeoutSeconds) || double.IsInfinity(timeoutSeconds) || timeoutSeconds < 1.0 || timeoutSeconds > 120.0)
			{
				throw new ArgumentOutOfRangeException("timeoutSeconds", "Timeout must be between 1 and 120 seconds.");
			}
			Role = role;
			HostAddress = hostAddress;
			AdvertisedAddress = advertisedAddress;
			RoomName = roomName;
			MasterPort = masterPort;
			GamePort = gamePort;
			TimeoutSeconds = timeoutSeconds;
		}

		private static void ValidateAddress(string address, string parameterName)
		{
			if (address == null)
			{
				throw new ArgumentNullException(parameterName);
			}
			if (address.Length < 7 || address.Length > 15)
			{
				throw InvalidAddress(parameterName);
			}
			string[] array = address.Split(new char[1] { '.' });
			if (array.Length != 4)
			{
				throw InvalidAddress(parameterName);
			}
			int num = -1;
			for (int i = 0; i < array.Length; i++)
			{
				string text = array[i];
				if (text.Length == 0 || text.Length > 3 || (text.Length > 1 && text[0] == '0'))
				{
					throw InvalidAddress(parameterName);
				}
				int num2 = 0;
				string text2 = text;
				foreach (char c in text2)
				{
					if (c < '0' || c > '9')
					{
						throw InvalidAddress(parameterName);
					}
					num2 = num2 * 10 + c - 48;
				}
				if (num2 > 255)
				{
					throw InvalidAddress(parameterName);
				}
				if (i == 0)
				{
					num = num2;
				}
			}
			if (num == 0 || num >= 224)
			{
				throw InvalidAddress(parameterName);
			}
		}

		private static ArgumentException InvalidAddress(string parameterName)
		{
			return new ArgumentException("Use a canonical unicast IPv4 address, such as 127.0.0.1 or 192.168.1.10.", parameterName);
		}

		private static void ValidateRoomName(string roomName)
		{
			if (roomName == null)
			{
				throw new ArgumentNullException("roomName");
			}
			if (roomName.Length < 1 || roomName.Length > 48)
			{
				throw new ArgumentException("Room names must contain 1 to 48 ASCII letters, digits, hyphens or underscores.", "roomName");
			}
			foreach (char c in roomName)
			{
				if ((c < 'a' || c > 'z') && (c < 'A' || c > 'Z') && (c < '0' || c > '9') && c != '-' && c != '_')
				{
					throw new ArgumentException("Room names must contain 1 to 48 ASCII letters, digits, hyphens or underscores.", "roomName");
				}
			}
		}

		private static void ValidatePort(int port, string parameterName)
		{
			if (port < 1024 || port > 65535)
			{
				throw new ArgumentOutOfRangeException(parameterName, "Use a UDP port between 1024 and 65535.");
			}
		}
	}
	public enum PrototypeRole
	{
		Disabled,
		Host,
		Client
	}
	public sealed class SteamLobbyDescriptor
	{
		public const string MarkerKey = "r2p_mod";

		public const string MarkerValue = "rounds-p2p";

		public const string Protocol = "6";

		public ulong HostId { get; }

		public string GameFingerprint { get; }

		public string RoomName { get; }

		public bool IsReady { get; }

		public SteamLobbyDescriptor(ulong hostId, string gameFingerprint, string roomName, bool isReady)
		{
			if (hostId == 0L)
			{
				throw new ArgumentOutOfRangeException("hostId");
			}
			if (gameFingerprint == null)
			{
				throw new ArgumentNullException("gameFingerprint");
			}
			if (!IsHex(gameFingerprint, 64, allowUppercase: true))
			{
				throw new ArgumentException("The game fingerprint must contain exactly 64 hexadecimal characters.", "gameFingerprint");
			}
			if (roomName == null)
			{
				throw new ArgumentNullException("roomName");
			}
			if (!IsHex(roomName, 32, allowUppercase: false))
			{
				throw new ArgumentException("The room name must contain exactly 32 lowercase hexadecimal characters.", "roomName");
			}
			HostId = hostId;
			GameFingerprint = gameFingerprint.ToLowerInvariant();
			RoomName = roomName;
			IsReady = isReady;
		}

		public Dictionary<string, string> ToMetadata()
		{
			return new Dictionary<string, string>(StringComparer.Ordinal)
			{
				{ "r2p_mod", "rounds-p2p" },
				{ "r2p_protocol", "6" },
				{ "r2p_gamefingerprint", GameFingerprint },
				{
					"r2p_host",
					HostId.ToString(CultureInfo.InvariantCulture)
				},
				{ "r2p_room", RoomName },
				{
					"r2p_ready",
					IsReady ? "1" : "0"
				}
			};
		}

		public static bool TryParse(IReadOnlyDictionary<string, string> metadata, ulong actualOwner, string expectedFingerprint, out SteamLobbyDescriptor? descriptor, out string error)
		{
			descriptor = null;
			error = string.Empty;
			if (metadata == null || !metadata.TryGetValue("r2p_mod", out string value) || value != "rounds-p2p")
			{
				return Reject("This is not a ROUNDS P2P lobby.", out error);
			}
			if (!metadata.TryGetValue("r2p_protocol", out string value2) || value2 != "6")
			{
				return Reject("The lobby uses an unsupported protocol version.", out error);
			}
			if (actualOwner == 0L)
			{
				return Reject("The lobby has no valid Steam owner.", out error);
			}
			if (!metadata.TryGetValue("r2p_host", out string value3) || !ulong.TryParse(value3, NumberStyles.None, CultureInfo.InvariantCulture, out var result) || result == 0L || value3 != result.ToString(CultureInfo.InvariantCulture))
			{
				return Reject("The lobby host identifier is invalid.", out error);
			}
			if (result != actualOwner)
			{
				return Reject("The lobby owner changed or does not match its declared host.", out error);
			}
			if (!metadata.TryGetValue("r2p_gamefingerprint", out string value4) || !IsHex(value4, 64, allowUppercase: true))
			{
				return Reject("The lobby game fingerprint is invalid.", out error);
			}
			if (!IsHex(expectedFingerprint, 64, allowUppercase: true))
			{
				return Reject("The local game fingerprint is invalid.", out error);
			}
			if (!string.Equals(value4, expectedFingerprint, StringComparison.OrdinalIgnoreCase))
			{
				return Reject("The lobby uses a different game build.", out error);
			}
			if (!metadata.TryGetValue("r2p_room", out string value5) || !IsHex(value5, 32, allowUppercase: false))
			{
				return Reject("The lobby room identifier is invalid.", out error);
			}
			if (!metadata.TryGetValue("r2p_ready", out string value6) || (value6 != "0" && value6 != "1"))
			{
				return Reject("The lobby readiness flag is invalid.", out error);
			}
			descriptor = new SteamLobbyDescriptor(result, value4, value5, value6 == "1");
			return true;
		}

		public static bool CanAdmitPeer(ulong peerId, ulong localHostId, ulong actualOwner, IEnumerable<ulong> members)
		{
			if (peerId == 0L || localHostId == 0L || peerId == localHostId || actualOwner != localHostId || members == null)
			{
				return false;
			}
			HashSet<ulong> hashSet = new HashSet<ulong>();
			foreach (ulong member in members)
			{
				if (member == 0L)
				{
					return false;
				}
				hashSet.Add(member);
				if (hashSet.Count > 2)
				{
					return false;
				}
			}
			if (hashSet.Count == 2 && hashSet.Contains(peerId))
			{
				return hashSet.Contains(localHostId);
			}
			return false;
		}

		private static bool IsHex(string value, int requiredLength, bool allowUppercase)
		{
			if (value == null || value.Length != requiredLength)
			{
				return false;
			}
			foreach (char c in value)
			{
				if ((c < '0' || c > '9') && (c < 'a' || c > 'f') && (!allowUppercase || c < 'A' || c > 'F'))
				{
					return false;
				}
			}
			return true;
		}

		private static bool Reject(string message, out string error)
		{
			error = message;
			return false;
		}
	}
}
namespace RoundsP2P.Core.Tunnel
{
	public static class DatagramFrame
	{
		public const int HeaderLength = 6;

		public const int MaxPayloadLength = 1200;

		public const int MaxFrameLength = 1206;

		public static byte[] Encode(DatagramRoute route, byte[] payload)
		{
			if (route != DatagramRoute.Master && route != DatagramRoute.Game)
			{
				throw new ArgumentOutOfRangeException("route");
			}
			if (payload == null)
			{
				throw new ArgumentNullException("payload");
			}
			if (payload.Length == 0 || payload.Length > 1200)
			{
				throw new ArgumentException("Tunnel payload must contain 1 to 1200 bytes.", "payload");
			}
			byte[] array = new byte[6 + payload.Length];
			array[0] = 82;
			array[1] = 80;
			array[2] = 1;
			array[3] = (byte)route;
			array[4] = (byte)(payload.Length >> 8);
			array[5] = (byte)payload.Length;
			Buffer.BlockCopy(payload, 0, array, 6, payload.Length);
			return array;
		}

		public static bool TryDecode(byte[] frame, out DatagramRoute route, out byte[] payload)
		{
			route = (DatagramRoute)0;
			payload = Array.Empty<byte>();
			if (frame == null || frame.Length <= 6 || frame.Length > 1206 || frame[0] != 82 || frame[1] != 80 || frame[2] != 1 || (frame[3] != 1 && frame[3] != 2))
			{
				return false;
			}
			int num = (frame[4] << 8) | frame[5];
			if (num == 0 || num > 1200 || frame.Length != 6 + num)
			{
				return false;
			}
			route = (DatagramRoute)frame[3];
			payload = new byte[num];
			Buffer.BlockCopy(frame, 6, payload, 0, num);
			return true;
		}
	}
	public enum DatagramRoute : byte
	{
		Master = 1,
		Game
	}
	public sealed class UdpTunnel : IDisposable
	{
		private readonly Socket[] sockets;

		private readonly IPEndPoint?[] clients = new IPEndPoint[2];

		private readonly Action<byte[]> sendFrame;

		private readonly bool host;

		private readonly byte[] receiveBuffer = new byte[1201];

		private bool disposed;

		private int nextRoute;

		public int MasterPort { get; }

		public int GamePort { get; }

		private UdpTunnel(bool host, int backendMasterPort, int backendGamePort, Action<byte[]> sendFrame)
		{
			this.sendFrame = sendFrame ?? throw new ArgumentNullException("sendFrame");
			this.host = host;
			sockets = new Socket[2];
			try
			{
				sockets[0] = CreateSocket(host ? backendMasterPort : 0);
				sockets[1] = CreateSocket(host ? backendGamePort : 0);
				MasterPort = ((IPEndPoint)sockets[0].LocalEndPoint).Port;
				GamePort = ((IPEndPoint)sockets[1].LocalEndPoint).Port;
			}
			catch
			{
				Socket[] array = sockets;
				for (int i = 0; i < array.Length; i++)
				{
					array[i]?.Dispose();
				}
				throw;
			}
		}

		public static UdpTunnel CreateClient(Action<byte[]> sendFrame)
		{
			return new UdpTunnel(host: false, 0, 0, sendFrame);
		}

		public static UdpTunnel CreateHost(int backendMasterPort, int backendGamePort, Action<byte[]> sendFrame)
		{
			ValidatePort(backendMasterPort, "backendMasterPort");
			ValidatePort(backendGamePort, "backendGamePort");
			if (backendMasterPort == backendGamePort)
			{
				throw new ArgumentException("Master and game backend ports must differ.", "backendGamePort");
			}
			return new UdpTunnel(host: true, backendMasterPort, backendGamePort, sendFrame);
		}

		public void Pump(int maxDatagrams = 64)
		{
			ThrowIfDisposed();
			if (maxDatagrams < 1 || maxDatagrams > 4096)
			{
				throw new ArgumentOutOfRangeException("maxDatagrams");
			}
			int num = 0;
			int num2 = 0;
			while (num < maxDatagrams && num2 < 2)
			{
				int num3 = nextRoute;
				nextRoute = 1 - nextRoute;
				if (!TryReceive(num3, out var length))
				{
					num2++;
					continue;
				}
				num2 = 0;
				num++;
				if (length > 0 && length <= 1200)
				{
					byte[] array = new byte[length];
					Buffer.BlockCopy(receiveBuffer, 0, array, 0, length);
					sendFrame(DatagramFrame.Encode((num3 == 0) ? DatagramRoute.Master : DatagramRoute.Game, array));
				}
			}
		}

		public bool ReceiveFrame(byte[] frame)
		{
			ThrowIfDisposed();
			if (!DatagramFrame.TryDecode(frame, out DatagramRoute route, out byte[] payload))
			{
				return false;
			}
			int num = ((route != DatagramRoute.Master) ? 1 : 0);
			if (!host && clients[num] == null)
			{
				return false;
			}
			try
			{
				return (host ? sockets[num].Send(payload) : sockets[num].SendTo(payload, clients[num])) == payload.Length;
			}
			catch (SocketException ex) when (IsTransientDatagramError(ex.SocketErrorCode))
			{
				return false;
			}
		}

		public void Dispose()
		{
			if (!disposed)
			{
				disposed = true;
				Socket[] array = sockets;
				for (int i = 0; i < array.Length; i++)
				{
					array[i].Dispose();
				}
			}
		}

		private static Socket CreateSocket(int backendPort)
		{
			Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
			try
			{
				socket.ExclusiveAddressUse = true;
				socket.Bind(new IPEndPoint(IPAddress.Loopback, 0));
				if (backendPort != 0)
				{
					socket.Connect(new IPEndPoint(IPAddress.Loopback, backendPort));
				}
				socket.Blocking = false;
				return socket;
			}
			catch
			{
				socket.Dispose();
				throw;
			}
		}

		private bool TryReceive(int index, out int length)
		{
			length = 0;
			try
			{
				if (host)
				{
					length = sockets[index].Receive(receiveBuffer);
				}
				else
				{
					EndPoint remoteEP = new IPEndPoint(IPAddress.Loopback, 0);
					length = sockets[index].ReceiveFrom(receiveBuffer, ref remoteEP);
					if (remoteEP is IPEndPoint iPEndPoint && IPAddress.IsLoopback(iPEndPoint.Address))
					{
						clients[index] = iPEndPoint;
					}
					else
					{
						length = 0;
					}
				}
				return true;
			}
			catch (SocketException ex) when (ex.SocketErrorCode == SocketError.MessageSize)
			{
				length = 1201;
				return true;
			}
			catch (SocketException ex2) when (IsTransientDatagramError(ex2.SocketErrorCode))
			{
				return false;
			}
		}

		private static bool IsTransientDatagramError(SocketError error)
		{
			if (error != SocketError.WouldBlock && error != SocketError.IOPending && error != SocketError.NoBufferSpaceAvailable && error != SocketError.ConnectionReset)
			{
				return error == SocketError.ConnectionRefused;
			}
			return true;
		}

		private static void ValidatePort(int port, string name)
		{
			if (port < 1 || port > 65535)
			{
				throw new ArgumentOutOfRangeException(name);
			}
		}

		private void ThrowIfDisposed()
		{
			if (disposed)
			{
				throw new ObjectDisposedException("UdpTunnel");
			}
		}
	}
}