Decompiled source of MultiplayerPlus v0.1.1

BepInEx/plugins/MechGaming-MultiplayerPlus/MultiplayerPlus.dll

Decompiled 2 weeks ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Configuration;
using BepInEx.Logging;
using ExitGames.Client.Photon;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using Photon.Pun;
using Photon.Realtime;
using TMPro;
using UnityEngine;
using UnityEngine.Events;
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("MechGaming")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("0.1.1.0")]
[assembly: AssemblyInformationalVersion("0.1.1")]
[assembly: AssemblyProduct("MultiplayerPlus")]
[assembly: AssemblyTitle("MultiplayerPlus")]
[assembly: AssemblyVersion("0.1.1.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 MechGaming.REPO.MultiplayerPlus
{
	internal static class DependencySettings
	{
		internal const string MorePlayersGuid = "dyxc666.MorePlayersSimple";

		internal const string LateJoinGuid = "cn_xc.LateJoinSimple";

		internal const string SharedGuid = "Vippy.SharedUpgradesPlus";

		internal const string CompatibilityGuid = "ByteSizeMetal.SharedUpgradesPlusCompatibilityTweaks";

		private static ManualLogSource _log = null;

		private static ConfigFile _players = null;

		private static ConfigFile _lateJoin = null;

		private static ConfigFile _sharing = null;

		private static ConfigFile _compatibility = null;

		private static readonly Dictionary<ConfigEntryBase, object> OriginalValues = new Dictionary<ConfigEntryBase, object>();

		private static Harmony? _harmony;

		private static MethodInfo _enforceLateJoin = null;

		private static FieldInfo _sceneCacheUntil = null;

		private static FieldInfo _lateJoinSteamLocked = null;

		private static FieldInfo _steamLobby = null;

		private static PropertyInfo _steamLobbyId = null;

		private static PropertyInfo _steamIdValid = null;

		private static MethodInfo _steamJoinable = null;

		private static bool _applied;

		private static bool _shared;

		private static bool _lateJoining;

		private static int _maxPlayers = 10;

		private static float _nextTick;

		internal static void Configure(ManualLogSource log)
		{
			//IL_021c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0226: Expected O, but got Unknown
			//IL_023d: Unknown result type (might be due to invalid IL or missing references)
			//IL_024a: Expected O, but got Unknown
			_log = log;
			_players = RequirePlugin("dyxc666.MorePlayersSimple").Config;
			BaseUnityPlugin obj = RequirePlugin("cn_xc.LateJoinSimple");
			_lateJoin = obj.Config;
			_sharing = RequirePlugin("Vippy.SharedUpgradesPlus").Config;
			_compatibility = RequirePlugin("ByteSizeMetal.SharedUpgradesPlusCompatibilityTweaks").Config;
			ValidateRequiredSettings();
			Type type = ((object)obj).GetType();
			_enforceLateJoin = AccessTools.Method(type, "EnforceLobbyState", (Type[])null, (Type[])null) ?? throw new MissingMethodException(type.FullName, "EnforceLobbyState");
			_sceneCacheUntil = AccessTools.Field(type, "_sceneAllowedCacheUntil") ?? throw new MissingFieldException(type.FullName, "_sceneAllowedCacheUntil");
			_lateJoinSteamLocked = AccessTools.Field(type, "_steamLobbyLocked") ?? throw new MissingFieldException(type.FullName, "_steamLobbyLocked");
			if (!_lateJoinSteamLocked.IsStatic || _lateJoinSteamLocked.FieldType != typeof(bool))
			{
				throw new InvalidOperationException("LateJoinSimple Steam lock state API changed.");
			}
			MethodInfo methodInfo = AccessTools.Method(type, "LockRoomNow", (Type[])null, (Type[])null) ?? throw new MissingMethodException(type.FullName, "LockRoomNow");
			_steamLobby = AccessTools.Field(typeof(SteamLobbyManager), "currentLobby") ?? throw new MissingFieldException(typeof(SteamLobbyManager).FullName, "currentLobby");
			_steamLobbyId = _steamLobby.FieldType.GetProperty("Id") ?? throw new MissingMemberException(_steamLobby.FieldType.FullName, "Id");
			_steamIdValid = _steamLobbyId.PropertyType.GetProperty("IsValid") ?? throw new MissingMemberException(_steamLobbyId.PropertyType.FullName, "IsValid");
			_steamJoinable = _steamLobby.FieldType.GetMethod("SetJoinable", new Type[1] { typeof(bool) }) ?? throw new MissingMethodException(_steamLobby.FieldType.FullName, "SetJoinable");
			_harmony = new Harmony("MechGaming.REPO.MultiplayerPlus.DependencySettings");
			_harmony.Patch((MethodBase)methodInfo, (HarmonyMethod)null, new HarmonyMethod(typeof(DependencySettings), "AfterLateJoinLock", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
		}

		private static BaseUnityPlugin RequirePlugin(string guid)
		{
			if (!Chainloader.PluginInfos.TryGetValue(guid, out var value) || (Object)(object)value.Instance == (Object)null)
			{
				throw new InvalidOperationException("Required dependency is not loaded: " + guid);
			}
			return value.Instance;
		}

		private static ConfigEntryBase Require(ConfigFile config, string section, string key, Type type)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0008: Expected O, but got Unknown
			ConfigDefinition val = new ConfigDefinition(section, key);
			if (!config.ContainsKey(val))
			{
				throw new InvalidOperationException("Required setting is missing: " + section + "/" + key);
			}
			ConfigEntryBase obj = config[val];
			if (obj.SettingType != type)
			{
				throw new InvalidOperationException("Dependency setting type changed: " + section + "/" + key);
			}
			return obj;
		}

		private static void ValidateRequiredSettings()
		{
			Require(_players, "常规", "公开房人数上限", typeof(int));
			Require(_players, "常规", "私人房人数上限", typeof(int));
			string[] array = new string[3] { "卡车阶段允许加入", "商店阶段允许加入", "关卡中允许加入" };
			foreach (string key in array)
			{
				Require(_lateJoin, "场景白名单", key, typeof(bool));
			}
			Require(_sharing, "General", "EnableSharedUpgrades", typeof(bool));
			Require(_sharing, "General", "SharedUpgradesChance", typeof(int));
			Require(_sharing, "General", "LateJoinSync", typeof(bool));
			Require(_sharing, "General", "EnableModdedUpgrades", typeof(bool));
			Require(_compatibility, "Consumable charges", "GrantHistoryOnJoin", typeof(bool));
			Require(_compatibility, "Reconciliation", "MatchHighestPermanentLevel", typeof(bool));
		}

		internal static void Apply(bool shared, int maxPlayers, bool lateJoining)
		{
			if (PhotonNetwork.InRoom && !PhotonNetwork.IsMasterClient)
			{
				throw new InvalidOperationException("Only the current host can apply multiplayer settings.");
			}
			if (maxPlayers < 1 || maxPlayers > 10)
			{
				throw new ArgumentOutOfRangeException("maxPlayers", "Max players must be between 1 and 10.");
			}
			ValidateRequiredSettings();
			_shared = shared;
			_maxPlayers = maxPlayers;
			_lateJoining = lateJoining;
			_applied = true;
			ApplyConfigValues();
			UpdatePlayerLimit();
			_sceneCacheUntil.SetValue(null, 0f);
			if (PhotonNetwork.InRoom && PhotonNetwork.IsMasterClient)
			{
				_enforceLateJoin.Invoke(null, null);
			}
			EnforceDisabledLateJoining();
			_nextTick = 0f;
		}

		private static void Set(ConfigFile config, string section, string key, object value)
		{
			Set(Require(config, section, key, value.GetType()), value);
		}

		private static void Set(ConfigEntryBase entry, object value)
		{
			if (!OriginalValues.ContainsKey(entry))
			{
				OriginalValues.Add(entry, entry.BoxedValue);
			}
			if (!object.Equals(entry.BoxedValue, value))
			{
				entry.BoxedValue = value;
			}
			if (!object.Equals(entry.BoxedValue, value))
			{
				throw new InvalidOperationException("Dependency rejected " + entry.Definition.Section + "/" + entry.Definition.Key);
			}
		}

		private static void WithoutSaving(ConfigFile config, Action action)
		{
			bool saveOnConfigSet = config.SaveOnConfigSet;
			config.SaveOnConfigSet = false;
			try
			{
				action();
			}
			finally
			{
				config.SaveOnConfigSet = saveOnConfigSet;
			}
		}

		private static void ApplyConfigValues()
		{
			WithoutSaving(_players, delegate
			{
				Set(_players, "常规", "公开房人数上限", _maxPlayers);
				Set(_players, "常规", "私人房人数上限", _maxPlayers);
			});
			WithoutSaving(_lateJoin, delegate
			{
				string[] array = new string[3] { "卡车阶段允许加入", "商店阶段允许加入", "关卡中允许加入" };
				foreach (string key in array)
				{
					Set(_lateJoin, "场景白名单", key, _lateJoining);
				}
			});
			WithoutSaving(_sharing, delegate
			{
				Set(_sharing, "General", "EnableSharedUpgrades", _shared);
				Set(_sharing, "General", "LateJoinSync", _shared);
				if (_shared)
				{
					Set(_sharing, "General", "SharedUpgradesChance", 100);
					Set(_sharing, "General", "EnableModdedUpgrades", true);
					KeyValuePair<ConfigDefinition, ConfigEntryBase>[] array = ((IEnumerable<KeyValuePair<ConfigDefinition, ConfigEntryBase>>)_sharing).ToArray();
					for (int i = 0; i < array.Length; i++)
					{
						KeyValuePair<ConfigDefinition, ConfigEntryBase> keyValuePair = array[i];
						if (!(keyValuePair.Key.Section != "Vanilla Upgrades") || !(keyValuePair.Key.Section != "Modded Upgrades"))
						{
							if (keyValuePair.Value.SettingType == typeof(bool))
							{
								Set(keyValuePair.Value, true);
							}
							else if (keyValuePair.Value.SettingType == typeof(int) && keyValuePair.Key.Key.EndsWith(" Share Limit", StringComparison.Ordinal))
							{
								Set(keyValuePair.Value, 0);
							}
						}
					}
				}
			});
			WithoutSaving(_compatibility, delegate
			{
				Set(_compatibility, "Consumable charges", "GrantHistoryOnJoin", _shared);
				Set(_compatibility, "Reconciliation", "MatchHighestPermanentLevel", _shared);
				if (_shared)
				{
					KeyValuePair<ConfigDefinition, ConfigEntryBase>[] array = ((IEnumerable<KeyValuePair<ConfigDefinition, ConfigEntryBase>>)_compatibility).ToArray();
					for (int i = 0; i < array.Length; i++)
					{
						KeyValuePair<ConfigDefinition, ConfigEntryBase> keyValuePair = array[i];
						if (keyValuePair.Key.Section.StartsWith("Upgrade - ", StringComparison.Ordinal) && keyValuePair.Key.Key.EndsWith(" - Allow sharing", StringComparison.Ordinal) && keyValuePair.Value.SettingType == typeof(bool))
						{
							Set(keyValuePair.Value, true);
						}
					}
				}
			});
		}

		private static void UpdatePlayerLimit()
		{
			if (!((Object)(object)GameManager.instance == (Object)null) && (!PhotonNetwork.InRoom || PhotonNetwork.IsMasterClient))
			{
				GameManager.instance.SetMaxPlayers(_maxPlayers);
			}
		}

		internal static void Tick()
		{
			if (_applied && PhotonNetwork.InRoom && PhotonNetwork.IsMasterClient && !(Time.unscaledTime < _nextTick))
			{
				_nextTick = Time.unscaledTime + 0.5f;
				ApplyConfigValues();
				int num = Math.Max(_maxPlayers, PhotonNetwork.CurrentRoom.PlayerCount);
				if ((Object)(object)GameManager.instance != (Object)null && (GameManager.instance.maxPlayers != _maxPlayers || PhotonNetwork.CurrentRoom.MaxPlayers != num))
				{
					UpdatePlayerLimit();
				}
				EnforceDisabledLateJoining();
			}
		}

		private static bool InRunScene()
		{
			if ((Object)(object)RunManager.instance != (Object)null)
			{
				if (!SemiFunc.RunIsLobby() && !SemiFunc.RunIsShop() && !SemiFunc.RunIsLevel())
				{
					return SemiFunc.RunIsArena();
				}
				return true;
			}
			return false;
		}

		private static void EnforceDisabledLateJoining()
		{
			if (!_applied || _lateJoining || !PhotonNetwork.InRoom || !PhotonNetwork.IsMasterClient || !InRunScene())
			{
				return;
			}
			if (PhotonNetwork.CurrentRoom.IsOpen)
			{
				PhotonNetwork.CurrentRoom.IsOpen = false;
			}
			if ((Object)(object)SteamLobbyManager.instance == (Object)null)
			{
				return;
			}
			object value = _steamLobby.GetValue(SteamLobbyManager.instance);
			object value2 = _steamLobbyId.GetValue(value, null);
			if ((bool)_steamIdValid.GetValue(value2, null))
			{
				object obj = _steamJoinable.Invoke(value, new object[1] { false });
				if (obj is bool && !(bool)obj)
				{
					throw new InvalidOperationException("Steam rejected closing the lobby to late joins.");
				}
				_lateJoinSteamLocked.SetValue(null, true);
			}
		}

		private static void AfterLateJoinLock()
		{
			try
			{
				EnforceDisabledLateJoining();
			}
			catch (Exception ex)
			{
				_log.LogError((object)("Could not close late-join admission: " + ex.GetBaseException().Message));
			}
		}

		internal static void RestoreLocalSettings()
		{
			_applied = false;
			IGrouping<ConfigFile, KeyValuePair<ConfigEntryBase, object>>[] array = (from pair in OriginalValues
				group pair by pair.Key.ConfigFile).ToArray();
			foreach (IGrouping<ConfigFile, KeyValuePair<ConfigEntryBase, object>> group in array)
			{
				try
				{
					WithoutSaving(group.Key, delegate
					{
						foreach (KeyValuePair<ConfigEntryBase, object> item in group)
						{
							item.Key.BoxedValue = item.Value;
						}
					});
					group.Key.Save();
				}
				catch (Exception ex)
				{
					ManualLogSource log = _log;
					if (log != null)
					{
						log.LogWarning((object)("Could not persist restored dependency settings in " + group.Key.ConfigFilePath + ": " + ex.GetBaseException().Message));
					}
				}
			}
			OriginalValues.Clear();
		}

		internal static void Dispose()
		{
			RestoreLocalSettings();
			Harmony? harmony = _harmony;
			if (harmony != null)
			{
				harmony.UnpatchSelf();
			}
			_harmony = null;
		}
	}
	internal sealed class LobbyPanel : MonoBehaviour
	{
		internal static readonly Color Orange = new Color(1f, 0.55f, 0f);

		private static readonly PropertyInfo? PageInteractable = AccessTools.Property(typeof(MenuPage), "isInteractable");

		private static readonly FieldInfo? CurrentPage = AccessTools.Field(typeof(MenuManager), "currentMenuPage");

		private MenuPage _page;

		private MenuPageLobby _native;

		private RectTransform _panel;

		private TextMeshProUGUI _role;

		private TextMeshProUGUI _status;

		private LobbyValueControl _name;

		private LobbyValueControl _shared;

		private LobbyValueControl _max;

		private LobbyValueControl _late;

		private readonly Dictionary<Selectable, Navigation> _originalNavigation = new Dictionary<Selectable, Navigation>();

		private bool _navigationLinked;

		private string _originalRoomName = "";

		private bool _originalRoomNameRichText;

		private bool _roomNameOverridden;

		private string _localMessage = "";

		private float _localMessageUntil;

		internal bool CanInteract
		{
			get
			{
				if ((Object)(object)_page != (Object)null && (Object)(object)MenuManager.instance != (Object)null && CurrentPage?.GetValue(MenuManager.instance) == _page && (bool?)PageInteractable?.GetValue(_page) == true && (Object)(object)Plugin.Instance != (Object)null && Plugin.Instance.IsHost)
				{
					return Plugin.Instance.HasHostSettings;
				}
				return false;
			}
		}

		internal static void Attach(MenuPageLobby native)
		{
			if ((Object)(object)native == (Object)null || (Object)(object)((Component)native).GetComponent<LobbyPanel>() != (Object)null)
			{
				return;
			}
			LobbyPanel lobbyPanel = ((Component)native).gameObject.AddComponent<LobbyPanel>();
			try
			{
				lobbyPanel.Build(native);
			}
			catch
			{
				if ((Object)(object)lobbyPanel._panel != (Object)null)
				{
					Object.Destroy((Object)(object)((Component)lobbyPanel._panel).gameObject);
				}
				Object.Destroy((Object)(object)lobbyPanel);
				throw;
			}
		}

		private void Build(MenuPageLobby native)
		{
			//IL_00ac: Unknown result type (might be due to invalid IL or missing references)
			//IL_00dd: Unknown result type (might be due to invalid IL or missing references)
			//IL_013d: Unknown result type (might be due to invalid IL or missing references)
			_native = native;
			_page = ((Component)native).GetComponent<MenuPage>();
			if ((Object)(object)native.roomNameText != (Object)null)
			{
				_originalRoomName = ((TMP_Text)native.roomNameText).text;
				_originalRoomNameRichText = ((TMP_Text)native.roomNameText).richText;
			}
			TextMeshProUGUI componentInChildren = ((Component)native.startButton).GetComponentInChildren<TextMeshProUGUI>(true);
			if ((Object)(object)componentInChildren == (Object)null)
			{
				componentInChildren = ((Component)native).GetComponentInChildren<TextMeshProUGUI>(true);
			}
			if ((Object)(object)componentInChildren == (Object)null)
			{
				throw new InvalidOperationException("The lobby font is unavailable.");
			}
			_panel = Rect("MultiplayerPlus.Settings", ((Component)native).transform);
			float num = LayoutPanel();
			Background(_panel, new Color(0f, 0f, 0f, 0.76f));
			float num2 = num * 0.067f;
			TextMeshProUGUI obj = Text("Title", (Transform)(object)_panel, componentInChildren, "MULTIPLAYER+", num * 0.115f);
			((Graphic)obj).color = Orange;
			Place(((TMP_Text)obj).rectTransform, 0.055f, 0.82f, 0.945f, 0.96f);
			_role = Text("Authority", (Transform)(object)_panel, componentInChildren, "", num * 0.045f);
			((Graphic)_role).color = new Color(0.63f, 0.63f, 0.63f);
			Place(((TMP_Text)_role).rectTransform, 0.06f, 0.75f, 0.94f, 0.815f);
			Place(((TMP_Text)Text("ServerName.Label", (Transform)(object)_panel, componentInChildren, "SERVER NAME", num * 0.052f)).rectTransform, 0.06f, 0.65f, 0.94f, 0.715f);
			_name = Control("ServerName", (Transform)(object)_panel, componentInChildren, num2, toggle: false, OpenName);
			Place(_name.Rect, 0.06f, 0.52f, 0.94f, 0.64f);
			Row("SharedUpgrades", "SHARED UPGRADES", 0.36f, 0.47f, componentInChildren, num2, toggle: true, ToggleShared, out _shared);
			Row("MaxPlayers", "MAX PLAYERS", 0.22f, 0.33f, componentInChildren, num2, toggle: false, OpenMax, out _max);
			Row("LateJoining", "LATE JOINING", 0.08f, 0.19f, componentInChildren, num2, toggle: true, ToggleLate, out _late);
			_status = Text("Status", (Transform)(object)_panel, componentInChildren, "", num * 0.038f);
			((TMP_Text)_status).textWrappingMode = (TextWrappingModes)1;
			((TMP_Text)_status).overflowMode = (TextOverflowModes)3;
			Place(((TMP_Text)_status).rectTransform, 0.06f, 0.01f, 0.94f, 0.065f);
			Refresh();
		}

		private void Row(string name, string label, float bottom, float top, TextMeshProUGUI source, float fontSize, bool toggle, Action action, out LobbyValueControl value)
		{
			Place(((TMP_Text)Text(name + ".Label", (Transform)(object)_panel, source, label, fontSize * 0.85f)).rectTransform, 0.06f, bottom, 0.66f, top);
			value = Control(name, (Transform)(object)_panel, source, fontSize, toggle, action);
			Place(value.Rect, 0.69f, bottom, 0.94f, top);
		}

		private LobbyValueControl Control(string name, Transform parent, TextMeshProUGUI source, float size, bool toggle, Action action)
		{
			//IL_001d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0054: Unknown result type (might be due to invalid IL or missing references)
			//IL_0069: 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_0139: Unknown result type (might be due to invalid IL or missing references)
			RectTransform val = Rect(name, parent);
			Image background = Background(val, new Color(0.15f, 0.15f, 0.15f, 0.7f));
			((Component)val).gameObject.AddComponent<RectMask2D>();
			Outline obj = ((Component)val).gameObject.AddComponent<Outline>();
			((Shadow)obj).effectColor = new Color(0.6f, 0.6f, 0.6f, 0.25f);
			((Shadow)obj).effectDistance = new Vector2(0.4f, -0.4f);
			((Shadow)obj).useGraphicAlpha = true;
			TextMeshProUGUI val2 = Text(name + ".Value", (Transform)(object)val, source, "", size);
			Place(((TMP_Text)val2).rectTransform, toggle ? 0.34f : 0.035f, 0.04f, 0.96f, 0.96f);
			((TMP_Text)val2).overflowMode = (TextOverflowModes)0;
			Image indicator = null;
			if (toggle)
			{
				RectTransform val3 = Rect("Checkbox", (Transform)(object)val);
				Place(val3, 0.08f, 0.26f, 0.25f, 0.74f);
				Background(val3, new Color(0.45f, 0.45f, 0.45f, 0.7f));
				RectTransform rect = Rect("Checked", (Transform)(object)val3);
				Place(rect, 0.17f, 0.17f, 0.83f, 0.83f);
				indicator = Background(rect, Orange);
			}
			MenuSelectableElement val4 = ((Component)val).gameObject.AddComponent<MenuSelectableElement>();
			((Selectable)val4).transition = (Transition)0;
			MenuElementHover hover = ((Component)val).gameObject.AddComponent<MenuElementHover>();
			LobbyValueControl lobbyValueControl = ((Component)val).gameObject.AddComponent<LobbyValueControl>();
			lobbyValueControl.Configure(this, val4, hover, background, val2, indicator, action);
			return lobbyValueControl;
		}

		private void Update()
		{
			if ((Object)(object)_panel != (Object)null)
			{
				Refresh();
			}
		}

		private float LayoutPanel()
		{
			//IL_000b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0011: Expected O, but got Unknown
			//IL_0051: 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_005e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0060: Unknown result type (might be due to invalid IL or missing references)
			//IL_0065: Unknown result type (might be due to invalid IL or missing references)
			//IL_003c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0041: Unknown result type (might be due to invalid IL or missing references)
			//IL_0078: Unknown result type (might be due to invalid IL or missing references)
			//IL_007d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0059: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ab: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ba: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bf: Unknown result type (might be due to invalid IL or missing references)
			//IL_00de: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ed: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f2: Unknown result type (might be due to invalid IL or missing references)
			//IL_0111: Unknown result type (might be due to invalid IL or missing references)
			//IL_0116: Unknown result type (might be due to invalid IL or missing references)
			//IL_0120: Unknown result type (might be due to invalid IL or missing references)
			//IL_0125: Unknown result type (might be due to invalid IL or missing references)
			//IL_0144: Unknown result type (might be due to invalid IL or missing references)
			//IL_0149: Unknown result type (might be due to invalid IL or missing references)
			//IL_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)
			RectTransform val = (RectTransform)((Component)_native).transform;
			Transform parent = ((Transform)val).parent;
			RectTransform val2 = (RectTransform)(object)((parent is RectTransform) ? parent : null);
			Rect rect;
			Rect rect2;
			if ((Object)(object)val2 != (Object)null)
			{
				rect = val2.rect;
				if (((Rect)(ref rect)).width > 0f)
				{
					rect = val2.rect;
					if (((Rect)(ref rect)).height > 0f)
					{
						rect2 = val2.rect;
						goto IL_005e;
					}
				}
			}
			rect2 = val.rect;
			goto IL_005e;
			IL_0187:
			Rect val3;
			return Mathf.Max(100f, ((Rect)(ref val3)).height * 0.68f);
			IL_005e:
			val3 = rect2;
			rect = val.rect;
			if (((Rect)(ref rect)).width > 0f)
			{
				rect = val.rect;
				if (((Rect)(ref rect)).height > 0f)
				{
					RectTransform panel = _panel;
					float num = ((Rect)(ref val3)).xMin + ((Rect)(ref val3)).width * 0.53f;
					rect = val.rect;
					float num2 = num - ((Rect)(ref rect)).xMin;
					rect = val.rect;
					float left = num2 / ((Rect)(ref rect)).width;
					float num3 = ((Rect)(ref val3)).yMin + ((Rect)(ref val3)).height * 0.08f;
					rect = val.rect;
					float num4 = num3 - ((Rect)(ref rect)).yMin;
					rect = val.rect;
					float bottom = num4 / ((Rect)(ref rect)).height;
					float num5 = ((Rect)(ref val3)).xMin + ((Rect)(ref val3)).width * 0.97f;
					rect = val.rect;
					float num6 = num5 - ((Rect)(ref rect)).xMin;
					rect = val.rect;
					float right = num6 / ((Rect)(ref rect)).width;
					float num7 = ((Rect)(ref val3)).yMin + ((Rect)(ref val3)).height * 0.76f;
					rect = val.rect;
					float num8 = num7 - ((Rect)(ref rect)).yMin;
					rect = val.rect;
					Place(panel, left, bottom, right, num8 / ((Rect)(ref rect)).height);
					goto IL_0187;
				}
			}
			Place(_panel, 0.53f, 0.08f, 0.97f, 0.76f);
			goto IL_0187;
		}

		private void Refresh()
		{
			//IL_019d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0196: Unknown result type (might be due to invalid IL or missing references)
			Plugin instance = Plugin.Instance;
			if ((Object)(object)instance == (Object)null)
			{
				RestoreRoomName();
				return;
			}
			bool hasHostSettings = instance.HasHostSettings;
			bool flag = instance.IsHost && hasHostSettings;
			((TMP_Text)_role).text = ((!hasHostSettings) ? "WAITING FOR HOST SETTINGS" : (flag ? "HOST CONTROLS" : "HOST SETTINGS - VIEW ONLY"));
			LobbySettings state = instance.State;
			if (hasHostSettings && (Object)(object)_native.roomNameText != (Object)null)
			{
				((TMP_Text)_native.roomNameText).richText = false;
				((TMP_Text)_native.roomNameText).text = state.ServerName;
				_roomNameOverridden = true;
			}
			else
			{
				RestoreRoomName();
			}
			_name.Set(hasHostSettings ? state.ServerName : "-", flag);
			_shared.Set((!hasHostSettings) ? "-" : (state.SharedUpgrades ? "ON" : "OFF"), flag, hasHostSettings && state.SharedUpgrades);
			_max.Set(hasHostSettings ? state.MaxPlayers.ToString(CultureInfo.InvariantCulture) : "-", flag);
			_late.Set((!hasHostSettings) ? "-" : (state.LateJoining ? "ON" : "OFF"), flag, hasHostSettings && state.LateJoining);
			bool flag2 = Time.unscaledTime < _localMessageUntil;
			((TMP_Text)_status).text = (flag2 ? _localMessage : instance.Status);
			((Graphic)_status).color = (Color)(flag2 ? Orange : new Color(0.57f, 0.57f, 0.57f));
			LinkNavigation(flag);
		}

		private void OpenName()
		{
			//IL_0014: Unknown result type (might be due to invalid IL or missing references)
			if (!CanInteract)
			{
				return;
			}
			MenuManager.instance.PagePopUpTextInput("SERVER NAME", (LocalizedAsset)null, Orange, "RENAME LOBBY", (LocalizedAsset)null, Plugin.Instance.State.ServerName, "SAVE", (LocalizedAsset)null, false, 60, false, (UnityAction<string>)delegate(string value)
			{
				if (!((Object)(object)this == (Object)null) && !((Object)(object)Plugin.Instance == (Object)null))
				{
					LobbySettings state = Plugin.Instance.State;
					Plugin.Instance.TryApply(value, state.SharedUpgrades, state.MaxPlayers, state.LateJoining);
				}
			}, (UnityAction)null);
			LobbyTextInputPopup.Configure(MenuPagePopUpTextInput.instance);
		}

		private void OpenMax()
		{
			//IL_0014: Unknown result type (might be due to invalid IL or missing references)
			if (!CanInteract)
			{
				return;
			}
			MenuManager.instance.PagePopUpTextInput("MAX PLAYERS", (LocalizedAsset)null, Orange, "1 through 10", (LocalizedAsset)null, Plugin.Instance.State.MaxPlayers.ToString(CultureInfo.InvariantCulture), "SAVE", (LocalizedAsset)null, false, 60, false, (UnityAction<string>)delegate(string value)
			{
				if (!((Object)(object)this == (Object)null) && !((Object)(object)Plugin.Instance == (Object)null))
				{
					if (!PlayerLimitInput.TryParse(value, out var count))
					{
						_localMessage = "1 through 10";
						_localMessageUntil = Time.unscaledTime + 6f;
					}
					else
					{
						LobbySettings state = Plugin.Instance.State;
						Plugin.Instance.TryApply(state.ServerName, state.SharedUpgrades, count, state.LateJoining);
					}
				}
			}, (UnityAction)null);
			LobbyTextInputPopup.Configure(MenuPagePopUpTextInput.instance);
		}

		private void ToggleShared()
		{
			if (CanInteract)
			{
				LobbySettings state = Plugin.Instance.State;
				Plugin.Instance.TryApply(state.ServerName, !state.SharedUpgrades, state.MaxPlayers, state.LateJoining);
			}
		}

		private void ToggleLate()
		{
			if (CanInteract)
			{
				LobbySettings state = Plugin.Instance.State;
				Plugin.Instance.TryApply(state.ServerName, state.SharedUpgrades, state.MaxPlayers, !state.LateJoining);
			}
		}

		private void LinkNavigation(bool editable)
		{
			//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_010c: Unknown result type (might be due to invalid IL or missing references)
			//IL_016b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0170: Unknown result type (might be due to invalid IL or missing references)
			//IL_0186: Unknown result type (might be due to invalid IL or missing references)
			//IL_015f: Unknown result type (might be due to invalid IL or missing references)
			if (_navigationLinked == editable)
			{
				return;
			}
			if (!editable)
			{
				RestoreNavigation();
				return;
			}
			MenuSelectableElement val = (((Object)(object)_native.inviteButton != (Object)null) ? ((Component)_native.inviteButton).GetComponent<MenuSelectableElement>() : null);
			MenuSelectableElement val2 = (((Object)(object)_native.startButton != (Object)null) ? ((Component)_native.startButton).GetComponent<MenuSelectableElement>() : null);
			MenuSelectableElement val3 = (((Object)(object)val != (Object)null) ? val : val2);
			MenuSelectableElement[] array = (MenuSelectableElement[])(object)new MenuSelectableElement[4] { _name.Selection, _shared.Selection, _max.Selection, _late.Selection };
			for (int i = 0; i < array.Length; i++)
			{
				Navigation navigation = ((Selectable)array[i]).navigation;
				((Navigation)(ref navigation)).mode = (Mode)4;
				((Navigation)(ref navigation)).selectOnUp = (Selectable)(object)((i > 0) ? array[i - 1] : val3);
				((Navigation)(ref navigation)).selectOnDown = (Selectable)(object)((i < array.Length - 1) ? array[i + 1] : val3);
				((Navigation)(ref navigation)).selectOnLeft = (Selectable)(object)val3;
				((Navigation)(ref navigation)).selectOnRight = (Selectable)(object)array[i];
				((Selectable)array[i]).navigation = navigation;
			}
			MenuSelectableElement[] array2 = (MenuSelectableElement[])(object)new MenuSelectableElement[2] { val, val2 };
			foreach (MenuSelectableElement val4 in array2)
			{
				if (!((Object)(object)val4 == (Object)null))
				{
					if (!_originalNavigation.ContainsKey((Selectable)(object)val4))
					{
						_originalNavigation[(Selectable)(object)val4] = ((Selectable)val4).navigation;
					}
					Navigation navigation2 = ((Selectable)val4).navigation;
					((Navigation)(ref navigation2)).mode = (Mode)4;
					((Navigation)(ref navigation2)).selectOnRight = (Selectable)(object)array[0];
					((Selectable)val4).navigation = navigation2;
				}
			}
			_navigationLinked = true;
		}

		private void RestoreNavigation()
		{
			//IL_002e: Unknown result type (might be due to invalid IL or missing references)
			foreach (KeyValuePair<Selectable, Navigation> item in _originalNavigation)
			{
				if ((Object)(object)item.Key != (Object)null)
				{
					item.Key.navigation = item.Value;
				}
			}
			_originalNavigation.Clear();
			_navigationLinked = false;
		}

		private void RestoreRoomName()
		{
			if (_roomNameOverridden && !((Object)(object)_native == (Object)null) && !((Object)(object)_native.roomNameText == (Object)null))
			{
				((TMP_Text)_native.roomNameText).text = _originalRoomName;
				((TMP_Text)_native.roomNameText).richText = _originalRoomNameRichText;
				_roomNameOverridden = false;
			}
		}

		private void OnDestroy()
		{
			RestoreNavigation();
			RestoreRoomName();
		}

		private static RectTransform Rect(string name, Transform parent)
		{
			//IL_0014: Unknown result type (might be due to invalid IL or missing references)
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			//IL_002b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0031: Expected O, but got Unknown
			GameObject val = new GameObject(name, new Type[1] { typeof(RectTransform) });
			val.transform.SetParent(parent, false);
			return (RectTransform)val.transform;
		}

		private static void Place(RectTransform rect, float left, float bottom, float right, float top)
		{
			//IL_0003: Unknown result type (might be due to invalid IL or missing references)
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_001d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0022: Unknown result type (might be due to invalid IL or missing references)
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			//IL_0029: 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_003b: Unknown result type (might be due to invalid IL or missing references)
			rect.anchorMin = new Vector2(left, bottom);
			rect.anchorMax = new Vector2(right, top);
			Vector2 offsetMin = (rect.offsetMax = Vector2.zero);
			rect.offsetMin = offsetMin;
			((Transform)rect).localScale = Vector3.one;
			((Transform)rect).localRotation = Quaternion.identity;
		}

		private static Image Background(RectTransform rect, Color color)
		{
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			Image obj = ((Component)rect).gameObject.AddComponent<Image>();
			((Graphic)obj).color = color;
			((Graphic)obj).raycastTarget = false;
			return obj;
		}

		private static TextMeshProUGUI Text(string name, Transform parent, TextMeshProUGUI source, string value, float size)
		{
			//IL_002b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0065: Unknown result type (might be due to invalid IL or missing references)
			TextMeshProUGUI obj = ((Component)Rect(name, parent)).gameObject.AddComponent<TextMeshProUGUI>();
			((TMP_Text)obj).font = ((TMP_Text)source).font;
			((TMP_Text)obj).fontSharedMaterial = ((TMP_Text)source).fontSharedMaterial;
			((TMP_Text)obj).fontStyle = ((TMP_Text)source).fontStyle;
			((TMP_Text)obj).characterSpacing = ((TMP_Text)source).characterSpacing;
			((TMP_Text)obj).wordSpacing = ((TMP_Text)source).wordSpacing;
			((TMP_Text)obj).fontSize = size;
			((Graphic)obj).color = new Color(0.78f, 0.78f, 0.78f);
			((TMP_Text)obj).alignment = (TextAlignmentOptions)4097;
			((TMP_Text)obj).richText = false;
			((Graphic)obj).raycastTarget = false;
			((TMP_Text)obj).textWrappingMode = (TextWrappingModes)0;
			((TMP_Text)obj).overflowMode = (TextOverflowModes)0;
			((TMP_Text)obj).text = value;
			return obj;
		}
	}
	internal sealed class LobbyValueControl : MonoBehaviour
	{
		private static readonly PropertyInfo? Hovered = AccessTools.Property(typeof(MenuElementHover), "isHovering");

		private LobbyPanel _owner;

		private MenuElementHover _hover;

		private Image _background;

		private TextMeshProUGUI _text;

		private Image? _checked;

		private Action _action;

		private bool _enabled;

		private int _bornFrame;

		internal MenuSelectableElement Selection { get; private set; }

		internal RectTransform Rect => (RectTransform)((Component)this).transform;

		internal void Configure(LobbyPanel owner, MenuSelectableElement selection, MenuElementHover hover, Image background, TextMeshProUGUI text, Image? indicator, Action action)
		{
			_owner = owner;
			Selection = selection;
			_hover = hover;
			_background = background;
			_text = text;
			_checked = indicator;
			_action = action;
			_bornFrame = Time.frameCount;
		}

		internal void Set(string value, bool editable, bool enabled = false)
		{
			((TMP_Text)_text).text = value;
			((Selectable)Selection).interactable = editable;
			_enabled = enabled;
			if ((Object)(object)_checked != (Object)null)
			{
				((Behaviour)_checked).enabled = enabled;
			}
		}

		private void LateUpdate()
		{
			//IL_0089: 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_00c1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ba: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b3: Unknown result type (might be due to invalid IL or missing references)
			if (!((Object)(object)_owner == (Object)null))
			{
				bool flag = _owner.CanInteract && ((Selectable)Selection).interactable && (bool?)Hovered?.GetValue(_hover) == true;
				((Graphic)_background).color = (flag ? new Color(0.28f, 0.2f, 0.1f, 0.9f) : new Color(0.12f, 0.12f, 0.12f, 0.7f));
				((Graphic)_text).color = (Color)(flag ? Color.white : (_enabled ? LobbyPanel.Orange : new Color(0.78f, 0.78f, 0.78f)));
				if (flag && Time.frameCount > _bornFrame && SemiFunc.InputUIClick())
				{
					MenuManager.instance.MenuEffectClick((MenuClickEffectType)1, (MenuPage)null, -1f, -1f, false, true);
					_action();
				}
			}
		}
	}
	internal sealed class LobbySettings
	{
		internal const string WireMarker = "MechGaming.MultiplayerPlus";

		internal const int Protocol = 1;

		internal string ServerName { get; }

		internal bool SharedUpgrades { get; }

		internal int MaxPlayers { get; }

		internal bool LateJoining { get; }

		private LobbySettings(string name, bool shared, int max, bool late)
		{
			ServerName = name;
			SharedUpgrades = shared;
			MaxPlayers = max;
			LateJoining = late;
		}

		internal static bool TryCreate(string? name, bool shared, int max, bool late, out LobbySettings settings, out string error)
		{
			settings = null;
			string text = (name ?? "").Trim();
			if (text.Length == 0 || text.Length > 60)
			{
				error = "Server name must contain 1–60 characters.";
				return false;
			}
			string text2 = text;
			foreach (char c in text2)
			{
				if (char.IsControl(c) || c == '<' || c == '>')
				{
					error = "Server name cannot contain control characters or < >.";
					return false;
				}
			}
			if (max < 1 || max > 10)
			{
				error = "Max players must be between 1 and 10.";
				return false;
			}
			settings = new LobbySettings(text, shared, max, late);
			error = "";
			return true;
		}

		internal static LobbySettings Defaults(string name = "R.E.P.O.")
		{
			if (!TryCreate(name, shared: true, 10, late: true, out LobbySettings settings, out string error))
			{
				TryCreate("R.E.P.O.", shared: true, 10, late: true, out settings, out error);
			}
			return settings;
		}

		internal object[] ToPayload()
		{
			return new object[6] { "MechGaming.MultiplayerPlus", 1, ServerName, SharedUpgrades, MaxPlayers, LateJoining };
		}

		internal static bool TryFromPayload(object? value, out LobbySettings settings)
		{
			settings = null;
			if (value is object[] array && array.Length == 6 && array[0] is string text && text == "MechGaming.MultiplayerPlus" && array[1] is int num && num == 1 && array[2] is string name && array[3] is bool shared && array[4] is int max && array[5] is bool late)
			{
				string error;
				return TryCreate(name, shared, max, late, out settings, out error);
			}
			return false;
		}
	}
	internal sealed class LobbyTextInputPopup : MonoBehaviour
	{
		private static readonly PropertyInfo? Hovered = AccessTools.Property(typeof(MenuElementHover), "isHovering");

		private static readonly PropertyInfo? PageInteractable = AccessTools.Property(typeof(MenuPage), "isInteractable");

		private MenuElementHover _hover;

		private MenuPage _page;

		private MenuPagePopUpTextInput _popup;

		private bool _originalHoverEffect;

		private bool _suppressed;

		private int _bornFrame;

		internal static void Configure(MenuPagePopUpTextInput popup)
		{
			if (!((Object)(object)popup == (Object)null) && !((Object)(object)popup.menuTextInput == (Object)null) && !((Object)(object)((Component)popup).GetComponent<LobbyTextInputPopup>() != (Object)null))
			{
				LobbyTextInputPopup lobbyTextInputPopup = ((Component)popup).gameObject.AddComponent<LobbyTextInputPopup>();
				lobbyTextInputPopup._popup = popup;
				lobbyTextInputPopup._page = ((Component)popup).GetComponent<MenuPage>();
				lobbyTextInputPopup._hover = ((Component)popup.menuTextInput).GetComponent<MenuElementHover>();
				lobbyTextInputPopup._originalHoverEffect = (Object)(object)lobbyTextInputPopup._hover != (Object)null && lobbyTextInputPopup._hover.hasHoverEffect;
				lobbyTextInputPopup._bornFrame = Time.frameCount;
				lobbyTextInputPopup.LayoutPrompt();
			}
		}

		private void LayoutPrompt()
		{
			//IL_00d6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00db: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00eb: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f6: 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_0100: Unknown result type (might be due to invalid IL or missing references)
			//IL_0102: Unknown result type (might be due to invalid IL or missing references)
			//IL_0109: 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)
			//IL_011f: Unknown result type (might be due to invalid IL or missing references)
			//IL_017d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0184: Unknown result type (might be due to invalid IL or missing references)
			//IL_0196: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a1: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a8: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b7: Unknown result type (might be due to invalid IL or missing references)
			//IL_01bc: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c0: Unknown result type (might be due to invalid IL or missing references)
			//IL_01cb: Unknown result type (might be due to invalid IL or missing references)
			//IL_01df: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e4: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e8: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f3: Unknown result type (might be due to invalid IL or missing references)
			//IL_0202: Unknown result type (might be due to invalid IL or missing references)
			//IL_024b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0250: Unknown result type (might be due to invalid IL or missing references)
			//IL_0255: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)_popup == (Object)null || (Object)(object)_popup.bodyTextMesh == (Object)null || (Object)(object)_popup.menuTextInput == (Object)null)
			{
				return;
			}
			TextMeshProUGUI bodyTextMesh = _popup.bodyTextMesh;
			((TMP_Text)bodyTextMesh).richText = false;
			((TMP_Text)bodyTextMesh).textWrappingMode = (TextWrappingModes)0;
			((TMP_Text)bodyTextMesh).enableAutoSizing = true;
			((TMP_Text)bodyTextMesh).fontSizeMax = ((TMP_Text)bodyTextMesh).fontSize;
			((TMP_Text)bodyTextMesh).fontSizeMin = ((TMP_Text)bodyTextMesh).fontSize * 0.65f;
			((TMP_Text)bodyTextMesh).overflowMode = (TextOverflowModes)3;
			((TMP_Text)bodyTextMesh).alignment = (TextAlignmentOptions)514;
			RectTransform rectTransform = ((TMP_Text)bodyTextMesh).rectTransform;
			Transform parent = ((Transform)rectTransform).parent;
			RectTransform val = (RectTransform)(object)((parent is RectTransform) ? parent : null);
			Transform transform = ((Component)_popup.menuTextInput).transform;
			RectTransform val2 = (RectTransform)(object)((transform is RectTransform) ? transform : null);
			if ((Object)(object)val == (Object)null || (Object)(object)val2 == (Object)null)
			{
				return;
			}
			Vector3[] array = (Vector3[])(object)new Vector3[4];
			val2.GetWorldCorners(array);
			Vector3 val3 = ((Transform)val).InverseTransformPoint(array[1]);
			Vector3 val4 = ((Transform)val).InverseTransformPoint(array[2]);
			Vector3 val5 = ((Transform)val).InverseTransformPoint(array[0]);
			float num = Mathf.Abs(val4.x - val3.x);
			float num2 = Mathf.Abs(val3.y - val5.y);
			if (num <= 0f || num2 <= 0f)
			{
				return;
			}
			float num3 = Mathf.Max(((TMP_Text)bodyTextMesh).fontSize * 1.25f, num2);
			float num4 = Mathf.Max(4f, num2 * 0.35f);
			Vector2 val6 = default(Vector2);
			((Vector2)(ref val6))..ctor(0.5f, 0.5f);
			rectTransform.anchorMax = val6;
			rectTransform.anchorMin = val6;
			rectTransform.pivot = new Vector2(0.5f, 0.5f);
			float num5 = (val3.x + val4.x) * 0.5f;
			Rect rect = val.rect;
			float num6 = num5 - ((Rect)(ref rect)).center.x;
			float num7 = val3.y + num4 + num3 * 0.5f;
			rect = val.rect;
			rectTransform.anchoredPosition = new Vector2(num6, num7 - ((Rect)(ref rect)).center.y);
			rectTransform.sizeDelta = new Vector2(num, num3);
			SemiUI[] componentsInParent = ((Component)bodyTextMesh).GetComponentsInParent<SemiUI>(true);
			foreach (SemiUI val7 in componentsInParent)
			{
				if ((Object)(object)((Component)val7).transform == (Object)(object)rectTransform || (!val7.animateTheEntireObject && (Object)(object)val7.textRectTransform == (Object)(object)rectTransform))
				{
					val7.showPosition = Vector2.op_Implicit(((Transform)rectTransform).localPosition);
				}
			}
		}

		private void LateUpdate()
		{
			if ((Object)(object)_hover == (Object)null || (Object)(object)_page == (Object)null)
			{
				return;
			}
			bool valueOrDefault = (bool?)Hovered?.GetValue(_hover) == true;
			if (_suppressed)
			{
				if (!valueOrDefault)
				{
					RestoreHover();
				}
			}
			else if (valueOrDefault && Time.frameCount > _bornFrame && (bool?)PageInteractable?.GetValue(_page) == true && SemiFunc.InputUIClick())
			{
				_hover.hasHoverEffect = false;
				_suppressed = true;
			}
		}

		private void RestoreHover()
		{
			if ((Object)(object)_hover != (Object)null)
			{
				_hover.hasHoverEffect = _originalHoverEffect;
			}
			_suppressed = false;
		}

		private void OnDisable()
		{
			RestoreHover();
		}

		private void OnDestroy()
		{
			RestoreHover();
		}
	}
	internal sealed class NetworkSync : MonoBehaviourPunCallbacks, IOnEventCallback
	{
		private const byte RequestCode = 197;

		private const byte SettingsCode = 198;

		private float _nextRequest;

		internal void Tick()
		{
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_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_007e: Expected O, but got Unknown
			if (!((Object)(object)Plugin.Instance == (Object)null) && PhotonNetwork.InRoom && !Plugin.Instance.IsHost && !Plugin.Instance.HasHostSettings && !(Time.unscaledTime < _nextRequest))
			{
				_nextRequest = Time.unscaledTime + 2f;
				PhotonNetwork.RaiseEvent((byte)197, (object)new object[2] { "MechGaming.MultiplayerPlus", 1 }, new RaiseEventOptions
				{
					Receivers = (ReceiverGroup)2
				}, SendOptions.SendReliable);
			}
		}

		internal void Publish(int targetActor = 0)
		{
			//IL_0038: Unknown result type (might be due to invalid IL or missing references)
			//IL_003e: Expected O, but got Unknown
			//IL_002a: Unknown result type (might be due to invalid IL or missing references)
			//IL_002f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0031: Unknown result type (might be due to invalid IL or missing references)
			//IL_0065: Unknown result type (might be due to invalid IL or missing references)
			if (!((Object)(object)Plugin.Instance == (Object)null) && Plugin.Instance.IsHost && Plugin.Instance.HasHostSettings)
			{
				object obj;
				if (targetActor <= 0)
				{
					obj = (object)new RaiseEventOptions
					{
						Receivers = (ReceiverGroup)0
					};
				}
				else
				{
					RaiseEventOptions val = new RaiseEventOptions();
					val.TargetActors = new int[1] { targetActor };
					obj = val;
				}
				RaiseEventOptions val2 = (RaiseEventOptions)obj;
				PhotonNetwork.RaiseEvent((byte)198, (object)Plugin.Instance.State.ToPayload(), val2, SendOptions.SendReliable);
			}
		}

		public void OnEvent(EventData photonEvent)
		{
			Plugin instance = Plugin.Instance;
			if ((Object)(object)instance == (Object)null || !PhotonNetwork.InRoom)
			{
				return;
			}
			LobbySettings settings;
			if (photonEvent.Code == 197 && instance.IsHost)
			{
				if (photonEvent.CustomData is object[] array && array.Length == 2 && array[0] is string text && text == "MechGaming.MultiplayerPlus" && array[1] is int num && num == 1 && PhotonNetwork.CurrentRoom.GetPlayer(photonEvent.Sender, false) != null)
				{
					Publish(photonEvent.Sender);
				}
			}
			else if (photonEvent.Code == 198 && !instance.IsHost && photonEvent.Sender == PhotonNetwork.CurrentRoom.MasterClientId && LobbySettings.TryFromPayload(photonEvent.CustomData, out settings))
			{
				instance.ReceiveHostState(settings);
			}
		}

		public override void OnPlayerEnteredRoom(Player newPlayer)
		{
			Publish(newPlayer.ActorNumber);
		}

		public override void OnLeftRoom()
		{
			_nextRequest = 0f;
			Plugin.Instance?.ResetSession();
		}

		public override void OnMasterClientSwitched(Player newMasterClient)
		{
			_nextRequest = 0f;
			Plugin.Instance?.ResetSession();
		}
	}
	internal static class PlayerLimitInput
	{
		internal static bool TryParse(string? text, out int count)
		{
			count = 1;
			string text2 = (text ?? "").Trim();
			if (text2.Length == 0)
			{
				return false;
			}
			int num = ((text2[0] == '+' || text2[0] == '-') ? 1 : 0);
			if (num == text2.Length)
			{
				return false;
			}
			bool flag = text2[0] == '-';
			int num2 = 0;
			for (int i = num; i < text2.Length; i++)
			{
				char c = text2[i];
				if (c < '0' || c > '9')
				{
					return false;
				}
				num2 = Math.Min(11, num2 * 10 + c - 48);
			}
			count = (flag ? 1 : Math.Max(1, Math.Min(10, num2)));
			return true;
		}
	}
	[BepInPlugin("MechGaming.REPO.MultiplayerPlus", "Multiplayer+", "0.1.1")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	public sealed class Plugin : BaseUnityPlugin
	{
		public const string PluginGuid = "MechGaming.REPO.MultiplayerPlus";

		public const string PluginName = "Multiplayer+";

		public const string PluginVersion = "0.1.1";

		private ConfigEntry<bool> _shared;

		private ConfigEntry<bool> _late;

		private ConfigEntry<int> _max;

		private Harmony _harmony;

		private NetworkSync _network;

		private Room? _room;

		private bool _lastHost;

		private string _saveId = "";

		private float _nextTick;

		internal static Plugin Instance { get; private set; }

		internal LobbySettings State { get; private set; } = LobbySettings.Defaults();

		internal bool IsHost
		{
			get
			{
				if (PhotonNetwork.InRoom)
				{
					return PhotonNetwork.IsMasterClient;
				}
				return false;
			}
		}

		internal bool HasHostSettings { get; private set; }

		internal string Status { get; private set; } = "Waiting for the host's settings...";

		private void Awake()
		{
			//IL_004c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0056: Expected O, but got Unknown
			//IL_009e: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a8: Expected O, but got Unknown
			//IL_00d5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e2: Expected O, but got Unknown
			Instance = this;
			try
			{
				_shared = ((BaseUnityPlugin)this).Config.Bind<bool>("Lobby", "SharedUpgrades", true, "Share all supported upgrades with every player. Changes apply to future upgrades.");
				_max = ((BaseUnityPlugin)this).Config.Bind<int>("Lobby", "MaxPlayers", 10, new ConfigDescription("Lobby player limit, applied live.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(1, 10), Array.Empty<object>()));
				_late = ((BaseUnityPlugin)this).Config.Bind<bool>("Lobby", "LateJoining", true, "Allow joining during the truck, shop and level phases. The pre-game lobby stays joinable.");
				DependencySettings.Configure(((BaseUnityPlugin)this).Logger);
				_network = ((Component)this).gameObject.AddComponent<NetworkSync>();
				_harmony = new Harmony("MechGaming.REPO.MultiplayerPlus");
				_harmony.Patch((MethodBase)AccessTools.Method(typeof(MenuPageLobby), "Start", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(typeof(Plugin), "LobbyStarted", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				((BaseUnityPlugin)this).Logger.LogInfo((object)"Multiplayer+ 0.1.1 loaded. Lobby controls are host-authoritative.");
			}
			catch (Exception ex)
			{
				((BaseUnityPlugin)this).Logger.LogError((object)("Multiplayer+ could not initialize and has been disabled: " + ex));
				((Behaviour)this).enabled = false;
				Harmony harmony = _harmony;
				if (harmony != null)
				{
					harmony.UnpatchSelf();
				}
				DependencySettings.Dispose();
				if ((Object)(object)_network != (Object)null)
				{
					Object.Destroy((Object)(object)_network);
				}
				Instance = null;
			}
		}

		private static void LobbyStarted(MenuPageLobby __instance)
		{
			try
			{
				LobbyPanel.Attach(__instance);
			}
			catch (Exception ex)
			{
				((BaseUnityPlugin)Instance).Logger.LogError((object)("Could not create the Multiplayer+ lobby panel: " + ex));
			}
		}

		private void Update()
		{
			if (_room != PhotonNetwork.CurrentRoom || _lastHost != IsHost)
			{
				ResetSession();
				_room = PhotonNetwork.CurrentRoom;
				_lastHost = IsHost;
			}
			_network.Tick();
			if (Time.unscaledTime < _nextTick)
			{
				return;
			}
			_nextTick = Time.unscaledTime + 0.5f;
			if (!IsHost)
			{
				return;
			}
			try
			{
				string currentSaveId = SaveName.CurrentSaveId;
				if (!HasHostSettings || currentSaveId != _saveId)
				{
					if (string.IsNullOrEmpty(currentSaveId) || (Object)(object)StatsManager.instance == (Object)null)
					{
						return;
					}
					LobbySettings lobbySettings = LobbySettings.Defaults(SaveName.CurrentName);
					if (!LobbySettings.TryCreate(lobbySettings.ServerName, _shared.Value, _max.Value, _late.Value, out LobbySettings settings, out string _))
					{
						settings = lobbySettings;
					}
					DependencySettings.Apply(settings.SharedUpgrades, settings.MaxPlayers, settings.LateJoining);
					State = settings;
					HasHostSettings = true;
					_saveId = currentSaveId;
					Status = "Changes apply immediately.";
					_network.Publish();
				}
				DependencySettings.Tick();
			}
			catch (Exception ex)
			{
				Status = "Settings could not be applied. See BepInEx log.";
				((BaseUnityPlugin)this).Logger.LogError((object)("Multiplayer+ settings: " + ex));
				_nextTick = Time.unscaledTime + 5f;
			}
		}

		internal bool TryApply(string name, bool shared, int max, bool late)
		{
			if (!IsHost || !HasHostSettings)
			{
				Status = "Only the host can change settings.";
				return false;
			}
			if (!LobbySettings.TryCreate(name, shared, max, late, out LobbySettings settings, out string error))
			{
				Status = error;
				return false;
			}
			LobbySettings state = State;
			try
			{
				DependencySettings.Apply(shared, max, late);
				if (settings.ServerName != state.ServerName)
				{
					SaveName.Rename(settings.ServerName);
				}
			}
			catch (Exception ex)
			{
				try
				{
					DependencySettings.Apply(state.SharedUpgrades, state.MaxPlayers, state.LateJoining);
				}
				catch (Exception ex2)
				{
					((BaseUnityPlugin)this).Logger.LogError((object)("Settings rollback failed: " + ex2));
				}
				Status = "Change failed. See BepInEx log.";
				((BaseUnityPlugin)this).Logger.LogError((object)ex);
				return false;
			}
			State = settings;
			bool saveOnConfigSet = ((BaseUnityPlugin)this).Config.SaveOnConfigSet;
			((BaseUnityPlugin)this).Config.SaveOnConfigSet = false;
			try
			{
				_shared.Value = shared;
				_max.Value = max;
				_late.Value = late;
				((BaseUnityPlugin)this).Config.Save();
			}
			catch (Exception ex3)
			{
				((BaseUnityPlugin)this).Logger.LogWarning((object)("Settings are live but could not be saved: " + ex3.Message));
			}
			finally
			{
				((BaseUnityPlugin)this).Config.SaveOnConfigSet = saveOnConfigSet;
			}
			Status = ((max < PhotonNetwork.CurrentRoom.PlayerCount) ? "Player limit takes effect as players leave." : "Changes apply immediately.");
			_network.Publish();
			((BaseUnityPlugin)this).Logger.LogInfo((object)$"Lobby settings updated: shared={shared}, max={max}, late joining={late}.");
			return true;
		}

		internal void ReceiveHostState(LobbySettings state)
		{
			if (!IsHost)
			{
				State = state;
				HasHostSettings = true;
				Status = "Host controls these settings.";
			}
		}

		internal void ResetSession()
		{
			DependencySettings.RestoreLocalSettings();
			HasHostSettings = false;
			State = LobbySettings.Defaults();
			_saveId = "";
			Status = "Waiting for the host's settings...";
		}

		private void OnDestroy()
		{
			Harmony harmony = _harmony;
			if (harmony != null)
			{
				harmony.UnpatchSelf();
			}
			DependencySettings.Dispose();
			if ((Object)(object)_network != (Object)null)
			{
				Object.Destroy((Object)(object)_network);
			}
			if (Instance == this)
			{
				Instance = null;
			}
		}
	}
	internal static class SaveName
	{
		internal static string CurrentSaveId
		{
			get
			{
				object obj;
				if (!((Object)(object)StatsManager.instance == (Object)null))
				{
					obj = (string)AccessTools.Field(typeof(StatsManager), "saveFileCurrent")?.GetValue(StatsManager.instance);
					if (obj == null)
					{
						return "";
					}
				}
				else
				{
					obj = "";
				}
				return (string)obj;
			}
		}

		internal static string CurrentName
		{
			get
			{
				if (!((Object)(object)StatsManager.instance == (Object)null))
				{
					return StatsManager.instance.teamName;
				}
				return "R.E.P.O.";
			}
		}

		internal static void Rename(string name)
		{
			//IL_009a: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a1: Expected O, but got Unknown
			StatsManager val = StatsManager.instance ?? throw new InvalidOperationException("The current save is not ready.");
			string currentSaveId = CurrentSaveId;
			if (string.IsNullOrEmpty(currentSaveId) || Path.GetFileName(currentSaveId) != currentSaveId)
			{
				throw new InvalidOperationException("The current save is not ready.");
			}
			string text = Path.Combine(Application.persistentDataPath, "saves", currentSaveId, currentSaveId + ".es3");
			if (File.Exists(text))
			{
				string text2 = ((string)AccessTools.Field(typeof(StatsManager), "totallyNormalString")?.GetValue(val)) ?? throw new InvalidOperationException("The game's save encryption settings are unavailable.");
				ES3Settings val2 = new ES3Settings(text, (EncryptionType)1, text2, (ES3Settings)null);
				byte[] bytes = File.ReadAllBytes(text);
				try
				{
					ES3.Save<string>("teamName", name, val2);
					ES3.Save<bool>("teamNameChanged", true, val2);
				}
				catch
				{
					File.WriteAllBytes(text, bytes);
					throw;
				}
			}
			val.teamName = name;
			val.teamNameChanged = true;
		}
	}
}