Decompiled source of EmergencyPhone v1.2.3

EmergencyPhone.dll

Decompiled 2 weeks ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using GameNetcodeStuff;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using Unity.Collections;
using Unity.Netcode;
using UnityEngine;
using UnityEngine.InputSystem;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyVersion("0.0.0.0")]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace EmergencyPhone
{
	[BepInPlugin("com.osbasgabmat.emergencyphone", "Emergency Phone", "1.2.3")]
	public class EmergencyPhonePlugin : BaseUnityPlugin
	{
		private static class Patches
		{
			[HarmonyPostfix]
			[HarmonyPatch(typeof(StartOfRound), "Awake")]
			private static void StartOfRoundAwake()
			{
				EnsurePhone();
				PhoneNet.Register();
			}

			[HarmonyPostfix]
			[HarmonyPatch(typeof(GrabbableObject), "Start")]
			private static void GrabbableStart(GrabbableObject __instance)
			{
				if ((Object)(object)phone != (Object)null && (Object)(object)__instance.itemProperties == (Object)(object)phone && (Object)(object)((Component)__instance).GetComponent<PhoneUse>() == (Object)null)
				{
					((Component)__instance).gameObject.AddComponent<PhoneUse>();
				}
			}

			[HarmonyPrefix]
			[HarmonyPatch(typeof(PlayerControllerB), "FirstEmptyItemSlot")]
			private static void FirstEmptySlotPrefix(GrabbableObject attemptingGrab, out bool __state)
			{
				__state = (Object)(object)attemptingGrab != (Object)null && (Object)(object)phone != (Object)null && (Object)(object)attemptingGrab.itemProperties == (Object)(object)phone && phone.isScrap;
				if (__state)
				{
					phone.isScrap = false;
				}
			}

			[HarmonyFinalizer]
			[HarmonyPatch(typeof(PlayerControllerB), "FirstEmptyItemSlot")]
			private static void FirstEmptySlotFinalizer(bool __state)
			{
				if (__state && (Object)(object)phone != (Object)null)
				{
					phone.isScrap = true;
				}
			}

			[HarmonyPrefix]
			[HarmonyPatch(typeof(RoundManager), "DespawnPropsAtEndOfRound")]
			private static void DespawnPrefix(out bool __state)
			{
				__state = (Object)(object)phone != (Object)null && phone.isScrap;
				if (__state)
				{
					phone.isScrap = false;
				}
			}

			[HarmonyFinalizer]
			[HarmonyPatch(typeof(RoundManager), "DespawnPropsAtEndOfRound")]
			private static void DespawnFinalizer(bool __state)
			{
				if (__state && (Object)(object)phone != (Object)null)
				{
					phone.isScrap = true;
				}
			}

			[HarmonyPostfix]
			[HarmonyPatch(typeof(Terminal), "Start")]
			private static void TerminalStart(Terminal __instance)
			{
				if (SellInStore.Value && EnsurePhone())
				{
					AddToStore(__instance);
				}
			}
		}

		public const string Guid = "com.osbasgabmat.emergencyphone";

		public const string ItemName = "Emergency Phone";

		public const string Version = "1.2.3";

		private const string StoreWord = "emergency-phone";

		internal static EmergencyPhonePlugin Instance;

		internal static ManualLogSource Log;

		internal static ConfigEntry<int> Price;

		internal static ConfigEntry<float> HoldSeconds;

		internal static ConfigEntry<bool> SellInStore;

		internal static ConfigEntry<int> SellValueMin;

		internal static ConfigEntry<int> SellValueMax;

		internal static ConfigEntry<bool> UseRenderedIcon;

		internal static ConfigEntry<bool> FailuresEnabled;

		internal static ConfigEntry<float> LongerChance;

		internal static ConfigEntry<float> LongerExtraSeconds;

		internal static ConfigEntry<float> BreakChance;

		internal static ConfigEntry<float> WrongButtonChance;

		internal static ConfigEntry<float> ExplodeChance;

		internal static ConfigEntry<float> EveryoneChance;

		private static Item phone;

		private static Sprite icon;

		private void Awake()
		{
			//IL_00e5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ef: Expected O, but got Unknown
			//IL_0122: Unknown result type (might be due to invalid IL or missing references)
			//IL_012c: Expected O, but got Unknown
			//IL_015f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0169: Expected O, but got Unknown
			//IL_019c: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a6: Expected O, but got Unknown
			//IL_01d9: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e3: Expected O, but got Unknown
			//IL_0216: Unknown result type (might be due to invalid IL or missing references)
			//IL_0220: Expected O, but got Unknown
			//IL_026e: Unknown result type (might be due to invalid IL or missing references)
			Instance = this;
			Log = ((BaseUnityPlugin)this).Logger;
			Price = ((BaseUnityPlugin)this).Config.Bind<int>("Shop", "Price", 250, "Store price of the Emergency Phone (credits). Every player should use the same value.");
			SellInStore = ((BaseUnityPlugin)this).Config.Bind<bool>("Shop", "SellInStore", true, "Sell the Emergency Phone in the terminal store. It always spawns as loot on moons like the vanilla Old Phone.");
			SellValueMin = ((BaseUnityPlugin)this).Config.Bind<int>("Shop", "SellValueMin", 40, "Lowest scrap value of a phone bought from the store (what the Company pays for it). Found phones keep their normal loot value.");
			SellValueMax = ((BaseUnityPlugin)this).Config.Bind<int>("Shop", "SellValueMax", 70, "Highest scrap value of a phone bought from the store.");
			FailuresEnabled = ((BaseUnityPlugin)this).Config.Bind<bool>("Failures", "Enabled", true, "Master switch. When on, a call can randomly go wrong. Chances below are in percent and are rolled once per call.");
			LongerChance = ((BaseUnityPlugin)this).Config.Bind<float>("Failures", "CallTakesLongerChance", 5f, new ConfigDescription("Chance (%) that the call takes extra time to connect. The phone still works afterwards.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 100f), Array.Empty<object>()));
			LongerExtraSeconds = ((BaseUnityPlugin)this).Config.Bind<float>("Failures", "CallTakesLongerSeconds", 5f, new ConfigDescription("How many extra seconds a slow call takes.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(1f, 30f), Array.Empty<object>()));
			BreakChance = ((BaseUnityPlugin)this).Config.Bind<float>("Failures", "PhoneBreaksChance", 3f, new ConfigDescription("Chance (%) that the phone breaks: nothing happens and the phone is gone.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 100f), Array.Empty<object>()));
			WrongButtonChance = ((BaseUnityPlugin)this).Config.Bind<float>("Failures", "WrongButtonChance", 3f, new ConfigDescription("Chance (%) that the wrong button is pressed and you land at a random spot inside the facility instead of the ship (needs a facility on the moon).", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 100f), Array.Empty<object>()));
			ExplodeChance = ((BaseUnityPlugin)this).Config.Bind<float>("Failures", "PhoneExplodesChance", 1f, new ConfigDescription("Chance (%) that the phone overheats and explodes after a short beeping fuse, like a landmine. Hurts everyone nearby, you included, unless you drop it and run.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 100f), Array.Empty<object>()));
			EveryoneChance = ((BaseUnityPlugin)this).Config.Bind<float>("Failures", "EveryoneTeleportsChance", 2f, new ConfigDescription("Chance (%) that the call beams every living player on the moon up to the ship, not just you.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 100f), Array.Empty<object>()));
			UseRenderedIcon = ((BaseUnityPlugin)this).Config.Bind<bool>("Use", "UseRenderedIcon", false, "Experimental: photograph the phone's model for the HUD icon instead of using the mod logo. It looked like a red cube in game.");
			HoldSeconds = ((BaseUnityPlugin)this).Config.Bind<float>("Use", "HoldSeconds", 2f, "How long (seconds) the right mouse button must be held to make the call.");
			new Harmony("com.osbasgabmat.emergencyphone").PatchAll(typeof(Patches));
			Log.LogInfo((object)"Emergency Phone 1.2.3 loaded.");
		}

		private static bool EnsurePhone()
		{
			StartOfRound instance = StartOfRound.Instance;
			if ((Object)(object)instance == (Object)null || (Object)(object)instance.allItemsList == (Object)null)
			{
				return false;
			}
			List<Item> itemsList = instance.allItemsList.itemsList;
			if ((Object)(object)phone == (Object)null || !itemsList.Contains(phone))
			{
				phone = ((IEnumerable<Item>)itemsList).FirstOrDefault((Func<Item, bool>)((Item i) => (Object)(object)i != (Object)null && i.itemName.IndexOf("phone", StringComparison.OrdinalIgnoreCase) >= 0));
				if ((Object)(object)phone == (Object)null)
				{
					Log.LogWarning((object)"Couldn't find the vanilla phone item.");
					return false;
				}
				Log.LogInfo((object)("Turning vanilla item '" + phone.itemName + "' into the Emergency Phone."));
			}
			phone.itemName = "Emergency Phone";
			phone.creditsWorth = Price.Value;
			phone.toolTips = new string[1] { "Call the ship : Hold [RMB]" };
			if ((Object)(object)icon == (Object)null && UseRenderedIcon.Value && (Object)(object)phone.spawnPrefab != (Object)null)
			{
				icon = RenderIcon(phone.spawnPrefab);
			}
			if ((Object)(object)icon == (Object)null)
			{
				icon = LoadIcon();
			}
			if ((Object)(object)icon != (Object)null)
			{
				phone.itemIcon = icon;
			}
			if ((Object)(object)phone.spawnPrefab != (Object)null)
			{
				RenameScanNode(phone.spawnPrefab);
				if ((Object)(object)phone.spawnPrefab.GetComponent<PhoneUse>() == (Object)null)
				{
					phone.spawnPrefab.AddComponent<PhoneUse>();
				}
			}
			return true;
		}

		private static Sprite RenderIcon(GameObject prefab)
		{
			//IL_0014: Unknown result type (might be due to invalid IL or missing references)
			//IL_001a: Expected O, but got Unknown
			//IL_002f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0158: Unknown result type (might be due to invalid IL or missing references)
			//IL_015d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0086: Unknown result type (might be due to invalid IL or missing references)
			//IL_0092: Unknown result type (might be due to invalid IL or missing references)
			//IL_0097: Unknown result type (might be due to invalid IL or missing references)
			//IL_009c: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cb: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00da: 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_00ec: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fe: 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_019f: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a5: Expected O, but got Unknown
			//IL_01c1: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c6: Unknown result type (might be due to invalid IL or missing references)
			//IL_01fc: Unknown result type (might be due to invalid IL or missing references)
			//IL_0239: Unknown result type (might be due to invalid IL or missing references)
			//IL_023e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0242: Unknown result type (might be due to invalid IL or missing references)
			//IL_0247: Unknown result type (might be due to invalid IL or missing references)
			//IL_0252: Unknown result type (might be due to invalid IL or missing references)
			//IL_0257: Unknown result type (might be due to invalid IL or missing references)
			//IL_025e: 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_0276: Unknown result type (might be due to invalid IL or missing references)
			//IL_0285: Unknown result type (might be due to invalid IL or missing references)
			//IL_028b: Expected O, but got Unknown
			//IL_02ba: Unknown result type (might be due to invalid IL or missing references)
			//IL_02f8: Unknown result type (might be due to invalid IL or missing references)
			//IL_02ff: Expected O, but got Unknown
			//IL_0315: Unknown result type (might be due to invalid IL or missing references)
			//IL_033d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0342: Unknown result type (might be due to invalid IL or missing references)
			//IL_0344: Unknown result type (might be due to invalid IL or missing references)
			//IL_0352: Unknown result type (might be due to invalid IL or missing references)
			//IL_0359: Unknown result type (might be due to invalid IL or missing references)
			//IL_0361: Unknown result type (might be due to invalid IL or missing references)
			//IL_03b1: Unknown result type (might be due to invalid IL or missing references)
			//IL_03c0: Unknown result type (might be due to invalid IL or missing references)
			GameObject val = null;
			GameObject val2 = null;
			GameObject val3 = null;
			RenderTexture val4 = null;
			RenderTexture active = RenderTexture.active;
			try
			{
				val = new GameObject("EmergencyPhoneIconRoot");
				val.transform.position = new Vector3(0f, -5000f, 0f);
				List<Renderer> list = new List<Renderer>();
				MeshRenderer[] componentsInChildren = prefab.GetComponentsInChildren<MeshRenderer>(true);
				foreach (MeshRenderer val5 in componentsInChildren)
				{
					MeshFilter component = ((Component)val5).GetComponent<MeshFilter>();
					if (!((Object)(object)component == (Object)null) && !((Object)(object)component.sharedMesh == (Object)null))
					{
						Matrix4x4 val6 = prefab.transform.worldToLocalMatrix * ((Component)val5).transform.localToWorldMatrix;
						GameObject val7 = new GameObject("part")
						{
							layer = 31
						};
						val7.transform.SetParent(val.transform, false);
						val7.transform.localPosition = Vector4.op_Implicit(((Matrix4x4)(ref val6)).GetColumn(3));
						val7.transform.localRotation = ((Matrix4x4)(ref val6)).rotation;
						val7.transform.localScale = ((Matrix4x4)(ref val6)).lossyScale;
						val7.AddComponent<MeshFilter>().sharedMesh = component.sharedMesh;
						MeshRenderer val8 = val7.AddComponent<MeshRenderer>();
						((Renderer)val8).sharedMaterials = ((Renderer)val5).sharedMaterials;
						list.Add((Renderer)(object)val8);
					}
				}
				if (list.Count == 0)
				{
					return null;
				}
				Bounds bounds = list[0].bounds;
				foreach (Renderer item in list)
				{
					((Bounds)(ref bounds)).Encapsulate(item.bounds);
				}
				val2 = new GameObject("EmergencyPhoneIconCamera");
				Camera val9 = val2.AddComponent<Camera>();
				((Behaviour)val9).enabled = false;
				val9.orthographic = true;
				Vector3 val10 = ((Bounds)(ref bounds)).extents;
				val9.orthographicSize = Mathf.Max(((Vector3)(ref val10)).magnitude, 0.01f);
				val9.clearFlags = (CameraClearFlags)2;
				val9.backgroundColor = new Color(0f, 0f, 0f, 0f);
				val9.cullingMask = int.MinValue;
				val9.nearClipPlane = 0.01f;
				val9.farClipPlane = 50f;
				val10 = new Vector3(0.5f, 0.6f, -1f);
				Vector3 normalized = ((Vector3)(ref val10)).normalized;
				((Component)val9).transform.position = ((Bounds)(ref bounds)).center + normalized * 10f;
				((Component)val9).transform.LookAt(((Bounds)(ref bounds)).center);
				val3 = new GameObject("EmergencyPhoneIconLight");
				Light obj = val3.AddComponent<Light>();
				obj.type = (LightType)1;
				obj.intensity = 1.2f;
				obj.cullingMask = int.MinValue;
				val3.transform.rotation = ((Component)val9).transform.rotation;
				val4 = (val9.targetTexture = RenderTexture.GetTemporary(128, 128, 24, (RenderTextureFormat)0));
				val9.Render();
				RenderTexture.active = val4;
				Texture2D val11 = new Texture2D(128, 128, (TextureFormat)4, false);
				val11.ReadPixels(new Rect(0f, 0f, 128f, 128f), 0, 0);
				val11.Apply();
				bool flag = false;
				Color32[] pixels = val11.GetPixels32();
				foreach (Color32 val12 in pixels)
				{
					if (val12.a > 128 && val12.r + val12.g + val12.b > 60)
					{
						flag = true;
						break;
					}
				}
				if (!flag)
				{
					Log.LogWarning((object)"Rendered phone icon came out empty; using the logo instead.");
					return null;
				}
				return Sprite.Create(val11, new Rect(0f, 0f, 128f, 128f), new Vector2(0.5f, 0.5f));
			}
			catch (Exception ex)
			{
				Log.LogWarning((object)("Couldn't render the phone icon: " + ex.Message));
				return null;
			}
			finally
			{
				RenderTexture.active = active;
				if ((Object)(object)val4 != (Object)null)
				{
					RenderTexture.ReleaseTemporary(val4);
				}
				if ((Object)(object)val2 != (Object)null)
				{
					Object.Destroy((Object)(object)val2);
				}
				if ((Object)(object)val3 != (Object)null)
				{
					Object.Destroy((Object)(object)val3);
				}
				if ((Object)(object)val != (Object)null)
				{
					Object.Destroy((Object)(object)val);
				}
			}
		}

		private static Sprite LoadIcon()
		{
			//IL_0041: Unknown result type (might be due to invalid IL or missing references)
			//IL_0047: Expected O, but got Unknown
			//IL_006d: 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)
			try
			{
				using Stream stream = typeof(EmergencyPhonePlugin).Assembly.GetManifestResourceStream("EmergencyPhone.icon.png");
				if (stream == null)
				{
					return null;
				}
				byte[] array = new byte[stream.Length];
				stream.Read(array, 0, array.Length);
				Texture2D val = new Texture2D(2, 2, (TextureFormat)4, false);
				if (!ImageConversion.LoadImage(val, array))
				{
					return null;
				}
				return Sprite.Create(val, new Rect(0f, 0f, (float)((Texture)val).width, (float)((Texture)val).height), new Vector2(0.5f, 0.5f));
			}
			catch (Exception ex)
			{
				Log.LogWarning((object)("Couldn't load the HUD icon: " + ex.Message));
				return null;
			}
		}

		internal static void RenameScanNode(GameObject phoneObject)
		{
			ScanNodeProperties[] componentsInChildren = phoneObject.GetComponentsInChildren<ScanNodeProperties>(true);
			for (int i = 0; i < componentsInChildren.Length; i++)
			{
				componentsInChildren[i].headerText = "Emergency Phone";
			}
		}

		private static void AddToStore(Terminal terminal)
		{
			//IL_021d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0223: Expected O, but got Unknown
			//IL_0263: Unknown result type (might be due to invalid IL or missing references)
			//IL_0269: Expected O, but got Unknown
			//IL_02f1: Unknown result type (might be due to invalid IL or missing references)
			//IL_02fb: Expected O, but got Unknown
			//IL_0312: Unknown result type (might be due to invalid IL or missing references)
			//IL_031c: Expected O, but got Unknown
			List<Item> list = terminal.buyableItemsList.ToList();
			if (!list.Contains(phone))
			{
				list.Add(phone);
			}
			int num = list.IndexOf(phone);
			terminal.buyableItemsList = list.ToArray();
			terminal.itemSalesPercentages = Enumerable.Repeat(100, terminal.buyableItemsList.Length + terminal.buyableVehicles.Length).ToArray();
			List<TerminalKeyword> list2 = terminal.terminalNodes.allKeywords.ToList();
			TerminalKeyword val = list2.First((TerminalKeyword k) => k.word == "buy");
			TerminalKeyword val2 = list2.First((TerminalKeyword k) => k.word == "info");
			CompatibleNoun val3 = ((IEnumerable<CompatibleNoun>)val.compatibleNouns).FirstOrDefault((Func<CompatibleNoun, bool>)((CompatibleNoun n) => (Object)(object)n.noun != (Object)null && n.noun.word == "emergency-phone"));
			if (val3 != null)
			{
				val3.result.buyItemIndex = num;
				val3.result.itemCost = Price.Value;
				TerminalNode result = val3.result.terminalOptions[0].result;
				result.buyItemIndex = num;
				result.itemCost = Price.Value;
				return;
			}
			TerminalNode val4 = ScriptableObject.CreateInstance<TerminalNode>();
			((Object)val4).name = "EmergencyPhoneBuyNode2";
			val4.displayText = "Ordered [variableAmount] Emergency Phone. Your new balance is [playerCredits].\n\nOur contractors enjoy fast, free shipping while on the job! Any purchased items will arrive hourly at your approximate location.\r\n\r\n";
			val4.clearPreviousText = true;
			val4.maxCharactersToType = 15;
			val4.buyItemIndex = num;
			val4.isConfirmationNode = false;
			val4.itemCost = Price.Value;
			val4.playSyncedClip = 0;
			TerminalNode val5 = ScriptableObject.CreateInstance<TerminalNode>();
			((Object)val5).name = "EmergencyPhoneBuyNode1";
			val5.displayText = "You have requested to order Emergency Phone. Amount: [variableAmount].\nTotal cost of items: [totalCost].\n\nPlease CONFIRM or DENY.\r\n\r\n";
			val5.clearPreviousText = true;
			val5.maxCharactersToType = 35;
			val5.buyItemIndex = num;
			val5.isConfirmationNode = true;
			val5.overrideOptions = true;
			val5.itemCost = Price.Value;
			val5.terminalOptions = (CompatibleNoun[])(object)new CompatibleNoun[2]
			{
				new CompatibleNoun(list2.First((TerminalKeyword k) => k.word == "confirm"), val4),
				new CompatibleNoun(list2.First((TerminalKeyword k) => k.word == "deny"), val.compatibleNouns[0].result.terminalOptions[1].result)
			};
			TerminalKeyword val6 = ScriptableObject.CreateInstance<TerminalKeyword>();
			((Object)val6).name = "EmergencyPhone";
			val6.word = "emergency-phone";
			val6.isVerb = false;
			val6.defaultVerb = val;
			TerminalNode val7 = ScriptableObject.CreateInstance<TerminalNode>();
			((Object)val7).name = "EmergencyPhoneInfoNode";
			val7.displayText = "EMERGENCY PHONE\n\nHold it and hold the right mouse button to call the ship's Teleporter on yourself. Needs a regular Teleporter on the ship. Single use.\n\n";
			val7.clearPreviousText = true;
			val7.maxCharactersToType = 25;
			list2.Add(val6);
			terminal.terminalNodes.allKeywords = list2.ToArray();
			val.compatibleNouns = val.compatibleNouns.Append(new CompatibleNoun(val6, val5)).ToArray();
			val2.compatibleNouns = val2.compatibleNouns.Append(new CompatibleNoun(val6, val7)).ToArray();
			Log.LogInfo((object)string.Format("Added {0} to the store (index {1}, ${2}).", "Emergency Phone", num, Price.Value));
		}
	}
	internal static class PhoneNet
	{
		internal enum Kind : byte
		{
			Explode
		}

		[CompilerGenerated]
		private static class <>O
		{
			public static HandleNamedMessageDelegate <0>__Receive;
		}

		private const string MessageName = "EmergencyPhone.Event";

		private const float KillRange = 5.7f;

		private const float DamageRange = 6f;

		internal static void Register()
		{
			//IL_0043: Unknown result type (might be due to invalid IL or missing references)
			//IL_0048: Unknown result type (might be due to invalid IL or missing references)
			//IL_004e: Expected O, but got Unknown
			NetworkManager singleton = NetworkManager.Singleton;
			if (!((Object)(object)singleton == (Object)null) && singleton.CustomMessagingManager != null)
			{
				singleton.CustomMessagingManager.UnregisterNamedMessageHandler("EmergencyPhone.Event");
				CustomMessagingManager customMessagingManager = singleton.CustomMessagingManager;
				object obj = <>O.<0>__Receive;
				if (obj == null)
				{
					HandleNamedMessageDelegate val = Receive;
					<>O.<0>__Receive = val;
					obj = (object)val;
				}
				customMessagingManager.RegisterNamedMessageHandler("EmergencyPhone.Event", (HandleNamedMessageDelegate)obj);
			}
		}

		internal unsafe static void Broadcast(Kind kind, Vector3 position)
		{
			//IL_003a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0042: Unknown result type (might be due to invalid IL or missing references)
			//IL_0043: Unknown result type (might be due to invalid IL or missing references)
			//IL_0048: Unknown result type (might be due to invalid IL or missing references)
			//IL_0079: Unknown result type (might be due to invalid IL or missing references)
			//IL_005c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0064: Unknown result type (might be due to invalid IL or missing references)
			EmergencyPhonePlugin.Log.LogInfo((object)$"Broadcast {kind}.");
			NetworkManager singleton = NetworkManager.Singleton;
			if ((Object)(object)singleton == (Object)null || !singleton.IsListening || singleton.CustomMessagingManager == null)
			{
				Run(kind, position);
				return;
			}
			FastBufferWriter val = Write(kind, position);
			try
			{
				if (singleton.IsServer)
				{
					singleton.CustomMessagingManager.SendNamedMessageToAll("EmergencyPhone.Event", val, (NetworkDelivery)3);
					Run(kind, position);
				}
				else
				{
					singleton.CustomMessagingManager.SendNamedMessage("EmergencyPhone.Event", 0uL, val, (NetworkDelivery)3);
				}
			}
			finally
			{
				((IDisposable)(*(FastBufferWriter*)(&val))/*cast due to .constrained prefix*/).Dispose();
			}
		}

		private static FastBufferWriter Write(Kind kind, Vector3 position)
		{
			//IL_0013: 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_0028: Unknown result type (might be due to invalid IL or missing references)
			FastBufferWriter result = default(FastBufferWriter);
			((FastBufferWriter)(ref result))..ctor(16, (Allocator)2, -1);
			byte b = (byte)kind;
			((FastBufferWriter)(ref result)).WriteValueSafe<byte>(ref b, default(ForPrimitives));
			((FastBufferWriter)(ref result)).WriteValueSafe(ref position);
			return result;
		}

		private unsafe static void Receive(ulong senderId, FastBufferReader reader)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: 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_0033: 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_0039: Unknown result type (might be due to invalid IL or missing references)
			//IL_0046: Unknown result type (might be due to invalid IL or missing references)
			byte kind = default(byte);
			((FastBufferReader)(ref reader)).ReadValueSafe<byte>(ref kind, default(ForPrimitives));
			Vector3 position = default(Vector3);
			((FastBufferReader)(ref reader)).ReadValueSafe(ref position);
			NetworkManager singleton = NetworkManager.Singleton;
			if ((Object)(object)singleton != (Object)null && singleton.IsServer)
			{
				FastBufferWriter val = Write((Kind)kind, position);
				try
				{
					singleton.CustomMessagingManager.SendNamedMessageToAll("EmergencyPhone.Event", val, (NetworkDelivery)3);
				}
				finally
				{
					((IDisposable)(*(FastBufferWriter*)(&val))/*cast due to .constrained prefix*/).Dispose();
				}
			}
			Run((Kind)kind, position);
		}

		private static void Run(Kind kind, Vector3 position)
		{
			//IL_001a: Unknown result type (might be due to invalid IL or missing references)
			EmergencyPhonePlugin.Log.LogInfo((object)$"Running {kind}.");
			try
			{
				Landmine.SpawnExplosion(position, true, 5.7f, 6f, 50, 0f, (GameObject)null, false);
			}
			catch (Exception ex)
			{
				EmergencyPhonePlugin.Log.LogWarning((object)$"Couldn't run phone event {kind}: {ex.Message}");
			}
		}
	}
	public class PhoneUse : MonoBehaviour
	{
		private sealed class Runner : MonoBehaviour
		{
		}

		private enum Failure
		{
			None,
			Longer,
			Breaks,
			WrongButton,
			Explodes,
			Everyone
		}

		private const string Title = "Emergency Phone";

		private static AudioClip ringClip;

		private const float SyncDelaySeconds = 1f;

		private GrabbableObject item;

		private AudioSource ringSource;

		private bool calling;

		private bool warned;

		private float heldFor;

		private void Awake()
		{
			item = ((Component)this).GetComponent<GrabbableObject>();
			EmergencyPhonePlugin.RenameScanNode(((Component)this).gameObject);
		}

		private void Start()
		{
			if ((Object)(object)item != (Object)null && item.scrapValue <= 0)
			{
				int value = EmergencyPhonePlugin.SellValueMin.Value;
				int num = Mathf.Max(value, EmergencyPhonePlugin.SellValueMax.Value);
				Random random = new Random((int)(((NetworkBehaviour)item).NetworkObjectId % int.MaxValue));
				item.SetScrapValue(random.Next(value, num + 1));
			}
		}

		private void Update()
		{
			if ((Object)(object)item == (Object)null || !((NetworkBehaviour)item).IsOwner)
			{
				return;
			}
			PlayerControllerB val = GameNetworkManager.Instance?.localPlayerController;
			bool flag = item.isHeld && !item.isPocketed && (Object)(object)item.playerHeldBy != (Object)null && (Object)(object)item.playerHeldBy == (Object)(object)val && (Object)(object)val.currentlyHeldObjectServer == (Object)(object)item;
			if (!flag || Mouse.current == null || !Mouse.current.rightButton.isPressed || UiBlocking(val))
			{
				warned = false;
				if (calling)
				{
					StopCalling();
					if (flag)
					{
						HUDManager.Instance.DisplayTip("Emergency Phone", "Call cancelled.", false, false, "LC_Tip1");
					}
				}
				return;
			}
			if (!calling)
			{
				if (warned)
				{
					return;
				}
				if (!CanCall(val, out var _, out var _, out var reason))
				{
					warned = true;
					HUDManager.Instance.DisplayTip("Emergency Phone", reason, true, false, "LC_Tip1");
					return;
				}
				StartCalling();
			}
			heldFor += Time.deltaTime;
			if (heldFor >= EmergencyPhonePlugin.HoldSeconds.Value)
			{
				StopCalling();
				Execute(val);
			}
		}

		private void OnDisable()
		{
			StopCalling();
		}

		private static bool UiBlocking(PlayerControllerB p)
		{
			if (!p.isTypingChat && !p.inTerminalMenu && !p.isPlayerDead)
			{
				if ((Object)(object)p.quickMenuManager != (Object)null)
				{
					return p.quickMenuManager.isMenuOpen;
				}
				return false;
			}
			return true;
		}

		private static bool CanCall(PlayerControllerB player, out ShipTeleporter teleporter, out int radarIndex, out string reason)
		{
			teleporter = null;
			radarIndex = -1;
			StartOfRound instance = StartOfRound.Instance;
			if (instance.inShipPhase)
			{
				reason = "Can't call right now.";
				return false;
			}
			if (player.isInHangarShipRoom || player.isInElevator)
			{
				reason = "You're already on the ship.";
				return false;
			}
			teleporter = ((IEnumerable<ShipTeleporter>)Object.FindObjectsOfType<ShipTeleporter>()).FirstOrDefault((Func<ShipTeleporter, bool>)((ShipTeleporter t) => !t.isInverseTeleporter));
			if ((Object)(object)teleporter == (Object)null)
			{
				reason = "Your ship has no Teleporter. Buy one first!";
				return false;
			}
			if ((Object)(object)teleporter.buttonTrigger != (Object)null && !teleporter.buttonTrigger.interactable)
			{
				reason = "The ship's Teleporter is on cooldown.";
				return false;
			}
			List<TransformAndName> radarTargets = instance.mapScreen.radarTargets;
			for (int num = 0; num < radarTargets.Count; num++)
			{
				if ((Object)(object)radarTargets[num].transform != (Object)null && (Object)(object)((Component)radarTargets[num].transform).GetComponent<PlayerControllerB>() == (Object)(object)player)
				{
					radarIndex = num;
					reason = null;
					return true;
				}
			}
			reason = "The ship can't find you on the radar.";
			return false;
		}

		private void StartCalling()
		{
			calling = true;
			heldFor = 0f;
			HUDManager.Instance.DisplayTip("Emergency Phone", "Calling the ship... keep holding.", false, false, "LC_Tip1");
			if ((Object)(object)ringSource == (Object)null)
			{
				ringSource = ((Component)this).gameObject.AddComponent<AudioSource>();
				ringSource.playOnAwake = false;
				ringSource.loop = true;
				ringSource.spatialBlend = 1f;
				ringSource.maxDistance = 25f;
				ringSource.volume = 0.6f;
				ringSource.clip = ringClip ?? (ringClip = MakeRingClip());
			}
			ringSource.pitch = 1f;
			ringSource.Play();
		}

		private void StopCalling()
		{
			calling = false;
			heldFor = 0f;
			if ((Object)(object)ringSource != (Object)null)
			{
				ringSource.Stop();
			}
		}

		private void Execute(PlayerControllerB player)
		{
			//IL_00d6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00dd: Expected O, but got Unknown
			if (!CanCall(player, out var teleporter, out var radarIndex, out var reason))
			{
				HUDManager.Instance.DisplayTip("Emergency Phone", reason, true, false, "LC_Tip1");
				return;
			}
			Failure failure = RollFailure();
			EmergencyPhonePlugin.Log.LogInfo((object)$"Calling the ship (radar index {radarIndex}, outcome {failure}).");
			switch (failure)
			{
			case Failure.Breaks:
				HUDManager.Instance.DisplayTip("Emergency Phone", "The phone broke! Nothing happened.", true, false, "LC_Tip1");
				if ((Object)(object)player.currentlyHeldObjectServer == (Object)(object)item)
				{
					player.DespawnHeldObject();
				}
				return;
			case Failure.WrongButton:
				if (TryWrongButton(player, teleporter, item))
				{
					return;
				}
				break;
			}
			float num;
			switch (failure)
			{
			case Failure.Explodes:
				((MonoBehaviour)this).StartCoroutine(ExplodeRoutine(player, item));
				return;
			case Failure.Everyone:
			{
				HUDManager.Instance.DisplayTip("Emergency Phone", "The call went out to everyone!", false, false, "LC_Tip1");
				GameObject val = new GameObject("EmergencyPhoneRunner");
				((MonoBehaviour)val.AddComponent<Runner>()).StartCoroutine(BeamEveryoneRoutine(player, teleporter, val));
				if ((Object)(object)player.currentlyHeldObjectServer == (Object)(object)item)
				{
					player.DespawnHeldObject();
				}
				return;
			}
			default:
				num = 0f;
				break;
			case Failure.Longer:
				num = EmergencyPhonePlugin.LongerExtraSeconds.Value;
				break;
			}
			float extraSeconds = num;
			((MonoBehaviour)this).StartCoroutine(TeleportRoutine(player, teleporter, radarIndex, item, extraSeconds));
		}

		private static IEnumerator BeamEveryoneRoutine(PlayerControllerB caller, ShipTeleporter teleporter, GameObject runner)
		{
			StartOfRound round = StartOfRound.Instance;
			ManualCameraRenderer map = round.mapScreen;
			List<PlayerControllerB> list = (from p in round.allPlayerScripts
				where (Object)(object)p != (Object)null && p.isPlayerControlled && !p.isPlayerDead && !p.isInHangarShipRoom && !p.isInElevator
				orderby (Object)(object)p != (Object)(object)caller
				select p).ToList();
			foreach (PlayerControllerB target in list)
			{
				if (round.inShipPhase || (Object)(object)teleporter == (Object)null)
				{
					break;
				}
				int num = -1;
				for (int num2 = 0; num2 < map.radarTargets.Count; num2++)
				{
					if ((Object)(object)map.radarTargets[num2].transform != (Object)null && (Object)(object)((Component)map.radarTargets[num2].transform).GetComponent<PlayerControllerB>() == (Object)(object)target)
					{
						num = num2;
						break;
					}
				}
				if (num >= 0)
				{
					map.SwitchRadarTargetAndSync(num);
					float timeout = 1.5f;
					while ((Object)(object)map.targetedPlayer != (Object)(object)target && timeout > 0f)
					{
						timeout -= Time.deltaTime;
						yield return null;
					}
					if (!((Object)(object)map.targetedPlayer != (Object)(object)target))
					{
						yield return (object)new WaitForSeconds(1f);
						teleporter.PressTeleportButtonOnLocalClient();
						EmergencyPhonePlugin.Log.LogInfo((object)$"Everyone: beaming up player {target.playerClientId}.");
						yield return (object)new WaitForSeconds(3.6f);
					}
				}
			}
			Object.Destroy((Object)(object)runner);
		}

		private static Failure RollFailure()
		{
			if (!EmergencyPhonePlugin.FailuresEnabled.Value)
			{
				return Failure.None;
			}
			float num = Random.Range(0f, 100f);
			if ((num -= EmergencyPhonePlugin.BreakChance.Value) < 0f)
			{
				return Failure.Breaks;
			}
			if ((num -= EmergencyPhonePlugin.WrongButtonChance.Value) < 0f)
			{
				return Failure.WrongButton;
			}
			if ((num -= EmergencyPhonePlugin.LongerChance.Value) < 0f)
			{
				return Failure.Longer;
			}
			if ((num -= EmergencyPhonePlugin.ExplodeChance.Value) < 0f)
			{
				return Failure.Explodes;
			}
			if ((num -= EmergencyPhonePlugin.EveryoneChance.Value) < 0f)
			{
				return Failure.Everyone;
			}
			return Failure.None;
		}

		private IEnumerator ExplodeRoutine(PlayerControllerB player, GrabbableObject phone)
		{
			HUDManager.Instance.DisplayTip("Emergency Phone", "The phone is overheating! Drop it and run!", true, false, "LC_Tip1");
			if ((Object)(object)ringSource != (Object)null)
			{
				ringSource.pitch = 3f;
				ringSource.Play();
			}
			yield return (object)new WaitForSeconds(2.5f);
			Vector3 position = ((Component)phone).transform.position + Vector3.up;
			PhoneNet.Broadcast(PhoneNet.Kind.Explode, position);
			if ((Object)(object)player.currentlyHeldObjectServer == (Object)(object)phone)
			{
				player.DespawnHeldObject();
			}
		}

		private static bool TryWrongButton(PlayerControllerB player, ShipTeleporter teleporter, GrabbableObject phone)
		{
			//IL_008e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0093: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00eb: Unknown result type (might be due to invalid IL or missing references)
			RoundManager instance = RoundManager.Instance;
			if (instance.dungeonIsGenerating || !StartOfRound.Instance.currentLevel.spawnEnemiesAndScrap || instance.insideAINodes == null || instance.insideAINodes.Length == 0)
			{
				return false;
			}
			FieldInfo fieldInfo = AccessTools.Field(typeof(ShipTeleporter), "shipTeleporterSeed");
			if (fieldInfo.GetValue(teleporter) == null)
			{
				fieldInfo.SetValue(teleporter, new Random(StartOfRound.Instance.randomMapSeed + 17 + (int)player.playerClientId));
			}
			Vector3 val = (Vector3)AccessTools.Method(typeof(ShipTeleporter), "GetInverseTelePosition", (Type[])null, (Type[])null).Invoke(teleporter, null);
			if ((Object)(object)player.currentlyHeldObjectServer == (Object)(object)phone)
			{
				player.DespawnHeldObject();
			}
			AccessTools.Method(typeof(ShipTeleporter), "TeleportPlayerOutWithInverseTeleporter", (Type[])null, (Type[])null).Invoke(teleporter, new object[2]
			{
				(int)player.playerClientId,
				val
			});
			teleporter.TeleportPlayerOutServerRpc((int)player.playerClientId, val);
			HUDManager.Instance.DisplayTip("Emergency Phone", "Wrong number! You ended up somewhere inside the facility.", true, false, "LC_Tip1");
			return true;
		}

		private static IEnumerator TeleportRoutine(PlayerControllerB player, ShipTeleporter teleporter, int radarIndex, GrabbableObject phone, float extraSeconds)
		{
			if (extraSeconds > 0f)
			{
				HUDManager.Instance.DisplayTip("Emergency Phone", "Bad reception... still connecting.", false, false, "LC_Tip1");
				yield return (object)new WaitForSeconds(extraSeconds);
			}
			ManualCameraRenderer map = StartOfRound.Instance.mapScreen;
			map.SwitchRadarTargetAndSync(radarIndex);
			float timeout = 1.5f;
			while ((Object)(object)map.targetedPlayer != (Object)(object)player && timeout > 0f)
			{
				timeout -= Time.deltaTime;
				yield return null;
			}
			if ((Object)(object)map.targetedPlayer == (Object)(object)player)
			{
				yield return (object)new WaitForSeconds(1f);
			}
			if ((Object)(object)map.targetedPlayer != (Object)(object)player || (Object)(object)teleporter == (Object)null || ((Object)(object)teleporter.buttonTrigger != (Object)null && !teleporter.buttonTrigger.interactable))
			{
				HUDManager.Instance.DisplayTip("Emergency Phone", "The call failed. Try again.", true, false, "LC_Tip1");
				yield break;
			}
			teleporter.PressTeleportButtonOnLocalClient();
			EmergencyPhonePlugin.Log.LogInfo((object)"Teleporter button pressed.");
			if ((Object)(object)phone != (Object)null && (Object)(object)player.currentlyHeldObjectServer == (Object)(object)phone)
			{
				player.DespawnHeldObject();
			}
		}

		private static AudioClip MakeRingClip()
		{
			float[] array = new float[26460];
			for (int i = 0; i < array.Length; i++)
			{
				float num = (float)i / 44100f;
				if (!(num > 0.4f))
				{
					float num2 = Mathf.Min(1f, num * 60f) * Mathf.Min(1f, (0.4f - num) * 60f);
					array[i] = 0.35f * num2 * (Mathf.Sin(MathF.PI * 880f * num) + Mathf.Sin(MathF.PI * 960f * num));
				}
			}
			AudioClip obj = AudioClip.Create("EmergencyPhoneRing", array.Length, 1, 44100, false);
			obj.SetData(array, 0);
			((Object)obj).hideFlags = (HideFlags)61;
			return obj;
		}
	}
}