Decompiled source of Weather Neutralizer v1.1.0

BepInEx/plugins/WeatherNeutralizer/WeatherNeutralizer.dll

Decompiled 2 weeks ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
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;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("WeatherNeutralizer")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.1.0.0")]
[assembly: AssemblyInformationalVersion("1.1.0")]
[assembly: AssemblyProduct("WeatherNeutralizer")]
[assembly: AssemblyTitle("WeatherNeutralizer")]
[assembly: AssemblyVersion("1.1.0.0")]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

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

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

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

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace WeatherNeutralizer
{
	internal static class LaunchEffects
	{
		private static GameObject? root;

		private static Coroutine? running;

		private static MonoBehaviour? owner;

		private static AudioClip? charge;

		private static AudioClip? launch;

		private static Material? shellMaterial;

		private static Material? glowMaterial;

		internal static void Play(MonoBehaviour runner, double elapsed)
		{
			Cancel();
			owner = runner;
			running = runner.StartCoroutine(Sequence((float)elapsed));
		}

		internal static void Cancel()
		{
			if ((Object)(object)owner != (Object)null && running != null)
			{
				owner.StopCoroutine(running);
			}
			running = null;
			if ((Object)(object)root != (Object)null)
			{
				Object.Destroy((Object)(object)root);
			}
			root = null;
		}

		private static IEnumerator Sequence(float elapsed)
		{
			if ((Object)(object)StartOfRound.Instance == (Object)null)
			{
				yield break;
			}
			if (charge == null)
			{
				charge = MakeSound("WeatherNeutralizer_Charge", 3.2f, firing: false);
			}
			if (launch == null)
			{
				launch = MakeSound("WeatherNeutralizer_Launch", 2.4f, firing: true);
			}
			root = new GameObject("WeatherNeutralizer_LaunchEffect");
			root.transform.SetParent(StartOfRound.Instance.elevatorTransform, false);
			root.transform.localPosition = new Vector3(0f, 4.2f, -3f);
			AudioSource source = root.AddComponent<AudioSource>();
			source.spatialBlend = 1f;
			source.rolloffMode = (AudioRolloffMode)1;
			source.minDistance = 8f;
			source.maxDistance = 100f;
			source.volume = Plugin.EffectVolume.Value;
			source.playOnAwake = false;
			float start = Time.realtimeSinceStartup - elapsed;
			if ((double)elapsed < 3.2)
			{
				source.clip = charge;
				source.time = elapsed;
				source.Play();
			}
			float rumbleAt = 2.35f;
			bool rumbled = elapsed >= rumbleAt;
			while ((Object)(object)root != (Object)null && (double)(Time.realtimeSinceStartup - start) < 3.2)
			{
				if (!rumbled && Time.realtimeSinceStartup - start >= rumbleAt)
				{
					rumbled = true;
					ShakeNearShip(firing: false);
				}
				yield return null;
			}
			if ((Object)(object)root == (Object)null)
			{
				yield break;
			}
			float num = Mathf.Max(0f, Time.realtimeSinceStartup - start - 3.2f);
			source.Stop();
			if (num < launch.length)
			{
				source.clip = launch;
				source.time = num;
				source.Play();
			}
			if (num < 0.35f)
			{
				ShakeNearShip(firing: true);
			}
			if (((NetworkBehaviour)StartOfRound.Instance).IsServer && !StartOfRound.Instance.inShipPhase && (Object)(object)RoundManager.Instance != (Object)null)
			{
				RoundManager.Instance.PlayAudibleNoise(root.transform.position, 35f, 0.9f, 0, false, 731947);
			}
			Shader val = Shader.Find("HDRP/Unlit") ?? Shader.Find("Unlit/Color") ?? Shader.Find("Sprites/Default");
			if ((Object)(object)val == (Object)null)
			{
				Plugin.Log.LogWarning((object)"No supported projectile shader found; launch audio and camera shake will still play.");
				yield return (object)new WaitForSeconds(2.5f);
				if ((Object)(object)root != (Object)null)
				{
					Object.Destroy((Object)(object)root);
				}
				root = null;
				running = null;
				yield break;
			}
			if (shellMaterial == null)
			{
				shellMaterial = Material(val, new Color(0.85f, 0.92f, 0.95f));
			}
			if (glowMaterial == null)
			{
				glowMaterial = Material(val, new Color(0.15f, 2.2f, 3.5f));
			}
			GameObject rocket = Primitive("Neutralizer rocket", (PrimitiveType)1, root.transform, new Vector3(0.18f, 0.6f, 0.18f), shellMaterial);
			GameObject flame = Primitive("Rocket exhaust", (PrimitiveType)0, rocket.transform, new Vector3(2.5f, 1.2f, 2.5f), glowMaterial);
			flame.transform.localPosition = new Vector3(0f, -1.4f, 0f);
			GameObject flash = Primitive("Launch burst", (PrimitiveType)0, root.transform, Vector3.zero, glowMaterial);
			flash.transform.localPosition = Vector3.up * 0.8f;
			TrailRenderer obj = rocket.AddComponent<TrailRenderer>();
			((Renderer)obj).sharedMaterial = glowMaterial;
			obj.time = 1.6f;
			obj.startWidth = 0.42f;
			obj.endWidth = 0.02f;
			obj.minVertexDistance = 0.2f;
			obj.startColor = Color.cyan;
			obj.endColor = new Color(0.2f, 0.8f, 1f, 0f);
			while ((Object)(object)root != (Object)null && Time.realtimeSinceStartup - start < 7f)
			{
				float num2 = Mathf.Max(0f, Time.realtimeSinceStartup - start - 3.2f);
				rocket.transform.localPosition = Vector3.up * (0.8f + num2 * 12f + num2 * num2 * 20f);
				flame.transform.localScale = new Vector3(2.5f, 1f + 0.3f * Mathf.Sin(num2 * 45f), 2.5f);
				if (num2 < 0.3f)
				{
					flash.transform.localScale = Vector3.one * (3.2f * Mathf.Sin((float)Math.PI * num2 / 0.3f));
				}
				else if (flash.activeSelf)
				{
					flash.SetActive(false);
				}
				yield return null;
			}
			if ((Object)(object)root != (Object)null)
			{
				Object.Destroy((Object)(object)root);
			}
			root = null;
			running = null;
		}

		private static void ShakeNearShip(bool firing)
		{
			//IL_0078: Unknown result type (might be due to invalid IL or missing references)
			//IL_0087: Unknown result type (might be due to invalid IL or missing references)
			if (!Plugin.CameraShake.Value || (Object)(object)root == (Object)null || (Object)(object)HUDManager.Instance == (Object)null || (Object)(object)GameNetworkManager.Instance == (Object)null)
			{
				return;
			}
			PlayerControllerB val = GameNetworkManager.Instance.localPlayerController;
			if ((Object)(object)val == (Object)null)
			{
				return;
			}
			if (val.isPlayerDead)
			{
				val = val.spectatedPlayerScript;
			}
			if ((Object)(object)val == (Object)null || val.isPlayerDead || val.isInsideFactory)
			{
				return;
			}
			float num = Vector3.Distance(((Component)val).transform.position, root.transform.position);
			if (!firing)
			{
				if (num <= 18f)
				{
					HUDManager.Instance.ShakeCamera((ScreenShakeType)0);
				}
			}
			else if (num <= 18f)
			{
				HUDManager.Instance.ShakeCamera((ScreenShakeType)3);
			}
			else if (num <= 35f)
			{
				HUDManager.Instance.ShakeCamera((ScreenShakeType)1);
			}
			else if (num <= 55f)
			{
				HUDManager.Instance.ShakeCamera((ScreenShakeType)0);
			}
		}

		private static Material Material(Shader shader, Color color)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_0012: Expected O, but got Unknown
			//IL_0025: Unknown result type (might be due to invalid IL or missing references)
			//IL_003e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0057: Unknown result type (might be due to invalid IL or missing references)
			Material val = new Material(shader)
			{
				name = "Weather Neutralizer generated material"
			};
			if (val.HasProperty("_UnlitColor"))
			{
				val.SetColor("_UnlitColor", color);
			}
			if (val.HasProperty("_BaseColor"))
			{
				val.SetColor("_BaseColor", color);
			}
			if (val.HasProperty("_Color"))
			{
				val.SetColor("_Color", color);
			}
			return val;
		}

		private static GameObject Primitive(string name, PrimitiveType type, Transform parent, Vector3 scale, Material material)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0020: Unknown result type (might be due to invalid IL or missing references)
			GameObject obj = GameObject.CreatePrimitive(type);
			((Object)obj).name = name;
			obj.transform.SetParent(parent, false);
			obj.transform.localScale = scale;
			Collider component = obj.GetComponent<Collider>();
			component.enabled = false;
			Object.Destroy((Object)(object)component);
			obj.GetComponent<Renderer>().sharedMaterial = material;
			return obj;
		}

		private static AudioClip MakeSound(string name, float seconds, bool firing)
		{
			float[] array = new float[(int)(seconds * 24000f)];
			double num = 0.0;
			double num2 = 0.0;
			double num3 = 0.0;
			uint num4 = 18473u;
			for (int i = 0; i < array.Length; i++)
			{
				double num5 = (double)i / 24000.0;
				double num6 = num5 / (double)seconds;
				num4 = num4 * 1664525 + 1013904223;
				double num7 = (double)num4 / 4294967295.0 * 2.0 - 1.0;
				num3 += (num7 - num3) * 0.075;
				if (!firing)
				{
					num += (130.0 + 1050.0 * num6 * num6) * 2.0 * Math.PI / 24000.0;
					double num8 = Math.Min(1.0, num5 * 10.0) * Math.Min(1.0, ((double)seconds - num5) * 30.0);
					double num9 = 0.65 + 0.35 * Math.Sin(Math.PI * 2.0 * num5 * (5.0 + num6 * 12.0));
					double num10 = 0.14 * Math.Sin(Math.PI * 96.0 * num5) * (0.25 + 0.75 * num6 * num6);
					array[i] = (float)(num8 * (num9 * (0.23 * Math.Sin(num) + 0.09 * Math.Sin(num * 1.505) + num7 * 0.035) + num10));
				}
				else
				{
					num2 += (38.0 + 54.0 * Math.Exp((0.0 - num5) * 6.0)) * 2.0 * Math.PI / 24000.0;
					double num11 = Math.Min(1.0, num5 * 100.0) * Math.Min(1.0, ((double)seconds - num5) * 18.0);
					double num12 = 0.32 * num7 * Math.Exp((0.0 - num5) * 6.5);
					double num13 = 0.56 * Math.Sin(num2) * Math.Exp((0.0 - num5) * 1.9);
					double num14 = 0.42 * num3 * Math.Exp((0.0 - num5) * 1.3);
					double num15 = ((num5 > 0.85) ? (Math.Sin(Math.PI * 2200.0 * num5) * Math.Exp((0.0 - (num5 - 0.85)) * 10.0) * 0.08) : 0.0);
					array[i] = (float)(num11 * 0.9 * Math.Tanh(1.2 * (num12 + num13 + num14 + num15)));
				}
			}
			AudioClip obj = AudioClip.Create(name, array.Length, 1, 24000, false);
			obj.SetData(array, 0);
			return obj;
		}
	}
	public sealed class NeutralizerRuntime : MonoBehaviour
	{
		private sealed class Launch
		{
			internal SelectableLevel Level;

			internal ulong Buyer;

			internal int Request;

			internal int Paid;

			internal double Started;

			internal bool FromOrbit;
		}

		internal static NeutralizerRuntime Instance = null;

		internal static int HostPrice = 400;

		internal static bool HasHostState;

		private const string RequestMessage = "WeatherNeutralizer.Request.v1";

		private const string StateMessage = "WeatherNeutralizer.State.v1";

		private const string ReplyMessage = "WeatherNeutralizer.Reply.v1";

		private const string SaveKey = "WeatherNeutralizer.Forecasts.v1";

		private readonly HashSet<string> cleared = new HashSet<string>(StringComparer.Ordinal);

		private readonly Dictionary<ulong, int> lastRequests = new Dictionary<ulong, int>();

		private NetworkManager? network;

		private StartOfRound? session;

		private float sessionSince;

		private float nextSync;

		private bool ready;

		private int requestNumber;

		private int sequence;

		private int playedSequence = -1;

		private int lastPrice = -1;

		private Launch? launch;

		private bool wasListening;

		internal bool Busy => launch != null;

		private double Now
		{
			get
			{
				//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)
				if (!((Object)(object)network == (Object)null))
				{
					NetworkTime serverTime = network.ServerTime;
					return ((NetworkTime)(ref serverTime)).Time;
				}
				return Time.realtimeSinceStartup;
			}
		}

		internal static string Key(SelectableLevel level)
		{
			return level.sceneName + "|" + level.PlanetName;
		}

		private void Awake()
		{
			Instance = this;
		}

		private unsafe void Update()
		{
			//IL_01b1: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b7: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d0: Unknown result type (might be due to invalid IL or missing references)
			TerminalIntegration.FlushReply();
			NetworkManager singleton = NetworkManager.Singleton;
			if ((Object)(object)singleton == (Object)null || !singleton.IsListening)
			{
				if (wasListening)
				{
					ResetSession();
				}
				wasListening = false;
				return;
			}
			if ((Object)(object)network != (Object)(object)singleton || !wasListening)
			{
				Bind(singleton);
			}
			wasListening = true;
			if ((Object)(object)StartOfRound.Instance == (Object)null)
			{
				return;
			}
			if ((Object)(object)session != (Object)(object)StartOfRound.Instance)
			{
				session = StartOfRound.Instance;
				sessionSince = Time.realtimeSinceStartup;
				ready = false;
				HasHostState = false;
				launch = null;
				cleared.Clear();
			}
			if (network.IsServer && !ready && (Object)(object)TimeOfDay.Instance != (Object)null && Time.realtimeSinceStartup - sessionSince > 2f && (Object)(object)FindTerminal() != (Object)null)
			{
				ready = true;
				HostPrice = PurchasePolicy.Price(Plugin.Cost.Value);
				HasHostState = true;
				LoadForecast();
				SendState();
			}
			if (network.IsServer && ready)
			{
				HostPrice = PurchasePolicy.Price(Plugin.Cost.Value);
				if (lastPrice != HostPrice)
				{
					lastPrice = HostPrice;
					SendState();
				}
				UpdateLaunch();
			}
			else if (!HasHostState && Time.realtimeSinceStartup >= nextSync)
			{
				nextSync = Time.realtimeSinceStartup + 2f;
				FastBufferWriter val = default(FastBufferWriter);
				((FastBufferWriter)(ref val))..ctor(4, (Allocator)2, -1);
				try
				{
					byte b = 0;
					((FastBufferWriter)(ref val)).WriteValueSafe<byte>(ref b, default(ForPrimitives));
					network.CustomMessagingManager.SendNamedMessage("WeatherNeutralizer.Request.v1", 0uL, val, (NetworkDelivery)3);
				}
				finally
				{
					((IDisposable)(*(FastBufferWriter*)(&val))/*cast due to .constrained prefix*/).Dispose();
				}
			}
		}

		private void Bind(NetworkManager value)
		{
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0029: Expected O, but got Unknown
			//IL_003b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0045: Expected O, but got Unknown
			//IL_0057: Unknown result type (might be due to invalid IL or missing references)
			//IL_0061: Expected O, but got Unknown
			Unbind();
			network = value;
			value.CustomMessagingManager.RegisterNamedMessageHandler("WeatherNeutralizer.Request.v1", new HandleNamedMessageDelegate(ReceiveRequest));
			value.CustomMessagingManager.RegisterNamedMessageHandler("WeatherNeutralizer.State.v1", new HandleNamedMessageDelegate(ReceiveState));
			value.CustomMessagingManager.RegisterNamedMessageHandler("WeatherNeutralizer.Reply.v1", new HandleNamedMessageDelegate(ReceiveReply));
			value.OnClientDisconnectCallback += Disconnected;
			nextSync = 0f;
		}

		private void Unbind()
		{
			if (!((Object)(object)network == (Object)null))
			{
				network.OnClientDisconnectCallback -= Disconnected;
				if (network.CustomMessagingManager != null)
				{
					network.CustomMessagingManager.UnregisterNamedMessageHandler("WeatherNeutralizer.Request.v1");
					network.CustomMessagingManager.UnregisterNamedMessageHandler("WeatherNeutralizer.State.v1");
					network.CustomMessagingManager.UnregisterNamedMessageHandler("WeatherNeutralizer.Reply.v1");
				}
			}
		}

		private void Disconnected(ulong client)
		{
			lastRequests.Remove(client);
		}

		private void OnDestroy()
		{
			Unbind();
		}

		private void ResetSession()
		{
			ready = false;
			HasHostState = false;
			session = null;
			launch = null;
			cleared.Clear();
			lastRequests.Clear();
			playedSequence = -1;
			lastPrice = -1;
			LaunchEffects.Cancel();
		}

		private static Terminal? FindTerminal()
		{
			return Object.FindObjectOfType<Terminal>();
		}

		internal unsafe void RequestPurchase(int quote, int level, string moon)
		{
			//IL_0079: Unknown result type (might be due to invalid IL or missing references)
			//IL_007f: Unknown result type (might be due to invalid IL or missing references)
			//IL_008c: 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_009f: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b2: 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_00da: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)network == (Object)null || !network.IsListening || !HasHostState)
			{
				TerminalIntegration.Report(PurchasePolicy.Message(PurchaseResult.NotReady));
				return;
			}
			int request = ++requestNumber;
			if (network.IsServer)
			{
				Purchase(network.LocalClientId, request, quote, level, moon);
				return;
			}
			FastBufferWriter val = default(FastBufferWriter);
			((FastBufferWriter)(ref val))..ctor(512, (Allocator)2, -1);
			try
			{
				byte b = 1;
				((FastBufferWriter)(ref val)).WriteValueSafe<byte>(ref b, default(ForPrimitives));
				((FastBufferWriter)(ref val)).WriteValueSafe<int>(ref request, default(ForPrimitives));
				((FastBufferWriter)(ref val)).WriteValueSafe<int>(ref quote, default(ForPrimitives));
				((FastBufferWriter)(ref val)).WriteValueSafe<int>(ref level, default(ForPrimitives));
				((FastBufferWriter)(ref val)).WriteValueSafe(moon, false);
				network.CustomMessagingManager.SendNamedMessage("WeatherNeutralizer.Request.v1", 0uL, val, (NetworkDelivery)3);
			}
			finally
			{
				((IDisposable)(*(FastBufferWriter*)(&val))/*cast due to .constrained prefix*/).Dispose();
			}
		}

		private void ReceiveRequest(ulong sender, FastBufferReader reader)
		{
			//IL_0031: Unknown result type (might be due to invalid IL or missing references)
			//IL_0037: Unknown result type (might be due to invalid IL or missing references)
			//IL_0063: Unknown result type (might be due to invalid IL or missing references)
			//IL_0069: Unknown result type (might be due to invalid IL or missing references)
			//IL_0076: 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)
			//IL_0089: Unknown result type (might be due to invalid IL or missing references)
			//IL_008f: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)network == (Object)null || !network.IsServer || ((FastBufferReader)(ref reader)).Length > 512)
			{
				return;
			}
			try
			{
				byte b = default(byte);
				((FastBufferReader)(ref reader)).ReadValueSafe<byte>(ref b, default(ForPrimitives));
				switch (b)
				{
				case 0:
					if (ready)
					{
						SendState(sender);
					}
					break;
				case 1:
				{
					int request = default(int);
					((FastBufferReader)(ref reader)).ReadValueSafe<int>(ref request, default(ForPrimitives));
					int quote = default(int);
					((FastBufferReader)(ref reader)).ReadValueSafe<int>(ref quote, default(ForPrimitives));
					int levelId = default(int);
					((FastBufferReader)(ref reader)).ReadValueSafe<int>(ref levelId, default(ForPrimitives));
					string moon = default(string);
					((FastBufferReader)(ref reader)).ReadValueSafe(ref moon, false);
					Purchase(sender, request, quote, levelId, moon);
					break;
				}
				}
			}
			catch (Exception ex)
			{
				Plugin.Log.LogWarning((object)("Ignored malformed purchase request: " + ex.Message));
			}
		}

		private void Purchase(ulong sender, int request, int quote, int levelId, string moon)
		{
			//IL_00c1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cc: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)network == (Object)null || !network.IsServer || (lastRequests.TryGetValue(sender, out var value) && request <= value))
			{
				return;
			}
			lastRequests[sender] = request;
			Terminal val = FindTerminal();
			StartOfRound instance = StartOfRound.Instance;
			PlayerControllerB val2 = null;
			if ((Object)(object)instance != (Object)null)
			{
				PlayerControllerB[] allPlayerScripts = instance.allPlayerScripts;
				foreach (PlayerControllerB val3 in allPlayerScripts)
				{
					if ((Object)(object)val3 != (Object)null && val3.actualClientId == sender && val3.isPlayerControlled)
					{
						val2 = val3;
						break;
					}
				}
			}
			bool validBuyer = (Object)(object)val2 != (Object)null && !val2.isPlayerDead && val2.isInHangarShipRoom && (Object)(object)val != (Object)null && Vector3.Distance(((Component)val2).transform.position, ((Component)val).transform.position) < 6f;
			SelectableLevel val4 = (((Object)(object)instance == (Object)null) ? null : instance.currentLevel);
			bool travelling = (Object)(object)instance == (Object)null || instance.travellingToNewLevel || instance.shipIsLeaving || instance.beganLoadingNewLevel || (!instance.inShipPhase && !instance.shipHasLanded);
			int num = PurchasePolicy.Price(Plugin.Cost.Value);
			PurchaseResult purchaseResult = PurchasePolicy.Validate(ready && (Object)(object)val != (Object)null && (Object)(object)val4 != (Object)null, Busy, validBuyer, travelling, (Object)(object)val4 != (Object)null && val4.levelID == levelId && val4.PlanetName == moon, (Object)(object)val4 != (Object)null && val4.spawnEnemiesAndScrap && val4.planetHasTime, (Object)(object)val4 != (Object)null && WeatherControl.Supported(val4), (Object)(object)val4 != (Object)null && WeatherControl.IsMild(val4), quote, num, (!((Object)(object)val == (Object)null)) ? val.groupCredits : 0);
			if (purchaseResult != PurchaseResult.Accepted)
			{
				Reply(sender, request, purchaseResult);
				return;
			}
			launch = new Launch
			{
				Level = val4,
				Buyer = sender,
				Request = request,
				Paid = num,
				Started = Now,
				FromOrbit = instance.inShipPhase
			};
			val.groupCredits -= num;
			val.SyncGroupCreditsClientRpc(val.groupCredits, val.numberOfItemsInDropship);
			sequence++;
			Reply(sender, request, PurchaseResult.Accepted);
			PlayLaunch(sequence, 0.0);
			SendState();
			Plugin.Log.LogInfo((object)("Purchased one launch for " + num + " credits targeting " + moon + "."));
		}

		private void UpdateLaunch()
		{
			Launch launch = this.launch;
			if (launch == null || (Object)(object)session == (Object)null)
			{
				return;
			}
			if ((Object)(object)session.currentLevel != (Object)(object)launch.Level || session.travellingToNewLevel || session.shipIsLeaving || (!launch.FromOrbit && session.inShipPhase))
			{
				CancelLaunch(launch);
			}
			else if (!(Now - launch.Started < 4.6))
			{
				try
				{
					WeatherControl.Clear(launch.Level, clearActiveEffects: true);
					cleared.Add(Key(launch.Level));
					this.launch = null;
					Reply(launch.Buyer, launch.Request, PurchaseResult.Complete);
					SendState();
					NotifyClear();
				}
				catch (Exception ex)
				{
					Plugin.Log.LogError((object)("Weather neutralization failed: " + ex));
					CancelLaunch(launch);
				}
			}
		}

		private void CancelLaunch(Launch active)
		{
			if (launch == active)
			{
				launch = null;
				Terminal val = FindTerminal();
				if ((Object)(object)val != (Object)null)
				{
					val.groupCredits += active.Paid;
					val.SyncGroupCreditsClientRpc(val.groupCredits, val.numberOfItemsInDropship);
				}
				LaunchEffects.Cancel();
				Reply(active.Buyer, active.Request, PurchaseResult.Cancelled);
				SendState();
			}
		}

		private unsafe void Reply(ulong client, int request, PurchaseResult result)
		{
			//IL_008e: 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)
			//IL_00a2: 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_00b7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bd: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cf: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e6: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)network == (Object)null)
			{
				return;
			}
			int num = FindTerminal()?.groupCredits ?? 0;
			HostPrice = PurchasePolicy.Price(Plugin.Cost.Value);
			if (client == network.LocalClientId)
			{
				if (request == requestNumber)
				{
					TerminalIntegration.Report(PurchasePolicy.Message(result) + "\nGroup credits: $" + num);
				}
			}
			else if (network.ConnectedClients.ContainsKey(client))
			{
				FastBufferWriter val = default(FastBufferWriter);
				((FastBufferWriter)(ref val))..ctor(24, (Allocator)2, -1);
				try
				{
					((FastBufferWriter)(ref val)).WriteValueSafe<int>(ref request, default(ForPrimitives));
					byte b = (byte)result;
					((FastBufferWriter)(ref val)).WriteValueSafe<byte>(ref b, default(ForPrimitives));
					((FastBufferWriter)(ref val)).WriteValueSafe<int>(ref HostPrice, default(ForPrimitives));
					((FastBufferWriter)(ref val)).WriteValueSafe<int>(ref num, default(ForPrimitives));
					network.CustomMessagingManager.SendNamedMessage("WeatherNeutralizer.Reply.v1", client, val, (NetworkDelivery)3);
				}
				finally
				{
					((IDisposable)(*(FastBufferWriter*)(&val))/*cast due to .constrained prefix*/).Dispose();
				}
			}
		}

		private void ReceiveReply(ulong sender, FastBufferReader reader)
		{
			//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)
			//IL_0038: Unknown result type (might be due to invalid IL or missing references)
			//IL_003e: Unknown result type (might be due to invalid IL or missing references)
			//IL_004b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0051: Unknown result type (might be due to invalid IL or missing references)
			//IL_005e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0064: Unknown result type (might be due to invalid IL or missing references)
			if (sender == 0L && !((Object)(object)network == (Object)null) && !network.IsServer)
			{
				int num = default(int);
				((FastBufferReader)(ref reader)).ReadValueSafe<int>(ref num, default(ForPrimitives));
				byte result = default(byte);
				((FastBufferReader)(ref reader)).ReadValueSafe<byte>(ref result, default(ForPrimitives));
				int hostPrice = default(int);
				((FastBufferReader)(ref reader)).ReadValueSafe<int>(ref hostPrice, default(ForPrimitives));
				int num2 = default(int);
				((FastBufferReader)(ref reader)).ReadValueSafe<int>(ref num2, default(ForPrimitives));
				HostPrice = hostPrice;
				if (num == requestNumber)
				{
					TerminalIntegration.Report(PurchasePolicy.Message((PurchaseResult)result) + "\nGroup credits: $" + num2);
				}
			}
		}

		private unsafe void SendState(ulong? target = null)
		{
			//IL_003c: 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_005e: 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_007a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0080: 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_00ae: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cc: Unknown result type (might be due to invalid IL or missing references)
			//IL_0146: Unknown result type (might be due to invalid IL or missing references)
			//IL_012d: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)network == (Object)null || !network.IsServer || !ready)
			{
				return;
			}
			FastBufferWriter val = default(FastBufferWriter);
			((FastBufferWriter)(ref val))..ctor(16384, (Allocator)2, -1);
			try
			{
				((FastBufferWriter)(ref val)).WriteValueSafe<int>(ref sequence, default(ForPrimitives));
				int num = PurchasePolicy.Price(Plugin.Cost.Value);
				((FastBufferWriter)(ref val)).WriteValueSafe<int>(ref num, default(ForPrimitives));
				bool flag = launch != null;
				((FastBufferWriter)(ref val)).WriteValueSafe<bool>(ref flag, default(ForPrimitives));
				double num2 = launch?.Started ?? 0.0;
				((FastBufferWriter)(ref val)).WriteValueSafe<double>(ref num2, default(ForPrimitives));
				num = cleared.Count;
				((FastBufferWriter)(ref val)).WriteValueSafe<int>(ref num, default(ForPrimitives));
				foreach (string item in cleared)
				{
					((FastBufferWriter)(ref val)).WriteValueSafe(item, false);
				}
				if (target.HasValue)
				{
					network.CustomMessagingManager.SendNamedMessage("WeatherNeutralizer.State.v1", target.Value, val, (NetworkDelivery)4);
				}
				else
				{
					network.CustomMessagingManager.SendNamedMessageToAll("WeatherNeutralizer.State.v1", val, (NetworkDelivery)4);
				}
			}
			finally
			{
				((IDisposable)(*(FastBufferWriter*)(&val))/*cast due to .constrained prefix*/).Dispose();
			}
		}

		private void ReceiveState(ulong sender, FastBufferReader reader)
		{
			//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)
			//IL_0038: Unknown result type (might be due to invalid IL or missing references)
			//IL_003e: Unknown result type (might be due to invalid IL or missing references)
			//IL_004b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0051: Unknown result type (might be due to invalid IL or missing references)
			//IL_005e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0064: Unknown result type (might be due to invalid IL or missing references)
			//IL_0071: Unknown result type (might be due to invalid IL or missing references)
			//IL_0077: Unknown result type (might be due to invalid IL or missing references)
			if (sender != 0L || (Object)(object)network == (Object)null || network.IsServer)
			{
				return;
			}
			int num = default(int);
			((FastBufferReader)(ref reader)).ReadValueSafe<int>(ref num, default(ForPrimitives));
			int hostPrice = default(int);
			((FastBufferReader)(ref reader)).ReadValueSafe<int>(ref hostPrice, default(ForPrimitives));
			bool flag = default(bool);
			((FastBufferReader)(ref reader)).ReadValueSafe<bool>(ref flag, default(ForPrimitives));
			double num2 = default(double);
			((FastBufferReader)(ref reader)).ReadValueSafe<double>(ref num2, default(ForPrimitives));
			int num3 = default(int);
			((FastBufferReader)(ref reader)).ReadValueSafe<int>(ref num3, default(ForPrimitives));
			if (num3 < 0 || num3 > 512)
			{
				return;
			}
			HashSet<string> hashSet = new HashSet<string>(StringComparer.Ordinal);
			string item = default(string);
			for (int i = 0; i < num3; i++)
			{
				((FastBufferReader)(ref reader)).ReadValueSafe(ref item, false);
				hashSet.Add(item);
			}
			bool flag2 = false;
			foreach (string item2 in hashSet)
			{
				if (!cleared.Contains(item2))
				{
					flag2 = true;
				}
			}
			cleared.Clear();
			foreach (string item3 in hashSet)
			{
				cleared.Add(item3);
			}
			HostPrice = hostPrice;
			HasHostState = true;
			ApplyForecasts();
			if (flag)
			{
				PlayLaunch(num, Math.Max(0.0, Now - num2));
			}
			else if (!flag2)
			{
				LaunchEffects.Cancel();
			}
			if (flag2 && num == playedSequence)
			{
				NotifyClear();
			}
		}

		private void PlayLaunch(int id, double elapsed)
		{
			if (id != playedSequence && !(elapsed >= 4.6))
			{
				playedSequence = id;
				LaunchEffects.Play((MonoBehaviour)(object)this, elapsed);
			}
		}

		private static void NotifyClear()
		{
			if ((Object)(object)HUDManager.Instance != (Object)null)
			{
				HUDManager.Instance.DisplayTip("Weather Neutralizer", "Launch complete. Current moon weather: MILD.", false, false, "LC_Tip1");
			}
		}

		private void ApplyForecasts()
		{
			if ((Object)(object)StartOfRound.Instance == (Object)null)
			{
				return;
			}
			SelectableLevel[] levels = StartOfRound.Instance.levels;
			foreach (SelectableLevel val in levels)
			{
				if ((Object)(object)val != (Object)null && cleared.Contains(Key(val)))
				{
					WeatherControl.Clear(val, clearActiveEffects: true);
				}
			}
		}

		internal void OnWeatherRoll()
		{
			if (ready && !((Object)(object)network == (Object)null) && network.IsServer)
			{
				if (launch != null)
				{
					CancelLaunch(launch);
				}
				cleared.Clear();
				SendState();
			}
		}

		internal void SaveForecast()
		{
			if (!ready || (Object)(object)network == (Object)null || !network.IsServer || (Object)(object)session == (Object)null || !session.inShipPhase || (Object)(object)GameNetworkManager.Instance == (Object)null)
			{
				return;
			}
			try
			{
				List<string> list = new List<string> { session.randomMapSeed.ToString(CultureInfo.InvariantCulture) };
				list.AddRange(cleared);
				ES3.Save<string[]>("WeatherNeutralizer.Forecasts.v1", list.ToArray(), GameNetworkManager.Instance.currentSaveFileName);
			}
			catch (Exception ex)
			{
				Plugin.Log.LogWarning((object)("Could not save neutralized forecasts: " + ex.Message));
			}
		}

		private void LoadForecast()
		{
			if ((Object)(object)session == (Object)null || (Object)(object)GameNetworkManager.Instance == (Object)null)
			{
				return;
			}
			try
			{
				string[] array = ES3.Load<string[]>("WeatherNeutralizer.Forecasts.v1", GameNetworkManager.Instance.currentSaveFileName, Array.Empty<string>());
				if (array.Length != 0 && !(array[0] != session.randomMapSeed.ToString(CultureInfo.InvariantCulture)))
				{
					for (int i = 1; i < array.Length; i++)
					{
						cleared.Add(array[i]);
					}
					ApplyForecasts();
				}
			}
			catch (Exception ex)
			{
				Plugin.Log.LogWarning((object)("Could not restore neutralized forecasts: " + ex.Message));
			}
		}
	}
	[BepInPlugin("sockpoop.weatherneutralizer", "Weather Neutralizer", "1.1.0")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	public sealed class Plugin : BaseUnityPlugin
	{
		public const string Guid = "sockpoop.weatherneutralizer";

		public const string Name = "Weather Neutralizer";

		public const string Version = "1.1.0";

		internal static ConfigEntry<int> Cost;

		internal static ConfigEntry<float> EffectVolume;

		internal static ConfigEntry<bool> CameraShake;

		internal static ManualLogSource Log;

		private Harmony? harmony;

		private void Awake()
		{
			//IL_0035: Unknown result type (might be due to invalid IL or missing references)
			//IL_003f: Expected O, but got Unknown
			//IL_0072: Unknown result type (might be due to invalid IL or missing references)
			//IL_007c: Expected O, but got Unknown
			//IL_00b3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bd: Expected O, but got Unknown
			Log = ((BaseUnityPlugin)this).Logger;
			Cost = ((BaseUnityPlugin)this).Config.Bind<int>("General", "Cost", 400, new ConfigDescription("Credits per single-use launch. The host's price applies to everyone. No inventory item is delivered.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 100000), Array.Empty<object>()));
			EffectVolume = ((BaseUnityPlugin)this).Config.Bind<float>("Audio", "EffectVolume", 0.7f, new ConfigDescription("Local playback volume for the charge-up and launch effects.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 1f), Array.Empty<object>()));
			CameraShake = ((BaseUnityPlugin)this).Config.Bind<bool>("Effects", "CameraShake", true, "Shake the local camera during charging and launch near the ship. Strongest inside or close to the ship; no shake inside the facility.");
			((Component)this).gameObject.AddComponent<NeutralizerRuntime>();
			harmony = new Harmony("sockpoop.weatherneutralizer");
			harmony.PatchAll(typeof(TerminalIntegration));
			harmony.PatchAll(typeof(WeatherLifecycle));
			Log.LogInfo((object)"Weather Neutralizer loaded. Terminal: weather neutralizer. Default cost: 400 credits per launch.");
		}

		private void OnDestroy()
		{
			Harmony? obj = harmony;
			if (obj != null)
			{
				obj.UnpatchSelf();
			}
		}
	}
	internal enum PurchaseResult : byte
	{
		Accepted,
		NotReady,
		Busy,
		InvalidBuyer,
		Travelling,
		WrongMoon,
		PriceChanged,
		AlreadyMild,
		UnsupportedWeather,
		InsufficientCredits,
		Cancelled,
		Complete
	}
	internal static class PurchasePolicy
	{
		internal const double ChargeSeconds = 3.2;

		internal const double ClearSeconds = 4.6;

		internal static int Price(int configured)
		{
			return Math.Max(0, Math.Min(100000, configured));
		}

		internal static PurchaseResult Validate(bool ready, bool busy, bool validBuyer, bool travelling, bool sameMoon, bool playable, bool supportedWeather, bool alreadyMild, int quote, int cost, int credits)
		{
			if (!ready)
			{
				return PurchaseResult.NotReady;
			}
			if (busy)
			{
				return PurchaseResult.Busy;
			}
			if (!validBuyer)
			{
				return PurchaseResult.InvalidBuyer;
			}
			if (travelling)
			{
				return PurchaseResult.Travelling;
			}
			if (!sameMoon || !playable)
			{
				return PurchaseResult.WrongMoon;
			}
			if (quote != Price(cost))
			{
				return PurchaseResult.PriceChanged;
			}
			if (!supportedWeather)
			{
				return PurchaseResult.UnsupportedWeather;
			}
			if (alreadyMild)
			{
				return PurchaseResult.AlreadyMild;
			}
			if (credits < Price(cost))
			{
				return PurchaseResult.InsufficientCredits;
			}
			return PurchaseResult.Accepted;
		}

		internal static string Message(PurchaseResult result)
		{
			return result switch
			{
				PurchaseResult.Accepted => "Purchase accepted. Charging the ship launcher...", 
				PurchaseResult.NotReady => "Waiting for the host. Try again shortly.", 
				PurchaseResult.Busy => "A Weather Neutralizer launch is already in progress. No credits spent.", 
				PurchaseResult.InvalidBuyer => "Use the ship terminal while alive and inside the ship. No credits spent.", 
				PurchaseResult.Travelling => "Wait until routing, landing or takeoff has finished. No credits spent.", 
				PurchaseResult.WrongMoon => "The destination changed or cannot be neutralized. Request a new quote. No credits spent.", 
				PurchaseResult.PriceChanged => "The host's price changed. Request a new quote. No credits spent.", 
				PurchaseResult.AlreadyMild => "Weather is already mild. No launch needed; no credits spent.", 
				PurchaseResult.UnsupportedWeather => "This custom weather is not supported. No credits spent.", 
				PurchaseResult.InsufficientCredits => "Not enough group credits. No credits spent.", 
				PurchaseResult.Cancelled => "Launch cancelled because the destination or flight state changed. Credits refunded.", 
				PurchaseResult.Complete => "Launch complete. Weather neutralized: MILD.", 
				_ => "Weather Neutralizer is unavailable.", 
			};
		}
	}
	internal enum NeutralizerCommand
	{
		None,
		Purchase,
		Info
	}
	internal static class TerminalCommands
	{
		internal static string Normalize(string command)
		{
			return string.Join(" ", command.ToLowerInvariant().Replace('-', ' ').Replace('_', ' ')
				.Split((char[]?)null, StringSplitOptions.RemoveEmptyEntries));
		}

		internal static NeutralizerCommand Parse(string command)
		{
			string[] array = Normalize(command).Split(' ');
			int num = 0;
			NeutralizerCommand result = NeutralizerCommand.Purchase;
			if (array[0] == "buy")
			{
				num = 1;
			}
			else if (array[0] == "info" || array[0] == "inf")
			{
				num = 1;
				result = NeutralizerCommand.Info;
			}
			bool flag = false;
			if (array.Length - num == 1)
			{
				string text = array[num];
				flag = text == "wn" || Prefix(text, "weather") || Prefix(text, "neutralizer") || Prefix(text, "weatherneutralizer");
			}
			else if (array.Length - num == 2)
			{
				flag = Prefix(array[num], "weather") && Prefix(array[num + 1], "neutralizer");
			}
			if (!flag)
			{
				return NeutralizerCommand.None;
			}
			return result;
		}

		private static bool Prefix(string input, string full)
		{
			if (input.Length >= 3)
			{
				return full.StartsWith(input, StringComparison.Ordinal);
			}
			return false;
		}
	}
	[HarmonyPatch]
	internal static class TerminalIntegration
	{
		private static Terminal? terminal;

		private static TerminalNode? quoteNode;

		private static TerminalNode? pendingNode;

		private static int quotedPrice;

		private static int quotedLevel;

		private static string quotedMoon = string.Empty;

		private static string? reply;

		internal const string BuyEvent = "WeatherNeutralizer.Purchase";

		internal static TerminalNode Node(string name, string text, string terminalEvent = "")
		{
			TerminalNode obj = ScriptableObject.CreateInstance<TerminalNode>();
			((Object)obj).name = "WeatherNeutralizer." + name;
			obj.displayText = text + "\n\n";
			obj.clearPreviousText = true;
			obj.maxCharactersToType = 60;
			obj.terminalEvent = terminalEvent;
			return obj;
		}

		[HarmonyPatch(typeof(Terminal), "Awake")]
		[HarmonyPostfix]
		private static void Awake(Terminal __instance)
		{
			terminal = __instance;
			quoteNode = null;
			pendingNode = null;
			reply = null;
		}

		[HarmonyPatch(typeof(Terminal), "TextPostProcess")]
		[HarmonyPrefix]
		private static void Store(ref string modifiedDisplayText)
		{
			if (modifiedDisplayText.Contains("[buyableItemsList]"))
			{
				string text = (NeutralizerRuntime.HasHostState ? ("$" + NeutralizerRuntime.HostPrice) : "syncing with host");
				modifiedDisplayText = modifiedDisplayText + "\nWEATHER SERVICES\n* Weather Neutralizer // " + text + " per launch\n  Type WN, NEUT or WEATHER NEUTRALIZER to purchase.\n";
			}
		}

		[HarmonyPatch(typeof(Terminal), "ParsePlayerSentence")]
		[HarmonyPrefix]
		private static bool Parse(Terminal __instance, ref TerminalNode __result)
		{
			terminal = __instance;
			string text = __instance.screenText.text;
			int num = Math.Max(0, Math.Min(__instance.textAdded, text.Length));
			string text2 = TerminalCommands.Normalize(text.Substring(text.Length - num));
			if ((Object)(object)__instance.currentNode == (Object)(object)quoteNode && (Object)(object)quoteNode != (Object)null)
			{
				switch (text2)
				{
				case "confirm":
				case "c":
					pendingNode = Node("Pending", "Contacting ship launcher...", "WeatherNeutralizer.Purchase");
					__result = pendingNode;
					quoteNode = null;
					return false;
				case "deny":
				case "d":
				case "cancel":
					__result = Node("Cancelled", "Order cancelled. No credits spent.");
					quoteNode = null;
					return false;
				}
			}
			switch (TerminalCommands.Parse(text2))
			{
			case NeutralizerCommand.Info:
				__result = Node("Info", "WEATHER NEUTRALIZER\n\nA single-use launch from the ship clears the current moon to mild weather. Works in orbit or after landing. No inventory item is delivered.\n\nCharge-up, launch, then clear skies. Existing enemies are not removed.\n\nType WN, NEUT, WEA or WEATHER NEUTRALIZER to order.");
				return false;
			default:
				return true;
			case NeutralizerCommand.Purchase:
				if (!NeutralizerRuntime.HasHostState || (Object)(object)StartOfRound.Instance == (Object)null || (Object)(object)StartOfRound.Instance.currentLevel == (Object)null)
				{
					__result = Node("Unavailable", PurchasePolicy.Message(PurchaseResult.NotReady));
					return false;
				}
				quotedPrice = NeutralizerRuntime.HostPrice;
				quotedLevel = StartOfRound.Instance.currentLevel.levelID;
				quotedMoon = StartOfRound.Instance.currentLevel.PlanetName;
				quoteNode = Node("Confirm", "WEATHER NEUTRALIZER\n\nTarget: " + quotedMoon + "\nOne launch: $" + quotedPrice + "\nResult: MILD weather\n\nThe ship charges and launches immediately after purchase.\n\nCONFIRM or DENY.");
				__result = quoteNode;
				return false;
			}
		}

		[HarmonyPatch(typeof(Terminal), "RunTerminalEvents")]
		[HarmonyPostfix]
		private static void Events(TerminalNode node)
		{
			if (node.terminalEvent == "WeatherNeutralizer.Purchase")
			{
				NeutralizerRuntime.Instance.RequestPurchase(quotedPrice, quotedLevel, quotedMoon);
			}
		}

		internal static void Report(string text)
		{
			reply = text;
		}

		internal static void FlushReply()
		{
			if (reply != null)
			{
				string text = reply;
				reply = null;
				if ((Object)(object)terminal != (Object)null && (Object)(object)terminal.currentNode != (Object)null && ((Object)terminal.currentNode).name.StartsWith("WeatherNeutralizer.", StringComparison.Ordinal))
				{
					terminal.LoadNewNode(Node("Result", text));
				}
				else if ((Object)(object)HUDManager.Instance != (Object)null)
				{
					HUDManager.Instance.DisplayTip("Weather Neutralizer", text, false, false, "LC_Tip1");
				}
			}
		}
	}
	internal static class WeatherControl
	{
		internal static bool Supported(SelectableLevel level)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Invalid comparison between Unknown and I4
			//IL_000a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0010: Invalid comparison between Unknown and I4
			if ((int)level.currentWeather >= -1 && (int)level.currentWeather <= 5)
			{
				return !HasCustomExtendedWeather(level);
			}
			return false;
		}

		internal static bool IsMild(SelectableLevel level)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Invalid comparison between Unknown and I4
			if ((int)level.currentWeather == -1)
			{
				return !HasCustomExtendedWeather(level);
			}
			return false;
		}

		private static object? ExtendedLevel(SelectableLevel level)
		{
			Type type = AccessTools.TypeByName("LethalLevelLoader.PatchedContent");
			if (type == null)
			{
				return null;
			}
			if (!(type.GetProperty("ExtendedLevels", BindingFlags.Static | BindingFlags.Public)?.GetValue(null) is IEnumerable enumerable))
			{
				return null;
			}
			foreach (object item in enumerable)
			{
				if (item.GetType().GetProperty("SelectableLevel")?.GetValue(item) == level)
				{
					return item;
				}
			}
			return null;
		}

		private static bool HasCustomExtendedWeather(SelectableLevel level)
		{
			object obj = ExtendedLevel(level);
			object obj2 = obj?.GetType().GetProperty("CurrentExtendedWeatherEffect")?.GetValue(obj);
			if (obj2 != null)
			{
				Object val = (Object)((obj2 is Object) ? obj2 : null);
				if (val == null || !(val == (Object)null))
				{
					object obj3 = obj2.GetType().GetProperty("ContentType")?.GetValue(obj2);
					if (obj3 != null)
					{
						return !string.Equals(obj3.ToString(), "Vanilla", StringComparison.Ordinal);
					}
					return false;
				}
			}
			return false;
		}

		internal unsafe static void Clear(SelectableLevel level, bool clearActiveEffects)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_0009: Unknown result type (might be due to invalid IL or missing references)
			//IL_0069: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fb: Invalid comparison between Unknown and I4
			//IL_01d2: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d4: Invalid comparison between Unknown and I4
			//IL_021d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0224: Expected O, but got Unknown
			//IL_0160: Unknown result type (might be due to invalid IL or missing references)
			//IL_0167: Expected O, but got Unknown
			LevelWeatherType currentWeather = level.currentWeather;
			level.currentWeather = (LevelWeatherType)(-1);
			object obj = ExtendedLevel(level);
			obj?.GetType().GetProperty("CurrentExtendedWeatherEffect")?.SetValue(obj, null);
			TimeOfDay instance = TimeOfDay.Instance;
			if (!clearActiveEffects || (Object)(object)instance == (Object)null || (Object)(object)StartOfRound.Instance == (Object)null || (Object)(object)StartOfRound.Instance.currentLevel != (Object)(object)level)
			{
				return;
			}
			instance.currentLevelWeather = (LevelWeatherType)(-1);
			if (instance.effects != null)
			{
				WeatherEffect[] effects = instance.effects;
				foreach (WeatherEffect val in effects)
				{
					if (val != null)
					{
						val.effectEnabled = false;
						val.transitioning = false;
						if ((Object)(object)instance.sunAnimator != (Object)null && !string.IsNullOrEmpty(val.sunAnimatorBool))
						{
							instance.sunAnimator.SetBool(val.sunAnimatorBool, false);
						}
						DisableEffect(val.effectObject);
						DisableEffect(val.effectPermanentObject);
					}
				}
			}
			RoundManager instance2 = RoundManager.Instance;
			if ((int)currentWeather == 1 && (Object)(object)instance2 != (Object)null && (Object)(object)instance2.quicksandPrefab != (Object)null && (Object)(object)instance2.mapPropsContainer != (Object)null)
			{
				string text = ((Object)instance2.quicksandPrefab).name + "(Clone)";
				foreach (Transform item in instance2.mapPropsContainer.transform)
				{
					Transform val2 = item;
					if (!(((Object)val2).name != text))
					{
						ReleasePlayers(((Component)val2).gameObject);
						((Component)val2).gameObject.SetActive(false);
						Object.Destroy((Object)(object)((Component)val2).gameObject);
					}
				}
			}
			instance.currentWeatherVariable = 0f;
			instance.currentWeatherVariable2 = 0f;
			if ((int)currentWeather == 4 && (Object)(object)instance.FloodWeatherNavArea != (Object)null)
			{
				GameObject val3 = GameObject.FindGameObjectWithTag("OutsideLevelNavMesh");
				if ((Object)(object)val3 != (Object)null)
				{
					bool flag = false;
					foreach (Transform item2 in val3.transform)
					{
						Transform val4 = item2;
						if (!(((Object)val4).name != ((Object)instance.FloodWeatherNavArea).name + "(Clone)"))
						{
							((Component)val4).gameObject.SetActive(false);
							Object.Destroy((Object)(object)((Component)val4).gameObject);
							flag = true;
						}
					}
					if (flag)
					{
						((MonoBehaviour)NeutralizerRuntime.Instance).StartCoroutine(RebuildNavigation(val3));
					}
				}
			}
			if ((Object)(object)instance.sunAnimator != (Object)null)
			{
				instance.sunAnimator.Update(0f);
			}
			Plugin.Log.LogInfo((object)("Cleared " + level.PlanetName + " from " + ((object)(*(LevelWeatherType*)(&currentWeather))/*cast due to .constrained prefix*/).ToString() + " to MILD."));
		}

		private static void DisableEffect(GameObject effect)
		{
			if (!((Object)(object)effect == (Object)null))
			{
				ReleasePlayers(effect);
				StormyWeather[] componentsInChildren = effect.GetComponentsInChildren<StormyWeather>(true);
				for (int i = 0; i < componentsInChildren.Length; i++)
				{
					((MonoBehaviour)componentsInChildren[i]).StopAllCoroutines();
				}
				effect.SetActive(false);
			}
		}

		private static void ReleasePlayers(GameObject effect)
		{
			PlayerControllerB val = GameNetworkManager.Instance?.localPlayerController;
			if ((Object)(object)val == (Object)null)
			{
				return;
			}
			QuicksandTrigger[] componentsInChildren = effect.GetComponentsInChildren<QuicksandTrigger>(true);
			foreach (QuicksandTrigger obj in componentsInChildren)
			{
				obj.StopSinkingLocalPlayer(val);
				Collider component = ((Component)obj).GetComponent<Collider>();
				if ((Object)(object)component != (Object)null && (Object)(object)val.underwaterCollider == (Object)(object)component)
				{
					val.isUnderwater = false;
					val.underwaterCollider = null;
				}
			}
		}

		private static IEnumerator RebuildNavigation(GameObject nav)
		{
			yield return null;
			if ((Object)(object)nav == (Object)null)
			{
				yield break;
			}
			MonoBehaviour[] components = nav.GetComponents<MonoBehaviour>();
			foreach (MonoBehaviour val in components)
			{
				if ((Object)(object)val != (Object)null && ((object)val).GetType().Name == "NavMeshSurface")
				{
					((object)val).GetType().GetMethod("BuildNavMesh", Type.EmptyTypes)?.Invoke(val, null);
				}
			}
		}
	}
	[HarmonyPatch]
	internal static class WeatherLifecycle
	{
		[HarmonyPatch(typeof(StartOfRound), "SetPlanetsWeather")]
		[HarmonyPostfix]
		[HarmonyPriority(0)]
		private static void WeatherRoll()
		{
			NeutralizerRuntime.Instance?.OnWeatherRoll();
		}

		[HarmonyPatch(typeof(GameNetworkManager), "SaveGameValues")]
		[HarmonyPostfix]
		private static void Save()
		{
			NeutralizerRuntime.Instance?.SaveForecast();
		}
	}
}