Decompiled source of RoundsP2P v1.0.0

BepInEx\plugins\RoundsP2P\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+fe1c869d4241016dd5b49a12e89370b67b476259")]
[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]
	[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 int? _pendingWinner;

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

		public void RecordMatchWinner(int actorNumber)
		{
			if (actorNumber > 0 && !_pendingWinner.HasValue)
			{
				_pendingWinner = actorNumber;
			}
		}

		public bool StartRematch()
		{
			if (!_pendingWinner.HasValue)
			{
				return false;
			}
			int value = _pendingWinner.Value;
			_wins[value] = WinsFor(value) + 1;
			_pendingWinner = null;
			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 = "2";

		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", "2" },
				{ "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 != "2")
			{
				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");
			}
		}
	}
}

BepInEx\plugins\RoundsP2P\RoundsP2P.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.Reflection.Emit;
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 RoundsP2P.Core;
using RoundsP2P.Core.Tunnel;
using Steamworks;
using TMPro;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.Events;
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("RoundsP2P")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0+fe1c869d4241016dd5b49a12e89370b67b476259")]
[assembly: AssemblyProduct("RoundsP2P")]
[assembly: AssemblyTitle("RoundsP2P")]
[assembly: AssemblyVersion("1.0.0.0")]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

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

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

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

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace 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
	{
		[Serializable]
		[CompilerGenerated]
		private sealed class <>c
		{
			public static readonly <>c <>9 = new <>c();

			public static UnityAction <>9__13_1;

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

		private readonly Plugin _plugin;

		private ListMenuPage? _sourcePage;

		private ListMenuPage? _onlinePage;

		private ListMenuPage? _lobbyPage;

		private Button? _createButton;

		private Button? _inviteButton;

		private TextMeshProUGUI? _onlineStatus;

		private TextMeshProUGUI? _lobbyStatus;

		internal NativeSteamMenu(Plugin plugin)
		{
			_plugin = plugin ?? throw new ArgumentNullException("plugin");
		}

		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))
			{
				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)_lobbyStatus != (Object)null && ((TMP_Text)_lobbyStatus).text != text)
				{
					((TMP_Text)_lobbyStatus).text = text;
				}
				if ((Object)(object)_createButton != (Object)null)
				{
					((Selectable)_createButton).interactable = !_plugin.HasSteamLobby;
				}
				if ((Object)(object)_inviteButton != (Object)null)
				{
					((Selectable)_inviteButton).interactable = _plugin.CanInviteSteamFriend;
				}
			}
		}

		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_00d1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00db: Expected O, but got Unknown
			//IL_015b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0165: Expected O, but got Unknown
			//IL_0178: Unknown result type (might be due to invalid IL or missing references)
			//IL_0182: Expected O, but got Unknown
			//IL_00fb: Unknown result type (might be due to invalid IL or missing references)
			//IL_0100: Unknown result type (might be due to invalid IL or missing references)
			//IL_0106: 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("Главное меню ещё загружается.");
			}
			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("Не удалось подготовить меню онлайн-игры.");
			}
			try
			{
				_onlinePage = CreatePage("RoundsP2P.Online", _sourcePage, out Transform grid);
				_onlineStatus = CreateStatus(val, grid, "OnlineStatus");
				_createButton = CreateButton(val, grid, "Создать лобби", (UnityAction)delegate
				{
					_plugin.CreateSteamLobby();
					ShowLobby();
				});
				Transform parent = grid;
				object obj = <>c.<>9__13_1;
				if (obj == null)
				{
					UnityAction val2 = delegate
					{
						ListMenu.instance.CloseTopPage();
					};
					<>c.<>9__13_1 = val2;
					obj = (object)val2;
				}
				CreateButton(val, parent, "Назад", (UnityAction)obj);
				FinishPage(_onlinePage, _createButton);
				_lobbyPage = CreatePage("RoundsP2P.Lobby", _sourcePage, out Transform grid2);
				_lobbyStatus = CreateStatus(val, grid2, "LobbyStatus");
				_inviteButton = CreateButton(val, grid2, "Пригласить друга", new UnityAction(_plugin.InviteSteamFriend));
				CreateButton(val, grid2, "Покинуть лобби", (UnityAction)delegate
				{
					_plugin.LeaveSteamLobby();
					CloseOwnedTopPages();
					OpenOnline();
				});
				FinishPage(_lobbyPage, _inviteButton);
			}
			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_002c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0032: Expected O, but got Unknown
			if (((Component)source).transform.childCount == 0)
			{
				throw new InvalidOperationException("Штатная страница меню не содержит список кнопок.");
			}
			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 label, UnityAction action)
		{
			//IL_002e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0038: Expected O, but got Unknown
			//IL_0047: Unknown result type (might be due to invalid IL or missing references)
			//IL_0055: Unknown result type (might be due to invalid IL or missing references)
			//IL_007a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0084: Expected O, but got Unknown
			//IL_00bf: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c4: Unknown result type (might be due to invalid IL or missing references)
			GameObject val = Object.Instantiate<GameObject>(((Component)template).gameObject, parent, false);
			((Object)val).name = "RoundsP2P." + label;
			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, label);
			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)
		{
			//IL_007a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0081: Unknown result type (might be due to invalid IL or missing references)
			GameObject val = 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 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 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;
			_inviteButton = null;
			_onlineStatus = null;
			_lobbyStatus = 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()
		{
			DestroyPages();
		}
	}
	[BepInPlugin("local.rounds.p2p.prototype", "ROUNDS P2P Mode", "1.0.0")]
	public sealed class Plugin : BaseUnityPlugin
	{
		public const string Id = "local.rounds.p2p.prototype";

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

		public const string ProtocolVersion = "rounds-p2p-prototype-0.1";

		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 SandboxInputFont _sandboxInputFont = new SandboxInputFont();

		private readonly MatchHud _matchHud = new MatchHud();

		private LobbyMatchScore? _matchScore;

		private bool _hudSmoke;

		private const string RematchReadyKey = "r2p_rematch_map";

		private MapWrapper? _mapBeforeRematch;

		private int _rematchNumber;

		private bool _rematchArmed;

		private bool _rematchPreparing;

		private SteamLobbySession? _steam;

		private NativeSteamMenu? _steamMenu;

		private PrototypeOptions? _steamOptions;

		private bool _usingSteam;

		private bool _steamPlayerJoined;

		private int _savedMtu;

		private string _steamUnavailable = "Создайте лобби, чтобы пригласить друга через Steam.";

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

		internal bool SmokeEnabled { get; private set; }

		internal bool Active => _active;

		internal string SteamStatus => _steam?.Status ?? _steamUnavailable;

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

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

		private void Awake()
		{
			//IL_0194: Unknown result type (might be due to invalid IL or missing references)
			//IL_019e: Expected O, but got Unknown
			//IL_01f4: Unknown result type (might be due to invalid IL or missing references)
			//IL_0201: Expected O, but got Unknown
			//IL_0249: Unknown result type (might be due to invalid IL or missing references)
			//IL_0257: Expected O, but got Unknown
			//IL_027b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0285: 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;
			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);
			InstallRematchHooks(_wireHarmony);
			_sandboxInputFont.Install(_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);
			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();
			if (Array.IndexOf(Environment.GetCommandLineArgs(), "--rounds-p2p-sandbox-font-smoke") >= 0)
			{
				int.TryParse(CommandLineValue("--rounds-p2p-steam-ui-hold="), out var result);
				yield return SandboxFontSmoke.Run(this, Math.Max(0, Math.Min(120, result)));
				yield break;
			}
			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)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_006f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0074: 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_00cf: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d9: Expected O, but got Unknown
			//IL_0120: Unknown result type (might be due to invalid IL or missing references)
			//IL_0122: Invalid comparison between Unknown and I4
			//IL_0179: Unknown result type (might be due to invalid IL or missing references)
			//IL_0183: Expected O, but got Unknown
			if ((int)role == 0)
			{
				return;
			}
			if (_active || PhotonNetwork.IsConnected || ((Object)(object)GameManager.instance != (Object)null && GameManager.instance.isPlaying))
			{
				throw new InvalidOperationException("Leave the current game/connection before starting the prototype.");
			}
			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;
			_active = true;
			_matchScore = ((!_usingSteam && !_hudSmoke) ? ((LobbyMatchScore)null) : new LobbyMatchScore());
			_rematchNumber = 0;
			_rematchArmed = false;
			_rematchPreparing = false;
			_seenRoom = false;
			_connecting = true;
			_operationError = null;
			PhotonNetwork.NetworkingClient.OpResponseReceived += OnOperationResponse;
			_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));
			}
			catch (Exception ex)
			{
				Fail(ex.Message);
			}
		}

		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-prototype-0.1",
				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;
			}
			FieldInfo fieldInfo = AccessTools.Field(typeof(NetworkConnectionHandler), "m_searchingType");
			fieldInfo.SetValue(NetworkConnectionHandler.instance, Enum.Parse(fieldInfo.FieldType, "HostRoom"));
			if (!_usingSteam)
			{
				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 = "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();
				}
			}
		}

		private unsafe void Update()
		{
			//IL_0030: Unknown result type (might be due to invalid IL or missing references)
			//IL_0035: Unknown result type (might be due to invalid IL or missing references)
			//IL_0036: Unknown result type (might be due to invalid IL or missing references)
			//IL_0038: Unknown result type (might be due to invalid IL or missing references)
			//IL_0040: Unknown result type (might be due to invalid IL or missing references)
			//IL_0041: Unknown result type (might be due to invalid IL or missing references)
			if (Input.GetKeyDown((KeyCode)289))
			{
				_panel = !_panel;
			}
			PumpStoppedPhoton();
			UpdateSteamFeatures();
			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.";
					StopSession();
				}
				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_0153: Unknown result type (might be due to invalid IL or missing references)
			//IL_0158: 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>()))
				{
					StopSession();
					NetworkConnectionHandler.instance.NetworkRestart();
				}
			}
			GUILayout.EndArea();
		}

		private void Fail(string message)
		{
			_status = "ERROR: " + message;
			_panel = true;
			((BaseUnityPlugin)this).Logger.LogError((object)_status);
			WriteTrace("error", message);
			StopSession();
			if ((Object)(object)LoadingScreen.instance != (Object)null && LoadingScreen.instance.IsLoading)
			{
				NetworkConnectionHandler instance = NetworkConnectionHandler.instance;
				if (instance != null)
				{
					instance.NetworkRestart();
				}
			}
		}

		private void StopSession()
		{
			//IL_00cf: Unknown result type (might be due to invalid IL or missing references)
			//IL_0115: Unknown result type (might be due to invalid IL or missing references)
			//IL_011c: Invalid comparison between Unknown and I4
			if (!_active)
			{
				return;
			}
			_active = false;
			_matchScore = null;
			_mapBeforeRematch = null;
			_rematchArmed = false;
			_rematchPreparing = false;
			_matchHud.Hide();
			_connecting = false;
			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;
				_steamOptions = null;
				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();
			_sandboxInputFont.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), "CommitRematchScore", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
		}

		private static void RecordMatchWinner(int winningTeamID)
		{
			Plugin instance = Instance;
			if (instance?._matchScore != null && PhotonNetwork.InRoom && PhotonNetwork.CurrentRoom.PlayerCount == 2)
			{
				instance._matchScore.RecordMatchWinner(ActorForTeam(winningTeamID));
				instance._mapBeforeRematch = MapManager.instance?.currentMap;
			}
		}

		private static void CommitRematchScore()
		{
			Plugin instance = Instance;
			if (instance?._matchScore != null && PhotonNetwork.InRoom && PhotonNetwork.CurrentRoom.PlayerCount == 2)
			{
				if (instance._matchScore.StartRematch())
				{
					instance.WriteTrace("lobby_rematch_score", $"team0={instance.MatchWinsForTeam(0)};team1={instance.MatchWinsForTeam(1)}");
				}
				instance._rematchNumber++;
				instance._rematchArmed = true;
			}
		}

		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 || (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);
			}
		}

		private void InstallRematchHooks(Harmony harmony)
		{
			//IL_0029: 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_0094: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a1: Expected O, but got Unknown
			//IL_00c9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d7: Expected O, but got Unknown
			harmony.Patch((MethodBase)AccessTools.Method(typeof(GM_ArmsRace), "GameOverRematch", (Type[])null, (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, new HarmonyMethod(typeof(Plugin), "ReplacePreviewLoad", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null);
			harmony.Patch((MethodBase)AccessTools.Method(typeof(GM_ArmsRace), "GetRematchYesNo", (Type[])null, (Type[])null), new HarmonyMethod(typeof(Plugin), "DismissRematchPrompt", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			harmony.Patch((MethodBase)AccessTools.Method(typeof(GM_ArmsRace), "DoStartGame", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(typeof(Plugin), "WrapRematchStart", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			harmony.Patch((MethodBase)AccessTools.Method(typeof(GM_ArmsRace), "PlayerDied", (Type[])null, (Type[])null), new HarmonyMethod(typeof(Plugin), "AllowRoundEnding", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
		}

		private static IEnumerable<CodeInstruction> ReplacePreviewLoad(IEnumerable<CodeInstruction> instructions)
		{
			MethodInfo load = AccessTools.Method(typeof(MapManager), "LoadNextLevel", (Type[])null, (Type[])null);
			MethodInfo operand = AccessTools.Method(typeof(Plugin), "LoadRematchPreview", (Type[])null, (Type[])null);
			List<CodeInstruction> list = new List<CodeInstruction>(instructions);
			CodeInstruction? obj = list.Find((CodeInstruction code) => CodeInstructionExtensions.Calls(code, load)) ?? throw new InvalidOperationException("RoundsP2P could not locate the stock rematch map preload.");
			obj.opcode = OpCodes.Call;
			obj.operand = operand;
			return list;
		}

		private static void LoadRematchPreview(MapManager manager, bool callInImmediately, bool forceLoad)
		{
			Plugin instance = Instance;
			if (instance?._matchScore == null)
			{
				manager.LoadNextLevel(callInImmediately, forceLoad);
			}
			else
			{
				instance.WriteTrace("rematch_preview_skipped", "map_is_requested_after_both_votes");
			}
		}

		private static void DismissRematchPrompt()
		{
			if (Instance?._matchScore != null)
			{
				PopUpHandler val = UIHandler.instance?.popUpHandler;
				if (!((Object)(object)val == (Object)null))
				{
					val.yesPart.Stop();
					val.noPart.Stop();
					val.yesAnim.PlayOut();
					val.noAnim.PlayOut();
				}
			}
		}

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

		private static void WrapRematchStart(GM_ArmsRace __instance, ref IEnumerator __result)
		{
			Plugin instance = Instance;
			if (instance != null && instance._rematchArmed && instance._matchScore != null)
			{
				instance._rematchArmed = false;
				__result = instance.RunRematchStart(__instance, __result, instance._matchScore, instance._mapBeforeRematch, instance._rematchNumber);
			}
		}

		private IEnumerator RunRematchStart(GM_ArmsRace game, IEnumerator original, LobbyMatchScore session, MapWrapper? oldMap, int number)
		{
			_rematchPreparing = true;
			bool waitedForLoad = false;
			try
			{
				while (IsRematchActive(game, session, number) && original.MoveNext())
				{
					if (!waitedForLoad && original.Current is WaitForSecondsRealtime)
					{
						yield return WaitForBothMaps(game, session, oldMap, number);
						waitedForLoad = true;
					}
					else
					{
						yield return original.Current;
					}
				}
				if (IsRematchActive(game, session, number))
				{
					GameManager.instance.battleOngoing = false;
					while (IsRematchActive(game, session, number) && !PlayersAndMapEntered())
					{
						yield return null;
					}
					if (IsRematchActive(game, session, number))
					{
						GameManager.instance.battleOngoing = true;
						WriteTrace("rematch_battle_ready", "cards_finished;map_entered;players_spawned");
					}
				}
			}
			finally
			{
				Plugin plugin = this;
				(original as IDisposable)?.Dispose();
				if (plugin._matchScore == session && plugin._rematchNumber == number)
				{
					plugin._rematchPreparing = false;
				}
			}
		}

		private IEnumerator WaitForBothMaps(GM_ArmsRace game, LobbyMatchScore session, MapWrapper? oldMap, int number)
		{
			string ready = null;
			while (IsRematchActive(game, session, number))
			{
				MapManager instance = MapManager.instance;
				MapWrapper val = instance?.currentMap;
				if (ready == null && val != null && val != oldMap)
				{
					Scene scene;
					if (oldMap != null)
					{
						scene = oldMap.Scene;
						if (((Scene)(ref scene)).isLoaded)
						{
							goto IL_00ed;
						}
					}
					scene = val.Scene;
					if (((Scene)(ref scene)).isLoaded && (Object)(object)val.Map != (Object)null && instance.currentLevelID >= 0)
					{
						string text = $"{number}:{instance.currentLevelID}";
						Player localPlayer = PhotonNetwork.LocalPlayer;
						Hashtable val2 = new Hashtable();
						((Dictionary<object, object>)val2).Add((object)"r2p_rematch_map", (object)text);
						if (localPlayer.SetCustomProperties(val2, (Hashtable)null, (WebFlags)null))
						{
							ready = text;
						}
					}
				}
				goto IL_00ed;
				IL_00ed:
				if (ready != null && BothPlayersLoaded(ready))
				{
					WriteTrace("rematch_map_ready", "both_clients_loaded_matching_map");
					break;
				}
				yield return null;
			}
		}

		private bool IsRematchActive(GM_ArmsRace game, LobbyMatchScore session, int number)
		{
			if (_matchScore == session && _rematchNumber == number && (Object)(object)game != (Object)null && ((Behaviour)game).isActiveAndEnabled && PhotonNetwork.InRoom)
			{
				return PhotonNetwork.CurrentRoom.PlayerCount == 2;
			}
			return false;
		}

		private static bool BothPlayersLoaded(string ready)
		{
			foreach (Player value2 in PhotonNetwork.CurrentRoom.Players.Values)
			{
				if (!((Dictionary<object, object>)(object)value2.CustomProperties).TryGetValue((object)"r2p_rematch_map", out object value) || value as string != ready)
				{
					return false;
				}
			}
			return true;
		}

		private static bool PlayersAndMapEntered()
		{
			MapManager instance = MapManager.instance;
			object obj;
			if (instance == null)
			{
				obj = null;
			}
			else
			{
				MapWrapper currentMap = instance.currentMap;
				obj = ((currentMap != null) ? currentMap.Map : null);
			}
			Map val = (Map)obj;
			List<Player> list = PlayerManager.instance?.players;
			if ((Object)(object)val == (Object)null || !val.hasEntered || list == null || list.Count != 2)
			{
				return false;
			}
			foreach (Player item in list)
			{
				if ((Object)(object)item == (Object)null || (Object)(object)item.data == (Object)null || !item.data.isPlaying || item.data.dead)
				{
					return false;
				}
			}
			return true;
		}

		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), "PrepareSteamMatchLoading", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
		}

		private void InitializeSteamFeatures()
		{
			//IL_00b1: Unknown result type (might be due to invalid IL or missing references)
			_steamMenu = new NativeSteamMenu(this);
			if (!SteamManager.Initialized)
			{
				_steamUnavailable = "Steam недоступен. Запустите Steam и войдите в аккаунт.";
				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 void PrepareSteamMatchLoading()
		{
			Plugin? instance = Instance;
			if (instance != null && instance._usingSteam)
			{
				Instance.ShowMatchLoading();
			}
		}

		private void ShowMatchLoading()
		{
			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(_steamUnavailable);
				}
				_steam.Create();
			}
			catch (Exception ex)
			{
				ShowSteamFailure(ex.Message);
			}
		}

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

		internal void LeaveSteamLobby()
		{
			_steam?.Leave();
			StopSession();
			if ((Object)(object)GameManager.instance != (Object)null && GameManager.instance.isPlaying)
			{
				NetworkConnectionHandler.instance.NetworkRestart();
			}
		}

		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_0017: Unknown result type (might be due to invalid IL or missing references)
			_usingSteam = true;
			_steamPlayerJoined = false;
			_steamOptions = options;
			Begin(options.Role);
			if (!_active)
			{
				throw new InvalidOperationException("Не удалось подготовить игровую сессию.");
			}
		}

		internal void StopSteamPhoton()
		{
			StopSession();
			if ((Object)(object)GameManager.instance != (Object)null && GameManager.instance.isPlaying)
			{
				NetworkConnectionHandler.instance.NetworkRestart();
			}
		}

		internal void ShowSteamLobbyPage()
		{
			_steamMenu?.ShowLobby();
		}

		internal void SimulateSteamFailureForSmoke()
		{
			if (!SmokeEnabled || _steam == null)
			{
				throw new InvalidOperationException("Steam failure smoke requires the explicit test driver and a running Steam client.");
			}
			_steam.Fail("Тестовое завершение соединения.");
		}

		private void UpdateSteamFeatures()
		{
			try
			{
				_steam?.Pump();
				_steamMenu?.Refresh();
				if (_usingSteam && !_steamPlayerJoined && !SmokeEnabled && PhotonNetwork.InRoom && PhotonNetwork.CurrentRoom.PlayerCount == 2 && (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)
			{
				_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;
			}
			ListMenuPage mainMenu = MainMenuHandler.instance.MainMenu;
			CheckUserPrivilegeButton componentInChildren = ((Component)mainMenu).GetComponentInChildren<CheckUserPrivilegeButton>(true);
			Button val = ((componentInChildren != null) ? ((Component)componentInChildren).GetComponent<Button>() : null);
			if ((Object)(object)val == (Object)null || !((Selectable)val).interactable)
			{
				FailSteamUiSmoke("Missing stock Online button.");
				yield break;
			}
			SkipIntro obj = Object.FindObjectOfType<SkipIntro>(true);
			if (obj != null)
			{
				obj.Skip();
			}
			mainMenu.Show();
			((UnityEvent)val.onClick).Invoke();
			yield return null;
			if (!_steamMenu.TryClickCreateLobbyForSmoke())
			{
				FailSteamUiSmoke("Stock Online button did not open the mod's Online page.");
				yield break;
			}
			WriteTrace("steam_ui_stock_online_verified", "clicked_native_online_and_create_lobby_buttons");
			double deadline = _clock.Elapsed.TotalSeconds + 45.0;
			while (_steam != null && !_steam.CanInvite && _clock.Elapsed.TotalSeconds < deadline)
			{
				yield return null;
			}
			SteamLobbySession? steam = _steam;
			if (steam == null || !steam.CanInvite)
			{
				WriteTrace("steam_ui_smoke_failed", SteamStatus);
				Application.Quit(2);
				yield break;
			}
			WriteTrace("steam_ui_smoke_ready", "lobby_created;host_photon_ready;invite_available;no_invites_sent");
			float result;
			float num = (float.TryParse(CommandLineValue("--rounds-p2p-steam-ui-hold="), out result) ? Math.Max(0f, Math.Min(120f, result)) : 15f);
			yield return (object)new WaitForSecondsRealtime(num);
			LeaveSteamLobby();
			WriteTrace("steam_ui_smoke_complete", "lobby_and_host_cleaned");
			Application.Quit(0);
		}

		private void FailSteamUiSmoke(string reason)
		{
			WriteTrace("steam_ui_smoke_failed", reason);
			Application.Quit(2);
		}
	}
	internal static class SandboxFontSmoke
	{
		internal static IEnumerator Run(Plugin plugin, int holdSeconds)
		{
			while ((Object)(object)ListMenu.instance == (Object)null || !ListMenu.instance.IsInitialized)
			{
				yield return null;
			}
			MainMenuHandler.instance.PlaySandbox();
			DevConsole console = Object.FindObjectOfType<DevConsole>();
			if ((Object)(object)console == (Object)null || (Object)(object)GM_Test.instance == (Object)null || !((Component)GM_Test.instance).gameObject.activeSelf)
			{
				plugin.WriteTrace("sandbox_font_smoke_failed", "sandbox or its input not found");
				Application.Quit(2);
				yield break;
			}
			TMP_InputField field = console.inputField;
			TMP_FontAsset originalFont = field.textComponent.font;
			for (int attempt = 0; attempt < 2; attempt++)
			{
				console.ToggleConsole();
				yield return null;
				field.SetTextWithoutNotify("Ёё Фрост Щит Яя ROUNDS 123");
				field.ForceLabelUpdate();
				field.textComponent.ForceMeshUpdate(false, false);
				TMP_TextInfo textInfo = field.textComponent.textInfo;
				bool rendered = field.text == "Ёё Фрост Щит Яя ROUNDS 123" && ((Component)field).gameObject.activeInHierarchy && textInfo.characterCount >= "Ёё Фрост Щит Яя ROUNDS 123".Length;
				int num = 0;
				while (rendered && num < "Ёё Фрост Щит Яя ROUNDS 123".Length)
				{
					TMP_TextElement textElement = textInfo.characterInfo[num].textElement;
					rendered = ((textElement != null) ? new uint?(textElement.unicode) : ((uint?)null)) == "Ёё Фрост Щит Яя ROUNDS 123"[num];
					num++;
				}
				if (rendered && attempt == 0 && holdSeconds > 0)
				{
					yield return (object)new WaitForSecondsRealtime((float)holdSeconds);
				}
				field.SetTextWithoutNotify(string.Empty);
				if (rendered)
				{
					CardInfo val = Array.Find(CardChoice.instance.cards, (CardInfo item) => (Object)(object)item != (Object)null && !string.IsNullOrEmpty(item.CardName));
					if ((Object)(object)val != (Object)null)
					{
						field.SetTextWithoutNotify(val.CardName);
					}
					else
					{
						rendered = false;
					}
				}
				if (!rendered)
				{
					plugin.WriteTrace("sandbox_font_smoke_failed", "rendered glyph codes or card catalog mismatch");
					Application.Quit(2);
					yield break;
				}
				console.ToggleConsole();
				if ((Object)(object)field.textComponent.font != (Object)(object)originalFont)
				{
					plugin.WriteTrace("sandbox_font_smoke_failed", "original font was not restored");
					Application.Quit(2);
					yield break;
				}
			}
			plugin.WriteTrace("sandbox_font_smoke_complete", "cyrillic_latin_digits_match_input_on_two_opens");
			Application.Quit(0);
		}
	}
	internal sealed class SandboxInputFont : IDisposable
	{
		private const string Cyrillic = "АБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдеёжзийклмнопрстуфхцчшщъыьэюя";

		private static SandboxInputFont? _instance;

		private TMP_Text? _label;

		private TMP_FontAsset? _original;

		private Material? _originalMaterial;

		private TMP_FontAsset? _localFont;

		private TMP_FontAsset? _generatedFallback;

		private Font? _systemFont;

		internal void Install(Harmony harmony)
		{
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			//IL_0035: Expected O, but got Unknown
			harmony.Patch((MethodBase)AccessTools.Method(typeof(DevConsole), "ToggleConsole", (Type[])null, (Type[])null), new HarmonyMethod(typeof(SandboxInputFont), "BeforeToggleConsole", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			_instance = this;
		}

		private static void BeforeToggleConsole(DevConsole __instance)
		{
			SandboxInputFont instance = _instance;
			if (instance == null)
			{
				return;
			}
			TMP_InputField inputField = __instance.inputField;
			GM_Test instance2 = GM_Test.instance;
			if ((Object)(object)inputField == (Object)null || ((Component)inputField).gameObject.activeSelf || (Object)(object)instance2 == (Object)null || !((Component)instance2).gameObject.activeSelf)
			{
				instance.RestoreLabel();
				return;
			}
			try
			{
				instance.Apply(inputField.textComponent);
			}
			catch (Exception ex)
			{
				instance.RestoreLabel();
				Plugin.Instance?.WriteTrace("sandbox_font_error", ex.Message);
			}
		}

		private void Apply(TMP_Text label)
		{
			if ((Object)(object)label == (Object)null || (Object)(object)label.font == (Object)null || ((Object)(object)_label == (Object)(object)label && (Object)(object)label.font == (Object)(object)_localFont))
			{
				return;
			}
			TMP_FontAsset font = label.font;
			uint[] array = default(uint[]);
			if (font.HasCharacters("АБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдеёжзийклмнопрстуфхцчшщъыьэюя", ref array, true, false))
			{
				return;
			}
			if ((Object)(object)_label != (Object)(object)label || (Object)(object)_original != (Object)(object)font)
			{
				ReleaseLocalFont();
				TMP_FontAsset val = FindFallback();
				if ((Object)(object)val == (Object)null)
				{
					return;
				}
				_localFont = Object.Instantiate<TMP_FontAsset>(font);
				((Object)_localFont).name = ((Object)font).name + " (ROUNDS P2P sandbox)";
				_localFont.fallbackFontAssetTable = ((font.fallbackFontAssetTable == null) ? new List<TMP_FontAsset>() : new List<TMP_FontAsset>(font.fallbackFontAssetTable));
				_localFont.fallbackFontAssetTable.Add(val);
				_label = label;
				_original = font;
				_originalMaterial = label.fontSharedMaterial;
				Plugin.Instance?.WriteTrace("sandbox_font_ready", ((Object)font).name + " => " + ((Object)val).name);
			}
			label.font = _localFont;
			if ((Object)(object)_originalMaterial != (Object)null)
			{
				label.fontSharedMaterial = _originalMaterial;
			}
		}

		private TMP_FontAsset? FindFallback()
		{
			TMP_FontAsset[] array = Resources.FindObjectsOfTypeAll<TMP_FontAsset>();
			foreach (TMP_FontAsset val in array)
			{
				if ((Object)(object)val != (Object)null && (Object)(object)val != (Object)(object)_localFont && val.HasCharacters("АБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдеёжзийклмнопрстуфхцчшщъыьэюя"))
				{
					return val;
				}
			}
			if ((Object)(object)_generatedFallback != (Object)null)
			{
				return _generatedFallback;
			}
			_systemFont = Font.CreateDynamicFontFromOSFont("Arial", 32);
			if ((Object)(object)_systemFont == (Object)null)
			{
				return null;
			}
			_generatedFallback = TMP_FontAsset.CreateFontAsset(_systemFont);
			uint[] array2 = default(uint[]);
			if ((Object)(object)_generatedFallback != (Object)null && _generatedFallback.HasCharacters("АБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдеёжзийклмнопрстуфхцчшщъыьэюя", ref array2, false, true))
			{
				return _generatedFallback;
			}
			ReleaseGeneratedFallback();
			return null;
		}

		private void RestoreLabel()
		{
			if ((Object)(object)_label != (Object)null && (Object)(object)_original != (Object)null && (Object)(object)_label.font == (Object)(object)_localFont)
			{
				_label.font = _original;
				if ((Object)(object)_originalMaterial != (Object)null)
				{
					_label.fontSharedMaterial = _originalMaterial;
				}
			}
		}

		private void ReleaseLocalFont()
		{
			RestoreLabel();
			if ((Object)(object)_localFont != (Object)null)
			{
				Object.Destroy((Object)(object)_localFont);
			}
			_localFont = null;
			_original = null;
			_originalMaterial = null;
			_label = null;
		}

		private void ReleaseGeneratedFallback()
		{
			if ((Object)(object)_generatedFallback != (Object)null)
			{
				Texture2D[] atlasTextures = _generatedFallback.atlasTextures;
				foreach (Texture2D val in atlasTextures)
				{
					if ((Object)(object)val != (Object)null)
					{
						Object.Destroy((Object)(object)val);
					}
				}
				if ((Object)(object)((TMP_Asset)_generatedFallback).material != (Object)null)
				{
					Object.Destroy((Object)(object)((TMP_Asset)_generatedFallback).material);
				}
				Object.Destroy((Object)(object)_generatedFallback);
				_generatedFallback = null;
			}
			if ((Object)(object)_systemFont != (Object)null)
			{
				Object.Destroy((Object)(object)_systemFont);
			}
			_systemFont = null;
		}

		public void Dispose()
		{
			if (_instance == this)
			{
				_instance = null;
			}
			ReleaseLocalFont();
			ReleaseGeneratedFallback();
		}
	}
	internal sealed class SmokeDriver : MonoBehaviour
	{
		private bool _joined;

		private bool _finished;

		private float _lastDamage;

		private float _started;

		private float _lastReport;

		private int _lastScore = -1;

		private bool _capacityVerified;

		private bool _initialHudVerified;

		private bool _matchEnded;

		private bool _rematchRequested;

		private bool _replayingDelayedLoad;

		private int _rematchMapRequests;

		private static readonly bool TestHud = Array.IndexOf(Environment.GetCommandLineArgs(), "--rounds-p2p-hud-smoke") >= 0;

		private readonly FieldInfo _cards = AccessTools.Field(typeof(CardChoice), "spawnedCards");

		private readonly FieldInfo _pickingAnimation = AccessTools.Field(typeof(CardChoice), "isPlaying");

		internal static void Install(Harmony harmony)
		{
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_0016: Expected O, but got Unknown
			//IL_0142: Unknown result type (might be due to invalid IL or missing references)
			//IL_014f: Expected O, but got Unknown
			//IL_017f: Unknown result type (might be due to invalid IL or missing references)
			//IL_018c: Expected O, but got Unknown
			//IL_01b4: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c2: Expected O, but got Unknown
			//IL_00fd: Unknown result type (might be due to invalid IL or missing references)
			//IL_010b: Expected O, but got Unknown
			HarmonyMethod val = new HarmonyMethod(typeof(SmokeDriver), "SuppressStats", (Type[])null);
			string[] array = new string[3] { "UnlockAchievement", "ProgressAchievement", "ClearAchievementsProgress" };
			foreach (string text in array)
			{
				harmony.Patch((MethodBase)AccessTools.Method(typeof(PlatformManager), text, (Type[])null, (Type[])null), val, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			}
			MethodInfo[] methods = typeof(SteamUserStats).GetMethods(BindingFlags.Static | BindingFlags.Public);
			foreach (MethodInfo methodInfo in methods)
			{
				if (methodInfo.ReturnType == typeof(bool) && Array.IndexOf(new string[7] { "SetAchievement", "SetStat", "UpdateAvgRateStat", "ClearAchievement", "ResetAllStats", "StoreStats", "IndicateAchievementProgress" }, methodInfo.Name) >= 0)
				{
					harmony.Patch((MethodBase)methodInfo, new HarmonyMethod(typeof(SmokeDriver), "SuppressSteamWrite", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				}
			}
			harmony.Patch((MethodBase)AccessTools.Method(typeof(GM_ArmsRace), "GameOver", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(typeof(SmokeDriver), "OnGameOver", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			if (TestHud)
			{
				harmony.Patch((MethodBase)AccessTools.Method(typeof(GM_ArmsRace), "GameOverRematch", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(typeof(SmokeDriver), "OnRematchPrompt", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				harmony.Patch((MethodBase)AccessTools.Method(typeof(MapManager), "RPCA_LoadLevel", (Type[])null, (Type[])null), new HarmonyMethod(typeof(SmokeDriver), "DelayRematchMapOnGuest", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			}
		}

		private static bool SuppressStats()
		{
			return false;
		}

		private static bool SuppressSteamWrite(ref bool __result)
		{
			__result = false;
			return false;
		}

		private void Start()
		{
			if (Array.IndexOf(Environment.GetCommandLineArgs(), "--rounds-p2p-mute") >= 0)
			{
				AudioListener.volume = 0f;
			}
			_started = Time.realtimeSinceStartup;
			Plugin.Instance.WriteTrace("smoke_started", "steam_stat_writes_suppressed;normal_rules_2_points_5_rounds");
		}

		private void Update()
		{
			//IL_05cf: Unknown result type (might be due to invalid IL or missing references)
			//IL_05db: Unknown result type (might be due to invalid IL or missing references)
			//IL_05e0: Unknown result type (might be due to invalid IL or missing references)
			if (_finished)
			{
				return;
			}
			Plugin instance = Plugin.Instance;
			if ((Object)(object)instance == (Object)null)
			{
				return;
			}
			if (Time.realtimeSinceStartup - _started > 300f)
			{
				instance.WriteTrace("smoke_failed", "timeout");
				_finished = true;
				Application.Quit(2);
				return;
			}
			if (Time.realtimeSinceStartup - _lastReport > 10f)
			{
				_lastReport = Time.realtimeSinceStartup;
				instance.WriteTrace("smoke_progress", "room=" + PhotonNetwork.InRoom + ";loading=" + ((Object)(object)LoadingScreen.instance != (Object)null && LoadingScreen.instance.IsLoading) + ";players=" + (((Object)(object)PlayerManager.instance == (Object)null) ? (-1) : PlayerManager.instance.players.Count));
			}
			if (!instance.Active || !PhotonNetwork.InRoom || PhotonNetwork.CurrentRoom.PlayerCount != 2)
			{
				return;
			}
			if (!_capacityVerified)
			{
				if (PhotonNetwork.CurrentRoom.MaxPlayers != 2)
				{
					instance.WriteTrace("smoke_failed", "wire_patch_did_not_enforce_max_players_2");
					_finished = true;
					Application.Quit(2);
					return;
				}
				_capacityVerified = true;
				instance.WriteTrace("smoke_capacity_verified", "max_players=2");
			}
			GM_ArmsRace instance2 = GM_ArmsRace.instance;
			LoadingScreen instance3 = LoadingScreen.instance;
			PlayerManager instance4 = PlayerManager.instance;
			if ((Object)(object)instance2 == (Object)null || (Object)(object)instance3 == (Object)null || (Object)(object)instance4 == (Object)null || !((Component)instance2).gameObject.activeInHierarchy || instance3.IsLoading)
			{
				return;
			}
			if (!_joined)
			{
				_joined = true;
				PlayerAssigner.instance.CreatePlayer((InputDevice)null, false);
				instance.WriteTrace("smoke_player_created", "actor=" + PhotonNetwork.LocalPlayer.ActorNumber);
			}
			CardChoice choice = CardChoice.instance;
			if ((Object)(object)choice != (Object)null && choice.IsPicking && choice.pickrID >= 0 && !(bool)_pickingAnimation.GetValue(choice))
			{
				if (_rematchRequested && !RematchPromptClosed())
				{
					instance.WriteTrace("smoke_failed", "rematch_prompt_visible_during_card_pick");
					_finished = true;
					Application.Quit(2);
					return;
				}
				Player val = instance4.players.Find((Player player) => player.PlayerID == choice.pickrID);
				List<GameObject> list = (List<GameObject>)_cards.GetValue(choice);
				if ((Object)(object)val != (Object)null && val.data.view.IsMine && list.Count > 0)
				{
					int pickrID = choice.pickrID;
					choice.Pick(list[0], false);
					choice.pickrID = -1;
					instance.WriteTrace("smoke_card_picked", "player=" + pickrID);
				}
			}
			int num = instance2.p1Rounds * 1000 + instance2.p2Rounds * 100 + instance2.p1Points * 10 + instance2.p2Points;
			if (num != _lastScore)
			{
				_lastScore = num;
				instance.WriteTrace("smoke_score", "rounds=" + instance2.p1Rounds + ":" + instance2.p2Rounds + ";points=" + instance2.p1Points + ":" + instance2.p2Points);
			}
			if (!GameManager.instance.battleOngoing || Time.realtimeSinceStartup - _lastDamage < 2f)
			{
				return;
			}
			int num2 = OrangeTeam();
			if (TestHud)
			{
				if (_rematchRequested)
				{
					if (!VerifyHud((num2 == 0) ? 1 : 0, (num2 == 1) ? 1 : 0))
					{
						return;
					}
					if (_rematchMapRequests == 1)
					{
						MapWrapper currentMap = MapManager.instance.currentMap;
						if (currentMap != null && currentMap.Map.hasEntered)
						{
							_finished = true;
							((MonoBehaviour)this).StartCoroutine(VerifyRematchStaysPlayable(instance, instance2, MapManager.instance.currentMap));
							return;
						}
					}
					instance.WriteTrace("smoke_failed", $"rematch_map_requests={_rematchMapRequests};expected=1;map_must_be_entered");
					_finished = true;
					Application.Quit(2);
					return;
				}
				if (!_initialHudVerified)
				{
					if (!VerifyHud(0, 0))
					{
						return;
					}
					_initialHudVerified = true;
					instance.WriteTrace("smoke_initial_hud_verified", "orange=0;blue=0;ping_placeholder_visible");
				}
			}
			if (PhotonNetwork.IsMasterClient && Array.IndexOf(Environment.GetCommandLineArgs(), "--rounds-p2p-steam-failure-smoke") >= 0)
			{
				_finished = true;
				instance.WriteTrace("smoke_steam_failure_injected", "battle_was_ongoing");
				instance.SimulateSteamFailureForSmoke();
				((MonoBehaviour)instance).StartCoroutine(VerifyFailureRecovery(instance));
			}
			else
			{
				if (_matchEnded)
				{
					return;
				}
				int losingTeam = ((!TestHud) ? 1 : (1 - num2));
				foreach (Player player in instance4.players)
				{
					if (player.TeamID == losingTeam && player.data.view.IsMine && player.data.isPlaying && !player.data.dead)
					{
						_lastDamage = Time.realtimeSinceStartup;
						Player val2 = instance4.players.Find((Player candidate) => candidate.TeamID != losingTeam);
						if (!((Object)(object)val2 == (Object)null))
						{
							((Damagable)player.data.healthHandler).CallTakeDamage(new Vector2(0f, 1E+09f), Vector2.op_Implicit(((Component)player).transform.position), (GameObject)null, val2, true, (DamageSource)1);
							instance.WriteTrace("smoke_damage_sent", "losing_team=" + losingTeam);
						}
					}
				}
			}
		}

		private static void OnGameOver(GM_ArmsRace __instance, int winningTeamID)
		{
			Plugin instance = Plugin.Instance;
			if (!((Object)(object)instance == (Object)null) && instance.SmokeEnabled && instance.Active)
			{
				bool flag = __instance.roundsToWinGame == 5 && ((winningTeamID == 0 && __instance.p1Rounds == 5) || (winningTeamID == 1 && __instance.p2Rounds == 5));
				instance.WriteTrace(flag ? "smoke_match_complete" : "smoke_failed", "winner=" + winningTeamID + ";rounds=" + __instance.p1Rounds + ":" + __instance.p2Rounds + ";limit=" + __instance.roundsToWinGame);
				SmokeDriver component = ((Component)instance).GetComponent<SmokeDriver>();
				if (TestHud && flag)
				{
					component._matchEnded = true;
					return;
				}
				component._finished = true;
				((MonoBehaviour)instance).StartCoroutine(QuitAfterDelivery((!flag) ? 2 : 0));
			}
		}

		private static void OnRematchPrompt(int winningTeamID)
		{
			Plugin instance = Plugin.Instance;
			SmokeDriver component = ((Component)instance).GetComponent<SmokeDriver>();
			if (winningTeamID != OrangeTeam() || !VerifyHud(0, 0))
			{
				instance.WriteTrace("smoke_failed", "orange_win_was_not_pending_before_rematch");
				component._finished = true;
				Application.Quit(2);
			}
			else
			{
				((MonoBehaviour)component).StartCoroutine(component.AcceptRematch(instance));
			}
		}

		private IEnumerator AcceptRematch(Plugin plugin)
		{
			yield return (object)new WaitForSecondsRealtime(0.75f);
			PopUpHandler popUpHandler = UIHandler.instance.popUpHandler;
			if (!popUpHandler.isPicking || RematchPromptClosed())
			{
				plugin.WriteTrace("smoke_failed", "rematch_prompt_did_not_open");
				_finished = true;
				Application.Quit(2);
				yield break;
			}
			_rematchRequested = true;
			AccessTools.Field(typeof(PopUpHandler), "currentYesNo").SetValue(popUpHandler, (object)(YesNo)0);
			AccessTools.Method(typeof(PopUpHandler), "DonePicking", (Type[])null, (Type[])null).Invoke(popUpHandler, null);
			if (!RematchPromptClosed())
			{
				plugin.WriteTrace("smoke_failed", "rematch_prompt_stayed_visible_after_confirmation");
				_finished = true;
				Application.Quit(2);
			}
			else
			{
				plugin.WriteTrace("smoke_rematch_prompt_closed", "stock_confirmation_stopped_and_cleared_yes_no");
			}
		}

		private static bool RematchPromptClosed()
		{
			PopUpHandler popUpHandler = UIHandler.instance.popUpHandler;
			if (!popUpHandler.isPicking && !popUpHandler.yesPart.loop && !popUpHandler.noPart.loop && !HasVisiblePromptParticles(popUpHandler.yesPart))
			{
				return !HasVisiblePromptParticles(popUpHandler.noPart);
			}
			return false;
		}

		private static bool HasVisiblePromptParticles(GeneralParticleSystem emitter)
		{
			//IL_0029: Unknown result type (might be due to invalid IL or missing references)
			if (((Component)emitter).transform.childCount == 0)
			{
				return false;
			}
			foreach (Transform item in ((Component)emitter).transform.GetChild(0))
			{
				if (((Component)item).gameObject.activeInHierarchy)
				{
					return true;
				}
			}
			return false;
		}

		private static bool DelayRematchMapOnGuest(MapManager __instance, string sceneName)
		{
			Plugin? instance = Plugin.Instance;
			SmokeDriver smokeDriver = ((instance != null) ? ((Component)instance).GetComponent<SmokeDriver>() : null);
			if ((Object)(object)smokeDriver == (Object)null || !smokeDriver._matchEnded || smokeDriver._replayingDelayedLoad)
			{
				return true;
			}
			smokeDriver._rema