Decompiled source of CloverPitCoop v0.9.3

plugins/CloverPitCoop.dll

Decompiled 2 hours ago
using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Numerics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using System.Text;
using System.Threading;
using BepInEx;
using BepInEx.Logging;
using CloverPitCoop.Net;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using Panik;
using Steamworks;
using Steamworks.Data;
using TMPro;
using UnityEngine;
using UnityEngine.Rendering;
using UnityEngine.UI;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETFramework,Version=v4.7.2", FrameworkDisplayName = ".NET Framework 4.7.2")]
[assembly: AssemblyCompany("CloverPitCoop")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("0.1.0.0")]
[assembly: AssemblyInformationalVersion("0.1.0")]
[assembly: AssemblyProduct("CloverPitCoop")]
[assembly: AssemblyTitle("CloverPitCoop")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("0.1.0.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace CloverPitCoop
{
	internal static class BanList
	{
		private static readonly HashSet<string> _session = new HashSet<string>(StringComparer.OrdinalIgnoreCase);

		private static readonly Dictionary<string, string> _permanent = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);

		private static bool _loaded;

		private static string FilePath => Path.Combine(Paths.ConfigPath, "CloverPitCoop.bans.txt");

		public static int SessionCount => _session.Count;

		public static int PermanentCount
		{
			get
			{
				Load();
				return _permanent.Count;
			}
		}

		public static bool IsBanned(string id)
		{
			if (string.IsNullOrEmpty(id))
			{
				return false;
			}
			Load();
			if (!_session.Contains(id))
			{
				return _permanent.ContainsKey(id);
			}
			return true;
		}

		public static void BanSession(string id)
		{
			if (!string.IsNullOrEmpty(id))
			{
				_session.Add(id);
			}
		}

		public static void BanPermanent(string id, string name)
		{
			if (!string.IsNullOrEmpty(id))
			{
				Load();
				_permanent[id] = name ?? "";
				Save();
			}
		}

		public static void ClearSession()
		{
			_session.Clear();
		}

		public static void ClearPermanent()
		{
			Load();
			_permanent.Clear();
			Save();
		}

		private static void Load()
		{
			if (_loaded)
			{
				return;
			}
			_loaded = true;
			try
			{
				if (!File.Exists(FilePath))
				{
					return;
				}
				string[] array = File.ReadAllLines(FilePath);
				for (int i = 0; i < array.Length; i++)
				{
					string text = array[i].Trim();
					if (text.Length != 0 && !text.StartsWith("#"))
					{
						int num = text.IndexOf('#');
						string text2 = ((num >= 0) ? text.Substring(0, num) : text).Trim();
						string value = ((num >= 0) ? text.Substring(num + 1).Trim() : "");
						if (text2.Length > 0)
						{
							_permanent[text2] = value;
						}
					}
				}
			}
			catch (Exception ex)
			{
				Plugin.Log.LogWarning((object)("Ban list unreadable: " + ex.Message));
			}
		}

		private static void Save()
		{
			try
			{
				List<string> list = new List<string> { "# CloverPit Co-op permanent bans. One id per line; text after # is a note. Delete a line to unban." };
				foreach (KeyValuePair<string, string> item in _permanent)
				{
					list.Add((item.Value.Length > 0) ? (item.Key + "  # " + item.Value) : item.Key);
				}
				File.WriteAllLines(FilePath, list);
			}
			catch (Exception ex)
			{
				Plugin.Log.LogWarning((object)("Ban list save failed: " + ex.Message));
			}
		}
	}
	[Serializable]
	internal class Placement
	{
		public Vector3 position;

		public float yaw;

		public float scale = 1f;

		public Placement()
		{
		}

		public Placement(Vector3 p, float y, float s = 1f)
		{
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			position = p;
			yaw = y;
			scale = s;
		}
	}
	[Serializable]
	internal class GeneralSettings
	{
		public bool enabled = true;

		public bool rebuildGameMeshes = true;
	}
	[Serializable]
	internal class RulesSettings
	{
		public int startingResourcesMultiplier = 2;

		public int vanillaStartingDeposit = 30;

		public int debtMultiplier = 2;

		public bool clientUsesHostDebt = true;

		public bool scaleMemoryCardGrants = true;

		public bool interestsGrowPaysForBoth = true;

		public bool atmShowsCombinedRounds = true;

		public bool waitForPartnerRoundsBeforeDying = true;

		public bool holdDeathForPartnerLastChance = true;

		public bool loseTogether = true;

		public bool holdDeadlineWhilePartnerSpins = true;

		public bool sharedSkeleton = true;

		public bool lockEquippedLimbs = true;

		public bool shareHostMemoryCard = true;

		public bool doorNeedsBothKeys = true;

		public bool doorNeedsBothClicks = true;

		public bool disableDlc = true;
	}
	[Serializable]
	internal class SyncSettings
	{
		public float statusPerSecond = 30f;

		public float stationPerSecond = 24f;

		public float screenFramesPerSecond = 16f;

		public int screenMaxSize = 512;

		public int screenJpegQuality = 70;

		public float charmCheckSeconds = 0.25f;

		public float charmResendSeconds = 3f;

		public float partnerTimeoutSeconds = 15f;

		public bool requireSameModVersion = true;

		public bool syncColors = true;

		public bool syncSprites = true;

		public bool syncLights = true;

		public bool syncParticles = true;

		public bool syncMaterials = true;

		public bool syncSounds = true;

		public float partnerSoundVolume = 0.7f;

		public float partnerSoundDistance = 20f;

		public int maxSoundsPerSecond = 25;

		public bool mutePartnerMachineWhilePlaying = true;

		public bool partnerHalfIsSolid = true;
	}
	[Serializable]
	internal class AvatarSettings
	{
		public bool show = true;

		public string style = "capsule";

		public float skullSize = 0.6f;

		public float skullYaw;

		public float armLength = 1f;

		public float legLength = 1f;

		public Color boneColor = new Color(0.86f, 0.8f, 0.68f, 1f);

		public Color color = new Color(0.55f, 0.75f, 0.45f, 1f);

		public Color strapColor = new Color(0.33f, 0.22f, 0.12f, 1f);

		public Color metalColor = new Color(0.58f, 0.6f, 0.57f, 1f);

		public Color darkColor = new Color(0.16f, 0.15f, 0.14f, 1f);

		public Color visorColor = new Color(0.05f, 0.08f, 0.09f, 1f);

		public Color skinColor = new Color(0.62f, 0.55f, 0.47f, 1f);

		public Color eyeColor = new Color(0.08f, 0.08f, 0.08f, 1f);

		public float smoothing = 12f;

		public bool showName = true;

		public float nameSize = 0.05f;

		public Color nameColor = Color.white;
	}
	[Serializable]
	internal class UiSettings
	{
		public string menuKey = "F6";

		public bool showStatus = true;

		public float toastSeconds = 6f;

		public int maxToasts = 4;

		public int toastFontSize = 26;
	}
	[Serializable]
	internal class ConnectionSettings
	{
		public string directJoinAddress = "127.0.0.1";

		public int directPort = 27777;

		public bool steamLobbyFriendsOnly = true;
	}
	[Serializable]
	internal class LayoutSettings
	{
		public Placement atm = new Placement(new Vector3(4f, 4f, 6.7f), -90f);

		public Placement deadlineMonitor = new Placement(new Vector3(4.1f, 7.39f, 6.95f), -90f);

		public Placement patternsPoster = new Placement(new Vector3(-3.98f, 6.25f, 3.15f), 180f, 0.75f);

		public Placement symbolsPoster = new Placement(new Vector3(-3.98f, 6.25f, 5.6f), 0f, 0.75f);

		public Placement ticketMachine = new Placement(new Vector3(4.6f, 4.48f, -6.95f), 90f);

		public Placement deadlineBonusScreen = new Placement(new Vector3(3.2f, 4.9f, -6.9f), 90f);

		public Placement rewardBox = new Placement(new Vector3(2.6f, 6.6f, -6.95f), 90f);

		public Placement securityCamera = new Placement(new Vector3(4f, 9.4f, -6.95f), 90f);

		public Placement goldenToiletSticker = new Placement(new Vector3(3f, 4f, -6.96f), 90f);

		public bool hideMagazineStand = true;

		public bool hideSurgeryMachine = true;
	}
	[Serializable]
	internal class DebugSettings
	{
		public bool dumpRoomOnLoad;

		public string dumpKey = "F8";

		public string reapplyKey = "F7";
	}
	[Serializable]
	internal class SharedSettings
	{
		public RulesSettings rules = new RulesSettings();

		public LayoutSettings layout = new LayoutSettings();
	}
	[Serializable]
	internal class CoopConfig
	{
		public string _about = "CloverPit Co-op settings. Save this file while the game runs to apply. Delete a key to get its default back. Keys use Unity KeyCode names (F6, Insert, ...). When you join someone, their rules and layout are used for that session; this file is not changed.";

		public GeneralSettings general = new GeneralSettings();

		public RulesSettings rules = new RulesSettings();

		public SyncSettings sync = new SyncSettings();

		public AvatarSettings avatar = new AvatarSettings();

		public UiSettings ui = new UiSettings();

		public ConnectionSettings connection = new ConnectionSettings();

		public LayoutSettings layout = new LayoutSettings();

		public DebugSettings debug = new DebugSettings();

		[NonSerialized]
		private string _path;

		[NonSerialized]
		private CoopConfig _file;

		[NonSerialized]
		private string _hostShared;

		[NonSerialized]
		private string _lastWritten;

		[NonSerialized]
		public Action Changed;

		public bool UsingHostSettings => _hostShared != null;

		public static CoopConfig Load(string path)
		{
			CoopConfig coopConfig = new CoopConfig();
			coopConfig._path = path;
			coopConfig._file = ReadFile(path);
			coopConfig.WriteFile();
			coopConfig.Rebuild();
			return coopConfig;
		}

		private static CoopConfig ReadFile(string path)
		{
			//IL_0065: Unknown result type (might be due to invalid IL or missing references)
			//IL_007e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0090: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ce: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e2: Unknown result type (might be due to invalid IL or missing references)
			//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_0143: Unknown result type (might be due to invalid IL or missing references)
			//IL_0148: 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_016c: Unknown result type (might be due to invalid IL or missing references)
			//IL_018f: 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_017f: 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_01bb: 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)
			CoopConfig coopConfig = new CoopConfig();
			try
			{
				if (File.Exists(path))
				{
					JsonUtility.FromJsonOverwrite(File.ReadAllText(path), (object)coopConfig);
				}
			}
			catch (Exception ex)
			{
				Plugin.Log.LogError((object)("Config: could not read " + path + " (" + ex.Message + "). Using defaults until it's fixed."));
			}
			AvatarSettings avatarSettings = new AvatarSettings();
			bool num = Near(coopConfig.avatar.color, new Color(0.25f, 0.45f, 0.62f, 1f)) || Near(coopConfig.avatar.color, new Color(0.3f, 0.31f, 0.26f, 1f));
			if (coopConfig.layout.patternsPoster != null)
			{
				Vector3 val = coopConfig.layout.patternsPoster.position - new Vector3(-3.98f, 10.2f, 4.25f);
				if (((Vector3)(ref val)).sqrMagnitude < 0.01f)
				{
					LayoutSettings layoutSettings = new LayoutSettings();
					coopConfig.layout.patternsPoster = layoutSettings.patternsPoster;
					coopConfig.layout.symbolsPoster = layoutSettings.symbolsPoster;
				}
			}
			if (num)
			{
				coopConfig.avatar.style = avatarSettings.style;
				coopConfig.avatar.color = avatarSettings.color;
				if (Near(coopConfig.avatar.eyeColor, new Color(0.9f, 0.25f, 0.1f, 1f)))
				{
					coopConfig.avatar.eyeColor = avatarSettings.eyeColor;
				}
				if (Near(coopConfig.avatar.nameColor, new Color(0.95f, 0.55f, 0.1f, 1f)))
				{
					coopConfig.avatar.nameColor = avatarSettings.nameColor;
				}
			}
			coopConfig.Sanitize();
			return coopConfig;
		}

		public void ReloadFile()
		{
			_file = ReadFile(_path);
			Rebuild();
			Plugin.Log.LogInfo((object)("Config reloaded" + (UsingHostSettings ? " (rules and layout still come from the host)." : ".")));
		}

		public void SetHostShared(string json)
		{
			if (!(json == _hostShared))
			{
				_hostShared = json;
				Rebuild();
			}
		}

		public string SharedJson()
		{
			return JsonUtility.ToJson((object)new SharedSettings
			{
				rules = rules,
				layout = layout
			});
		}

		private void Rebuild()
		{
			JsonUtility.FromJsonOverwrite(JsonUtility.ToJson((object)_file), (object)this);
			if (_hostShared != null)
			{
				try
				{
					SharedSettings sharedSettings = new SharedSettings();
					JsonUtility.FromJsonOverwrite(_hostShared, (object)sharedSettings);
					rules = sharedSettings.rules;
					layout = sharedSettings.layout;
				}
				catch (Exception ex)
				{
					Plugin.Log.LogWarning((object)("Host settings unreadable, using our own: " + ex.Message));
				}
			}
			Sanitize();
			try
			{
				Changed?.Invoke();
			}
			catch (Exception ex2)
			{
				Plugin.Log.LogWarning((object)("Config change handler: " + ex2.Message));
			}
		}

		public void SaveConnection(string address, int port)
		{
			_file.connection.directJoinAddress = address;
			_file.connection.directPort = port;
			_file.Sanitize();
			connection.directJoinAddress = _file.connection.directJoinAddress;
			connection.directPort = _file.connection.directPort;
			WriteFile();
		}

		private void WriteFile()
		{
			try
			{
				string text = JsonUtility.ToJson((object)_file, true);
				if (!(text == _lastWritten))
				{
					if (File.Exists(_path) && File.ReadAllText(_path) == text)
					{
						_lastWritten = text;
						return;
					}
					File.WriteAllText(_path, text);
					_lastWritten = text;
				}
			}
			catch (Exception ex)
			{
				Plugin.Log.LogWarning((object)("Config save failed: " + ex.Message));
			}
		}

		private void Sanitize()
		{
			//IL_03f6: Unknown result type (might be due to invalid IL or missing references)
			//IL_0415: Unknown result type (might be due to invalid IL or missing references)
			//IL_041a: Unknown result type (might be due to invalid IL or missing references)
			if (general == null)
			{
				general = new GeneralSettings();
			}
			if (rules == null)
			{
				rules = new RulesSettings();
			}
			if (sync == null)
			{
				sync = new SyncSettings();
			}
			if (avatar == null)
			{
				avatar = new AvatarSettings();
			}
			if (ui == null)
			{
				ui = new UiSettings();
			}
			if (connection == null)
			{
				connection = new ConnectionSettings();
			}
			if (layout == null)
			{
				layout = new LayoutSettings();
			}
			if (debug == null)
			{
				debug = new DebugSettings();
			}
			rules.startingResourcesMultiplier = Mathf.Clamp(rules.startingResourcesMultiplier, 1, 100);
			rules.debtMultiplier = Mathf.Clamp(rules.debtMultiplier, 1, 100);
			rules.vanillaStartingDeposit = Mathf.Max(0, rules.vanillaStartingDeposit);
			sync.statusPerSecond = Mathf.Clamp(sync.statusPerSecond, 1f, 120f);
			sync.stationPerSecond = Mathf.Clamp(sync.stationPerSecond, 1f, 120f);
			sync.screenFramesPerSecond = Mathf.Clamp(sync.screenFramesPerSecond, 0f, 60f);
			sync.screenMaxSize = Mathf.Clamp(sync.screenMaxSize, 64, 1024);
			sync.screenJpegQuality = Mathf.Clamp(sync.screenJpegQuality, 10, 100);
			sync.charmCheckSeconds = Mathf.Clamp(sync.charmCheckSeconds, 0.05f, 10f);
			sync.charmResendSeconds = Mathf.Clamp(sync.charmResendSeconds, 0.5f, 60f);
			sync.partnerTimeoutSeconds = Mathf.Clamp(sync.partnerTimeoutSeconds, 3f, 600f);
			sync.partnerSoundVolume = Mathf.Clamp01(sync.partnerSoundVolume);
			sync.partnerSoundDistance = Mathf.Clamp(sync.partnerSoundDistance, 1f, 200f);
			sync.maxSoundsPerSecond = Mathf.Clamp(sync.maxSoundsPerSecond, 0, 200);
			avatar.smoothing = Mathf.Clamp(avatar.smoothing, 0.1f, 100f);
			avatar.nameSize = Mathf.Clamp(avatar.nameSize, 0.005f, 1f);
			ui.toastSeconds = Mathf.Clamp(ui.toastSeconds, 0.5f, 60f);
			ui.maxToasts = Mathf.Clamp(ui.maxToasts, 1, 20);
			ui.toastFontSize = Mathf.Clamp(ui.toastFontSize, 8, 96);
			connection.directPort = Mathf.Clamp(connection.directPort, 1, 65535);
			if (string.IsNullOrWhiteSpace(connection.directJoinAddress))
			{
				connection.directJoinAddress = "127.0.0.1";
			}
			Placement[] array = new Placement[9] { layout.atm, layout.deadlineMonitor, layout.patternsPoster, layout.ticketMachine, layout.deadlineBonusScreen, layout.rewardBox, layout.securityCamera, layout.goldenToiletSticker, layout.symbolsPoster };
			foreach (Placement placement in array)
			{
				if (placement != null)
				{
					if (!IsFinite(placement.position) || ((Vector3)(ref placement.position)).magnitude > 100f)
					{
						placement.position = Vector3.zero;
					}
					if (float.IsNaN(placement.yaw) || float.IsInfinity(placement.yaw))
					{
						placement.yaw = 0f;
					}
					if (float.IsNaN(placement.scale) || placement.scale <= 0.05f || placement.scale > 5f)
					{
						placement.scale = 1f;
					}
				}
			}
			if (layout.atm == null)
			{
				layout.atm = new LayoutSettings().atm;
			}
			if (layout.deadlineMonitor == null)
			{
				layout.deadlineMonitor = new LayoutSettings().deadlineMonitor;
			}
			if (layout.patternsPoster == null)
			{
				layout.patternsPoster = new LayoutSettings().patternsPoster;
			}
			if (layout.ticketMachine == null)
			{
				layout.ticketMachine = new LayoutSettings().ticketMachine;
			}
			if (layout.deadlineBonusScreen == null)
			{
				layout.deadlineBonusScreen = new LayoutSettings().deadlineBonusScreen;
			}
			if (layout.rewardBox == null)
			{
				layout.rewardBox = new LayoutSettings().rewardBox;
			}
			if (layout.securityCamera == null)
			{
				layout.securityCamera = new LayoutSettings().securityCamera;
			}
			if (layout.goldenToiletSticker == null)
			{
				layout.goldenToiletSticker = new LayoutSettings().goldenToiletSticker;
			}
			if (layout.symbolsPoster == null)
			{
				layout.symbolsPoster = new LayoutSettings().symbolsPoster;
			}
		}

		private static bool Near(Color a, Color b)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			//IL_0018: Unknown result type (might be due to invalid IL or missing references)
			//IL_0025: Unknown result type (might be due to invalid IL or missing references)
			//IL_002b: Unknown result type (might be due to invalid IL or missing references)
			return Mathf.Abs(a.r - b.r) + Mathf.Abs(a.g - b.g) + Mathf.Abs(a.b - b.b) < 0.02f;
		}

		private static bool IsFinite(Vector3 v)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			//IL_001a: 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_0034: 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 (!float.IsNaN(v.x) && !float.IsNaN(v.y) && !float.IsNaN(v.z) && !float.IsInfinity(v.x) && !float.IsInfinity(v.y))
			{
				return !float.IsInfinity(v.z);
			}
			return false;
		}

		public static KeyCode Key(string name, KeyCode fallback)
		{
			//IL_0018: 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)
			if (string.IsNullOrEmpty(name) || !Enum.TryParse<KeyCode>(name.Trim(), ignoreCase: true, out KeyCode result))
			{
				return fallback;
			}
			return result;
		}
	}
	internal class PartnerState
	{
		public string Name = "Partner";

		public string ModVersion = "";

		public bool InRun;

		public int RoundsLeft;

		public long DebtIndex;

		public BigInteger Debt;

		public bool HasDoorKey;

		public bool ReadyToDie;

		public int Phase;

		public Vector3 CamPos;

		public Quaternion CamRot = Quaternion.identity;

		public float LastStatusTime = -999f;
	}
	internal class CoopSession : MonoBehaviour
	{
		public enum RemoveKind
		{
			Kick,
			BanSession,
			BanPermanent
		}

		public bool PartnerDied;

		public static bool ApplyingRemote;

		private float _nextHello;

		private float _nextStatus;

		private readonly List<(Action act, bool anyPhase)> _deferred = new List<(Action, bool)>();

		private readonly List<string> _toasts = new List<string>();

		private float _toastUntil;

		private bool _steamHooked;

		private float _nextSteamHookTry;

		private float _lastRelink = -999f;

		private bool _versionWarned;

		public static CoopSession Instance { get; private set; }

		public ITransport Transport { get; private set; }

		public PartnerState Partner { get; private set; } = new PartnerState();

		public bool HelloReceived { get; private set; }

		public static bool Active
		{
			get
			{
				if ((Object)(object)Instance != (Object)null)
				{
					return Instance.IsLinked;
				}
				return false;
			}
		}

		public static bool IsHost => Instance?.Transport?.IsHost == true;

		public bool IsLinked
		{
			get
			{
				if (Transport != null && Transport.IsConnected)
				{
					return HelloReceived;
				}
				return false;
			}
		}

		public bool BothInRun
		{
			get
			{
				if (IsLinked && LocalInRun && Partner.InRun)
				{
					return Time.unscaledTime - Partner.LastStatusTime < 10f;
				}
				return false;
			}
		}

		public static bool LocalInRun
		{
			get
			{
				if ((Object)(object)GameplayMaster.instance != (Object)null)
				{
					return GameplayData.Instance != null;
				}
				return false;
			}
		}

		public IReadOnlyList<string> Toasts
		{
			get
			{
				if (!(Time.unscaledTime < _toastUntil))
				{
					return Array.Empty<string>();
				}
				return _toasts;
			}
		}

		public static void Create()
		{
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			//IL_0018: Unknown result type (might be due to invalid IL or missing references)
			//IL_001e: Expected O, but got Unknown
			//IL_001e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0026: Unknown result type (might be due to invalid IL or missing references)
			//IL_005b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0062: 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)
			if (!((Object)(object)Instance != (Object)null))
			{
				GameObject val = new GameObject("CloverPitCoop.Session");
				Object.DontDestroyOnLoad((Object)val);
				((Object)val).hideFlags = (HideFlags)61;
				Instance = val.AddComponent<CoopSession>();
				CoopConfig cfg = Plugin.Cfg;
				cfg.Changed = (Action)Delegate.Combine(cfg.Changed, new Action(Instance.OnConfigChanged));
				val.AddComponent<CoopUI>();
				val.AddComponent<SharedEconomy>();
				val.AddComponent<PartnerView>();
				val.AddComponent<StationSync>();
			}
		}

		private void TryHookSteam()
		{
			if (_steamHooked || Time.unscaledTime < _nextSteamHookTry)
			{
				return;
			}
			_nextSteamHookTry = Time.unscaledTime + 2f;
			try
			{
				if (SteamTransport.SteamAvailable)
				{
					SteamFriends.OnGameLobbyJoinRequested += OnSteamJoinRequested;
					_steamHooked = true;
					Plugin.Log.LogInfo((object)"Co-op: Steam invites hooked.");
				}
			}
			catch (Exception ex)
			{
				_steamHooked = true;
				Plugin.Log.LogWarning((object)("Steam join hook unavailable: " + ex.Message));
			}
		}

		public void HostSteam()
		{
			Disconnect();
			SteamTransport steamTransport = SteamTransport.Host();
			steamTransport.PartnerFound += SayHello;
			Transport = steamTransport;
		}

		public void InviteSteamFriend()
		{
			(Transport as SteamTransport)?.InviteOverlay();
		}

		private void OnSteamJoinRequested(Lobby lobby, SteamId friend)
		{
			//IL_0024: 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_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0064: Unknown result type (might be due to invalid IL or missing references)
			//IL_0082: Unknown result type (might be due to invalid IL or missing references)
			if (BanList.IsBanned("steam:" + friend.Value) || BanList.IsBanned("steam:" + ((Lobby)(ref lobby)).Owner.Id.Value))
			{
				Toast("That player is on your ban list.");
				return;
			}
			Plugin.Log.LogInfo((object)("Steam: join requested for lobby " + ((object)((Lobby)(ref lobby)).Id/*cast due to .constrained prefix*/).ToString()));
			Disconnect();
			SteamTransport steamTransport = SteamTransport.Join(lobby);
			steamTransport.PartnerFound += SayHello;
			Transport = steamTransport;
		}

		public void RemovePartner(RemoveKind kind)
		{
			if (Transport != null)
			{
				string partnerId = Transport.PartnerId;
				string name = Partner.Name;
				if (kind == RemoveKind.BanSession)
				{
					BanList.BanSession(partnerId);
				}
				if (kind == RemoveKind.BanPermanent)
				{
					BanList.BanPermanent(partnerId, name);
				}
				if (kind != RemoveKind.Kick && string.IsNullOrEmpty(partnerId))
				{
					Toast("Couldn't tell who they are, so only kicked them.");
				}
				(MemoryStream ms, BinaryWriter w) tuple = Msg.Begin(MsgType.Kick);
				var (ms, _) = tuple;
				tuple.w.Write(kind switch
				{
					RemoveKind.BanSession => "banned for this session", 
					RemoveKind.Kick => "kicked", 
					_ => "banned", 
				});
				Send(ms);
				ITransport transport = Transport;
				if (HelloReceived)
				{
					Unlink((kind == RemoveKind.Kick) ? ("Kicked " + name + ".") : ("Banned " + name + ((kind == RemoveKind.BanPermanent) ? "." : " for this session.")));
				}
				((MonoBehaviour)this).StartCoroutine(DropSoon(transport));
				if (!transport.IsHost)
				{
					Transport = null;
				}
			}
		}

		private IEnumerator DropSoon(ITransport t)
		{
			float until = Time.unscaledTime + 0.5f;
			while (Time.unscaledTime < until)
			{
				yield return null;
			}
			try
			{
				if (t.IsHost)
				{
					t.DropPartner();
				}
				else
				{
					t.Dispose();
				}
			}
			catch (Exception ex)
			{
				Plugin.Log.LogWarning((object)("Dropping partner: " + ex.Message));
			}
		}

		public void HostDirect(int port)
		{
			Disconnect();
			Transport = TcpTransport.Host(port);
		}

		public void JoinDirect(string ip, int port)
		{
			Disconnect();
			Transport = TcpTransport.Join(ip, port);
		}

		private void Unlink(string why)
		{
			HelloReceived = false;
			PartnerDied = false;
			GameRules.ResetDoor();
			_deferred.Clear();
			Partner = new PartnerState();
			Plugin.Cfg.SetHostShared(null);
			Toast(why);
		}

		public void Disconnect()
		{
			if (Transport != null)
			{
				try
				{
					Transport.Dispose();
				}
				catch (Exception ex)
				{
					Plugin.Log.LogWarning((object)("Disconnect: " + ex.Message));
				}
			}
			Transport = null;
			HelloReceived = false;
			Plugin.Cfg?.SetHostShared(null);
			PartnerDied = false;
			GameRules.ResetDoor();
			_deferred.Clear();
			Partner = new PartnerState();
			_versionWarned = false;
		}

		private void Update()
		{
			TryHookSteam();
			if (Transport != null)
			{
				try
				{
					Transport.Poll(Handle);
				}
				catch (Exception ex)
				{
					Plugin.Log.LogError((object)("Receive error: " + ex));
				}
				float unscaledTime = Time.unscaledTime;
				if (!HelloReceived && unscaledTime >= _nextHello && (Transport.IsConnected || Transport is SteamTransport))
				{
					_nextHello = unscaledTime + 1f;
					SayHello();
				}
				if (HelloReceived && (!Transport.IsConnected || (Partner.LastStatusTime > 0f && unscaledTime - Partner.LastStatusTime > Plugin.Cfg.sync.partnerTimeoutSeconds)))
				{
					Unlink(Transport.IsConnected ? (Partner.Name + " stopped responding.") : (Partner.Name + " disconnected."));
				}
				if (IsLinked && unscaledTime >= _nextStatus)
				{
					_nextStatus = unscaledTime + 1f / Plugin.Cfg.sync.statusPerSecond;
					SendStatus();
				}
				RunDeferred();
			}
		}

		public void Defer(Action a, bool anyPhase = false)
		{
			if (_deferred.Count >= 64)
			{
				Plugin.Log.LogWarning((object)"Co-op: too many queued partner actions, dropping one.");
			}
			else
			{
				_deferred.Add((a, anyPhase));
			}
		}

		private void RunDeferred()
		{
			if (_deferred.Count == 0 || !LocalInRun)
			{
				return;
			}
			bool flag = GameRules.IsSafeToApplyRemote();
			for (int i = 0; i < _deferred.Count; i++)
			{
				if (flag || _deferred[i].anyPhase)
				{
					Action item = _deferred[i].act;
					_deferred.RemoveAt(i);
					try
					{
						item();
						break;
					}
					catch (Exception ex)
					{
						Plugin.Log.LogError((object)("Applying partner action failed: " + ex));
						break;
					}
				}
			}
		}

		public void Toast(string text)
		{
			_toasts.Add(text);
			while (_toasts.Count > Plugin.Cfg.ui.maxToasts)
			{
				_toasts.RemoveAt(0);
			}
			_toastUntil = Time.unscaledTime + Plugin.Cfg.ui.toastSeconds;
			Plugin.Log.LogInfo((object)("[toast] " + text));
		}

		public void Send(MemoryStream ms, bool bulk = false)
		{
			if (Transport == null)
			{
				return;
			}
			try
			{
				Transport.Send(ms.ToArray(), bulk);
			}
			catch (Exception ex)
			{
				Plugin.Log.LogWarning((object)("Send failed: " + ex.Message));
			}
		}

		public void SendSettings()
		{
			if (IsHost && IsLinked)
			{
				(MemoryStream ms, BinaryWriter w) tuple = Msg.Begin(MsgType.Settings);
				var (ms, _) = tuple;
				tuple.w.Write(Plugin.Cfg.SharedJson());
				Send(ms);
			}
		}

		private void OnConfigChanged()
		{
			if (IsHost && IsLinked)
			{
				SendSettings();
			}
		}

		private void SayHello()
		{
			var (ms, binaryWriter) = Msg.Begin(MsgType.Hello);
			binaryWriter.Write(LocalName());
			binaryWriter.Write("0.9.3");
			Send(ms);
		}

		private static string LocalName()
		{
			try
			{
				if (SteamTransport.SteamAvailable)
				{
					return SteamClient.Name;
				}
			}
			catch
			{
			}
			return Environment.UserName;
		}

		private void SendStatus()
		{
			//IL_0085: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c5: 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_00e5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d8: Unknown result type (might be due to invalid IL or missing references)
			(MemoryStream ms, BinaryWriter w) tuple = Msg.Begin(MsgType.Status);
			MemoryStream item = tuple.ms;
			BinaryWriter item2 = tuple.w;
			bool localInRun = LocalInRun;
			item2.Write(localInRun);
			item2.Write(localInRun ? GameplayData.RoundsLeftToDeadline() : 0);
			item2.Write(localInRun ? ((long)GameplayData.DebtIndexGet()) : 0);
			item2.WriteBig(localInRun ? GameplayData.DebtGet() : BigInteger.Zero);
			item2.Write(localInRun && GameRules.LocalHasDoorKey());
			item2.Write(localInRun && GameRules.LocalReadyToDie);
			item2.Write((!localInRun) ? (-1) : ((int)GameplayMaster.GetGamePhase()));
			Camera val = (((Object)(object)CameraGame.firstInstance != (Object)null) ? CameraGame.firstInstance.myCamera : Camera.main);
			item2.Write(((Object)(object)val != (Object)null) ? ((Component)val).transform.position : Vector3.zero);
			item2.Write(((Object)(object)val != (Object)null) ? ((Component)val).transform.rotation : Quaternion.identity);
			Send(item);
		}

		private void Handle(byte[] data)
		{
			try
			{
				HandleUnsafe(data);
			}
			catch (Exception ex)
			{
				Plugin.Log.LogWarning((object)("Co-op: bad message from partner skipped: " + ex.Message));
			}
		}

		public static string CleanName(string n)
		{
			if (string.IsNullOrEmpty(n))
			{
				return "Partner";
			}
			n = n.Replace("<", "").Replace(">", "").Replace("\n", " ")
				.Trim();
			if (n.Length > 32)
			{
				n = n.Substring(0, 32);
			}
			if (n.Length != 0)
			{
				return n;
			}
			return "Partner";
		}

		private static bool Finite(Vector3 v)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			//IL_001a: 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_0034: 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 (!float.IsNaN(v.x) && !float.IsNaN(v.y) && !float.IsNaN(v.z) && !float.IsInfinity(v.x) && !float.IsInfinity(v.y))
			{
				return !float.IsInfinity(v.z);
			}
			return false;
		}

		private void HandleUnsafe(byte[] data)
		{
			//IL_021c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0221: Unknown result type (might be due to invalid IL or missing references)
			//IL_0223: Unknown result type (might be due to invalid IL or missing references)
			//IL_0228: Unknown result type (might be due to invalid IL or missing references)
			//IL_0229: Unknown result type (might be due to invalid IL or missing references)
			//IL_0231: Unknown result type (might be due to invalid IL or missing references)
			//IL_0237: Unknown result type (might be due to invalid IL or missing references)
			//IL_023d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0243: Unknown result type (might be due to invalid IL or missing references)
			//IL_024f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0262: Unknown result type (might be due to invalid IL or missing references)
			//IL_0263: Unknown result type (might be due to invalid IL or missing references)
			//IL_026e: Unknown result type (might be due to invalid IL or missing references)
			//IL_026f: Unknown result type (might be due to invalid IL or missing references)
			if (data == null || data.Length == 0)
			{
				return;
			}
			using BinaryReader binaryReader = new BinaryReader(new MemoryStream(data));
			MsgType msgType = (MsgType)binaryReader.ReadByte();
			switch (msgType)
			{
			case MsgType.Hello:
			{
				string text3 = CleanName(binaryReader.ReadString());
				string text4 = binaryReader.ReadString();
				if (text4 != "0.9.3" && Plugin.Cfg.sync.requireSameModVersion)
				{
					if (!_versionWarned)
					{
						_versionWarned = true;
						Toast(text3 + " has co-op mod " + CleanName(text4) + ", you have 0.9.3. Both players need the same version.");
					}
					break;
				}
				Partner.Name = text3;
				Partner.ModVersion = text4;
				bool flag = !HelloReceived;
				if (flag || !(Time.unscaledTime - _lastRelink < 3f))
				{
					HelloReceived = true;
					_lastRelink = Time.unscaledTime;
					Partner.LastStatusTime = Time.unscaledTime;
					SayHello();
					if (flag)
					{
						Toast(Partner.Name + " connected.");
					}
					if (IsHost)
					{
						SendSettings();
					}
					SharedEconomy.Instance?.OnLinked();
					GameRules.OnLinked();
					PartnerView.Instance?.OnLinked();
					StationSync.Instance?.OnLinked();
				}
				break;
			}
			case MsgType.Status:
			{
				Partner.InRun = binaryReader.ReadBoolean();
				Partner.RoundsLeft = binaryReader.ReadInt32();
				Partner.DebtIndex = binaryReader.ReadInt64();
				Partner.Debt = binaryReader.ReadBig();
				Partner.HasDoorKey = binaryReader.ReadBoolean();
				Partner.ReadyToDie = binaryReader.ReadBoolean();
				Partner.Phase = binaryReader.ReadInt32();
				Vector3 val = binaryReader.ReadVector3();
				Quaternion val2 = binaryReader.ReadQuaternion();
				if (Finite(val) && Finite(new Vector3(val2.x, val2.y, val2.z)) && !float.IsNaN(val2.w))
				{
					Partner.CamPos = val;
					Partner.CamRot = val2;
				}
				Partner.LastStatusTime = Time.unscaledTime;
				break;
			}
			case MsgType.EconomyDelta:
				SharedEconomy.Instance?.ReceiveDelta(binaryReader);
				break;
			case MsgType.EconomySnapshot:
				SharedEconomy.Instance?.ReceiveSnapshot(binaryReader);
				break;
			case MsgType.GameOver:
				GameRules.ReceiveGameOver();
				break;
			case MsgType.SkeletonPiece:
				GameRules.ReceiveSkeletonPiece(binaryReader);
				break;
			case MsgType.MemoryCard:
				GameRules.ReceiveMemoryCard(binaryReader);
				break;
			case MsgType.Charms:
				PartnerView.Instance?.ReceiveCharms(binaryReader);
				break;
			case MsgType.Card:
				PartnerView.Instance?.ReceiveCard(binaryReader);
				break;
			case MsgType.ScreenFrame:
				PartnerView.Instance?.ReceiveScreen(binaryReader);
				break;
			case MsgType.StationState:
				StationSync.Instance?.Receive(binaryReader);
				break;
			case MsgType.StationRequest:
				StationSync.Instance?.ResendAll();
				break;
			case MsgType.DoorReady:
				GameRules.ReceiveDoorReady(binaryReader);
				break;
			case MsgType.Sound:
				PartnerSounds.Receive(binaryReader);
				break;
			case MsgType.Kick:
			{
				string text2 = CleanName(binaryReader.ReadString());
				string name = Partner.Name;
				if (IsHost)
				{
					if (HelloReceived)
					{
						Unlink(name + " left the game.");
					}
					Transport.DropPartner();
				}
				else
				{
					Disconnect();
					Toast(name + " removed you from the game (" + text2 + ").");
				}
				break;
			}
			case MsgType.Settings:
			{
				string text = binaryReader.ReadString();
				if (!IsHost && text.Length <= 65536)
				{
					bool num = !Plugin.Cfg.UsingHostSettings;
					Plugin.Cfg.SetHostShared(text);
					if (num)
					{
						Toast("Playing by " + Partner.Name + "'s rules and layout.");
					}
				}
				break;
			}
			default:
				Plugin.Log.LogWarning((object)("Unknown message " + msgType));
				break;
			}
		}

		private void OnDestroy()
		{
			Disconnect();
		}
	}
	internal class CoopUI : MonoBehaviour
	{
		private class Row
		{
			public Func<string> Label;

			public Action Activate;

			public Func<bool> Visible = () => true;

			public bool EditIp;

			public bool EditPort;

			public int Page;

			public bool Confirm;

			public TextMeshProUGUI Text;

			public Image Back;
		}

		private GameObject _canvasGo;

		private GameObject _panel;

		private TextMeshProUGUI _status;

		private TextMeshProUGUI _toasts;

		private TextMeshProUGUI _hint;

		private readonly List<Row> _rows = new List<Row>();

		private readonly List<Row> _allRows = new List<Row>();

		private int _page;

		private TextMeshProUGUI _title;

		private Row _armed;

		private float _armedUntil;

		private int _sel;

		private bool _open;

		private string _ip;

		private string _port;

		private bool _openInviteWhenReady;

		private TMP_FontAsset _font;

		private Material _textMat;

		private static readonly Color PanelColor = new Color(0.04f, 0.05f, 0.04f, 0.92f);

		private static readonly Color RowColor = new Color(1f, 1f, 1f, 0.04f);

		private static readonly Color SelColor = new Color(0.95f, 0.55f, 0.1f, 0.9f);

		private static readonly Color TextColor = new Color(0.92f, 0.9f, 0.8f);

		private static readonly Color AccentColor = new Color(0.45f, 0.85f, 0.35f);

		private bool _savedVisible;

		private CursorLockMode _savedLock;

		private Vector3 _lastMouse;

		private CoopSession S => CoopSession.Instance;

		private bool HasPartner
		{
			get
			{
				if (S.Transport != null)
				{
					return S.IsLinked;
				}
				return false;
			}
		}

		private static KeyCode MenuKey => CoopConfig.Key(Plugin.Cfg.ui.menuKey, (KeyCode)287);

		private void Start()
		{
			_ip = Plugin.Cfg.connection.directJoinAddress;
			_port = Plugin.Cfg.connection.directPort.ToString();
		}

		private bool EnsureBuilt()
		{
			//IL_0037: Unknown result type (might be due to invalid IL or missing references)
			//IL_0041: Expected O, but got Unknown
			//IL_00c6: 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: Expected O, but got Unknown
			//IL_020c: Unknown result type (might be due to invalid IL or missing references)
			//IL_025b: Unknown result type (might be due to invalid IL or missing references)
			//IL_026a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0279: Unknown result type (might be due to invalid IL or missing references)
			//IL_0288: Unknown result type (might be due to invalid IL or missing references)
			//IL_02d7: Unknown result type (might be due to invalid IL or missing references)
			//IL_02e6: Unknown result type (might be due to invalid IL or missing references)
			//IL_02f5: Unknown result type (might be due to invalid IL or missing references)
			//IL_0304: Unknown result type (might be due to invalid IL or missing references)
			//IL_0331: Unknown result type (might be due to invalid IL or missing references)
			//IL_033b: Expected O, but got Unknown
			//IL_0362: Unknown result type (might be due to invalid IL or missing references)
			//IL_0377: Unknown result type (might be due to invalid IL or missing references)
			//IL_037d: Expected O, but got Unknown
			//IL_016a: Unknown result type (might be due to invalid IL or missing references)
			//IL_03ea: Unknown result type (might be due to invalid IL or missing references)
			//IL_03f9: Unknown result type (might be due to invalid IL or missing references)
			//IL_03fe: Unknown result type (might be due to invalid IL or missing references)
			//IL_0413: Unknown result type (might be due to invalid IL or missing references)
			//IL_0433: Unknown result type (might be due to invalid IL or missing references)
			//IL_0447: Unknown result type (might be due to invalid IL or missing references)
			//IL_047e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0497: Unknown result type (might be due to invalid IL or missing references)
			//IL_04a6: Unknown result type (might be due to invalid IL or missing references)
			//IL_04b5: Unknown result type (might be due to invalid IL or missing references)
			//IL_04c4: Unknown result type (might be due to invalid IL or missing references)
			//IL_0543: Unknown result type (might be due to invalid IL or missing references)
			//IL_054a: Expected O, but got Unknown
			//IL_056d: Unknown result type (might be due to invalid IL or missing references)
			//IL_057e: Unknown result type (might be due to invalid IL or missing references)
			//IL_058d: Unknown result type (might be due to invalid IL or missing references)
			//IL_059c: Unknown result type (might be due to invalid IL or missing references)
			//IL_05a8: Unknown result type (might be due to invalid IL or missing references)
			//IL_05b7: Unknown result type (might be due to invalid IL or missing references)
			//IL_05cb: Expected O, but got Unknown
			//IL_0604: Unknown result type (might be due to invalid IL or missing references)
			//IL_0613: Unknown result type (might be due to invalid IL or missing references)
			//IL_0622: Unknown result type (might be due to invalid IL or missing references)
			//IL_0631: Unknown result type (might be due to invalid IL or missing references)
			//IL_0640: Unknown result type (might be due to invalid IL or missing references)
			//IL_06a3: Unknown result type (might be due to invalid IL or missing references)
			//IL_06c2: Unknown result type (might be due to invalid IL or missing references)
			//IL_06d1: Unknown result type (might be due to invalid IL or missing references)
			//IL_06e0: Unknown result type (might be due to invalid IL or missing references)
			//IL_06ef: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)_canvasGo != (Object)null)
			{
				return true;
			}
			_font = FindGameFont();
			if ((Object)(object)_font == (Object)null)
			{
				return false;
			}
			_textMat = new Material(((TMP_Asset)_font).material);
			Shader val = Shader.Find("TextMeshPro/Mobile/Distance Field") ?? Shader.Find("TextMeshPro/Distance Field");
			if ((Object)(object)val != (Object)null && !((Object)_textMat.shader).name.StartsWith("TextMeshPro"))
			{
				_textMat.shader = val;
			}
			string[] array = new string[2] { "_FaceColor", "_Color" };
			foreach (string text in array)
			{
				if (_textMat.HasProperty(text))
				{
					_textMat.SetColor(text, Color.white);
				}
			}
			array = new string[3] { "_OutlineWidth", "_UnderlayDilate", "_GlowPower" };
			foreach (string text2 in array)
			{
				if (_textMat.HasProperty(text2))
				{
					_textMat.SetFloat(text2, 0f);
				}
			}
			if (_textMat.HasProperty("_UnderlayColor"))
			{
				_textMat.SetColor("_UnderlayColor", new Color(0f, 0f, 0f, 0f));
			}
			_textMat.renderQueue = 3000;
			Plugin.Log.LogInfo((object)("CoopUI: font " + ((Object)_font).name + ", material shader " + ((Object)_textMat.shader).name));
			_canvasGo = new GameObject("CloverPitCoop.UI");
			Object.DontDestroyOnLoad((Object)(object)_canvasGo);
			Canvas obj = _canvasGo.AddComponent<Canvas>();
			obj.renderMode = (RenderMode)0;
			obj.sortingOrder = 32000;
			CanvasScaler obj2 = _canvasGo.AddComponent<CanvasScaler>();
			obj2.uiScaleMode = (ScaleMode)1;
			obj2.referenceResolution = new Vector2(1920f, 1080f);
			obj2.matchWidthOrHeight = 1f;
			_status = MakeText(_canvasGo.transform, "Status", 22f, (TextAlignmentOptions)260);
			Place(((TMP_Text)_status).rectTransform, new Vector2(1f, 1f), new Vector2(1f, 1f), new Vector2(-24f, -16f), new Vector2(1200f, 40f));
			_toasts = MakeText(_canvasGo.transform, "Toasts", 26f, (TextAlignmentOptions)1025);
			Place(((TMP_Text)_toasts).rectTransform, new Vector2(0f, 0f), new Vector2(0f, 0f), new Vector2(24f, 24f), new Vector2(1400f, 200f));
			_panel = new GameObject("Panel", new Type[1] { typeof(RectTransform) });
			_panel.transform.SetParent(_canvasGo.transform, false);
			((Graphic)_panel.AddComponent<Image>()).color = PanelColor;
			RectTransform val2 = (RectTransform)_panel.transform;
			BuildRows();
			int num = 0;
			for (int j = 0; j <= 1; j++)
			{
				int num2 = 0;
				foreach (Row allRow in _allRows)
				{
					if (allRow.Page == j)
					{
						num2++;
					}
				}
				num = Mathf.Max(num, num2);
			}
			Place(val2, new Vector2(0.5f, 0.5f), new Vector2(0.5f, 0.5f), Vector2.zero, new Vector2(760f, (float)(100 + 56 * num + 80)));
			Outline obj3 = _panel.AddComponent<Outline>();
			((Shadow)obj3).effectColor = SelColor;
			((Shadow)obj3).effectDistance = new Vector2(3f, -3f);
			TextMeshProUGUI obj4 = (_title = MakeText((Transform)(object)val2, "Title", 40f, (TextAlignmentOptions)258));
			((TMP_Text)obj4).text = "CO-OP";
			((Graphic)obj4).color = SelColor;
			Place(((TMP_Text)obj4).rectTransform, new Vector2(0.5f, 1f), new Vector2(0.5f, 1f), new Vector2(0f, -20f), new Vector2(700f, 56f));
			float[] array2 = new float[2] { -100f, -100f };
			foreach (Row allRow2 in _allRows)
			{
				float num3 = array2[allRow2.Page];
				array2[allRow2.Page] -= 56f;
				GameObject val3 = new GameObject("Row", new Type[1] { typeof(RectTransform) });
				val3.transform.SetParent((Transform)(object)val2, false);
				allRow2.Back = val3.AddComponent<Image>();
				((Graphic)allRow2.Back).color = RowColor;
				Place((RectTransform)val3.transform, new Vector2(0.5f, 1f), new Vector2(0.5f, 1f), new Vector2(0f, num3), new Vector2(680f, 48f));
				allRow2.Text = MakeText(val3.transform, "Label", 28f, (TextAlignmentOptions)4097);
				Place(((TMP_Text)allRow2.Text).rectTransform, new Vector2(0f, 0.5f), new Vector2(0f, 0.5f), new Vector2(18f, 0f), new Vector2(650f, 44f), (Vector2?)new Vector2(0f, 0.5f));
			}
			ShowPage(0);
			_hint = MakeText((Transform)(object)val2, "Hint", 20f, (TextAlignmentOptions)1026);
			((Graphic)_hint).color = new Color(0.7f, 0.7f, 0.65f);
			Place(((TMP_Text)_hint).rectTransform, new Vector2(0.5f, 0f), new Vector2(0.5f, 0f), new Vector2(0f, 16f), new Vector2(720f, 60f));
			_panel.SetActive(false);
			return true;
		}

		private void ShowPage(int page)
		{
			_page = page;
			_rows.Clear();
			foreach (Row allRow in _allRows)
			{
				bool flag = allRow.Page == page;
				if ((Object)(object)allRow.Back != (Object)null)
				{
					((Component)allRow.Back).gameObject.SetActive(flag);
				}
				if (flag)
				{
					_rows.Add(allRow);
				}
			}
			_sel = 0;
			_armed = null;
			if ((Object)(object)_title != (Object)null)
			{
				((TMP_Text)_title).text = ((page == 0) ? "CO-OP" : "CO-OP  /  PLAYERS");
			}
		}

		private void Activate(Row r)
		{
			if (r.Confirm && (_armed != r || Time.unscaledTime > _armedUntil))
			{
				_armed = r;
				_armedUntil = Time.unscaledTime + 4f;
			}
			else
			{
				_armed = null;
				r.Activate();
			}
		}

		private bool Armed(Row r)
		{
			if (r != null && _armed == r)
			{
				return Time.unscaledTime <= _armedUntil;
			}
			return false;
		}

		private Row Add(Row r)
		{
			_allRows.Add(r);
			return r;
		}

		private string PartnerLine()
		{
			if (S.Transport == null)
			{
				return "Not connected";
			}
			if (!S.IsLinked)
			{
				return "No partner yet";
			}
			string partnerId = S.Transport.PartnerId;
			return S.Partner.Name + (string.IsNullOrEmpty(partnerId) ? "" : ("   <color=#888>" + partnerId + "</color>"));
		}

		private void BuildPlayerRows()
		{
			Row kick = null;
			Row banS = null;
			Row banP = null;
			Row clearS = null;
			Row clearP = null;
			Add(new Row
			{
				Page = 1,
				Label = () => "Partner:  " + PartnerLine(),
				Activate = delegate
				{
				}
			});
			kick = Add(new Row
			{
				Page = 1,
				Confirm = true,
				Label = () => HasPartner ? ((!Armed(kick)) ? ((!CoopSession.IsHost) ? "Leave the game" : "Kick") : "Kick: click again to confirm") : "Kick  <color=#888>(no partner)</color>",
				Activate = delegate
				{
					if (HasPartner)
					{
						S.RemovePartner(CoopSession.RemoveKind.Kick);
					}
				}
			});
			banS = Add(new Row
			{
				Page = 1,
				Confirm = true,
				Label = () => HasPartner ? ((!Armed(banS)) ? "Ban for this session" : "Ban for this session: click again to confirm") : "Ban for this session  <color=#888>(no partner)</color>",
				Activate = delegate
				{
					if (HasPartner)
					{
						S.RemovePartner(CoopSession.RemoveKind.BanSession);
					}
				}
			});
			banP = Add(new Row
			{
				Page = 1,
				Confirm = true,
				Label = () => HasPartner ? ((!Armed(banP)) ? "Ban permanently" : "Ban permanently: click again to confirm") : "Ban permanently  <color=#888>(no partner)</color>",
				Activate = delegate
				{
					if (HasPartner)
					{
						S.RemovePartner(CoopSession.RemoveKind.BanPermanent);
					}
				}
			});
			clearS = Add(new Row
			{
				Page = 1,
				Confirm = true,
				Label = () => (!Armed(clearS)) ? $"Clear session bans  <color=#888>({BanList.SessionCount})</color>" : "Clear session bans: click again to confirm",
				Activate = delegate
				{
					BanList.ClearSession();
					S.Toast("Session bans cleared.");
				}
			});
			clearP = Add(new Row
			{
				Page = 1,
				Confirm = true,
				Label = () => (!Armed(clearP)) ? $"Clear permanent bans  <color=#888>({BanList.PermanentCount})</color>" : "Clear permanent bans: click again to confirm",
				Activate = delegate
				{
					BanList.ClearPermanent();
					S.Toast("Permanent bans cleared.");
				}
			});
			Add(new Row
			{
				Page = 1,
				Label = () => "Back",
				Activate = delegate
				{
					ShowPage(0);
				}
			});
		}

		private void BuildRows()
		{
			_allRows.Clear();
			Add(new Row
			{
				Label = () => (!(S.Transport is SteamTransport { IsHost: not false })) ? "Host with Steam" : "Invite a Steam friend",
				Activate = delegate
				{
					if (S.Transport is SteamTransport { IsHost: not false })
					{
						S.InviteSteamFriend();
					}
					else if (!SteamTransport.SteamAvailable)
					{
						S.Toast("Steam isn't running. Use a direct connection.");
					}
					else
					{
						S.HostSteam();
						_openInviteWhenReady = true;
						S.Toast("Hosting a Steam lobby. The invite window opens when it's ready.");
					}
				}
			});
			Add(new Row
			{
				Label = () => "Join with Steam: accept your friend's invite in Steam",
				Activate = delegate
				{
					S.Toast("Open Steam (Shift+Tab) and accept your friend's game invite.");
				}
			});
			Add(new Row
			{
				Label = () => "Direct IP:   " + _ip + (Blink(0) ? "_" : ""),
				EditIp = true,
				Activate = delegate
				{
				}
			});
			Add(new Row
			{
				Label = () => "Port:   " + _port + (Blink(1) ? "_" : ""),
				EditPort = true,
				Activate = delegate
				{
				}
			});
			Add(new Row
			{
				Label = () => "Host direct game",
				Activate = delegate
				{
					if (TryPort(out var port))
					{
						S.HostDirect(port);
						S.Toast($"Hosting a direct game on port {port}.");
					}
				}
			});
			Add(new Row
			{
				Label = () => "Join direct game",
				Activate = delegate
				{
					if (TryPort(out var port))
					{
						SaveAddress();
						S.JoinDirect(_ip.Trim(), port);
						S.Toast($"Joining {_ip}:{port}...");
					}
				}
			});
			Add(new Row
			{
				Label = () => (S.Transport == null) ? "Disconnect (not connected)" : "Disconnect",
				Activate = delegate
				{
					if (S.Transport != null)
					{
						S.Disconnect();
						S.Toast("Disconnected.");
					}
				}
			});
			Add(new Row
			{
				Label = () => "Players" + (HasPartner ? ("  <color=#888>(" + S.Partner.Name + ")</color>") : ""),
				Activate = delegate
				{
					ShowPage(1);
				}
			});
			Add(new Row
			{
				Label = () => "Close",
				Activate = delegate
				{
					SetOpen(open: false);
				}
			});
			BuildPlayerRows();
		}

		private bool Blink(int which)
		{
			Row row = _rows[_sel];
			if ((which == 0) ? row.EditIp : row.EditPort)
			{
				return Time.unscaledTime % 1f < 0.5f;
			}
			return false;
		}

		private bool TryPort(out int port)
		{
			if (int.TryParse(_port, out port) && port > 0 && port < 65536)
			{
				return true;
			}
			S.Toast("That port isn't valid.");
			return false;
		}

		private void SaveAddress()
		{
			try
			{
				Plugin.Cfg.SaveConnection(_ip.Trim(), int.TryParse(_port, out var result) ? result : Plugin.Cfg.connection.directPort);
			}
			catch
			{
			}
		}

		private static TMP_FontAsset FindGameFont()
		{
			TextMeshProUGUI[] array = Object.FindObjectsByType<TextMeshProUGUI>((FindObjectsInactive)1, (FindObjectsSortMode)0);
			foreach (TextMeshProUGUI val in array)
			{
				if ((Object)(object)((TMP_Text)val).font != (Object)null)
				{
					return ((TMP_Text)val).font;
				}
			}
			TextMeshPro[] array2 = Object.FindObjectsByType<TextMeshPro>((FindObjectsInactive)1, (FindObjectsSortMode)0);
			foreach (TextMeshPro val2 in array2)
			{
				if ((Object)(object)((TMP_Text)val2).font != (Object)null)
				{
					return ((TMP_Text)val2).font;
				}
			}
			return TMP_Settings.defaultFontAsset;
		}

		private TextMeshProUGUI MakeText(Transform parent, string name, float size, TextAlignmentOptions align)
		{
			//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_004b: 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)
			GameObject val = new GameObject(name, new Type[1] { typeof(RectTransform) });
			val.transform.SetParent(parent, false);
			TextMeshProUGUI obj = val.AddComponent<TextMeshProUGUI>();
			((TMP_Text)obj).font = _font;
			((TMP_Text)obj).fontSharedMaterial = _textMat;
			((TMP_Text)obj).fontSize = size;
			((TMP_Text)obj).alignment = align;
			((Graphic)obj).color = TextColor;
			((Graphic)obj).raycastTarget = false;
			((TMP_Text)obj).enableWordWrapping = false;
			return obj;
		}

		private static void Place(RectTransform rt, Vector2 anchor, Vector2 pivotIgnored, Vector2 pos, Vector2 size, Vector2? pivot = null)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0003: Unknown result type (might be due to invalid IL or missing references)
			//IL_0004: Unknown result type (might be due to invalid IL or missing references)
			//IL_000a: 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_001d: Unknown result type (might be due to invalid IL or missing references)
			//IL_002d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0034: Unknown result type (might be due to invalid IL or missing references)
			Vector2 anchorMin = (rt.anchorMax = anchor);
			rt.anchorMin = anchorMin;
			rt.pivot = (Vector2)(((??)pivot) ?? anchor);
			rt.anchoredPosition = pos;
			rt.sizeDelta = size;
		}

		private void SetOpen(bool open)
		{
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			//IL_0040: Unknown result type (might be due to invalid IL or missing references)
			//IL_0045: Unknown result type (might be due to invalid IL or missing references)
			//IL_004b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0050: Unknown result type (might be due to invalid IL or missing references)
			if (open != _open)
			{
				_open = open;
				InputBlock.Blocked = open;
				if ((Object)(object)_panel != (Object)null)
				{
					_panel.SetActive(open);
				}
				if (open)
				{
					_savedVisible = Cursor.visible;
					_savedLock = Cursor.lockState;
					_lastMouse = Input.mousePosition;
				}
				else
				{
					SaveAddress();
					Cursor.visible = _savedVisible;
					Cursor.lockState = _savedLock;
				}
			}
		}

		private void LateUpdate()
		{
			if (_open)
			{
				Cursor.lockState = (CursorLockMode)0;
				Cursor.visible = true;
			}
		}

		private void HandleMouse()
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0012: 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_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_0047: Unknown result type (might be due to invalid IL or missing references)
			//IL_004c: 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_0058: Expected O, but got Unknown
			//IL_00dd: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ee: Expected O, but got Unknown
			Vector3 mousePosition = Input.mousePosition;
			Vector3 val = mousePosition - _lastMouse;
			bool flag = ((Vector3)(ref val)).sqrMagnitude > 0.5f;
			_lastMouse = mousePosition;
			int num = -1;
			for (int i = 0; i < _rows.Count; i++)
			{
				if (RectTransformUtility.RectangleContainsScreenPoint((RectTransform)((Component)_rows[i].Back).transform, Vector2.op_Implicit(mousePosition), (Camera)null))
				{
					num = i;
					break;
				}
			}
			if (num >= 0 && flag)
			{
				_sel = num;
			}
			if (!Input.GetMouseButtonDown(0))
			{
				return;
			}
			if (num >= 0)
			{
				_sel = num;
				if (!_rows[num].EditIp && !_rows[num].EditPort)
				{
					Activate(_rows[num]);
				}
			}
			else if (!RectTransformUtility.RectangleContainsScreenPoint((RectTransform)_panel.transform, Vector2.op_Implicit(mousePosition), (Camera)null))
			{
				SetOpen(open: false);
			}
		}

		private void Update()
		{
			if (!((Object)(object)S == (Object)null) && EnsureBuilt())
			{
				try
				{
					HandleInput();
				}
				catch (Exception ex)
				{
					Plugin.Log.LogError((object)("CoopUI input: " + ex));
				}
				if (_openInviteWhenReady && S.Transport is SteamTransport { HasLobby: not false })
				{
					_openInviteWhenReady = false;
					S.InviteSteamFriend();
				}
				Refresh();
			}
		}

		private void HandleInput()
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			if (Input.GetKeyDown(MenuKey))
			{
				SetOpen(!_open);
			}
			else
			{
				if (!_open)
				{
					return;
				}
				if (Input.GetKeyDown((KeyCode)27))
				{
					if (_page != 0)
					{
						ShowPage(0);
					}
					else
					{
						SetOpen(open: false);
					}
					return;
				}
				HandleMouse();
				if (!_open)
				{
					return;
				}
				if (Input.GetKeyDown((KeyCode)274))
				{
					_sel = (_sel + 1) % _rows.Count;
				}
				if (Input.GetKeyDown((KeyCode)273))
				{
					_sel = (_sel + _rows.Count - 1) % _rows.Count;
				}
				Row row = _rows[_sel];
				if (row.EditIp || row.EditPort)
				{
					string inputString = Input.inputString;
					for (int i = 0; i < inputString.Length; i++)
					{
						char c = inputString[i];
						if (c == '\b')
						{
							if (row.EditIp && _ip.Length > 0)
							{
								_ip = _ip.Substring(0, _ip.Length - 1);
							}
							if (row.EditPort && _port.Length > 0)
							{
								_port = _port.Substring(0, _port.Length - 1);
							}
						}
						else if (row.EditIp && (char.IsLetterOrDigit(c) || c == '.' || c == '-' || c == ':') && _ip.Length < 64)
						{
							_ip += c;
						}
						else if (row.EditPort && char.IsDigit(c) && _port.Length < 5)
						{
							_port += c;
						}
					}
				}
				if (Input.GetKeyDown((KeyCode)13) || Input.GetKeyDown((KeyCode)271))
				{
					if (row.EditIp || row.EditPort)
					{
						_sel = (_sel + 1) % _rows.Count;
					}
					else
					{
						Activate(row);
					}
				}
			}
		}

		private void Refresh()
		{
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0283: Unknown result type (might be due to invalid IL or missing references)
			//IL_0218: Unknown result type (might be due to invalid IL or missing references)
			//IL_0211: Unknown result type (might be due to invalid IL or missing references)
			//IL_0234: Unknown result type (might be due to invalid IL or missing references)
			//IL_022d: Unknown result type (might be due to invalid IL or missing references)
			string text = (S.IsLinked ? ("<color=#7CD957>CO-OP</color>  with " + S.Partner.Name + (Plugin.Cfg.UsingHostSettings ? "  |  host's rules" : "") + (S.Partner.InRun ? ($"  |  their rounds left: {S.Partner.RoundsLeft}" + (S.Partner.HasDoorKey ? "  |  has key" : "")) : "  |  not in a run")) : ((S.Transport != null) ? ("<color=#F08C1A>CO-OP</color>  " + S.Transport.Status) : $"<color=#888>CO-OP  not connected ({MenuKey})</color>"));
			if (!Plugin.Cfg.ui.showStatus)
			{
				text = "";
			}
			if (((TMP_Text)_status).text != text)
			{
				((TMP_Text)_status).text = text;
			}
			if (((TMP_Text)_toasts).fontSize != (float)Plugin.Cfg.ui.toastFontSize)
			{
				((TMP_Text)_toasts).fontSize = Plugin.Cfg.ui.toastFontSize;
			}
			IReadOnlyList<string> toasts = S.Toasts;
			string text2 = ((toasts.Count == 0) ? "" : string.Join("\n", toasts));
			if (((TMP_Text)_toasts).text != text2)
			{
				((TMP_Text)_toasts).text = text2;
			}
			if (!_open)
			{
				return;
			}
			for (int i = 0; i < _rows.Count; i++)
			{
				Row row = _rows[i];
				bool flag = i == _sel;
				string text3 = (flag ? "> " : "  ") + row.Label();
				if (((TMP_Text)row.Text).text != text3)
				{
					((TMP_Text)row.Text).text = text3;
				}
				((Graphic)row.Back).color = (flag ? SelColor : RowColor);
				((Graphic)row.Text).color = (flag ? Color.black : TextColor);
			}
			Row row2 = _rows[_sel];
			((TMP_Text)_hint).text = ((row2.EditIp || row2.EditPort) ? "Type to edit  |  Backspace to delete  |  Enter: next  |  Esc: close" : $"Click or Enter: choose  |  Up/Down: move  |  Esc or {MenuKey}: close");
		}

		private void OnDestroy()
		{
			if ((Object)(object)_canvasGo != (Object)null)
			{
				Object.Destroy((Object)(object)_canvasGo);
			}
		}
	}
	[HarmonyPatch]
	internal static class DlcOffPatches
	{
		[HarmonyPatch(typeof(PlatformAPI_Steam), "OwnsDlc1_UnholyFusion")]
		[HarmonyPrefix]
		private static bool SteamNoDlc(ref bool __result)
		{
			if (!Plugin.Cfg.rules.disableDlc)
			{
				return true;
			}
			__result = false;
			return false;
		}

		[HarmonyPatch(typeof(PlatformAPI_Noone), "OwnsDlc1_UnholyFusion")]
		[HarmonyPrefix]
		private static bool NooneNoDlc(ref bool __result)
		{
			if (!Plugin.Cfg.rules.disableDlc)
			{
				return true;
			}
			__result = false;
			return false;
		}

		[HarmonyPatch(typeof(PlatformAPI), "Leaderboards_PlayerHighcoreSet_Try")]
		[HarmonyPrefix]
		private static bool NoLeaderboardUpload(ref bool __result)
		{
			__result = false;
			return false;
		}
	}
	internal static class GameRules
	{
		[HarmonyPatch(typeof(GameplayData), "DebtGetExt")]
		private static class DebtPatch
		{
			private static void Postfix(BigInteger debtIndex, ref BigInteger __result)
			{
				__result *= (BigInteger)Plugin.Cfg.rules.debtMultiplier;
				if (Plugin.Cfg.rules.clientUsesHostDebt && Linked && !CoopSession.IsHost && S.Partner.Debt.Sign > 0 && debtIndex == S.Partner.DebtIndex && debtIndex == GameplayData.DebtIndexGet())
				{
					__result = S.Partner.Debt;
				}
			}
		}

		[HarmonyPatch(typeof(ATMScript), "UpdateStrings")]
		private static class AtmTextPatch
		{
			private static void Prefix()
			{
				_inAtmText = true;
			}

			private static void Finalizer()
			{
				_inAtmText = false;
			}
		}

		[HarmonyPatch(typeof(GameplayData), "RoundsLeftToDeadline")]
		private static class RoundsShownPatch
		{
			private static void Postfix(ref int __result)
			{
				if (_inAtmText && Plugin.Cfg.rules.atmShowsCombinedRounds && Linked && S.Partner.InRun)
				{
					__result += Mathf.Max(0, S.Partner.RoundsLeft);
				}
			}
		}

		[HarmonyPatch(typeof(GameplayMaster), "IsDeathCondition")]
		private static class DeathWaitPatch
		{
			private static float _nextToast;

			private static void Postfix(bool considerRounds, ref bool __result)
			{
				if (considerRounds && !__result)
				{
					LocalReadyToDie = false;
				}
				if (!__result || !considerRounds || !Linked || !S.Partner.InRun || !Plugin.Cfg.rules.waitForPartnerRoundsBeforeDying)
				{
					return;
				}
				bool flag = S.Partner.Phase == 5;
				if ((S.Partner.RoundsLeft > 0 || flag) && !S.PartnerDied)
				{
					__result = false;
					LocalReadyToDie = false;
					if (Time.unscaledTime > _nextToast)
					{
						_nextToast = Time.unscaledTime + 20f;
						S.Toast((S.Partner.RoundsLeft > 0) ? $"Out of rounds. Waiting for {S.Partner.Name} ({S.Partner.RoundsLeft} left)..." : ("Out of rounds. " + S.Partner.Name + " is playing their last round..."));
					}
				}
			}
		}

		[HarmonyPatch(typeof(GameplayMaster), "DieTry")]
		private static class DiePatch
		{
			private static float _nextToast;

			private static bool Prefix(GameplayMaster __instance, bool callLastChanceCallback, ref bool __result)
			{
				if (!Linked || CoopSession.ApplyingRemote || S.PartnerDied || !S.Partner.InRun || !Plugin.Cfg.rules.holdDeathForPartnerLastChance)
				{
					return true;
				}
				if (callLastChanceCallback && __instance.onDeathLastChance != null)
				{
					return true;
				}
				if (S.Partner.ReadyToDie || S.Partner.Phase == 6)
				{
					return true;
				}
				LocalReadyToDie = true;
				__result = false;
				if (Time.unscaledTime > _nextToast)
				{
					_nextToast = Time.unscaledTime + 15f;
					S.Toast("Out of luck... waiting to see if " + S.Partner.Name + " can save the run.");
				}
				return false;
			}

			private static void Postfix(bool __result)
			{
				if (__result && !CoopSession.ApplyingRemote && Linked && Plugin.Cfg.rules.loseTogether)
				{
					S.Send(Msg.Begin(MsgType.GameOver).ms);
				}
			}
		}

		[HarmonyPatch(typeof(DoorScript), "IsInConditionToUnlock")]
		private static class DoorPatch
		{
			private static float _nextToast;

			private static void Postfix(ref bool __result)
			{
				if (!_rawDoorCheck && __result && Linked && Plugin.Cfg.rules.doorNeedsBothKeys && !S.Partner.HasDoorKey)
				{
					__result = false;
					if (Time.unscaledTime > _nextToast)
					{
						_nextToast = Time.unscaledTime + 10f;
						S.Toast("The door needs both keys. " + S.Partner.Name + " doesn't have theirs yet.");
					}
				}
			}
		}

		[HarmonyPatch(typeof(GameplayMaster), "FCall_DoorOpenTry")]
		private static class DoorClickPatch
		{
			private static bool Prefix()
			{
				if (_doorGo || !Linked || !Plugin.Cfg.rules.doorNeedsBothClicks)
				{
					return true;
				}
				if (!LocalHasDoorKey() || (Plugin.Cfg.rules.doorNeedsBothKeys && !S.Partner.HasDoorKey))
				{
					return true;
				}
				if (LocalAtDoor)
				{
					LocalAtDoor = false;
					SendDoor(ready: false);
					S.Toast("You stepped away from the door.");
					return false;
				}
				LocalAtDoor = true;
				SendDoor(ready: true);
				if (PartnerAtDoor)
				{
					OpenDoorNow();
					return false;
				}
				S.Toast("Waiting for " + S.Partner.Name + " to click the door. Click it again to cancel.");
				return false;
			}
		}

		[HarmonyPatch(typeof(ATMScript), "DebtClearCutsceneStart")]
		private static class DeadlineWaitPatch
		{
			private static bool Prefix()
			{
				if (!Linked || !Plugin.Cfg.rules.holdDeadlineWhilePartnerSpins || !S.Partner.InRun || S.Partner.Phase != 5)
				{
					return true;
				}
				if (Time.unscaledTime > _nextDeadlineToast)
				{
					_nextDeadlineToast = Time.unscaledTime + 15f;
					S.Toast("Deadline paid. Waiting for " + S.Partner.Name + " to finish their round...");
				}
				return false;
			}

			private static void Postfix()
			{
				if (ATMScript.DebtClearCutsceneIsPlaying())
				{
					_cutsceneDebtIndex = GameplayData.DebtIndexGet();
					_cutsceneRoundsLeft = Mathf.Max(GameplayData.RoundsLeftToDeadline(), 0);
					_baseTicketsPending = (_baseInterestPending = Linked && !CoopSession.IsHost);
				}
			}
		}

		[HarmonyPatch(typeof(GameplayData), "CloverTicketsAdd")]
		private static class DeadlineTicketsPatch
		{
			private static void Prefix(ref long value, bool addToStats)
			{
				if (_baseTicketsPending && addToStats && ClientInCutscene)
				{
					_baseTicketsPending = false;
					long num = GameplayData.DeadlineReward_CloverTickets(_cutsceneRoundsLeft);
					value = Math.Max(0L, value - num);
				}
			}
		}

		[HarmonyPatch(typeof(GameplayData), "InterestEarnedGrow_Manual")]
		private static class DeadlineInterestPatch
		{
			private static bool Prefix(BigInteger value)
			{
				if (!_baseInterestPending || !ClientInCutscene)
				{
					return true;
				}
				if (value != GameplayData.DeadlineReward_CoinsGet(_cutsceneDebtIndex))
				{
					return true;
				}
				_baseInterestPending = false;
				return false;
			}
		}

		[HarmonyPatch(typeof(PowerupScript), "Equip")]
		private static class EquipPatch
		{
			private static void Postfix(Identifier identifier, bool isInitializationCall, bool __result)
			{
				//IL_0028: 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)
				if (!(!__result || isInitializationCall) && !CoopSession.ApplyingRemote && Linked && Plugin.Cfg.rules.sharedSkeleton && IsSkeleton(identifier))
				{
					SendSkeletonPiece(identifier);
				}
			}
		}

		[HarmonyPatch(typeof(PowerupScript), "PutInDrawer")]
		private static class NoDrawerPatch
		{
			private static bool Prefix(Identifier identifier, bool isInitializationCall, ref bool __result)
			{
				//IL_0016: Unknown result type (might be due to invalid IL or missing references)
				//IL_001e: Unknown result type (might be due to invalid IL or missing references)
				if (isInitializationCall || !Plugin.Cfg.rules.lockEquippedLimbs)
				{
					return true;
				}
				if (IsSkeleton(identifier) && PowerupScript.IsEquipped(identifier))
				{
					__result = false;
					return false;
				}
				return true;
			}
		}

		[HarmonyPatch(typeof(PowerupScript), "ThrowAway")]
		private static class NoThrowPatch
		{
			private static bool Prefix(Identifier identifier, bool isInitializationCall, ref bool __result)
			{
				//IL_0016: Unknown result type (might be due to invalid IL or missing references)
				//IL_001e: Unknown result type (might be due to invalid IL or missing references)
				if (isInitializationCall || !Plugin.Cfg.rules.lockEquippedLimbs)
				{
					return true;
				}
				if (IsSkeleton(identifier) && PowerupScript.IsEquipped(identifier))
				{
					__result = false;
					return false;
				}
				return true;
			}
		}

		[HarmonyPatch(typeof(GameplayData), "RunModifier_SetCurrent")]
		private static class CardPatch
		{
			private static bool Prefix(ref Identifier identifier, ref bool setByPlayer, out bool __state)
			{
				//IL_005c: Unknown result type (might be due to invalid IL or missing references)
				//IL_0062: Expected I4, but got Unknown
				__state = false;
				if (CoopSession.ApplyingRemote || !Linked || CoopSession.IsHost || !Plugin.Cfg.rules.shareHostMemoryCard)
				{
					return true;
				}
				if (_cardAppliedRun != null && _cardAppliedRun == GameplayData.Instance)
				{
					return false;
				}
				if (_hostCard.HasValue)
				{
					_cardAppliedRun = GameplayData.Instance;
					identifier = (Identifier)(int)_hostCard.Value;
					__state = setByPlayer;
					setByPlayer = false;
					return true;
				}
				S.Toast("Your memory card will be the host's. Waiting for them to pick...");
				return false;
			}

			private static void Postfix(Identifier identifier, bool __state)
			{
				//IL_0003: 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)
				if (__state)
				{
					RunModifierScript.OnRunModifierSet(identifier);
				}
				if (CoopSession.IsHost && Linked && !CoopSession.ApplyingRemote && Plugin.Cfg.rules.shareHostMemoryCard)
				{
					SendMemoryCard(identifier);
				}
			}
		}

		[HarmonyPatch(typeof(RunModifierScript), "OnRunModifierSet")]
		private static class CardGrantPatch
		{
			private static void Prefix(out (BigInteger c, BigInteger d, long t) __state)
			{
				GameplayData instance = GameplayData.Instance;
				__state = ((instance == null) ? default((BigInteger, BigInteger, long)) : (c: FCoins.Invoke(instance), d: FDeposit.Invoke(instance), t: FTickets.Invoke(instance)));
			}

			private static void Postfix((BigInteger c, BigInteger d, long t) __state)
			{
				GameplayData instance = GameplayData.Instance;
				if (instance == null)
				{
					return;
				}
				if (Linked && !CoopSession.IsHost && Plugin.Cfg.rules.shareHostMemoryCard)
				{
					FCoins.Invoke(instance) = __state.c;
					FDeposit.Invoke(instance) = __state.d;
					FTickets.Invoke(instance) = __state.t;
				}
				else if (Plugin.Cfg.rules.scaleMemoryCardGrants)
				{
					int startingResourcesMultiplier = Plugin.Cfg.rules.startingResourcesMultiplier;
					BigInteger bigInteger = FCoins.Invoke(instance) - __state.c;
					long num = FTickets.Invoke(instance) - __state.t;
					if (bigInteger.Sign > 0)
					{
						FCoins.Invoke(instance) += bigInteger * (startingResourcesMultiplier - 1);
					}
					if (num > 0)
					{
						FTickets.Invoke(instance) += num * (startingResourcesMultiplier - 1);
					}
					if (FDeposit.Invoke(instance) != __state.d)
					{
						FDeposit.Invoke(instance) *= (BigInteger)startingResourcesMultiplier;
					}
				}
			}
		}

		[HarmonyPatch(typeof(GameplayData), "InterestEarnedGrow")]
		private static class InterestsGrowPatch
		{
			private static bool Prefix()
			{
				//IL_0007: Unknown result type (might be due to invalid IL or missing references)
				//IL_000d: Invalid comparison between Unknown and I4
				if (ClientInCutscene && (int)GameplayData.RunModifier_GetCurrent() == 5)
				{
					return false;
				}
				return true;
			}

			private static void Postfix()
			{
				//IL_0020: Unknown result type (might be due to invalid IL or missing references)
				//IL_0026: Invalid comparison between Unknown and I4
				if (Plugin.Cfg.rules.interestsGrowPaysForBoth && (!Linked || CoopSession.IsHost) && (int)GameplayData.RunModifier_GetCurrent() == 5 && ATMScript.DebtClearCutsceneIsPlaying())
				{
					GameplayData.InterestEarnedGrow_Manual(GameplayData.InterestEarnedHypotetically());
				}
			}
		}

		private static bool _rawDoorCheck;

		private static bool _inAtmText;

		public static bool LocalReadyToDie;

		private static bool _doorGo;

		private static float _nextDeadlineToast;

		private static BigInteger _cutsceneDebtIndex;

		private static int _cutsceneRoundsLeft;

		private static bool _baseTicketsPending;

		private static bool _baseInterestPending;

		private static Identifier? _hostCard;

		private static GameplayData _cardAppliedRun;

		private static readonly FieldRef<GameplayData, BigInteger> FCoins = AccessTools.FieldRefAccess<GameplayData, BigInteger>("coins");

		private static readonly FieldRef<GameplayData, BigInteger> FDeposit = AccessTools.FieldRefAccess<GameplayData, BigInteger>("depositedCoins");

		private static readonly FieldRef<GameplayData, long> FTickets = AccessTools.FieldRefAccess<GameplayData, long>("cloverTickets");

		private static CoopSession S => CoopSession.Instance;

		private static bool Linked
		{
			get
			{
				if ((Object)(object)S != (Object)null)
				{
					return S.IsLinked;
				}
				return false;
			}
		}

		public static bool LocalAtDoor { get; private set; }

		public static bool PartnerAtDoor { get; private set; }

		private static bool ClientInCutscene
		{
			get
			{
				if (Linked && !CoopSession.IsHost)
				{
					return ATMScript.DebtClearCutsceneIsPlaying();
				}
				return false;
			}
		}

		public static bool TryParseId<T>(string name, out T id) where T : struct
		{
			id = default(T);
			if (string.IsNullOrEmpty(name) || name.Length > 64 || char.IsDigit(name[0]) || name[0] == '-')
			{
				return false;
			}
			if (Enum.TryParse<T>(name, ignoreCase: false, out id))
			{
				return Enum.IsDefined(typeof(T), id);
			}
			return false;
		}

		public static bool IsSafeToApplyRemote()
		{
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0015: Invalid comparison between Unknown and I4
			if ((Object)(object)GameplayMaster.instance == (Object)null)
			{
				return false;
			}
			if ((int)GameplayMaster.GetGamePhase() != 3)
			{
				return false;
			}
			if (DialogueScript.IsEnabled() || ATMScript.DebtClearCutsceneIsPlaying() || SlotMachineScript.IsSpinning())
			{
				return false;
			}
			return true;
		}

		public static bool LocalHasDoorKey()
		{
			_rawDoorCheck = true;
			try
			{
				return DoorScript.IsInConditionToUnlock();
			}
			catch
			{
				return false;
			}
			finally
			{
				_rawDoorCheck = false;
			}
		}

		public static void OnLinked()
		{
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			if (CoopSession.IsHost && GameplayData.Instance != null && GameplayData.RunModifier_AlreadyPicked())
			{
				SendMemoryCard(GameplayData.RunModifier_GetCurrent());
			}
			SendAllSkeletonPieces();
		}

		public static void ReceiveGameOver()
		{
			if ((Object)(object)S == (Object)null || !Plugin.Cfg.rules.loseTogether)
			{
				return;
			}
			S.PartnerDied = true;
			S.Toast(S.Partner.Name + " is out. The run is lost.");
			S.Defer(delegate
			{
				//IL_000d: Unknown result type (might be due to invalid IL or missing references)
				//IL_0013: Invalid comparison between Unknown and I4
				if ((Object)(object)GameplayMaster.instance == (Object)null || (int)GameplayMaster.GetGamePhase() == 6)
				{
					return;
				}
				CoopSession.ApplyingRemote = true;
				try
				{
					GameplayMaster.instance.DieTry((DeathStep)0, false);
				}
				finally
				{
					CoopSession.ApplyingRemote = false;
				}
			}, anyPhase: true);
		}

		public static void ResetDoor()
		{
			LocalAtDoor = false;
			PartnerAtDoor = false;
		}

		private static void SendDoor(bool ready)
		{
			(MemoryStream ms, BinaryWriter w) tuple = Msg.Begin(MsgType.DoorReady);
			var (ms, _) = tuple;
			tuple.w.Write(ready);
			S.Send(ms);
		}

		private static void OpenDoorNow()
		{
			if ((Object)(object)GameplayMaster.instance == (Object)null)
			{
				return;
			}
			_doorGo = true;
			try
			{
				GameplayMaster.instance.FCall_DoorOpenTry();
			}
			finally
			{
				_doorGo = false;
				ResetDoor();
			}
		}

		public static void ReceiveDoorReady(BinaryReader r)
		{
			if (!(PartnerAtDoor = r.ReadBoolean()))
			{
				S.Toast(S.Partner.Name + " stepped away from the door.");
			}
			else if (LocalAtDoor)
			{
				S.Defer(OpenDoorNow, anyPhase: true);
			}
			else
			{
				S.Toast(S.Partner.Name + " is at the door. Click the door to leave together.");
			}
		}

		internal static bool IsSkeleton(Identifier id)
		{
			//IL_0000: 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_0017: Invalid comparison between Unknown and I4
			PowerupScript powerup_Quick = PowerupScript.GetPowerup_Quick(id);
			if ((Object)(object)powerup_Quick != (Object)null)
			{
				return (int)powerup_Quick.category == 0;
			}
			return false;
		}

		private unsafe static void SendSkeletonPiece(Identifier id)
		{
			(MemoryStream ms, BinaryWriter w) tuple = Msg.Begin(MsgType.SkeletonPiece);
			var (ms, _) = tuple;
			tuple.w.Write(((object)(*(Identifier*)(&id))/*cast due to .constrained prefix*/).ToString());
			S.Send(ms);
		}

		private static void SendAllSkeletonPieces()
		{
			//IL_0038: Unknown result type (might be due to invalid IL or missing references)
			if (!Plugin.Cfg.rules.sharedSkeleton || GameplayData.Instance == null)
			{
				return;
			}
			foreach (PowerupScript item in PowerupScript.list_EquippedSkeleton)
			{
				if ((Object)(object)item != (Object)null)
				{
					SendSkeletonPiece(item.identifier);
				}
			}
		}

		public static void ReceiveSkeletonPiece(BinaryReader r)
		{
			//IL_002d: Unknown result type (might be due to invalid IL or missing references)
			string name = r.ReadString();
			if (!Plugin.Cfg.rules.sharedSkeleton || !GameRules.TryParseId<Identifier>(name, out Identifier id) || !IsSkeleton(id))
			{
				return;
			}
			S.Defer(delegate
			{
				//IL_0001: 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)
				if (PowerupScript.IsEquipped(id))
				{
					return;
				}
				CoopSession.ApplyingRemote = true;
				try
				{
					PowerupScript.EquipFlag_IgnoreSpaceCondition();
					if (PowerupScript.Equip(id, false, false))
					{
						S.Toast(S.Partner.Name + " found a limb. It's on your skeleton too.");
					}
				}
				finally
				{
					CoopSession.ApplyingRemote = false;
				}
			});
		}

		public static void OnLocalNewRun()
		{
			//IL_003a: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)S == (Object)null)
			{
				return;
			}
			S.PartnerDied = false;
			LocalReadyToDie = false;
			ResetDoor();
			if (Linked && CoopSession.IsHost)
			{
				if (GameplayData.RunModifier_AlreadyPicked())
				{
					SendMemoryCard(GameplayData.RunModifier_GetCurrent());
					return;
				}
				(MemoryStream ms, BinaryWriter w) tuple = Msg.Begin(MsgType.MemoryCard);
				var (ms, _) = tuple;
				tuple.w.Write("");
				S.Send(ms);
			}
		}

		private unsafe static void SendMemoryCard(Identifier id)
		{
			(MemoryStream ms, BinaryWriter w) tuple = Msg.Begin(MsgType.MemoryCard);
			var (ms, _) = tuple;
			tuple.w.Write(((object)(*(Identifier*)(&id))/*cast due to .constrained prefix*/).ToString());
			S.Send(ms);
		}

		public unsafe static void ReceiveMemoryCard(BinaryReader r)
		{
			//IL_003f: 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_006a: Unknown result type (might be due to invalid IL or missing references)
			//IL_008d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0094: Unknown result type (might be due to invalid IL or missing references)
			if (CoopSession.IsHost || !Plugin.Cfg.rules.shareHostMemoryCard)
			{
				return;
			}
			string text = r.ReadString();
			if (text.Length == 0)
			{
				_hostCard = null;
			}
			else
			{
				if (!GameRules.TryParseId<Identifier>(text, out Identifier id))
				{
					return;
				}
				_hostCard = id;
				if (GameplayData.Instance == null)
				{
					return;
				}
				if (!GameplayData.RunModifier_AlreadyPicked() && _cardAppliedRun != GameplayData.Instance)
				{
					_cardAppliedRun = GameplayData.Instance;
					CoopSession.ApplyingRemote = true;
					try
					{
						GameplayData.RunModifier_SetCurrent(id, false);
						RunModifierScript.OnRunModifierSet(id);
						S.Toast("Memory card: " + ((object)(*(Identifier*)(&id))/*cast due to .constrained prefix*/).ToString() + " (from the host).");
						return;
					}
					finally
					{
						CoopSession.ApplyingRemote = false;
					}
				}
				if (GameplayData.RunModifier_GetCurrent() != id)
				{
					S.Toast("The host is playing a different memory card. Start new runs together to share it.");
				}
			}
		}
	}
	internal static class InputBlock
	{
		[HarmonyPatch]
		private static class Buttons
		{
			private static IEnumerable<MethodBase> TargetMethods()
			{
				return Find(typeof(bool), "ActionButton_PressedGet", "ActionButton_ReleasedGet", "ActionButton_HoldGet");
			}

			private static bool Prefix(ref bool __result)
			{
				if (!Blocked)
				{
					return true;
				}
				__result = false;
				return false;
			}
		}

		[HarmonyPatch]
		private static class Axes
		{
			private static IEnumerable<MethodBase> TargetMethods()
			{
				return Find(typeof(float), "ActionAxis_GetValue", "ActionAxisPair_GetValue", "MouseAxis_ValueGet", "JoystickAxis_ValueGet");
			}

			private static bool Prefix(ref float __result)
			{
				if (!Blocked)
				{
					return true;
				}
				__result = 0f;
				return false;
			}
		}

		public static bool Blocked;

		private static IEnumerable<MethodBase> Find(Type returns, params string[] names)
		{
			foreach (MethodInfo declaredMethod in AccessTools.GetDeclaredMethods(typeof(Controls)))
			{
				if (!(declaredMethod.ReturnType != returns) && Array.IndexOf(names, declaredMethod.Name) >= 0)
				{
					ParameterInfo[] parameters = declaredMethod.GetParameters();
					if (parameters.Length != 0 && parameters[0].ParameterType == typeof(PlayerExt))
					{
						yield return declaredMethod;
					}
				}
			}
		}
	}
	internal static class MeshTools
	{
		public static Mesh ReadableCopy(Mesh src)
		{
			if ((Object)(object)src == (Object)null)
			{
				return null;
			}
			if (src.isReadable)
			{
				Mesh obj = Object.Instantiate<Mesh>(src);
				((Object)obj).name = ((Object)src).name;
				return obj;
			}
			try
			{
				return ReadBack(src);
			}
			catch (Exception ex)
			{
				Plugin.Log.LogWarning((object)("MeshTools: could not read back mesh '" + ((Object)src).name + "': " + ex.Message));
				return null;
			}
		}

		private static Mesh ReadBack(Mesh src)
		{
			//IL_044d: 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_0117: Unknown result type (might be due to invalid IL or missing references)
			//IL_011c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0137: Unknown result type (might be due to invalid IL or missing references)
			//IL_013e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0149: Expected O, but got Unknown
			//IL_0163: Unknown result type (might be due to invalid IL or missing references)
			//IL_0168: Unknown result type (might be due to invalid IL or missing references)
			//IL_016a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0177: Unknown result type (might be due to invalid IL or missing references)
			//IL_017c: Unknown result type (might be due to invalid IL or missing references)
			//IL_017e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0195: Expected I4, but got Unknown
			//IL_0195: Unknown result type (might be due to invalid IL or missing references)
			//IL_0199: Invalid comparison between Unknown and I4
			//IL_046a: Unknown result type (might be due to invalid IL or missing references)
			//IL_046f: Unknown result type (might be due to invalid IL or missing references)
			//IL_019e: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a2: Invalid comparison between Unknown and I4
			//IL_02bd: Unknown result type (might be due to invalid IL or missing references)
			//IL_0265: Unknown result type (might be due to invalid IL or missing references)
			//IL_026b: Invalid comparison between Unknown and I4
			//IL_026f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0276: Invalid comparison between Unknown and I4
			//IL_027b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0281: Unknown result type (might be due to invalid IL or missing references)
			//IL_028e: Expected I4, but got Unknown
			//IL_04fe: Unknown result type (might be due to invalid IL or missing references)
			//IL_0503: Unknown result type (might be due to invalid IL or missing references)
			//IL_0563: Unknown result type (might be due to invalid IL or missing references)
			//IL_040f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0411: Unknown result type (might be due to invalid IL or missing references)
			int vc = src.vertexCount;
			VertexAttributeDescriptor[] vertexAttributes = src.GetVertexAttributes();
			Dictionary<int, byte[]> streams = new Dictionary<int, byte[]>();
			Dictionary<int, int> strides = new Dictionary<int, int>();
			VertexAttributeDescriptor[] array = vertexAttributes;
			for (int i = 0; i < array.Length; i++)
			{
				VertexAttributeDescriptor val = array[i];
				if (streams.ContainsKey(((VertexAttributeDescriptor)(ref val)).stream))
				{
					continue;
				}
				int vertexBufferStride = src.GetVertexBufferStride(((VertexAttributeDescriptor)(ref val)).stream);
				byte[] array2 = new byte[vc * vertexBufferStride];
				GraphicsBuffer vertexBuffer = src.GetVertexBuffer(((VertexAttributeDescriptor)(ref val)).stream);
				try
				{
					if (vertexBuffer == null)
					{
						throw new Exception("no vertex buffer " + ((VertexAttributeDescriptor)(ref val)).stream);
					}
					vertexBuffer.GetData((Array)array2);
				}
				finally
				{
					((IDisposable)vertexBuffer)?.Dispose();
				}
				streams[((VertexAttributeDescriptor)(ref val)).stream] = array2;
				strides[((VertexAttributeDescriptor)(ref val)).stream] = vertexBufferStride;
			}
			Mesh val2 = new Mesh
			{
				name = ((Object)src).name + " (coop)",
				indexFormat = src.indexFormat
			};
			Vector4[] array3 = null;
			Vector4[] array4 = null;
			int num = 0;
			int num2 = 0;
			array = vertexAttributes;
			for (int i = 0; i < array.Length; i++)
			{
				VertexAttributeDescriptor a = array[i];
				Vector4[] array5 = Read(a);
				VertexAttribute attribute = ((VertexAttributeDescriptor)(ref a)).attribute;
				switch ((int)attribute)
				{
				case 0:
					val2.SetVertices(Array.ConvertAll(array5, (Vector4 x) => Vector4.op_Implicit(x)));
					continue;
				case 1:
					val2.SetNormals(Array.ConvertAll(array5, (Vector4 x) => Vector4.op_Implicit(x)));
					continue;
				case 2:
					val2.SetTangents(array5);
					continue;
				case 3:
					val2.SetColors(Array.ConvertAll(array5, (Vector4 x) => Color.op_Implicit(x)));
					continue;
				}
				if ((int)attribute != 12)
				{
					if ((int)attribute == 13)
					{
						array4 = array5;
						num2 = ((VertexAttributeDescriptor)(ref a)).dimension;
					}
					else if ((int)((VertexAttributeDescriptor)(ref a)).attribute >= 4 && (int)((VertexAttributeDescriptor)(ref a)).attribute <= 11)
					{
						val2.SetUVs(((VertexAttributeDescriptor)(ref a)).attribute - 4, new List<Vector4>(array5));
					}
				}
				else
				{
					array3 = array5;
					num = ((VertexAttributeDescriptor)(ref a)).dimension;
				}
			}
			if (array4 != null)
			{
				BoneWeight[] array6 = (BoneWeight[])(object)new BoneWeight[vc];
				for (int num3 = 0; num3 < vc; num3++)
				{
					BoneWeight val3 = default(BoneWeight);
					float num4 = array3?[num3].x ?? 1f;
					float num5 = ((array3 != null && num > 1) ? array3[num3].y : 0f);
					float num6 = ((array3 != null && num > 2) ? array3[num3].z : 0f);
					float weight = ((array3 != null && num > 3) ? array3[num3].w : 0f);
					if (array3 != null && num < 4)
					{
						float num7 = num4 + num5 + num6;
						if (num == 1)
						{
							num4 = 1f;
						}
						else if (num7 < 1f)
						{
							if (num == 2)
							{
								num5 = 1f - num4;
							}
							if (num == 3)
							{
								num6 = 1f - num4 - num5;
							}
						}
					}
					((BoneWeight)(ref val3)).boneIndex0 = (int)array4[num3].x;
					((BoneWeight)(ref val3)).weight0 = num4;
					if (num2 > 1)
					{
						((BoneWeight)(ref val3)).boneIndex1 = (int)array4[num3].y;
						((BoneWeight)(ref val3)).weight1 = num5;
					}
					if (num2 > 2)
					{
						((BoneWeight)(ref val3)).boneIndex2 = (int)array4[num3].z;
						((BoneWeight)(ref val3)).weight2 = num6;
					}
					if (num2 > 3)
					{
						((BoneWeight)(ref val3)).boneIndex3 = (int)array4[num3].w;
						((BoneWeight)(ref val3)).weight3 = weight;
					}
					array6[num3] = val3;
				}
				val2.boneWeights = array6;
				try
				{
					val2.bindposes = src.bindposes;
				}
				catch
				{
				}
			}
			int num8 = (((int)src.indexFormat == 0) ? 2 : 4);
			int num9 = 0;
			for (int num10 = 0; num10 < src.subMeshCount; num10++)
			{
				SubMeshDescriptor subMesh = src.GetSubMesh(num10);
				num9 = Math.Max(num9, ((SubMeshDescriptor)(ref subMesh)).indexStart + ((SubMeshDescriptor)(ref subMesh)).indexCount);
			}
			byte[] array7 = new byte[num9 * num8];
			GraphicsBuffer indexBuffer = src.GetIndexBuffer();
			try
			{
				if (indexBuffer == null)
				{
					throw new Exception("no index buffer");
				}
				indexBuffer.GetData((Array)array7);
			}
			finally
			{
				((IDisposable)indexBuffer)?.Dispose();
			}
			val2.subMeshCount = src.subMeshCount;
			for (int num11 = 0; num11 < src.subMeshCount; num11++)
			{
				SubMeshDescriptor subMesh2 = src.GetSubMesh(num11);
				int[] array8 = new int[((SubMeshDescriptor)(ref subMesh2)).indexCount];
				for (int num12 = 0; num12 < ((SubMeshDescriptor)(ref subMesh2)).indexCount; num12++)
				{
					int startIndex = (((SubMeshDescriptor)(ref subMesh2)).indexStart + num12) * num8;
					array8[num12] = (int)((num8 == 2) ? BitConverter.ToUInt16(array7, startIndex) : BitConverter.ToUInt32(array7, startIndex)) + ((SubMeshDescriptor)(ref subMesh2)).baseVertex;
				}
				val2.SetIndices(array8, ((SubMeshDescriptor)(ref subMesh2)).topology, num11, false);
			}
			val2.RecalculateBounds();
			return val2;
			Vector4[] Read(VertexAttributeDescriptor val4)
			{
				//IL_002e: Unknown result type (might be due to invalid IL or missing references)
				//IL_0047: Unknown result type (might be due to invalid IL or missing references)
				//IL_0062: Unknown result type (might be due to invalid IL or missing references)
				//IL_00a4: Unknown result type (might be due to invalid IL or missing references)
				//IL_00a6: Unknown result type (might be due to invalid IL or missing references)
				//IL_007c: Unknown result type (might be due to invalid IL or missing references)
				byte[] b = streams[((VertexAttributeDescriptor)(ref val4)).stream];
				int num13 = strides[((VertexAttributeDescriptor)(ref val4)).stream];
				int vertexAttributeOffset = src.GetVertexAttributeOffset(((VertexAttributeDescriptor)(ref val4)).attribute);
				Vector4[] array9 = (Vector4[])(object)new Vector4[vc];
				int num14 = FormatSize(((VertexAttributeDescriptor)(ref val4)).format);
				for (int j = 0; j < vc; j++)
				{
					int num15 = j * num13 + vertexAttributeOffset;
					Vector4 val5 = default(Vector4);
					for (int k = 0; k < ((VertexAttributeDescriptor)(ref val4)).dimension && k < 4; k++)
					{
						((Vector4)(ref val5))[k] = Decode(b, num15 + k * num14, ((VertexAttributeDescriptor)(ref val4)).format);
					}
					array9[j] = val5;
				}
				return array9;
			}
		}

		private static int FormatSize(VertexAttributeFormat f)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0036: Expected I4, but got Unknown
			switch ((int)f)
			{
			case 0:
			case 10:
			case 11:
				return 4;
			case 1:
			case 4:
			case 5:
			case 8:
			case 9:
				return 2;
			default:
				return 1;
			}
		}

		private static float Decode(byte[] b, int p, VertexAttributeFormat f)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0036: Expected I4, but got Unknown
			return (int)f switch
			{
				0 => BitConverter.ToSingle(b, p), 
				1 => HalfToFloat(BitConverter.ToUInt16(b, p)), 
				2 => (float)(int)b[p] / 255f, 
				3 => Mathf.Max((float)(sbyte)b[p] / 127f, -1f), 
				6 => (int)b[p], 
				7 => (sbyte)b[p], 
				4 => (float)(int)BitConverter.ToUInt16(b, p) / 65535f, 
				5 => Mathf.Max((float)BitConverter.ToInt16(b, p) / 32767f, -1f), 
				8 => (int)BitConverter.ToUInt16(b, p), 
				9 => BitConverter.ToInt16(b, p), 
				10 => BitConverter.ToUInt32(b, p), 
				11 => BitConverter.ToInt32(b, p), 
				_ => 0f, 
			};
		}

		private static float HalfToFloat(ushort h)
		{
			int num = (h >> 15) & 1;
			int num2 = (h >> 10) & 0x1F;
			int num3 = h & 0x3FF;
			float num4 = num2 switch
			{
				0 => (float)num3 / 1024f * Mathf.Pow(2f, -14f), 
				31 => (num3 == 0) ? float.PositiveInfinity : float.NaN, 
				_ => (1f + (float)num3 / 1024f) * Mathf.Pow(2f, (float)(num2 - 15)), 
			};
			if (num != 1)
			{
				return num4;
			}
			return 0f - num4;
		}

		public static List<int>[] Pieces(Mesh m, out int[] vertexPiece)
		{
			//IL_011f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0138: Unknown result type (might be due to invalid IL or missing references)
			Vector3[] vertices = m.vertices;
			int[] parent = new int[vertices.Length];
			for (int i = 0; i < parent.Length; i++)
			{
				parent[i] = i;
			}
			List<int>[] array = new List<int>[m.subMeshCount];
			for (int j = 0; j < m.subMeshCount; j++)
			{
				array[j] = new List<int>(m.GetTriangles(j));
				for (int k = 0; k + 2 < array[j].Count; k += 3)
				{
					Union(array[j][k], array[j][k + 1]);
					Union(array[j][k + 2], array[j][k + 1]);
				}
			}
			Dictionary<Vector3Int, int> dictionary = new Dictionary<Vector3Int, int>();
			Vector3Int key = default(Vector3Int);
			for (int l = 0; l < vertices.Length; l++)
			{
				((Vector3Int)(ref key))..ctor(Mathf.RoundToInt(vertices[l].x * 1000f), Mathf.RoundToInt(vertices[l].y * 1000f), Mathf.RoundToInt(vertices[l].z * 1000f));
				if (dictionary.TryGetValue(key, out var value))
				{
					Union(l, value);
				}
				else
				{
					dictionary[key] = l;
				}
			}
			vertexPiece = new int[vertices.Length];
			for (int n = 0; n < vertices.Length; n++)
			{
				vertexPiece[n] = Find(n);
			}
			return array;
			int Find(int x)
			{
				while (parent[x] != x)
				{
					parent[x] = parent[parent[x]];
					x = parent[x];
				}
				return x;
			}
			void Union(int a, int b)
			{
				a = Find(a);
				b = Find(b);
				if (a != b)
				{
					parent[a] = b;
				}
			}
		}
	}
	internal static class PartnerIdle
	{
		public static void Apply()
		{
			Try("giant number", delegate
			{
				for (int i = 0; i < RoomLayout.PropCount; i++)
				{
					var (val, val2, _) = RoomLayout.GetProp(i);
					if (!((Object)(object)val2 == (Object)null) && !((Object)(object)val == (Object)null) && !(((Object)val2).name != "Giant Number"))
					{
						TMP_Text component = ((Component)val).GetComponent<TMP_Text>();
						if ((Object)(object)component != (Object)null)
						{
							component.text = "00";
						}
					}
				}
			});
			Try("posters", delegate
			{
				//IL_0065: Unknown result type (might be due to