Decompiled source of SignalInterference v1.0.1

SignalInterference.dll

Decompiled 5 hours 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 System.Text;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using GameNetcodeStuff;
using HarmonyLib;
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("SignalInterference")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.1.0")]
[assembly: AssemblyInformationalVersion("1.0.1")]
[assembly: AssemblyProduct("SignalInterference")]
[assembly: AssemblyTitle("SignalInterference")]
[assembly: AssemblyMetadata("AI_Assisted_Creation", "Code generated with Anthropic Claude (Claude Opus 5.5 and other Claude models, via Claude Code); designed and tested by the author")]
[assembly: AssemblyMetadata("AI_Model_Vendor", "Anthropic")]
[assembly: AssemblyVersion("1.0.1.0")]
namespace SignalInterference;

public static class Radio
{
	public const int ApiVersion = 1;

	public static bool Active => S.Active;

	public static int Severity
	{
		get
		{
			if (!S.Active)
			{
				return 0;
			}
			return S.Severity;
		}
	}

	public static int Serial => S.Serial;

	public static bool HeldWalkiesOnly
	{
		get
		{
			if (S.Active)
			{
				return S.Has(1024);
			}
			return false;
		}
	}

	public static bool Attach(AudioSource src)
	{
		try
		{
			if (!Plugin.Enabled.Value || (Object)(object)src == (Object)null)
			{
				return false;
			}
			if (S.IsHost)
			{
				Director.MarkRadioLine();
			}
			return Voice.AttachSource(src, null);
		}
		catch (Exception e)
		{
			Runner.Error("Radio.Attach", e);
			return false;
		}
	}

	public static void Detach(AudioSource src)
	{
		try
		{
			if (!((Object)(object)src == (Object)null))
			{
				InterferenceFilter component = ((Component)src).GetComponent<InterferenceFilter>();
				if ((Object)(object)component != (Object)null)
				{
					component.SetOn(on: false);
				}
			}
		}
		catch
		{
		}
	}
}
public static class InterferenceState
{
	public static bool Active;

	public static int Severity;

	public static bool Revealed;

	public static string Weather = "";

	public static int ChancePercent;

	public static string ShortLine;

	public static string OrbitLine;
}
public static class Debug
{
	public const int ApiVersion = 1;

	public static bool Available
	{
		get
		{
			if (S.IsHost)
			{
				return Plugin.Enabled != null;
			}
			return false;
		}
	}

	public static bool Force(int severity)
	{
		if (!Available)
		{
			return false;
		}
		try
		{
			return Director.Force(severity);
		}
		catch (Exception ex)
		{
			Plugin.Log.LogWarning((object)("Force failed: " + ex.Message));
			return false;
		}
	}

	public static bool Stop()
	{
		if (!Available)
		{
			return false;
		}
		try
		{
			return Director.StopNow();
		}
		catch (Exception ex)
		{
			Plugin.Log.LogWarning((object)("Stop failed: " + ex.Message));
			return false;
		}
	}

	public static bool Burst(string kind)
	{
		if (!Available)
		{
			return false;
		}
		try
		{
			int num = Bursts.Parse(kind);
			if (num == 0)
			{
				return false;
			}
			StartOfRound instance = StartOfRound.Instance;
			if ((Object)(object)instance == (Object)null || instance.inShipPhase)
			{
				return false;
			}
			if ((num == 6 || num == 7) && !S.Active)
			{
				return false;
			}
			Director.FireBurst(num, num switch
			{
				4 => 0.6f, 
				3 => Director.U(2f, 6f), 
				1 => Director.U(0.8f, 3f), 
				_ => 0f, 
			}, num switch
			{
				1 => (Random.value < 0.5f) ? 1 : 0, 
				2 => 2, 
				_ => 1, 
			});
			return true;
		}
		catch (Exception ex)
		{
			Plugin.Log.LogWarning((object)("Burst failed: " + ex.Message));
			return false;
		}
	}

	public static bool FailNextCode()
	{
		if (!Available)
		{
			return false;
		}
		S.FailNext = true;
		Net.BroadcastState();
		return true;
	}

	public static string[] TodayState()
	{
		if (!Available)
		{
			return new string[0];
		}
		try
		{
			return Director.TodayState();
		}
		catch (Exception ex)
		{
			return new string[1] { "Error: " + ex.Message };
		}
	}
}
internal static class Effects
{
	internal static readonly Random LocalRng = new Random();

	private static float _nextCrackle = -1f;

	private static float _nextScan;

	private static float _nextFlarePoll;

	private static float _lastLightning = -99f;

	private static int _lastVoiceEvents;

	internal static bool FlareMode;

	internal static float U(float a, float b)
	{
		return a + (float)LocalRng.NextDouble() * (b - a);
	}

	internal static void OnStateChanged(bool wasActive)
	{
		PushParams();
		float realtimeSinceStartup = Time.realtimeSinceStartup;
		if (S.Active && !wasActive)
		{
			Reveal.NewDay();
			ScheduleCrackle(realtimeSinceStartup);
			_nextScan = 0f;
			Voice.Recheck();
			Voice.ScanWalkies();
		}
		else if (!S.Active && wasActive)
		{
			StopAll();
		}
		DayInfo.Refresh();
	}

	internal static void StopAll()
	{
		_nextCrackle = -1f;
		try
		{
			Walkies.StopAll();
		}
		catch
		{
		}
		try
		{
			Radar.Clear();
		}
		catch
		{
		}
		try
		{
			Flashlights.RestoreAll();
		}
		catch
		{
		}
		try
		{
			Voice.AllOff();
		}
		catch
		{
		}
	}

	internal static void PushParams()
	{
		float factor = S.Factor;
		int num;
		float hiss;
		if (S.Active)
		{
			num = (S.Has(1) ? 1 : 0);
			if (num != 0)
			{
				hiss = S.R.Hiss * factor;
				goto IL_002c;
			}
		}
		else
		{
			num = 0;
		}
		hiss = 0f;
		goto IL_002c;
		IL_002c:
		RadioDsp.Hiss = hiss;
		RadioDsp.DropPerSec = ((num != 0) ? (S.R.DropRate / 10f * factor) : 0f);
		RadioDsp.DropMin = S.R.DropMin;
		RadioDsp.DropMax = S.R.DropMax;
		RadioDsp.GarbPerSec = ((num != 0) ? (S.R.GarbRate / 10f * factor) : 0f);
		RadioDsp.GarbMin = S.R.GarbMin;
		RadioDsp.GarbMax = S.R.GarbMax;
		RadioDsp.VoiceEffects = (byte)num != 0;
	}

	private static void ScheduleCrackle(float now)
	{
		if (!S.Active || !S.Has(8) || S.R.CrackMax <= 0f)
		{
			_nextCrackle = -1f;
		}
		else
		{
			_nextCrackle = now + U(S.R.CrackMin, S.R.CrackMax) / Mathf.Max(0.01f, S.Factor);
		}
	}

	internal static void Tick(float now)
	{
		StartOfRound instance = StartOfRound.Instance;
		if (now >= _nextFlarePoll)
		{
			_nextFlarePoll = now + 2f;
			bool flag = (Object)(object)instance != (Object)null && !instance.inShipPhase && FlareLink.Active();
			if (flag != FlareMode)
			{
				FlareMode = flag;
				if (flag)
				{
					Plugin.Log.LogInfo((object)"Solar flare day: Mimic+ radio lines get LethalElements' radio distortion.");
				}
				else
				{
					Voice.ForgetFlareSources();
				}
			}
		}
		if (!S.Active)
		{
			if (FlareMode && now >= _nextScan)
			{
				_nextScan = now + 0.5f;
				Voice.ScanWalkies();
			}
			return;
		}
		if (_nextCrackle > 0f && now >= _nextCrackle)
		{
			if (Walkies.Crackle(0.2f, 1.2f, 0.3f, 0.7f) > 0)
			{
				Reveal.Symptom("walkie crackle");
			}
			ScheduleCrackle(now);
		}
		if (now >= _nextScan)
		{
			_nextScan = now + 0.5f;
			Voice.Recheck();
			Voice.ScanWalkies();
		}
		int voiceEventSerial = InterferenceFilter.VoiceEventSerial;
		if (voiceEventSerial != _lastVoiceEvents)
		{
			_lastVoiceEvents = voiceEventSerial;
			Reveal.Symptom("radio dropout or garble");
		}
	}

	internal static void OnLightning()
	{
		if (!S.Active || !S.Has(64))
		{
			return;
		}
		float realtimeSinceStartup = Time.realtimeSinceStartup;
		if (!(realtimeSinceStartup - _lastLightning < 2f))
		{
			_lastLightning = realtimeSinceStartup;
			InterferenceFilter.TriggerBurst(U(0.3f, 0.8f));
			int num = (S.Has(8) ? Walkies.Crackle(0.3f, 0.8f, 0.5f, 0.9f) : 0);
			bool flag = S.Has(32) && Radar.LocalFlash(U(0.3f, 0.8f));
			if (num > 0 || flag)
			{
				Reveal.Symptom("lightning");
			}
		}
	}
}
internal static class Bursts
{
	internal const int Ghost = 1;

	internal const int MapNoise = 2;

	internal const int MapFreeze = 3;

	internal const int Flicker = 4;

	internal const int Crackle = 5;

	internal const int Dropout = 6;

	internal const int Garble = 7;

	internal const int Lightning = 8;

	internal static void Run(int kind, int seed, float duration, int count)
	{
		try
		{
			switch (kind)
			{
			case 1:
				if (Walkies.StartGhost(seed, duration, count == 1))
				{
					Reveal.Symptom("ghost call");
				}
				break;
			case 2:
				if (Radar.Noise(seed, count))
				{
					Reveal.Symptom("map noise");
				}
				break;
			case 3:
				if (Radar.Freeze(duration))
				{
					Reveal.Symptom("map freeze");
				}
				break;
			case 4:
				if (Plugin.Flicker.Value && Flashlights.Flicker(duration) > 0)
				{
					Reveal.Symptom("flashlight flicker");
				}
				break;
			case 5:
				Walkies.Crackle(0.2f, 1.2f, 0.4f, 0.8f);
				break;
			case 6:
				InterferenceFilter.ForceVoiceEvent(1);
				break;
			case 7:
				InterferenceFilter.ForceVoiceEvent(2);
				break;
			case 8:
				InterferenceFilter.TriggerBurst(0.6f);
				Walkies.Crackle(0.3f, 0.8f, 0.5f, 0.9f);
				Radar.LocalFlash(0.6f);
				break;
			}
		}
		catch (Exception ex)
		{
			Plugin.Log.LogWarning((object)("Burst " + kind + " failed: " + ex.Message));
		}
	}

	internal static int Parse(string s)
	{
		return (s ?? "").Trim().ToLowerInvariant() switch
		{
			"ghost" => 1, 
			"mapnoise" => 2, 
			"mapfreeze" => 3, 
			"flicker" => 4, 
			"crackle" => 5, 
			"dropout" => 6, 
			"garble" => 7, 
			"lightning" => 8, 
			_ => 0, 
		};
	}
}
internal static class Voice
{
	private sealed class Entry
	{
		public InterferenceFilter F;

		public AudioHighPassFilter H;
	}

	private static readonly Dictionary<AudioSource, Entry> VoiceSources = new Dictionary<AudioSource, Entry>();

	private static readonly List<AudioSource> Dead = new List<AudioSource>();

	private static readonly List<AudioSource> Children = new List<AudioSource>(16);

	private static readonly HashSet<AudioSource> FlareAttached = new HashSet<AudioSource>();

	private static readonly HashSet<AudioSource> Muted = new HashSet<AudioSource>();

	private static bool _loggedComponents;

	internal static void Recheck()
	{
		StartOfRound instance = StartOfRound.Instance;
		if ((Object)(object)instance == (Object)null || instance.allPlayerScripts == null)
		{
			return;
		}
		bool flag = S.Active && S.Has(1);
		PlayerControllerB[] allPlayerScripts = instance.allPlayerScripts;
		foreach (PlayerControllerB val in allPlayerScripts)
		{
			if ((Object)(object)val == (Object)null)
			{
				continue;
			}
			AudioSource currentVoiceChatAudioSource = val.currentVoiceChatAudioSource;
			if ((Object)(object)currentVoiceChatAudioSource == (Object)null)
			{
				continue;
			}
			VoiceSources.TryGetValue(currentVoiceChatAudioSource, out var value);
			if (value == null)
			{
				if (!flag)
				{
					continue;
				}
				AudioHighPassFilter component = ((Component)currentVoiceChatAudioSource).GetComponent<AudioHighPassFilter>();
				if ((Object)(object)component == (Object)null || !((Behaviour)component).enabled)
				{
					continue;
				}
				value = new Entry
				{
					H = component,
					F = InterferenceFilter.GetOrAdd(currentVoiceChatAudioSource, 0)
				};
				VoiceSources[currentVoiceChatAudioSource] = value;
				LogComponentsOnce(currentVoiceChatAudioSource);
			}
			bool flag2 = flag && (Object)(object)value.H != (Object)null && ((Behaviour)value.H).enabled && !val.isPlayerDead;
			if ((Object)(object)value.F != (Object)null)
			{
				bool flag3 = value.F.On;
				value.F.SetOn(flag2);
				if (flag2 && !flag3)
				{
					Reveal.Symptom("static on a radio call");
				}
			}
		}
		bool flag4 = S.Active && S.Has(2);
		List<WalkieTalkie> allWalkieTalkies = WalkieTalkie.allWalkieTalkies;
		if (allWalkieTalkies == null)
		{
			return;
		}
		for (int j = 0; j < allWalkieTalkies.Count; j++)
		{
			WalkieTalkie val2 = allWalkieTalkies[j];
			if ((Object)(object)val2 == (Object)null || (Object)(object)val2.target == (Object)null)
			{
				continue;
			}
			bool flag5 = flag4 && Walkies.On(val2);
			InterferenceFilter interferenceFilter = ((Component)val2.target).GetComponent<InterferenceFilter>();
			if ((Object)(object)interferenceFilter == (Object)null)
			{
				if (!flag5)
				{
					continue;
				}
				interferenceFilter = InterferenceFilter.GetOrAdd(val2.target, 1);
			}
			interferenceFilter.SetOn(flag5);
		}
	}

	private static void LogComponentsOnce(AudioSource src)
	{
		if (_loggedComponents || !Plugin.LogVoiceComponents.Value)
		{
			return;
		}
		_loggedComponents = true;
		try
		{
			Component[] components = ((Component)src).gameObject.GetComponents<Component>();
			string[] array = new string[components.Length];
			for (int i = 0; i < components.Length; i++)
			{
				array[i] = (((Object)(object)components[i] == (Object)null) ? "?" : ((object)components[i]).GetType().Name);
			}
			Plugin.Log.LogInfo((object)("Voice object '" + ((Object)((Component)src).gameObject).name + "' components in order: " + string.Join(", ", array) + ". InterferenceFilter should be last."));
		}
		catch
		{
		}
	}

	internal static void ScanWalkies()
	{
		bool num = S.Active && S.Has(4);
		bool flag = Effects.FlareMode && !S.Active;
		if (!num && !flag)
		{
			return;
		}
		List<WalkieTalkie> allWalkieTalkies = WalkieTalkie.allWalkieTalkies;
		if (allWalkieTalkies == null)
		{
			return;
		}
		for (int i = 0; i < allWalkieTalkies.Count; i++)
		{
			WalkieTalkie val = allWalkieTalkies[i];
			if ((Object)(object)val == (Object)null || !((GrabbableObject)val).isBeingUsed)
			{
				continue;
			}
			Children.Clear();
			((Component)val).GetComponentsInChildren<AudioSource>(true, Children);
			for (int j = 0; j < Children.Count; j++)
			{
				AudioSource val2 = Children[j];
				if ((Object)(object)val2 == (Object)null || (Object)(object)val2 == (Object)(object)val.thisAudio || (Object)(object)val2 == (Object)(object)val.target || (Object)(object)val2 == (Object)(object)val.wallAudio || Walkies.IsOurs(val2))
				{
					continue;
				}
				if (!flag)
				{
					InterferenceFilter component = ((Component)val2).GetComponent<InterferenceFilter>();
					if ((Object)(object)component != (Object)null)
					{
						component.SetOn(S.Has(1));
						GateHeld(val, val2);
						continue;
					}
				}
				else if (FlareAttached.Contains(val2))
				{
					continue;
				}
				if (val2.isPlaying || ((Object)((Component)val2).gameObject).name.StartsWith("mp_radio", StringComparison.Ordinal))
				{
					AttachSource(val2, val);
				}
			}
		}
		Children.Clear();
	}

	internal static bool AttachSource(AudioSource src, WalkieTalkie parent)
	{
		if ((Object)(object)src == (Object)null)
		{
			return false;
		}
		if (Effects.FlareMode && !S.Active)
		{
			if (FlareAttached.Contains(src))
			{
				return true;
			}
			FlareAttached.Add(src);
			return FlareLink.Attach(src);
		}
		if (!S.Active)
		{
			return true;
		}
		InterferenceFilter orAdd = InterferenceFilter.GetOrAdd(src, 0);
		if ((Object)(object)orAdd != (Object)null)
		{
			orAdd.SetOn(S.Has(1));
		}
		if ((Object)(object)parent == (Object)null)
		{
			parent = ((Component)src).GetComponentInParent<WalkieTalkie>();
		}
		if ((Object)(object)parent != (Object)null)
		{
			GateHeld(parent, src);
		}
		Reveal.Symptom("static on a radio line");
		return true;
	}

	private static void GateHeld(WalkieTalkie w, AudioSource src)
	{
		if (S.Active && S.Has(1024) && !((Object)(object)w == (Object)null) && !((Object)(object)src == (Object)null) && (Object)(object)((GrabbableObject)w).playerHeldBy == (Object)null && !src.mute)
		{
			src.mute = true;
			Muted.Add(src);
		}
	}

	internal static void ForgetFlareSources()
	{
		foreach (AudioSource item in FlareAttached)
		{
			if ((Object)(object)item != (Object)null)
			{
				FlareLink.Forget(item);
			}
		}
		FlareAttached.Clear();
	}

	internal static void OnVoiceSettingsDisabled(AudioSource src)
	{
		if (!((Object)(object)src == (Object)null) && VoiceSources.TryGetValue(src, out var value))
		{
			if ((Object)(object)value.F != (Object)null)
			{
				value.F.SetOn(on: false);
			}
			VoiceSources.Remove(src);
		}
	}

	internal static void OnVoiceObjectsRefreshed()
	{
		foreach (KeyValuePair<AudioSource, Entry> voiceSource in VoiceSources)
		{
			if ((Object)(object)voiceSource.Value.F != (Object)null)
			{
				voiceSource.Value.F.SetOn(on: false);
			}
		}
		VoiceSources.Clear();
		if (S.Active)
		{
			Recheck();
		}
	}

	internal static void AllOff()
	{
		InterferenceFilter.AllOff();
		Dead.Clear();
		foreach (KeyValuePair<AudioSource, Entry> voiceSource in VoiceSources)
		{
			if ((Object)(object)voiceSource.Key == (Object)null)
			{
				Dead.Add(voiceSource.Key);
			}
		}
		for (int i = 0; i < Dead.Count; i++)
		{
			VoiceSources.Remove(Dead[i]);
		}
		Dead.Clear();
		foreach (AudioSource item in Muted)
		{
			if ((Object)(object)item != (Object)null)
			{
				item.mute = false;
			}
		}
		Muted.Clear();
	}

	internal static void Clear()
	{
		AllOff();
		VoiceSources.Clear();
		FlareAttached.Clear();
	}
}
internal static class Walkies
{
	internal const string StaticName = "SignalInterference_static";

	private static readonly Dictionary<WalkieTalkie, AudioSource> StaticSources = new Dictionary<WalkieTalkie, AudioSource>();

	private static readonly List<WalkieTalkie> Tmp = new List<WalkieTalkie>(8);

	private static readonly List<WalkieTalkie> DeadKeys = new List<WalkieTalkie>();

	private static readonly List<AudioSource> GhostSources = new List<AudioSource>(8);

	private static readonly List<WalkieTalkie> GhostWalkies = new List<WalkieTalkie>(8);

	private static readonly HashSet<AudioSource> Ours = new HashSet<AudioSource>();

	private static AudioSource _src2D;

	private static InterferenceFilter _f2D;

	private static Coroutine _ghost;

	internal static bool GhostPlaying;

	private static readonly AudioSource[] StopSrc = (AudioSource[])(object)new AudioSource[16];

	private static readonly float[] StopAt = new float[16];

	internal static int PendingStops;

	internal static bool IsOurs(AudioSource s)
	{
		return Ours.Contains(s);
	}

	internal static bool On(WalkieTalkie w)
	{
		if ((Object)(object)w != (Object)null && ((GrabbableObject)w).isBeingUsed && ((GrabbableObject)w).insertedBattery != null && !((GrabbableObject)w).insertedBattery.empty)
		{
			return ((GrabbableObject)w).insertedBattery.charge > 0f;
		}
		return false;
	}

	internal static bool AnyOn()
	{
		List<WalkieTalkie> allWalkieTalkies = WalkieTalkie.allWalkieTalkies;
		if (allWalkieTalkies == null)
		{
			return false;
		}
		for (int i = 0; i < allWalkieTalkies.Count; i++)
		{
			if (On(allWalkieTalkies[i]))
			{
				return true;
			}
		}
		return false;
	}

	internal static PlayerControllerB Listener()
	{
		GameNetworkManager instance = GameNetworkManager.Instance;
		PlayerControllerB val = (((Object)(object)instance != (Object)null) ? instance.localPlayerController : null);
		if ((Object)(object)val == (Object)null)
		{
			return null;
		}
		if (val.isPlayerDead && (Object)(object)val.spectatedPlayerScript != (Object)null)
		{
			return val.spectatedPlayerScript;
		}
		return val;
	}

	private static bool Clicks(WalkieTalkie w)
	{
		if (!On(w) || (Object)(object)w.thisAudio == (Object)null)
		{
			return false;
		}
		PlayerControllerB playerHeldBy = ((GrabbableObject)w).playerHeldBy;
		if ((Object)(object)playerHeldBy != (Object)null && ((GrabbableObject)w).isPocketed && (Object)(object)playerHeldBy.currentlyHeldObjectServer != (Object)null && playerHeldBy.currentlyHeldObjectServer is WalkieTalkie)
		{
			return false;
		}
		return true;
	}

	private static void Click(WalkieTalkie w, AudioClip[] clips, Random r)
	{
		if (clips != null && clips.Length != 0 && !((Object)(object)w.thisAudio == (Object)null))
		{
			AudioClip val = clips[r.Next(clips.Length)];
			if ((Object)(object)val != (Object)null)
			{
				w.thisAudio.PlayOneShot(val);
			}
		}
	}

	private static AudioSource StaticSource(WalkieTalkie w)
	{
		//IL_001f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0024: Unknown result type (might be due to invalid IL or missing references)
		//IL_0066: Unknown result type (might be due to invalid IL or missing references)
		//IL_00a1: Unknown result type (might be due to invalid IL or missing references)
		//IL_00a7: Invalid comparison between Unknown and I4
		if (StaticSources.TryGetValue(w, out var value) && (Object)(object)value != (Object)null)
		{
			return value;
		}
		GameObject val = new GameObject("SignalInterference_static");
		val.transform.SetParent(((Component)w).transform, false);
		value = val.AddComponent<AudioSource>();
		AudioSource thisAudio = w.thisAudio;
		if ((Object)(object)thisAudio != (Object)null)
		{
			value.outputAudioMixerGroup = thisAudio.outputAudioMixerGroup;
			value.spatialBlend = thisAudio.spatialBlend;
			value.rolloffMode = thisAudio.rolloffMode;
			value.minDistance = thisAudio.minDistance;
			value.maxDistance = thisAudio.maxDistance;
			value.spread = thisAudio.spread;
			value.priority = thisAudio.priority;
			if ((int)thisAudio.rolloffMode == 2)
			{
				value.SetCustomCurve((AudioSourceCurveType)0, thisAudio.GetCustomCurve((AudioSourceCurveType)0));
			}
		}
		else
		{
			value.spatialBlend = 1f;
			value.maxDistance = 25f;
		}
		value.dopplerLevel = 0f;
		value.playOnAwake = false;
		value.loop = false;
		value.clip = Sounds.Static;
		InterferenceFilter.GetOrAdd(value, 2);
		StaticSources[w] = value;
		Ours.Add(value);
		return value;
	}

	private static void PlayStatic(AudioSource src, float volume, float seconds, bool loop, Random r, int mode)
	{
		AudioClip val = Sounds.Static;
		if (!((Object)(object)src == (Object)null) && !((Object)(object)val == (Object)null))
		{
			src.clip = val;
			src.volume = volume;
			src.loop = loop;
			float num = Mathf.Max(0f, val.length - (loop ? 0.05f : seconds) - 0.02f);
			src.time = (float)r.NextDouble() * num;
			InterferenceFilter component = ((Component)src).GetComponent<InterferenceFilter>();
			if ((Object)(object)component != (Object)null)
			{
				component.Mode = mode;
				component.SetOn(S.Active);
			}
			src.Play();
			if (!loop)
			{
				StopLater(src, Time.realtimeSinceStartup + seconds);
			}
		}
	}

	private static void StopLater(AudioSource src, float at)
	{
		for (int i = 0; i < PendingStops; i++)
		{
			if ((Object)(object)StopSrc[i] == (Object)(object)src)
			{
				StopAt[i] = at;
				return;
			}
		}
		if (PendingStops >= StopSrc.Length)
		{
			src.Stop();
			return;
		}
		StopSrc[PendingStops] = src;
		StopAt[PendingStops] = at;
		PendingStops++;
	}

	internal static void StopDue(float now)
	{
		for (int num = PendingStops - 1; num >= 0; num--)
		{
			if (!((Object)(object)StopSrc[num] != (Object)null) || !(now < StopAt[num]))
			{
				if ((Object)(object)StopSrc[num] != (Object)null)
				{
					StopSrc[num].Stop();
				}
				PendingStops--;
				StopSrc[num] = StopSrc[PendingStops];
				StopAt[num] = StopAt[PendingStops];
				StopSrc[PendingStops] = null;
			}
		}
	}

	internal static int Crackle(float minLen, float maxLen, float minVol, float maxVol)
	{
		if (!Sounds.Ready || GhostPlaying)
		{
			return 0;
		}
		List<WalkieTalkie> allWalkieTalkies = WalkieTalkie.allWalkieTalkies;
		if (allWalkieTalkies == null)
		{
			return 0;
		}
		int num = 0;
		float seconds = Effects.U(minLen, maxLen);
		for (int i = 0; i < allWalkieTalkies.Count; i++)
		{
			WalkieTalkie val = allWalkieTalkies[i];
			if (On(val))
			{
				AudioSource val2 = StaticSource(val);
				if (!val2.isPlaying)
				{
					float num2 = (((Object)(object)val.thisAudio != (Object)null) ? val.thisAudio.volume : 1f);
					PlayStatic(val2, num2 * Effects.U(minVol, maxVol), seconds, loop: false, Effects.LocalRng, 2);
					num++;
				}
			}
		}
		return num;
	}

	internal static bool StartGhost(int seed, float seconds, bool voiceLayer)
	{
		if (!Sounds.Ready || (Object)(object)Plugin.RunnerInstance == (Object)null || GhostPlaying)
		{
			return false;
		}
		if (!AnyOn())
		{
			return false;
		}
		_ghost = ((MonoBehaviour)Plugin.RunnerInstance).StartCoroutine(GhostRoutine(seed, seconds, voiceLayer));
		return true;
	}

	private static bool AnyoneTalking()
	{
		StartOfRound instance = StartOfRound.Instance;
		if ((Object)(object)instance == (Object)null || instance.allPlayerScripts == null)
		{
			return false;
		}
		PlayerControllerB[] allPlayerScripts = instance.allPlayerScripts;
		for (int i = 0; i < allPlayerScripts.Length; i++)
		{
			if ((Object)(object)allPlayerScripts[i] != (Object)null && allPlayerScripts[i].isPlayerControlled && allPlayerScripts[i].speakingToWalkieTalkie)
			{
				return true;
			}
		}
		return false;
	}

	private static IEnumerator GhostRoutine(int seed, float seconds, bool voiceLayer)
	{
		GhostPlaying = true;
		Random r = new Random(seed);
		GhostWalkies.Clear();
		GhostSources.Clear();
		List<WalkieTalkie> allWalkieTalkies = WalkieTalkie.allWalkieTalkies;
		if (allWalkieTalkies != null)
		{
			for (int i = 0; i < allWalkieTalkies.Count; i++)
			{
				if (On(allWalkieTalkies[i]))
				{
					GhostWalkies.Add(allWalkieTalkies[i]);
				}
			}
		}
		for (int j = 0; j < GhostWalkies.Count; j++)
		{
			if (Clicks(GhostWalkies[j]))
			{
				Click(GhostWalkies[j], GhostWalkies[j].startTransmissionSFX, r);
			}
		}
		InterferenceFilter.TriggerBurst(0.3f + (float)r.NextDouble() * 0.5f);
		yield return (object)new WaitForSecondsRealtime(0.12f);
		int mode = (voiceLayer ? 3 : 2);
		bool flag = S.Has(1024) || !S.Active;
		PlayerControllerB val = Listener();
		WalkieTalkie listenerWalkie = null;
		if ((Object)(object)val != (Object)null && val.holdingWalkieTalkie)
		{
			for (int k = 0; k < GhostWalkies.Count; k++)
			{
				if ((Object)(object)GhostWalkies[k] != (Object)null && (Object)(object)((GrabbableObject)GhostWalkies[k]).playerHeldBy == (Object)(object)val)
				{
					listenerWalkie = GhostWalkies[k];
					break;
				}
			}
		}
		for (int l = 0; l < GhostWalkies.Count; l++)
		{
			WalkieTalkie val2 = GhostWalkies[l];
			if (!((Object)(object)val2 == (Object)null) && !((Object)(object)val2 == (Object)(object)listenerWalkie) && (!flag || !((Object)(object)((GrabbableObject)val2).playerHeldBy == (Object)null)))
			{
				AudioSource val3 = StaticSource(val2);
				float num = (((Object)(object)val2.thisAudio != (Object)null) ? val2.thisAudio.volume : 1f);
				PlayStatic(val3, num * 0.8f, seconds, loop: true, r, mode);
				GhostSources.Add(val3);
			}
		}
		if ((Object)(object)listenerWalkie != (Object)null)
		{
			Ensure2D();
			PlayStatic(_src2D, 0.9f, seconds, loop: true, r, mode);
			GhostSources.Add(_src2D);
		}
		float end = Time.realtimeSinceStartup + seconds;
		while (Time.realtimeSinceStartup < end && !AnyoneTalking())
		{
			for (int m = 0; m < GhostWalkies.Count; m++)
			{
				WalkieTalkie val4 = GhostWalkies[m];
				if ((Object)(object)val4 != (Object)null && !On(val4))
				{
					if (StaticSources.TryGetValue(val4, out var value) && (Object)(object)value != (Object)null)
					{
						value.Stop();
					}
					if ((Object)(object)val4 == (Object)(object)listenerWalkie && (Object)(object)_src2D != (Object)null)
					{
						_src2D.Stop();
					}
				}
			}
			yield return null;
		}
		for (int n = 0; n < GhostSources.Count; n++)
		{
			if ((Object)(object)GhostSources[n] != (Object)null)
			{
				GhostSources[n].Stop();
				GhostSources[n].loop = false;
			}
		}
		for (int num2 = 0; num2 < GhostWalkies.Count; num2++)
		{
			if (Clicks(GhostWalkies[num2]))
			{
				Click(GhostWalkies[num2], GhostWalkies[num2].stopTransmissionSFX, r);
			}
		}
		GhostSources.Clear();
		GhostWalkies.Clear();
		GhostPlaying = false;
		_ghost = null;
	}

	private static void Ensure2D()
	{
		//IL_0015: Unknown result type (might be due to invalid IL or missing references)
		//IL_001a: Unknown result type (might be due to invalid IL or missing references)
		//IL_0030: 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 ((Object)(object)_src2D == (Object)null)
		{
			GameObject val = new GameObject("SignalInterference_radio2d");
			val.transform.SetParent(((Component)Plugin.RunnerInstance).transform, false);
			_src2D = val.AddComponent<AudioSource>();
			_src2D.spatialBlend = 0f;
			_src2D.playOnAwake = false;
			_src2D.panStereo = 0.4f;
			AudioLowPassFilter obj = val.AddComponent<AudioLowPassFilter>();
			obj.cutoffFrequency = 4000f;
			obj.lowpassResonanceQ = 3f;
			AudioHighPassFilter obj2 = val.AddComponent<AudioHighPassFilter>();
			obj2.cutoffFrequency = 1500f;
			obj2.highpassResonanceQ = 1f;
			_f2D = InterferenceFilter.GetOrAdd(_src2D, 2);
		}
		StartOfRound instance = StartOfRound.Instance;
		SoundManager instance2 = SoundManager.Instance;
		PlayerControllerB val2 = (((Object)(object)GameNetworkManager.Instance != (Object)null) ? GameNetworkManager.Instance.localPlayerController : null);
		if ((Object)(object)instance != (Object)null && instance.allPlayerScripts != null)
		{
			PlayerControllerB[] allPlayerScripts = instance.allPlayerScripts;
			foreach (PlayerControllerB val3 in allPlayerScripts)
			{
				if ((Object)(object)val3 == (Object)null || (Object)(object)val3 == (Object)(object)val2 || !val3.isPlayerControlled)
				{
					continue;
				}
				if ((Object)(object)val3.currentVoiceChatAudioSource != (Object)null)
				{
					AudioHighPassFilter component = ((Component)val3.currentVoiceChatAudioSource).GetComponent<AudioHighPassFilter>();
					AudioHighPassFilter component2 = ((Component)_src2D).GetComponent<AudioHighPassFilter>();
					if ((Object)(object)component != (Object)null && (Object)(object)component2 != (Object)null)
					{
						component2.cutoffFrequency = component.cutoffFrequency;
						component2.highpassResonanceQ = component.highpassResonanceQ;
					}
				}
				int num = (int)val3.playerClientId;
				if ((Object)(object)instance2 != (Object)null && instance2.playerVoiceMixers != null && num >= 0 && num < instance2.playerVoiceMixers.Length)
				{
					_src2D.outputAudioMixerGroup = instance2.playerVoiceMixers[num];
				}
				break;
			}
		}
		_src2D.panStereo = (((Object)(object)val2 != (Object)null && val2.isPlayerDead) ? 0f : 0.4f);
	}

	internal static void StopAll()
	{
		if (_ghost != null && (Object)(object)Plugin.RunnerInstance != (Object)null)
		{
			((MonoBehaviour)Plugin.RunnerInstance).StopCoroutine(_ghost);
			_ghost = null;
		}
		GhostPlaying = false;
		GhostSources.Clear();
		GhostWalkies.Clear();
		StopDue(float.MaxValue);
		DeadKeys.Clear();
		foreach (KeyValuePair<WalkieTalkie, AudioSource> staticSource in StaticSources)
		{
			if ((Object)(object)staticSource.Key == (Object)null || (Object)(object)staticSource.Value == (Object)null)
			{
				DeadKeys.Add(staticSource.Key);
				continue;
			}
			staticSource.Value.Stop();
			staticSource.Value.loop = false;
		}
		for (int i = 0; i < DeadKeys.Count; i++)
		{
			StaticSources.Remove(DeadKeys[i]);
		}
		DeadKeys.Clear();
		Ours.RemoveWhere(IsDead);
		if ((Object)(object)_src2D != (Object)null)
		{
			_src2D.Stop();
			_src2D.loop = false;
		}
	}

	private static bool IsDead(AudioSource s)
	{
		return (Object)(object)s == (Object)null;
	}

	internal static void Prune()
	{
		Ours.RemoveWhere(IsDead);
		DeadKeys.Clear();
		foreach (KeyValuePair<WalkieTalkie, AudioSource> staticSource in StaticSources)
		{
			if ((Object)(object)staticSource.Key == (Object)null || (Object)(object)staticSource.Value == (Object)null)
			{
				DeadKeys.Add(staticSource.Key);
			}
		}
		for (int i = 0; i < DeadKeys.Count; i++)
		{
			StaticSources.Remove(DeadKeys[i]);
		}
		DeadKeys.Clear();
	}
}
internal static class Radar
{
	internal static bool Any;

	private static readonly float[] FlashStart = new float[4];

	private static readonly float[] FlashEnd = new float[4];

	private static int _flashCount;

	private static float _freezeUntil;

	private static bool _forcedUI;

	private static bool _camForced;

	private static bool _loggedNoUI;

	private static bool _loggedNoRT;

	private static Texture2D _noise;

	private static FieldRef<ManualCameraRenderer, bool> _inCaves;

	private static FieldRef<ManualCameraRenderer, bool> _screenOn;

	private static bool _refsInit;

	private static void InitRefs()
	{
		if (_refsInit)
		{
			return;
		}
		_refsInit = true;
		try
		{
			_inCaves = AccessTools.FieldRefAccess<ManualCameraRenderer, bool>("playerIsInCaves");
		}
		catch
		{
		}
		try
		{
			_screenOn = AccessTools.FieldRefAccess<ManualCameraRenderer, bool>("isScreenOn");
		}
		catch
		{
		}
	}

	private static ManualCameraRenderer Map()
	{
		StartOfRound instance = StartOfRound.Instance;
		if ((Object)(object)instance == (Object)null || instance.inShipPhase)
		{
			return null;
		}
		return instance.mapScreen;
	}

	private static bool ScreenOn(ManualCameraRenderer m)
	{
		InitRefs();
		if ((Object)(object)m == (Object)null)
		{
			return false;
		}
		if (_screenOn == null)
		{
			return true;
		}
		try
		{
			return _screenOn.Invoke(m);
		}
		catch
		{
			return true;
		}
	}

	internal static bool Noise(int seed, int count)
	{
		ManualCameraRenderer val = Map();
		if ((Object)(object)val == (Object)null)
		{
			return false;
		}
		Random random = new Random(seed);
		float num = Time.realtimeSinceStartup;
		_flashCount = Mathf.Clamp(count, 1, 3);
		for (int i = 0; i < _flashCount; i++)
		{
			if (i > 0)
			{
				num += 0.2f + (float)random.NextDouble() * 0.6f;
			}
			FlashStart[i] = num;
			num += 0.3f + (float)random.NextDouble() * 1.2f;
			FlashEnd[i] = num;
		}
		Any = true;
		return ScreenOn(val);
	}

	internal static bool LocalFlash(float seconds)
	{
		ManualCameraRenderer val = Map();
		if ((Object)(object)val == (Object)null)
		{
			return false;
		}
		float realtimeSinceStartup = Time.realtimeSinceStartup;
		_flashCount = 1;
		FlashStart[0] = realtimeSinceStartup;
		FlashEnd[0] = realtimeSinceStartup + seconds;
		Any = true;
		return ScreenOn(val);
	}

	internal static bool Freeze(float seconds)
	{
		ManualCameraRenderer val = Map();
		if ((Object)(object)val == (Object)null)
		{
			return false;
		}
		_freezeUntil = Time.realtimeSinceStartup + Mathf.Clamp(seconds, 0.5f, 10f);
		Any = true;
		return ScreenOn(val);
	}

	private static bool InFlash(float now)
	{
		for (int i = 0; i < _flashCount; i++)
		{
			if (now >= FlashStart[i] && now < FlashEnd[i])
			{
				return true;
			}
		}
		return false;
	}

	private static bool Pending(float now)
	{
		if (now < _freezeUntil)
		{
			return true;
		}
		for (int i = 0; i < _flashCount; i++)
		{
			if (now < FlashEnd[i])
			{
				return true;
			}
		}
		return false;
	}

	private static bool UseOverlay(ManualCameraRenderer m)
	{
		if (S.NoiseStyleValue == 2)
		{
			return false;
		}
		if ((Object)(object)m.LostSignalUI != (Object)null)
		{
			return true;
		}
		if (!_loggedNoUI)
		{
			_loggedNoUI = true;
			Plugin.Log.LogInfo((object)"The ship map has no lost-signal overlay; map noise uses drawn static.");
		}
		return false;
	}

	internal static int BeforeConditions(ManualCameraRenderer m, ref bool inCaves)
	{
		ManualCameraRenderer val = Map();
		if ((Object)(object)val == (Object)null || (Object)(object)m != (Object)(object)val)
		{
			return 0;
		}
		if (!InFlash(Time.realtimeSinceStartup) || !UseOverlay(m))
		{
			return 0;
		}
		int result = ((!inCaves) ? 1 : 2);
		inCaves = true;
		_forcedUI = true;
		return result;
	}

	internal static void AfterConditions(int state, ref bool inCaves)
	{
		if (state != 0)
		{
			inCaves = state == 2;
		}
	}

	private static void RestoreUI(ManualCameraRenderer m)
	{
		_forcedUI = false;
		if ((Object)(object)m == (Object)null || (Object)(object)m.LostSignalUI == (Object)null)
		{
			return;
		}
		InitRefs();
		bool active = false;
		try
		{
			if (_inCaves != null)
			{
				active = _inCaves.Invoke(m);
			}
		}
		catch
		{
		}
		m.LostSignalUI.SetActive(active);
	}

	internal static void AfterUpdate(ManualCameraRenderer m)
	{
		ManualCameraRenderer val = Map();
		if ((Object)(object)val == (Object)null || (Object)(object)m != (Object)(object)val)
		{
			return;
		}
		float realtimeSinceStartup = Time.realtimeSinceStartup;
		bool flag = realtimeSinceStartup < _freezeUntil;
		bool flag2 = InFlash(realtimeSinceStartup) && !UseOverlay(m) && S.NoiseStyleValue != 1;
		if ((flag || flag2) && (Object)(object)m.cam != (Object)null)
		{
			((Behaviour)m.cam).enabled = false;
			_camForced = true;
			if (flag2)
			{
				DrawStatic(m.cam);
			}
		}
		else if (_camForced)
		{
			_camForced = false;
			if ((Object)(object)m.cam != (Object)null)
			{
				((Behaviour)m.cam).enabled = true;
			}
		}
		if (_forcedUI && !InFlash(realtimeSinceStartup))
		{
			_forcedUI = false;
		}
		if (!Pending(realtimeSinceStartup) && !_camForced && !_forcedUI)
		{
			Any = false;
		}
	}

	private static void DrawStatic(Camera cam)
	{
		//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_004f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0056: Unknown result type (might be due to invalid IL or missing references)
		//IL_0063: Expected O, but got Unknown
		//IL_00d3: Unknown result type (might be due to invalid IL or missing references)
		//IL_00ee: 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)
		RenderTexture targetTexture = cam.targetTexture;
		if ((Object)(object)targetTexture == (Object)null)
		{
			if (!_loggedNoRT)
			{
				_loggedNoRT = true;
				Plugin.Log.LogInfo((object)"Map camera has no render texture; drawn static is skipped.");
			}
			return;
		}
		if ((Object)(object)_noise == (Object)null)
		{
			_noise = new Texture2D(96, 96, (TextureFormat)4, false)
			{
				filterMode = (FilterMode)0,
				wrapMode = (TextureWrapMode)0,
				hideFlags = (HideFlags)61
			};
			Random random = new Random(77);
			Color32[] array = (Color32[])(object)new Color32[9216];
			for (int i = 0; i < array.Length; i++)
			{
				byte b = (byte)random.Next(20, 235);
				array[i] = new Color32(b, b, b, byte.MaxValue);
			}
			_noise.SetPixels32(array);
			_noise.Apply(false, false);
		}
		try
		{
			Graphics.Blit((Texture)(object)_noise, targetTexture, new Vector2(2.5f, 2.5f), new Vector2((float)Effects.LocalRng.NextDouble(), (float)Effects.LocalRng.NextDouble()));
		}
		catch (Exception ex)
		{
			if (!_loggedNoRT)
			{
				_loggedNoRT = true;
				Plugin.Log.LogWarning((object)("Drawing map static failed: " + ex.Message));
			}
		}
	}

	internal static void Clear()
	{
		_flashCount = 0;
		_freezeUntil = 0f;
		StartOfRound instance = StartOfRound.Instance;
		ManualCameraRenderer val = (((Object)(object)instance != (Object)null) ? instance.mapScreen : null);
		if (_forcedUI)
		{
			RestoreUI(val);
		}
		if (_camForced)
		{
			_camForced = false;
			if ((Object)(object)val != (Object)null && (Object)(object)val.cam != (Object)null)
			{
				((Behaviour)val.cam).enabled = true;
			}
		}
		Any = false;
	}
}
internal static class Flashlights
{
	private static readonly List<FlashlightItem> Known = new List<FlashlightItem>();

	private static readonly List<FlashlightItem> Flickering = new List<FlashlightItem>();

	private static Coroutine _co;

	internal static void Track(FlashlightItem f)
	{
		if ((Object)(object)f != (Object)null && !Known.Contains(f))
		{
			Known.Add(f);
		}
	}

	internal static int Flicker(float seconds)
	{
		for (int num = Known.Count - 1; num >= 0; num--)
		{
			if ((Object)(object)Known[num] == (Object)null)
			{
				Known.RemoveAt(num);
			}
		}
		RestoreAll();
		for (int i = 0; i < Known.Count; i++)
		{
			FlashlightItem val = Known[i];
			if (((GrabbableObject)val).isBeingUsed && val.flashlightInterferenceLevel == 0)
			{
				val.flashlightInterferenceLevel = 1;
				Flickering.Add(val);
			}
		}
		if (Flickering.Count > 0 && (Object)(object)Plugin.RunnerInstance != (Object)null)
		{
			_co = ((MonoBehaviour)Plugin.RunnerInstance).StartCoroutine(RestoreAfter(seconds));
		}
		return Flickering.Count;
	}

	private static IEnumerator RestoreAfter(float seconds)
	{
		yield return (object)new WaitForSecondsRealtime(Mathf.Clamp(seconds, 0.1f, 2f));
		_co = null;
		RestoreAll();
	}

	internal static void RestoreAll()
	{
		if (_co != null && (Object)(object)Plugin.RunnerInstance != (Object)null)
		{
			((MonoBehaviour)Plugin.RunnerInstance).StopCoroutine(_co);
			_co = null;
		}
		for (int i = 0; i < Flickering.Count; i++)
		{
			FlashlightItem val = Flickering[i];
			if ((Object)(object)val != (Object)null && val.flashlightInterferenceLevel == 1)
			{
				val.flashlightInterferenceLevel = 0;
			}
		}
		Flickering.Clear();
	}
}
internal static class Hooks
{
	private static string _lastFailedCode;

	private static readonly Random CodeRng = new Random();

	internal static void AfterLevelGenerated()
	{
		try
		{
			Director.EnsureDecided();
		}
		catch (Exception ex)
		{
			Plugin.Log.LogWarning((object)("Roll failed: " + ex.Message));
		}
	}

	internal static void AfterShipLanded()
	{
		try
		{
			Director.OnLanded();
		}
		catch (Exception ex)
		{
			Plugin.Log.LogWarning((object)("Landing hook failed: " + ex.Message));
		}
	}

	internal static void AfterShipLeave()
	{
		try
		{
			Director.OnShipLeave();
			if (S.Active && !S.IsHost)
			{
				bool active = S.Active;
				S.Active = false;
				S.Severity = 0;
				S.Factor = 1f;
				S.Serial++;
				Effects.OnStateChanged(active);
			}
			Effects.StopAll();
			_lastFailedCode = null;
		}
		catch (Exception ex)
		{
			Plugin.Log.LogWarning((object)("Ship leave hook failed: " + ex.Message));
		}
	}

	internal static void AfterShipHasLeft()
	{
		try
		{
			Effects.StopAll();
			Walkies.Prune();
		}
		catch
		{
		}
	}

	internal static void AfterBackInOrbit()
	{
		try
		{
			Director.OnBackInOrbit();
			DayInfo.Refresh();
		}
		catch
		{
		}
	}

	internal static void AfterStartOfRoundStart()
	{
		try
		{
			Net.EnsureRegistered();
		}
		catch (Exception ex)
		{
			Plugin.Log.LogWarning((object)("Network setup failed: " + ex.Message));
		}
	}

	internal static void AfterUpdatePlayerVoiceEffects()
	{
		if (!S.Active)
		{
			return;
		}
		try
		{
			Voice.Recheck();
		}
		catch (Exception e)
		{
			Runner.Error("voice filters", e);
		}
	}

	internal static void AfterRefreshVoiceObjects()
	{
		try
		{
			Voice.OnVoiceObjectsRefreshed();
		}
		catch
		{
		}
	}

	internal static void BeforeVoiceSettingsDisable(PlayerVoiceIngameSettings __instance)
	{
		try
		{
			if ((Object)(object)__instance != (Object)null)
			{
				Voice.OnVoiceSettingsDisabled(__instance.voiceAudio);
			}
		}
		catch
		{
		}
	}

	internal static void BeforeMeetsCameraEnabledConditions(ManualCameraRenderer __instance, ref bool ___playerIsInCaves, out int __state)
	{
		__state = 0;
		if (!Radar.Any)
		{
			return;
		}
		try
		{
			__state = Radar.BeforeConditions(__instance, ref ___playerIsInCaves);
		}
		catch (Exception e)
		{
			Runner.Error("map noise", e);
		}
	}

	internal static void AfterMeetsCameraEnabledConditions(ref bool ___playerIsInCaves, int __state)
	{
		if (__state == 0)
		{
			return;
		}
		try
		{
			Radar.AfterConditions(__state, ref ___playerIsInCaves);
		}
		catch (Exception e)
		{
			Runner.Error("map noise", e);
		}
	}

	internal static void AfterCameraUpdate(ManualCameraRenderer __instance)
	{
		if (!Radar.Any)
		{
			return;
		}
		try
		{
			Radar.AfterUpdate(__instance);
		}
		catch (Exception e)
		{
			Runner.Error("map freeze", e);
		}
	}

	internal static void AfterLightningStrike()
	{
		if (!S.Active)
		{
			return;
		}
		try
		{
			Effects.OnLightning();
		}
		catch (Exception e)
		{
			Runner.Error("lightning", e);
		}
	}

	internal static bool BeforeBroadcastCode(Terminal __instance, string __0, ref bool ___broadcastedCodeThisFrame)
	{
		if (!S.Active && !S.FailNext)
		{
			return true;
		}
		try
		{
			if (string.IsNullOrEmpty(__0))
			{
				return true;
			}
			StartOfRound instance = StartOfRound.Instance;
			if ((Object)(object)instance == (Object)null || instance.inShipPhase)
			{
				return true;
			}
			bool failNext = S.FailNext;
			if (!failNext)
			{
				if (!S.Has(256))
				{
					return true;
				}
				if (S.Has(4096) && _lastFailedCode == __0)
				{
					_lastFailedCode = null;
					return true;
				}
				if (CodeRng.NextDouble() >= (double)S.R.CodeFail)
				{
					_lastFailedCode = null;
					return true;
				}
			}
			bool flag = false;
			TerminalAccessibleObject[] array = Object.FindObjectsOfType<TerminalAccessibleObject>();
			for (int i = 0; i < array.Length; i++)
			{
				if (flag)
				{
					break;
				}
				TerminalAccessibleObject val = array[i];
				if (!((Object)(object)val == (Object)null) && !(val.objectCode != __0))
				{
					flag = (CodeTargets)S.CodeTargetsValue switch
					{
						CodeTargets.DoorsOnly => val.isBigDoor, 
						CodeTargets.HazardsOnly => !val.isBigDoor, 
						_ => true, 
					};
				}
			}
			if (!flag)
			{
				return true;
			}
			___broadcastedCodeThisFrame = true;
			_lastFailedCode = __0;
			if (failNext)
			{
				Reveal.UsedFailNext();
			}
			if (S.Has(2048) && (Object)(object)Sounds.Short != (Object)null && (Object)(object)__instance != (Object)null && (Object)(object)__instance.terminalAudio != (Object)null)
			{
				__instance.terminalAudio.PlayOneShot(Sounds.Short, 0.7f);
			}
			Plugin.Log.LogInfo((object)("Code " + __0 + " didn't get through (signal interference)."));
			Reveal.Symptom("failed code");
			return false;
		}
		catch (Exception e)
		{
			Runner.Error("terminal codes", e);
			return true;
		}
	}

	internal static bool BeforeSignalTranslatorMessage(HUDManager __instance, ref string __0, int __1, SignalTranslator __2, ref IEnumerator __result)
	{
		if (!S.Active)
		{
			return true;
		}
		try
		{
			if (!S.Has(128) || string.IsNullOrEmpty(__0))
			{
				return true;
			}
			StartOfRound instance = StartOfRound.Instance;
			if ((Object)(object)instance == (Object)null)
			{
				return true;
			}
			Random random = new Random(__1 * 7919 + instance.randomMapSeed + 20897);
			if (random.NextDouble() < (double)S.R.TransLost)
			{
				__result = LostMessage(__instance, __2);
				Plugin.Log.LogInfo((object)"Signal translator message lost (signal interference).");
				Reveal.Symptom("lost translator message");
				return false;
			}
			float transCorrupt = S.R.TransCorrupt;
			if (transCorrupt <= 0f)
			{
				return true;
			}
			char[] array = __0.ToCharArray();
			bool flag = false;
			for (int i = 1; i < array.Length; i++)
			{
				if (random.NextDouble() < (double)transCorrupt)
				{
					array[i] = (char)random.Next(33, 127);
					flag = true;
				}
			}
			if (flag)
			{
				__0 = new string(array);
				Reveal.Symptom("garbled translator message");
			}
			return true;
		}
		catch (Exception e)
		{
			Runner.Error("signal translator", e);
			return true;
		}
	}

	private static IEnumerator LostMessage(HUDManager hud, SignalTranslator st)
	{
		AudioSource a = (((Object)(object)hud != (Object)null) ? hud.UIAudio : null);
		if ((Object)(object)a != (Object)null && (Object)(object)st != (Object)null && (Object)(object)st.startTransmissionSFX != (Object)null)
		{
			a.PlayOneShot(st.startTransmissionSFX, 1f);
		}
		yield return (object)new WaitForSeconds(0.4f);
		if ((Object)(object)a != (Object)null && (Object)(object)Sounds.Lost != (Object)null)
		{
			a.PlayOneShot(Sounds.Lost, 0.8f);
		}
	}

	internal static void AfterFlashlightStart(FlashlightItem __instance)
	{
		try
		{
			Flashlights.Track(__instance);
		}
		catch
		{
		}
	}
}
public class InterferenceFilter : MonoBehaviour
{
	internal const int ModeVoice = 0;

	internal const int ModeRelay = 1;

	internal const int ModeStatic = 2;

	internal const int ModeStaticVoice = 3;

	internal static readonly List<InterferenceFilter> All = new List<InterferenceFilter>();

	internal volatile bool On;

	internal volatile int Mode;

	private RadioDsp _dsp;

	internal static int VoiceEventSerial => RadioDsp.VoiceEventSerial;

	private void Awake()
	{
		int seed = (((Object)this).GetInstanceID() * 2654435) ^ Environment.TickCount;
		_dsp = new RadioDsp(AudioSettings.outputSampleRate, seed);
		All.Add(this);
	}

	private void OnDestroy()
	{
		On = false;
		All.Remove(this);
	}

	internal void SetOn(bool on)
	{
		if (On != on || ((Behaviour)this).enabled != on)
		{
			On = on;
			((Behaviour)this).enabled = on;
		}
	}

	private void OnAudioFilterRead(float[] data, int channels)
	{
		if (!On)
		{
			return;
		}
		RadioDsp dsp = _dsp;
		if (dsp == null)
		{
			return;
		}
		try
		{
			dsp.Process(data, channels, Mode);
		}
		catch
		{
		}
	}

	internal static InterferenceFilter GetOrAdd(AudioSource src, int mode)
	{
		if ((Object)(object)src == (Object)null)
		{
			return null;
		}
		InterferenceFilter interferenceFilter = ((Component)src).GetComponent<InterferenceFilter>();
		if ((Object)(object)interferenceFilter == (Object)null)
		{
			interferenceFilter = ((Component)src).gameObject.AddComponent<InterferenceFilter>();
			interferenceFilter.On = false;
			((Behaviour)interferenceFilter).enabled = false;
		}
		interferenceFilter.Mode = mode;
		return interferenceFilter;
	}

	internal static void TriggerBurst(float seconds)
	{
		RadioDsp.BurstLen = seconds;
		RadioDsp.BurstSerial++;
	}

	internal static void ForceVoiceEvent(int kind)
	{
		RadioDsp.ForceKind = kind;
		RadioDsp.ForceSerial++;
	}

	internal static void AllOff()
	{
		for (int num = All.Count - 1; num >= 0; num--)
		{
			InterferenceFilter interferenceFilter = All[num];
			if ((Object)(object)interferenceFilter == (Object)null)
			{
				All.RemoveAt(num);
			}
			else
			{
				interferenceFilter.SetOn(on: false);
			}
		}
	}
}
internal sealed class RadioDsp
{
	internal const int ModeVoice = 0;

	internal const int ModeRelay = 1;

	internal const int ModeStatic = 2;

	internal const int ModeStaticVoice = 3;

	internal static volatile float Hiss;

	internal static volatile float DropPerSec;

	internal static volatile float DropMin;

	internal static volatile float DropMax;

	internal static volatile float GarbPerSec;

	internal static volatile float GarbMin;

	internal static volatile float GarbMax;

	internal static volatile bool VoiceEffects = true;

	internal static volatile int BurstSerial;

	internal static volatile float BurstLen;

	internal static volatile int ForceSerial;

	internal static volatile int ForceKind;

	internal static volatile int VoiceEventSerial;

	private const float SignalThreshold = 0.00316f;

	private const float TwoPi = (float)Math.PI * 2f;

	private readonly int _sr;

	private uint _rng;

	private readonly float _kA;

	private readonly float _kB;

	private readonly float _popDecay;

	private readonly float _rampStep;

	private readonly int _holdN;

	private readonly float[] _latch = new float[8];

	private float _lpA;

	private float _lpB;

	private float _pop;

	private float _gain = 1f;

	private float _phase;

	private float _ringInc;

	private int _dropLeft;

	private int _garbLeft;

	private int _burstLeft;

	private int _chopLeft;

	private int _holdCount;

	private bool _chopOn = true;

	private int _lastBurst;

	private int _lastForce;

	internal int Dropouts;

	internal int Garbles;

	internal RadioDsp(int sampleRate, int seed)
	{
		_sr = ((sampleRate > 8000) ? sampleRate : 48000);
		_rng = (uint)seed;
		if (_rng == 0)
		{
			_rng = 2654435769u;
		}
		_kA = 1f - (float)Math.Exp((float)Math.PI * -6800f / (float)_sr);
		_kB = 1f - (float)Math.Exp((float)Math.PI * -600f / (float)_sr);
		_popDecay = (float)Math.Exp(-1.0 / (0.003 * (double)_sr));
		_rampStep = 1f / (0.01f * (float)_sr);
		_holdN = Math.Max(1, (int)Math.Round((double)_sr / 3000.0));
		_ringInc = (float)Math.PI * 100f / (float)_sr;
		_lastBurst = BurstSerial;
		_lastForce = ForceSerial;
	}

	private float Rand()
	{
		uint rng = _rng;
		rng ^= rng << 13;
		rng ^= rng >> 17;
		return (float)((_rng = rng ^ (rng << 5)) & 0xFFFFFF) / 16777216f;
	}

	private void StartDropout()
	{
		float num = DropMin;
		float num2 = DropMax;
		if (num2 <= 0f)
		{
			num = 0.2f;
			num2 = 0.8f;
		}
		_dropLeft = (int)((num + Rand() * (num2 - num)) * (float)_sr);
		Dropouts++;
		VoiceEventSerial++;
	}

	private void StartGarble()
	{
		float num = GarbMin;
		float num2 = GarbMax;
		if (num2 <= 0f)
		{
			num = 0.5f;
			num2 = 1.5f;
		}
		_garbLeft = (int)((num + Rand() * (num2 - num)) * (float)_sr);
		_ringInc = (float)Math.PI * 2f * (30f + Rand() * 50f) / (float)_sr;
		_chopLeft = 0;
		Garbles++;
		VoiceEventSerial++;
	}

	internal void Process(float[] data, int ch, int mode)
	{
		if (data == null || ch <= 0)
		{
			return;
		}
		int num = data.Length;
		int num2 = num / ch;
		if (num2 <= 0)
		{
			return;
		}
		double num3 = 0.0;
		for (int i = 0; i < num; i++)
		{
			float num4 = data[i];
			num3 += (double)(num4 * num4);
		}
		float num5 = (float)Math.Sqrt(num3 / (double)num);
		int burstSerial = BurstSerial;
		if (burstSerial != _lastBurst)
		{
			_lastBurst = burstSerial;
			_burstLeft = (int)(BurstLen * (float)_sr);
		}
		int forceSerial = ForceSerial;
		if (forceSerial != _lastForce)
		{
			_lastForce = forceSerial;
			if (mode == 0)
			{
				if (ForceKind == 1)
				{
					StartDropout();
				}
				else if (ForceKind == 2)
				{
					StartGarble();
				}
			}
		}
		if (mode != 0 && num5 < 1E-06f && _burstLeft <= 0)
		{
			return;
		}
		float num6 = (float)num2 / (float)_sr;
		if (mode == 0 && VoiceEffects && num5 > 0.00316f && _dropLeft <= 0 && _garbLeft <= 0)
		{
			if (Rand() < DropPerSec * num6)
			{
				StartDropout();
			}
			else if (Rand() < GarbPerSec * num6)
			{
				StartGarble();
			}
		}
		bool flag = mode == 3;
		float num7 = Hiss;
		if (mode == 2 || mode == 3)
		{
			num7 *= 0.5f;
		}
		uint num8 = (uint)(4.0 / (double)_sr * 4294967295.0);
		uint num9 = (uint)(40.0 / (double)_sr * 4294967295.0);
		float num10 = (flag ? 1.8f : 1.4f);
		float kA = _kA;
		float kB = _kB;
		float popDecay = _popDecay;
		float rampStep = _rampStep;
		float num11 = _lpA;
		float num12 = _lpB;
		float num13 = _pop;
		float num14 = _gain;
		float num15 = _phase;
		float num16 = _ringInc;
		int num17 = _dropLeft;
		int num18 = _garbLeft;
		int num19 = _burstLeft;
		int num20 = _chopLeft;
		int num21 = _holdCount;
		int holdN = _holdN;
		bool flag2 = _chopOn;
		uint num22 = _rng;
		int sr = _sr;
		float[] latch = _latch;
		for (int j = 0; j < num2; j++)
		{
			float num23 = 1f;
			if (num17 > 0)
			{
				num17--;
				num23 = 0f;
			}
			if (num14 != num23)
			{
				if (num14 < num23)
				{
					num14 += rampStep;
					if (num14 > num23)
					{
						num14 = num23;
					}
				}
				else
				{
					num14 -= rampStep;
					if (num14 < num23)
					{
						num14 = num23;
					}
				}
			}
			num22 ^= num22 << 13;
			num22 ^= num22 >> 17;
			num22 ^= num22 << 5;
			float num24 = (float)(num22 & 0xFFFFFF) * 1.1920929E-07f - 1f;
			num11 += kA * (num24 - num11);
			num12 += kB * (num11 - num12);
			float num25 = (num11 - num12) * 2.2f;
			uint num26 = num22 * 2654435761u;
			if (num26 < num8)
			{
				num13 = num24 * 0.9f;
			}
			num13 *= popDecay;
			if (num13 < 1E-05f && num13 > -1E-05f)
			{
				num13 = 0f;
			}
			float num27 = num25 * num7 * (3f - 2f * num14) + num13 * num7 * 6f;
			if (num19 > 0)
			{
				num19--;
				num27 += num25 * 0.12f;
				if (num26 < num9)
				{
					num13 = num24;
				}
			}
			bool flag3 = num18 > 0 || flag;
			float num28 = 1f;
			if (flag3)
			{
				if (num18 > 0)
				{
					num18--;
				}
				num15 += num16;
				if (num15 > (float)Math.PI * 2f)
				{
					num15 -= (float)Math.PI * 2f;
				}
				if (--num20 <= 0)
				{
					flag2 = !flag2;
					uint num29 = num22 * 747796405 + 2891336453u;
					num20 = (int)((0.03f + (float)(num29 >> 8) * 5.3644182E-09f) * (float)sr);
					if (flag && flag2)
					{
						num16 = (float)Math.PI * 2f * (30f + (float)((num29 >> 4) & 0xFFFF) * 0.00076293945f) / (float)sr;
					}
				}
				num28 = (float)Math.Sin(num15) * (flag2 ? num10 : (num10 * 0.06f));
				if (++num21 >= holdN)
				{
					num21 = 0;
				}
			}
			int num30 = j * ch;
			for (int k = 0; k < ch; k++)
			{
				float num31 = data[num30 + k];
				if (flag3)
				{
					int num32 = ((k < 8) ? k : 7);
					if (num21 == 0)
					{
						latch[num32] = num31;
					}
					num31 = latch[num32] * num28;
				}
				num31 = num31 * num14 + num27;
				if (num31 > 1f)
				{
					num31 = 1f;
				}
				else if (num31 < -1f)
				{
					num31 = -1f;
				}
				data[num30 + k] = num31;
			}
		}
		_lpA = num11;
		_lpB = num12;
		_pop = num13;
		_gain = num14;
		_phase = num15;
		_ringInc = num16;
		_dropLeft = num17;
		_garbLeft = num18;
		_burstLeft = num19;
		_chopLeft = num20;
		_holdCount = num21;
		_chopOn = flag2;
		_rng = num22;
	}
}
internal static class Sounds
{
	internal static AudioClip Static;

	internal static AudioClip Short;

	internal static AudioClip Lost;

	internal static bool Ready => (Object)(object)Static != (Object)null;

	internal static void Build()
	{
		int num = AudioSettings.outputSampleRate;
		if (num < 8000)
		{
			num = 48000;
		}
		Static = Make("SignalInterference_static", 1.5f, num, 1234);
		Short = Make("SignalInterference_short", 0.3f, num, 4321);
		Lost = Make("SignalInterference_lost", 0.5f, num, 2468);
	}

	private static AudioClip Make(string name, float seconds, int sr, int seed)
	{
		int num = Mathf.Max(64, (int)(seconds * (float)sr));
		float[] array = new float[num];
		Random random = new Random(seed);
		float num2 = 1f - Mathf.Exp((float)Math.PI * -6800f / (float)sr);
		float num3 = 1f - Mathf.Exp((float)Math.PI * -600f / (float)sr);
		float num4 = Mathf.Exp(-1f / (0.003f * (float)sr));
		float num5 = 0f;
		float num6 = 0f;
		float num7 = 0f;
		float num8 = 0.7f;
		int num9 = 0;
		for (int i = 0; i < num; i++)
		{
			if (--num9 <= 0)
			{
				num8 = 0.35f + (float)random.NextDouble() * 0.65f;
				num9 = (int)((0.02f + (float)random.NextDouble() * 0.06f) * (float)sr);
			}
			float num10 = (float)random.NextDouble() * 2f - 1f;
			num5 += num2 * (num10 - num5);
			num6 += num3 * (num5 - num6);
			if (random.NextDouble() < 25.0 / (double)sr)
			{
				num7 = ((float)random.NextDouble() * 2f - 1f) * (0.5f + (float)random.NextDouble() * 0.5f);
			}
			num7 *= num4;
			array[i] = (num5 - num6) * 2.2f * 0.5f * num8 + num7 * 0.5f;
		}
		float num11 = 0f;
		for (int j = 0; j < num; j++)
		{
			num11 = Mathf.Max(num11, Mathf.Abs(array[j]));
		}
		float num12 = ((num11 > 0f) ? (0.8f / num11) : 1f);
		int num13 = Mathf.Min(num / 4, (int)(0.005f * (float)sr));
		for (int k = 0; k < num; k++)
		{
			float num14 = 1f;
			if (k < num13)
			{
				num14 = (float)k / (float)num13;
			}
			else if (k > num - num13)
			{
				num14 = (float)(num - k) / (float)num13;
			}
			array[k] *= num12 * num14;
		}
		AudioClip obj = AudioClip.Create(name, num, 1, sr, false);
		obj.SetData(array, 0);
		((Object)obj).hideFlags = (HideFlags)61;
		return obj;
	}
}
internal static class WeatherLink
{
	private static bool _init;

	private static MethodInfo _getName;

	private static PropertyInfo _setupFinished;

	private static void Init()
	{
		if (_init)
		{
			return;
		}
		_init = true;
		try
		{
			Type type = QuietTypes.Find("WeatherRegistry.WeatherManager");
			if (!(type == null))
			{
				_getName = AccessTools.Method(type, "GetCurrentWeatherName", new Type[2]
				{
					typeof(SelectableLevel),
					typeof(bool)
				}, (Type[])null);
				_setupFinished = AccessTools.Property(type, "IsSetupFinished");
				if (_getName == null)
				{
					Plugin.Log.LogWarning((object)"WeatherRegistry found but GetCurrentWeatherName(level, bool) is missing; using the vanilla weather name.");
				}
			}
		}
		catch (Exception ex)
		{
			Plugin.Log.LogWarning((object)("WeatherRegistry lookup failed: " + ex.Message));
		}
	}

	private static string Ask(SelectableLevel level, bool ignoreOverride)
	{
		if ((Object)(object)level == (Object)null)
		{
			return "None";
		}
		Init();
		if (_getName != null)
		{
			try
			{
				if (_setupFinished == null || (bool)_setupFinished.GetValue(null, null))
				{
					string text = _getName.Invoke(null, new object[2] { level, ignoreOverride }) as string;
					if (!string.IsNullOrEmpty(text))
					{
						return text;
					}
				}
			}
			catch
			{
			}
		}
		return ((object)Unsafe.As<LevelWeatherType, LevelWeatherType>(ref level.currentWeather)/*cast due to .constrained prefix*/).ToString();
	}

	internal static string DisplayName(SelectableLevel level)
	{
		return Ask(level, ignoreOverride: false);
	}

	internal static string CurrentName(SelectableLevel level)
	{
		return Ask(level, ignoreOverride: true);
	}
}
internal static class FlareLink
{
	private static bool _init;

	private static bool _warned;

	private static PropertyInfo _instance;

	private static PropertyInfo _isActive;

	private static MethodInfo _getOrAdd;

	private static MethodInfo _enable;

	private static MethodInfo _clear;

	internal static bool Found
	{
		get
		{
			Init();
			if (_instance != null)
			{
				return _isActive != null;
			}
			return false;
		}
	}

	internal static bool CanFilter
	{
		get
		{
			Init();
			if (_getOrAdd != null)
			{
				return _enable != null;
			}
			return false;
		}
	}

	private static void Init()
	{
		if (_init)
		{
			return;
		}
		_init = true;
		try
		{
			Type type = QuietTypes.Find("VoxxWeatherPlugin.Weathers.SolarFlareWeather");
			if (type != null)
			{
				_instance = type.GetProperty("Instance", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
				_isActive = type.GetProperty("IsActive", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
			}
			Type type2 = QuietTypes.Find("VoxxWeatherPlugin.Behaviours.WalkieDistortionManager");
			if (type2 != null)
			{
				_getOrAdd = type2.GetMethod("GetOrAddFilter", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic, null, new Type[1] { typeof(AudioSource) }, null);
				Type type3 = ((_getOrAdd != null) ? _getOrAdd.ReturnType : null);
				if (type3 != null)
				{
					_enable = type2.GetMethod("EnableVoiceChatDistortion", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic, null, new Type[1] { type3 }, null);
				}
				_clear = type2.GetMethod("ClearFilterCache", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic, null, new Type[1] { typeof(AudioSource) }, null);
			}
			if (type != null && (_instance == null || _isActive == null))
			{
				Plugin.Log.LogWarning((object)"LethalElements found but SolarFlareWeather.Instance/IsActive is missing; flare days aren't detected.");
			}
		}
		catch (Exception ex)
		{
			Plugin.Log.LogWarning((object)("LethalElements lookup failed: " + ex.Message));
		}
	}

	internal static bool Active()
	{
		Init();
		if (_instance == null || _isActive == null)
		{
			return false;
		}
		try
		{
			object? value = _instance.GetValue(null, null);
			Object val = (Object)((value is Object) ? value : null);
			if (val == (Object)null)
			{
				return false;
			}
			return (bool)_isActive.GetValue(val, null);
		}
		catch
		{
			return false;
		}
	}

	internal static bool Attach(AudioSource src)
	{
		Init();
		if ((Object)(object)src == (Object)null)
		{
			return false;
		}
		if (!CanFilter)
		{
			if (!_warned)
			{
				_warned = true;
				Plugin.Log.LogWarning((object)"Solar flare day, but LethalElements' WalkieDistortionManager methods weren't found; Mimic+ lines get no flare distortion.");
			}
			return false;
		}
		try
		{
			object? obj = _getOrAdd.Invoke(null, new object[1] { src });
			Behaviour val = (Behaviour)((obj is Behaviour) ? obj : null);
			if ((Object)(object)val == (Object)null)
			{
				return false;
			}
			val.enabled = false;
			_enable.Invoke(null, new object[1] { val });
			return true;
		}
		catch (Exception ex)
		{
			if (!_warned)
			{
				_warned = true;
				Plugin.Log.LogWarning((object)("LethalElements filter attach failed: " + ex.Message));
			}
			return false;
		}
	}

	internal static void Forget(AudioSource src)
	{
		if ((Object)(object)src == (Object)null || _clear == null)
		{
			return;
		}
		try
		{
			_clear.Invoke(null, new object[1] { src });
		}
		catch
		{
		}
	}
}
internal static class MimicLink
{
	private static bool _init;

	private static Func<bool> _playing;

	internal static bool Found
	{
		get
		{
			Init();
			return _playing != null;
		}
	}

	private static void Init()
	{
		if (_init)
		{
			return;
		}
		_init = true;
		try
		{
			Type type = QuietTypes.Find("MimicPlus.RadioPlayer");
			if (!(type == null))
			{
				PropertyInfo property = type.GetProperty("Playing", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
				MethodInfo methodInfo = ((property != null) ? property.GetGetMethod(nonPublic: true) : null);
				if (methodInfo != null && methodInfo.ReturnType == typeof(bool))
				{
					_playing = (Func<bool>)Delegate.CreateDelegate(typeof(Func<bool>), methodInfo);
				}
			}
		}
		catch (Exception ex)
		{
			Plugin.Log.LogWarning((object)("Mimic+ lookup failed: " + ex.Message));
		}
	}

	internal static bool Playing()
	{
		if (!_init)
		{
			Init();
		}
		if (_playing == null)
		{
			return false;
		}
		try
		{
			return _playing();
		}
		catch
		{
			return false;
		}
	}
}
internal static class Net
{
	internal const string StateMsg = "jacob.signalinterference.state";

	internal const string BurstMsg = "jacob.signalinterference.burst";

	internal const string ReportMsg = "jacob.signalinterference.report";

	private const byte Version = 1;

	internal const byte ReportHello = 0;

	internal const byte ReportSymptom = 1;

	internal const byte ReportFailNextUsed = 2;

	private static CustomMessagingManager _registeredOn;

	private static NetworkManager _callbackOn;

	private static bool _warnedVersion;

	private static bool _helloSent;

	private static readonly float[] RateBuf = new float[19];

	internal static void EnsureRegistered()
	{
		//IL_004b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0055: Expected O, but got Unknown
		//IL_0062: Unknown result type (might be due to invalid IL or missing references)
		//IL_006c: Expected O, but got Unknown
		//IL_0078: Unknown result type (might be due to invalid IL or missing references)
		//IL_0082: Expected O, but got Unknown
		NetworkManager singleton = NetworkManager.Singleton;
		if ((Object)(object)singleton == (Object)null || !singleton.IsListening || singleton.CustomMessagingManager == null)
		{
			return;
		}
		if (_registeredOn != singleton.CustomMessagingManager)
		{
			_registeredOn = singleton.CustomMessagingManager;
			CustomMessagingManager customMessagingManager = singleton.CustomMessagingManager;
			customMessagingManager.RegisterNamedMessageHandler("jacob.signalinterference.state", new HandleNamedMessageDelegate(OnState));
			customMessagingManager.RegisterNamedMessageHandler("jacob.signalinterference.burst", new HandleNamedMessageDelegate(OnBurst));
			customMessagingManager.RegisterNamedMessageHandler("jacob.signalinterference.report", new HandleNamedMessageDelegate(OnReport));
			_helloSent = false;
		}
		if (!_helloSent && !singleton.IsServer && singleton.IsConnectedClient)
		{
			_helloSent = true;
			SendReport(0);
		}
		if (!((Object)(object)_callbackOn != (Object)(object)singleton))
		{
			return;
		}
		if ((Object)(object)_callbackOn != (Object)null)
		{
			try
			{
				_callbackOn.OnClientConnectedCallback -= OnClientConnected;
			}
			catch
			{
			}
		}
		_callbackOn = singleton;
		singleton.OnClientConnectedCallback += OnClientConnected;
	}

	internal static void Forget()
	{
		_registeredOn = null;
	}

	private static void OnClientConnected(ulong clientId)
	{
		try
		{
			NetworkManager singleton = NetworkManager.Singleton;
			if ((Object)(object)singleton != (Object)null && singleton.IsServer && clientId != 0L)
			{
				SendState(clientId);
			}
		}
		catch (Exception ex)
		{
			Plugin.Log.LogWarning((object)("Sending state to a new client failed: " + ex.Message));
		}
	}

	internal static void BroadcastState()
	{
		NetworkManager singleton = NetworkManager.Singleton;
		if ((Object)(object)singleton == (Object)null || !singleton.IsListening || !singleton.IsServer)
		{
			return;
		}
		EnsureRegistered();
		IReadOnlyList<ulong> connectedClientsIds = singleton.ConnectedClientsIds;
		for (int i = 0; i < connectedClientsIds.Count; i++)
		{
			if (connectedClientsIds[i] != 0L)
			{
				SendState(connectedClientsIds[i]);
			}
		}
	}

	private unsafe static void SendState(ulong clientId)
	{
		//IL_0041: Unknown result type (might be due to invalid IL or missing references)
		//IL_0047: Unknown result type (might be due to invalid IL or missing references)
		//IL_0057: Unknown result type (might be due to invalid IL or missing references)
		//IL_005d: Unknown result type (might be due to invalid IL or missing references)
		//IL_006d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0073: Unknown result type (might be due to invalid IL or missing references)
		//IL_0083: 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_0099: 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_00af: Unknown result type (might be due to invalid IL or missing references)
		//IL_00b5: Unknown result type (might be due to invalid IL or missing references)
		//IL_00c5: Unknown result type (might be due to invalid IL or missing references)
		//IL_00cb: Unknown result type (might be due to invalid IL or missing references)
		//IL_00db: Unknown result type (might be due to invalid IL or missing references)
		//IL_00e1: Unknown result type (might be due to invalid IL or missing references)
		//IL_00f1: Unknown result type (might be due to invalid IL or missing references)
		//IL_00f7: Unknown result type (might be due to invalid IL or missing references)
		//IL_011d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0123: Unknown result type (might be due to invalid IL or missing references)
		//IL_0133: Unknown result type (might be due to invalid IL or missing references)
		//IL_0139: Unknown result type (might be due to invalid IL or missing references)
		//IL_0149: Unknown result type (might be due to invalid IL or missing references)
		//IL_014f: Unknown result type (might be due to invalid IL or missing references)
		//IL_015f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0165: Unknown result type (might be due to invalid IL or missing references)
		//IL_0175: Unknown result type (might be due to invalid IL or missing references)
		//IL_017b: Unknown result type (might be due to invalid IL or missing references)
		//IL_018b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0191: Unknown result type (might be due to invalid IL or missing references)
		//IL_01ad: Unknown result type (might be due to invalid IL or missing references)
		//IL_01b3: Unknown result type (might be due to invalid IL or missing references)
		//IL_01d1: Unknown result type (might be due to invalid IL or missing references)
		NetworkManager singleton = NetworkManager.Singleton;
		if ((Object)(object)singleton == (Object)null || singleton.CustomMessagingManager == null)
		{
			return;
		}
		S.R.Write(RateBuf);
		FastBufferWriter val = default(FastBufferWriter);
		((FastBufferWriter)(ref val))..ctor(512, (Allocator)2, 4096);
		try
		{
			byte b = 1;
			((FastBufferWriter)(ref val)).WriteValueSafe<byte>(ref b, default(ForPrimitives));
			((FastBufferWriter)(ref val)).WriteValueSafe<bool>(ref S.Active, default(ForPrimitives));
			((FastBufferWriter)(ref val)).WriteValueSafe<int>(ref S.Severity, default(ForPrimitives));
			((FastBufferWriter)(ref val)).WriteValueSafe<float>(ref S.Factor, default(ForPrimitives));
			((FastBufferWriter)(ref val)).WriteValueSafe<int>(ref S.Source, default(ForPrimitives));
			((FastBufferWriter)(ref val)).WriteValueSafe<int>(ref S.DaySeed, default(ForPrimitives));
			((FastBufferWriter)(ref val)).WriteValueSafe<bool>(ref S.Revealed, default(ForPrimitives));
			((FastBufferWriter)(ref val)).WriteValueSafe<bool>(ref S.FailNext, default(ForPrimitives));
			((FastBufferWriter)(ref val)).WriteValueSafe<int>(ref S.ChancePercent, default(ForPrimitives));
			((FastBufferWriter)(ref val)).WriteValueSafe(S.Weather ?? "", false);
			((FastBufferWriter)(ref val)).WriteValueSafe<int>(ref S.Flags, default(ForPrimitives));
			((FastBufferWriter)(ref val)).WriteValueSafe<int>(ref S.RevealModeValue, default(ForPrimitives));
			((FastBufferWriter)(ref val)).WriteValueSafe<bool>(ref S.ShowOrbit, default(ForPrimitives));
			((FastBufferWriter)(ref val)).WriteValueSafe<int>(ref S.CodeTargetsValue, default(ForPrimitives));
			((FastBufferWriter)(ref val)).WriteValueSafe<int>(ref S.NoiseStyleValue, default(ForPrimitives));
			int num = 19;
			((FastBufferWriter)(ref val)).WriteValueSafe<int>(ref num, default(ForPrimitives));
			for (int i = 0; i < num; i++)
			{
				((FastBufferWriter)(ref val)).WriteValueSafe<float>(ref RateBuf[i], default(ForPrimitives));
			}
			singleton.CustomMessagingManager.SendNamedMessage("jacob.signalinterference.state", clientId, val, (NetworkDelivery)2);
		}
		finally
		{
			((IDisposable)(*(FastBufferWriter*)(&val))/*cast due to .constrained prefix*/).Dispose();
		}
	}

	private static void OnState(ulong sender, FastBufferReader r)
	{
		//IL_0022: 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)
		//IL_006b: 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_007e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0084: Unknown result type (might be due to invalid IL or missing references)
		//IL_0091: 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_00a4: Unknown result type (might be due to invalid IL or missing references)
		//IL_00aa: 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_00ca: 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_00dd: Unknown result type (might be due to invalid IL or missing references)
		//IL_00e3: Unknown result type (might be due to invalid IL or missing references)
		//IL_00f0: Unknown result type (might be due to invalid IL or missing references)
		//IL_00f6: Unknown result type (might be due to invalid IL or missing references)
		//IL_010d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0113: Unknown result type (might be due to invalid IL or missing references)
		//IL_0120: Unknown result type (might be due to invalid IL or missing references)
		//IL_0126: Unknown result type (might be due to invalid IL or missing references)
		//IL_0133: Unknown result type (might be due to invalid IL or missing references)
		//IL_0139: Unknown result type (might be due to invalid IL or missing references)
		//IL_0146: Unknown result type (might be due to invalid IL or missing references)
		//IL_014c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0159: Unknown result type (might be due to invalid IL or missing references)
		//IL_015f: Unknown result type (might be due to invalid IL or missing references)
		//IL_016c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0172: Unknown result type (might be due to invalid IL or missing references)
		//IL_019b: Unknown result type (might be due to invalid IL or missing references)
		//IL_01a1: Unknown result type (might be due to invalid IL or missing references)
		try
		{
			NetworkManager singleton = NetworkManager.Singleton;
			if ((Object)(object)singleton == (Object)null || singleton.IsServer)
			{
				return;
			}
			byte b = default(byte);
			((FastBufferReader)(ref r)).ReadValueSafe<byte>(ref b, default(ForPrimitives));
			if (b != 1)
			{
				if (!_warnedVersion)
				{
					_warnedVersion = true;
					Plugin.Log.LogWarning((object)("Host runs a different SignalInterference version (message v" + b + "); ignoring its state."));
				}
				return;
			}
			bool flag = default(bool);
			((FastBufferReader)(ref r)).ReadValueSafe<bool>(ref flag, default(ForPrimitives));
			int num = default(int);
			((FastBufferReader)(ref r)).ReadValueSafe<int>(ref num, default(ForPrimitives));
			float factor = default(float);
			((FastBufferReader)(ref r)).ReadValueSafe<float>(ref factor, default(ForPrimitives));
			int source = default(int);
			((FastBufferReader)(ref r)).ReadValueSafe<int>(ref source, default(ForPrimitives));
			int seed = default(int);
			((FastBufferReader)(ref r)).ReadValueSafe<int>(ref seed, default(ForPrimitives));
			bool revealed = default(bool);
			((FastBufferReader)(ref r)).ReadValueSafe<bool>(ref revealed, default(ForPrimitives));
			bool failNext = default(bool);
			((FastBufferReader)(ref r)).ReadValueSafe<bool>(ref failNext, default(ForPrimitives));
			int chance = default(int);
			((FastBufferReader)(ref r)).ReadValueSafe<int>(ref chance, default(ForPrimitives));
			string weather = default(string);
			((FastBufferReader)(ref r)).ReadValueSafe(ref weather, false);
			int flags = default(int);
			((FastBufferReader)(ref r)).ReadValueSafe<int>(ref flags, default(ForPrimitives));
			int revealMode = default(int);
			((FastBufferReader)(ref r)).ReadValueSafe<int>(ref revealMode, default(ForPrimitives));
			bool showOrbit = default(bool);
			((FastBufferReader)(ref r)).ReadValueSafe<bool>(ref showOrbit, default(ForPrimitives));
			int codeTargets = default(int);
			((FastBufferReader)(ref r)).ReadValueSafe<int>(ref codeTargets, default(ForPrimitives));
			int noiseStyle = default(int);
			((FastBufferReader)(ref r)).ReadValueSafe<int>(ref noiseStyle, default(ForPrimitives));
			int num2 = default(int);
			((FastBufferReader)(ref r)).ReadValueSafe<int>(ref num2, default(ForPrimitives));
			float[] array = new float[Math.Max(19, Math.Min(num2, 64))];
			float num3 = default(float);
			for (int i = 0; i < num2 && i < 64; i++)
			{
				((FastBufferReader)(ref r)).ReadValueSafe<float>(ref num3, default(ForPrimitives));
				array[i] = num3;
			}
			bool active = S.Active;
			S.ApplyFromHost(flag, num, factor, source, seed, revealed, failNext, chance, weather, flags, revealMode, showOrbit, codeTargets, noiseStyle, array);
			if (flag != active)
			{
				Plugin.Log.LogInfo((object)(flag ? ("Host: signal interference started (" + Odds.SeverityName(num) + ").") : "Host: signal interference ended."));
			}
		}
		catch (Exception ex)
		{
			Plugin.Log.LogWarning((object)("Bad state message: " + ex.Message));
		}
	}

	internal unsafe static void BroadcastBurst(int kind, int seed, float duration, int count)
	{
		//IL_0056: Unknown result type (might be due to invalid IL or missing references)
		//IL_005c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0069: Unknown result type (might be due to invalid IL or missing references)
		//IL_006f: Unknown result type (might be due to invalid IL or missing references)
		//IL_007c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0082: Unknown result type (might be due to invalid IL or missing references)
		//IL_008f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0095: 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_00c1: Unknown result type (might be due to invalid IL or missing references)
		NetworkManager singleton = NetworkManager.Singleton;
		if ((Object)(object)singleton == (Object)null || !singleton.IsListening || !singleton.IsServer || singleton.CustomMessagingManager == null)
		{
			return;
		}
		IReadOnlyList<ulong> connectedClientsIds = singleton.ConnectedClientsIds;
		FastBufferWriter val = default(FastBufferWriter);
		for (int i = 0; i < connectedClientsIds.Count; i++)
		{
			if (connectedClientsIds[i] != 0L)
			{
				((FastBufferWriter)(ref val))..ctor(32, (Allocator)2, -1);
				try
				{
					byte b = 1;
					((FastBufferWriter)(ref val)).WriteValueSafe<byte>(ref b, default(ForPrimitives));
					((FastBufferWriter)(ref val)).WriteValueSafe<int>(ref kind, default(ForPrimitives));
					((FastBufferWriter)(ref val)).WriteValueSafe<int>(ref seed, default(ForPrimitives));
					((FastBufferWriter)(ref val)).WriteValueSafe<float>(ref duration, default(ForPrimitives));
					((FastBufferWriter)(ref val)).WriteValueSafe<int>(ref count, default(ForPrimitives));
					singleton.CustomMessagingManager.SendNamedMessage("jacob.signalinterference.burst", connectedClientsIds[i], val, (NetworkDelivery)2);
				}
				finally
				{
					((IDisposable)(*(FastBufferWriter*)(&val))/*cast due to .constrained prefix*/).Dispose();
				}
			}
		}
	}

	private static void OnBurst(ulong sender, FastBufferReader r)
	{
		//IL_0022: 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)
		//IL_003b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0041: Unknown result type (might be due to invalid IL or missing references)
		//IL_004e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0054: Unknown result type (might be due to invalid IL or missing references)
		//IL_0061: Unknown result type (might be due to invalid IL or missing references)
		//IL_0067: Unknown result type (might be due to invalid IL or missing references)
		//IL_0074: 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)
		try
		{
			NetworkManager singleton = NetworkManager.Singleton;
			if (!((Object)(object)singleton == (Object)null) && !singleton.IsServer)
			{
				byte b = default(byte);
				((FastBufferReader)(ref r)).ReadValueSafe<byte>(ref b, default(ForPrimitives));
				if (b == 1)
				{
					int kind = default(int);
					((FastBufferReader)(ref r)).ReadValueSafe<int>(ref kind, default(ForPrimitives));
					int seed = default(int);
					((FastBufferReader)(ref r)).ReadValueSafe<int>(ref seed, default(ForPrimitives));
					float duration = default(float);
					((FastBufferReader)(ref r)).ReadValueSafe<float>(ref duration, default(ForPrimitives));
					int count = default(int);
					((FastBufferReader)(ref r)).ReadValueSafe<int>(ref count, default(ForPrimitives));
					Bursts.Run(kind, seed, duration, count);
				}
			}
		}
		catch (Exception ex)
		{
			Plugin.Log.LogWarning((object)("Bad burst message: " + ex.Message));
		}
	}

	internal unsafe static void SendReport(byte kind)
	{
		//IL_0042: 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_0054: Unknown result type (might be due to invalid IL or missing references)
		//IL_005a: Unknown result type (might be due to invalid IL or missing references)
		//IL_006d: Unknown result type (might be due to invalid IL or missing references)
		NetworkManager singleton = NetworkManager.Singleton;
		if ((Object)(object)singleton == (Object)null || !singleton.IsListening || singleton.IsServer || !singleton.IsConnectedClient || singleton.CustomMessagingManager == null)
		{
			return;
		}
		FastBufferWriter val = default(FastBufferWriter);
		((FastBufferWriter)(ref val))..ctor(8, (Allocator)2, -1);
		try
		{
			byte b = 1;
			((FastBufferWriter)(ref val)).WriteValueSafe<byte>(ref b, default(ForPrimitives));
			((FastBufferWriter)(ref val)).WriteValueSafe<byte>(ref kind, default(ForPrimitives));
			singleton.CustomMessagingManager.SendNamedMessage("jacob.signalinterference.report", 0uL, val, (NetworkDelivery)2);
		}
		finally
		{
			((IDisposable)(*(FastBufferWriter*)(&val))/*cast due to .constrained prefix*/).Dispose();
		}
	}

	private static void OnReport(ulong sender, FastBufferReader r)
	{
		//IL_0022: 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)
		//IL_003a: Unknown result type (might be due to invalid IL or missing references)
		//IL_0040: Unknown result type (might be due to invalid IL or missing references)
		try
		{
			NetworkManager singleton = NetworkManager.Singleton;
			if ((Object)(object)singleton == (Object)null || !singleton.IsServer)
			{
				return;
			}
			byte b = default(byte);
			((FastBufferReader)(ref r)).ReadValueSafe<byte>(ref b, default(ForPrimitives));
			if (b != 1)
			{
				return;
			}
			byte b2 = default(byte);
			((FastBufferReader)(ref r)).ReadValueSafe<byte>(ref b2, default(ForPrimitives));
			switch (b2)
			{
			case 0:
				SendState(sender);
				break;
			case 1:
				Reveal.HostReveal("seen on the other PC");
				break;
			case 2:
				if (S.FailNext)
				{
					S.FailNext = false;
					BroadcastState();
				}
				break;
			}
		}
		catch (Exception ex)
		{
			Plugin.Log.LogWarning((object)("Bad report message: " + ex.Message));
		}
	}
}
internal static class Odds
{
	public const string DefaultWeatherPercents = "stormy:30, auroraborealis:20, eclipsed:8, blackout:10, blizzard:10, blackfog:8, rainy:6, dustclouds:6, foggy:5, toxicsmog:5, flooded:4, snowfall:4, heatwave:4, cloudy:3, none:2, solarflare:0, eclipsedflare:0";

	public static string Normalise(string s)
	{
		if (string.IsNullOrEmpty(s))
		{
			return "";
		}
		StringBuilder stringBuilder = new StringBuilder(s.Length);
		foreach (char c in s)
		{
			if (!char.IsWhiteSpace(c) && c != '-' && c != '_')
			{
				stringBuilder.Append(char.ToLowerInvariant(c));
			}
		}
		return stringBuilder.ToString();
	}

	public static string LandingPart(string weather)
	{
		if (string.IsNullOrEmpty(weather))
		{
			return "None";
		}
		int num = weather.IndexOf('>');
		string text = ((num >= 0) ? weather.Substring(0, num) : weather).Trim();
		if (text.Length != 0)
		{
			return text;
		}
		return "None";
	}

	public static string LaterPart(string weather)
	{
		if (string.IsNullOrEmpty(weather))
		{
			return null;
		}
		int num = weather.LastIndexOf('>');
		if (num < 0)
		{
			return null;
		}
		string text = weather.Substring(num + 1).Trim();
		if (text.Length != 0)
		{
			return text;
		}
		return null;
	}

	public static Dictionary<string, float> ParseTable(string cfg, List<string> problems)
	{
		Dictionary<string, float> dictionary = new Dictionary<string, float>();
		if (string.IsNullOrEmpty(cfg))
		{
			return dictionary;
		}
		string[] array = cfg.Split(',');
		for (int i = 0; i < array.Length; i++)
		{
			string text = array[i].Trim();
			if (text.Length != 0)
			{
				int num = text.IndexOf(':');
				if (num <= 0 || !float.TryParse(text.Substring(num + 1).Trim(), NumberStyles.Float, CultureInfo.InvariantCulture, out var result))
				{
					problems?.Add(text);
				}
				else
				{
					dictionary[Normalise(text.Substring(0, num))] = Math.Max(0f, result);
				}
			}
		}
		return dictionary;
	}

	public static float WeatherPercent(string weather, Dictionary<string, float> table, float unknown)
	{
		string text = LandingPart(weather);
		float num = -1f;
		float num2 = -1f;
		string[] array = text.Split('+');
		for (int i = 0; i < array.Length; i++)
		{
			string text2 = Normalise(array[i]);
			if (text2.Length != 0)
			{
				if (table == null || !table.TryGetValue(text2, out var value))
				{
					value = unknown;
				}
				if (value > num)
				{
					num2 = num;
					num = value;
				}
				else if (value > num2)
				{
					num2 = value;
				}
			}
		}
		if (num < 0f)
		{
			if (table == null || !table.TryGetValue("none", out var value2))
			{
				return unknown;
			}
			return value2;
		}
		return num + ((num2 > 0f) ? (num2 * 0.5f) : 0f);
	}

	public static bool IsStormLike(string weather)
	{
		string[] array = LandingPart(weather).Split('+');
		for (int i = 0; i < array.Length; i++)
		{
			string text = Normalise(array[i]);
			if (text == "stormy" || text == "auroraborealis")
			{
				return true;
			}
		}
		return false;
	}

	public static float Chance(float weatherPct, float moonMult, bool yesterdayWasInterference, float repeatMult, float maxPct)
	{
		float num = weatherPct * moonMult * (yesterdayWasInterference ? repeatMult : 1f);
		if (num < 0f)
		{
			num = 0f;
		}
		if (num > maxPct)
		{
			num = maxPct;
		}
		return num;
	}

	public static int PickSeverity(Random r, int[] weights, bool stormLike, float bump)
	{
		int num = 0;
		for (int i = 0; i < 3; i++)
		{
			num += Math.Max(0, (weights != null && i < weights.Length) ? weights[i] : 0);
		}
		int num2 = 1;
		if (num > 0)
		{
			int num3 = r.Next(num);
			int num4 = 0;
			for (int j = 0; j < 3; j++)
			{
				num4 += Math.Max(0, weights[j]);
				if (num3 < num4)
				{
					num2 = j + 1;
					break;
				}
			}
		}
		if (stormLike && num2 < 3 && r.NextDouble() < (double)bump)
		{
			num2++;
		}
		return num2;
	}

	public static string MoonKey(string planetName)
	{
		if (string.IsNullOrEmpty(planetName))
		{
			return "";
		}
		string text = planetName.Trim();
		int i;
		for (i = 0; i < text.Length && (char.IsDigit(text[i]) || char.IsWhiteSpace(text[i])); i++)
		{
		}
		if (i < text.Length)
		{
			text = text.Substring(i);
		}
		return Normalise(text);
	}

	public static HashSet<string> ParseMoonList(string cfg)
	{
		HashSet<string> hashSet = new HashSet<string>();
		if (string.IsNullOrEmpty(cfg))
		{
			return hashSet;
		}
		string[] array = cfg.Split(',');
		for (int i = 0; i < array.Length; i++)
		{
			string text = MoonKey(array[i]);
			if (text.Length > 0)
			{
				hashSet.Add(text);
			}
		}
		return hashSet;
	}

	public static Dictionary<string, float> ParseMoonMultipliers(string cfg, List<string> problems)
	{
		Dictionary<string, float> dictionary = new Dictionary<string, float>();
		if (string.IsNullOrEmpty(cfg))
		{
			return dictionary;
		}
		string[] array = cfg.Split(',');
		for (int i = 0; i < array.Length; i++)
		{
			string text = array[i].Trim();
			if (text.Length != 0)
			{
				int num = text.LastIndexOf(':');
				if (num <= 0 || !float.TryParse(text.Substring(num + 1).Trim(), NumberStyles.Float, CultureInfo.InvariantCulture, out var result))
				{
					problems?.Add(text);
				}
				else
				{
					dictionary[MoonKey(text.Substring(0, num))] = Math.Max(0f, result);
				}
			}
		}
		return dictionary;
	}

	public static bool TryParseRange(string s, out float a, out float b)
	{
		a = (b = 0f);
		if (string.IsNullOrEmpty(s))
		{
			return false;
		}
		string[] array = s.Split('-');
		if (array.Length == 1)
		{
			if (!float.TryParse(array[0].Trim(), NumberStyles.Float, CultureInfo.InvariantCulture, out a))
			{
				return false;
			}
			b = a;
			return a >= 0f;
		}
		if (array.Length != 2)
		{
			return false;
		}
		if (!float.TryParse(array[0].Trim(), NumberStyles.Float, CultureInfo.InvariantCulture, out a))
		{
			return false;
		}
		if (!float.TryParse(array[1].Trim(), NumberStyles.Float, CultureInfo.InvariantCulture, out b))
		{
			return false;
		}
		if (a < 0f || b < 0f)
		{
			return false;
		}
		if (b < a)
		{
			float num = a;
			a = b;
			b = num;
		}
		return true;
	}

	public static int[] ParseWeights(string s)
	{
		int[] result = new int[3] { 50, 35, 15 };
		if (string.IsNullOrEmpty(s))
		{
			return result;
		}
		string[] array = s.Split(',');
		if (array.Length != 3)
		{
			return result;
		}
		int[] array2 = new int[3];
		for (int i = 0; i < 3; i++)
		{
			if (!int.TryParse(array[i].Trim(), NumberStyles.Integer, CultureInfo.InvariantCulture, out array2[i]) || array2[i] < 0)
			{
				return result;
			}
		}
		if (array2[0] + array2[1] + array2[2] <= 0)
		{
			return result;
		}
		return array2;
	}

	public static string SeverityName(int s)
	{
		return s switch
		{
			1 => "Mild", 
			2 => "Moderate", 
			3 => "Severe", 
			_ => "None", 
		};
	}

	public static string MoonLine(int severity)
	{
		return severity switch
		{
			1 => "Radio: patchy signal today", 
			2 => "Radio: poor signal today", 
			3 => "Radio: signal breaking up today", 
			_ => null, 
		};
	}

	public static string OrbitLine(int chancePercent, string landingWeather)
	{
		if (chancePercent <= 0)
		{
			return null;
		}
		string text = LandingPart(landingWeather);
		if (Normalise(text) == "none")
		{
			return "Radio interference: " + chancePercent + "% (clear weather)";
		}
		return "Radio interference: " + chancePercent + "% on " + text;
	}
}
internal sealed class Rates
{
	public const int Count = 19;

	public float Hiss;

	public float DropRate;

	public float DropMin;

	public float DropMax;

	public float GarbRate;

	public float GarbMin;

	public float GarbMax;

	public float CrackMin;

	public float CrackMax;

	public float GhostMin;

	public float GhostMax;

	public float RadarMin;

	public float RadarMax;

	public float FreezeShare;

	public float CodeFail;

	public float TransCorrupt;

	public float TransLost;

	public float FlickMin;

	public float FlickMax;

	public static Rates ForSeverity(int s)
	{
		Rates rates = new Rates();
		switch (s)
		{
		case 1:
			rates.Set(0.015f, 0.5f, 0.15f, 0.6f, 0.3f, 0.4f, 1f, 60f, 120f, 240f, 480f, 180f, 360f, 0f, 0.1f, 0.15f, 0f, 0f, 0f);
			break;
		case 2:
			rates.Set(0.03f, 1.2f, 0.2f, 0.8f, 0.8f, 0.5f, 1.5f, 30f, 90f, 120f, 300f, 90f, 240f, 0.3f, 0.2f, 0.3f, 0.1f, 180f, 360f);
			break;
		case 3:
			rates.Set(0.05f, 2.5f, 0.3f, 1.2f, 1.5f, 0.8f, 2f, 15f, 60f, 60f, 180f, 40f, 120f, 0.5f, 0.3f, 0.45f, 0.2f, 60f, 180f);
			break;
		}
		return rates;
	}

	private void Set(float hiss, float dr, float dmin, float dmax, float gr, float gmin, float gmax, float cmin, float cmax, float ghmin, float ghmax, float rmin, float rmax, float freeze, float code, float corrupt, float lost, float fmin, float fmax)
	{
		Hiss = hiss;
		DropRate = dr;
		DropMin = dmin;
		DropMax = dmax;
		GarbRate = gr;
		GarbMin = gmin;
		GarbMax = gmax;
		CrackMin = cmin;
		CrackMax = cmax;
		GhostMin = ghmin;
		GhostMax = ghmax;
		RadarMin = rmin;
		RadarMax = rmax;
		FreezeShare = freeze;
		CodeFail = code;
		TransCorrupt = corrupt;
		TransLost = lost;
		FlickMin = fmin;
		FlickMax = fmax;
	}

	public void Write(float[] a)
	{
		a[0] = Hiss;
		a[1] = DropRate;
		a[2] = DropMin;
		a[3] = DropMax;
		a[4] = GarbRate;
		a[5] = GarbMin;
		a[6] = GarbMax;
		a[7] = CrackMin;
		a[8] = CrackMax;
		a[9] = GhostMin;
		a[10] = GhostMax;
		a[11] = RadarMin;
		a[12] = RadarMax;
		a[13] = FreezeShare;
		a[14] = CodeFail;
		a[15] = TransCorrupt;
		a[16] = TransLost;
		a[17] = FlickMin;
		a[18] = FlickMax;
	}

	public void Read(float[] a)
	{
		Set(a[0], a[1], a[2], a[3], a[4], a[5], a[6], a[7], a[8], a[9], a[10], a[11], a[12], a[13], a[14], a[15], a[16], a[17], a[18]);
	}

	public void CopyFrom(Rates o)
	{
		float[] a = new float[19];
		o.Write(a);
		Read(a);
	}

	public void Clear()
	{
		Read(new float[19]);
	}
}
public enum RevealMode
{
	AfterFirstSymptom,
	OnLanding,
	Never
}
public enum CodeTargets
{
	All,
	DoorsOnly,
	HazardsOnly
}
public enum NoiseStyle
{
	Auto,
	LostSignal,
	Static
}
[BepInPlugin("jacob.signalinterference", "SignalInterference", "1.0.1")]
[BepInDependency(/*Could not decode attribute arguments.*/)]
[BepInDependency(/*Could not decode attribute arguments.*/)]
public class Plugin : BaseUnityPlugin
{
	public const string Guid = "jacob.signalinterference";

	public const string Name = "SignalInterference";

	public const string Version = "1.0.1";

	internal static ManualLogSource Log;

	internal static Runner RunnerInstance;

	internal static ConfigEntry<bool> Enabled;

	internal static ConfigEntry<string> WeatherPercents;

	internal static ConfigEntry<float> UnknownWeatherPercent;

	internal static ConfigEntry<string> MoonMultipliers;

	internal static ConfigEntry<float> MaxChancePercent;

	internal static ConfigEntry<float> RepeatMultiplier;

	internal static ConfigEntry<string> SeverityWeights;

	internal static ConfigEntry<float> StormBump;

	internal static ConfigEntry<string> ExcludedMoons;

	internal static ConfigEntry<string> StartDelaySeconds;

	internal static ConfigEntry<string> CalmSpellSeconds;

	internal static ConfigEntry<string> BadSpellSeconds;

	internal static ConfigEntry<float> CalmFactor;

	internal static ConfigEntry<float> BadFactor;

	internal static ConfigEntry<bool> VoiceEnabled;

	internal static ConfigEntry<float> HissScale;

	internal static ConfigEntry<float> DropoutScale;

	internal static ConfigEntry<float> GarbleScale;

	internal static ConfigEntry<bool> FilterRelayedSounds;

	internal static ConfigEntry<bool> FilterWalkieChildSources;

	internal static ConfigEntry<bool> Crackle;

	internal static ConfigEntry<bool> GhostTransmissions;

	internal static ConfigEntry<float> GhostVoiceShare;

	internal static ConfigEntry<float> GhostQuietSeconds;

	internal static ConfigEntry<bool> HeldWalkiesOnly;

	internal static ConfigEntry<bool> RadarEnabled;

	internal static ConfigEntry<bool> AllowFreeze;

	internal static ConfigEntry<bool> LightningGlitch;

	internal static ConfigEntry<NoiseStyle> MapNoiseStyle;

	internal static ConfigEntry<bool> CodeFailEnabled;

	internal static ConfigEntry<float> CodeFailScale;

	internal static ConfigEntry<CodeTargets> CodeFailTargets;

	internal static ConfigEntry<bool> NeverFailTwiceInARow;

	internal static ConfigEntry<bool> CodeFailCrackle;

	internal static ConfigEntry<bool> TranslatorEnabled;

	internal static ConfigEntry<bool> LoseMessages;

	internal static ConfigEntry<bool> Flicker;

	internal static ConfigEntry<RevealMode> RevealInDayInfo;

	internal static ConfigEntry<bool> ShowChanceInOrbit;

	internal static ConfigEntry<bool> LogRolls;

	internal static ConfigEntry<bool> LogVoiceComponents;

	private int _patched;

	private int _failed;

	private void Awake()
	{
		//IL_0016: Unknown result type (might be due to invalid IL or missing references)
		//IL_001c: Expected O, but got Unknown
		//IL_01c9: Unknown result type (might be due to invalid IL or missing references)
		//IL_01ce: Unknown result type (might be due to invalid IL or missing references)
		//IL_01d6: Unknown result type (might be due to invalid IL or missing references)
		//IL_01dc: Expected O, but got Unknown
		Log = ((BaseUnityPlugin)this).Logger;
		BindConfig();
		Harmony h = new Harmony("jacob.signalinterference");
		Patch(h, typeof(RoundManager), "FinishGeneratingNewLevelClientRpc", null, "AfterLevelGenerated");
		Patch(h, typeof(StartOfRound), "OnShipLandedMiscEvents", null, "AfterShipLanded");
		Patch(h, typeof(StartOfRound), "ShipLeave", null, "AfterShipLeave");
		Patch(h, typeof(StartOfRound), "ShipHasLeft", null, "AfterShipHasLeft");
		Patch(h, typeof(StartOfRound), "SetShipReadyToLand", null, "AfterBackInOrbit");
		Patch(h, typeof(StartOfRound), "Start", null, "AfterStartOfRoundStart");
		Patch(h, typeof(StartOfRound), "UpdatePlayerVoiceEffects", null, "AfterUpdatePlayerVoiceEffects");
		Patch(h, typeof(StartOfRound), "RefreshPlayerVoicePlaybackObjects", null, "AfterRefreshVoiceObjects");
		Patch(h, typeof(PlayerVoiceIngameSettings), "OnDisable", "BeforeVoiceSettingsDisable", null);
		Patch(h, typeof(ManualCameraRenderer), "MeetsCameraEnabledConditions", "BeforeMeetsCameraEnabledConditions", "AfterMeetsCameraEnabledConditions");
		Patch(h, typeof(ManualCameraRenderer), "Update", null, "AfterCameraUpdate");
		Patch(h, typeof(StormyWeather), "LightningStrike", null, "AfterLightningStrike");
		Patch(h, typeof(Terminal), "CallFunctionInAccessibleTerminalObject", "BeforeBroadcastCode", null);
		Patch(h, typeof(HUDManager), "DisplaySignalTranslatorMessage", "BeforeSignalTranslatorMessage", null);
		Patch(h, typeof(FlashlightItem), "Start", null, "AfterFlashlightStart");
		GameObject val = new GameObject("SignalInterferenceRunner")
		{
			hideFlags = (HideFlags)61
		};
		Object.DontDestroyOnLoad((Object)val);
		RunnerInstance = val.AddComponent<Runner>();
		try
		{
			Sounds.Build();
		}
		catch (Exception ex)
		{
			((BaseUnityPlugin)this).Logger.LogWarning((object)("Couldn't generate the static sound: " + ex.Message + ". Walkie crackle and ghost calls are off."));
		}
		((BaseUnityPlugin)this).Logger.LogInfo((object)("SignalInterference 1.0.1 loaded (" + _patched + " hooks" + ((_failed > 0) ? (", " + _failed + " missing") : "") + "). Enabled=" + Enabled.Value + "."));
	}

	private void BindConfig()
	{
		Enabled = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "Enabled", true, "Master switch. Host's value decides whether interference days happen at all.");
		WeatherPercents = ((BaseUnityPlugin)this).Config.Bind<string>("Odds", "WeatherPercents", "stormy:30, auroraborealis:20, eclipsed:8, blackout:10, blizzard:10, blackfog:8, rainy:6, dustclouds:6, foggy:5, toxicsmog:5, flooded:4, snowfall:4, heatwave:4, cloudy:3, none:2, solarflare:0, eclipsedflare:0", "Chance per landing by weather, as name:percent pairs. Names are lower case without spaces (\"Black Fog\" = blackfog). Combined weathers use the highest part plus half the second highest. Progressing weathers (\"None > Stormy\") use the part before '>' at landing, and roll once more mid-day when the weather changes. Host's value is used.");
		UnknownWeatherPercent = ((BaseUnityPlugin)this).Config.Bind<float>("Odds", "UnknownWeatherPercent", 3f, "Percent for a weather not in WeatherPercents.");
		MoonMultipliers = ((BaseUnityPlugin)this).Config.Bind<string>("Odds", "MoonMultipliers", "", "Per-moon multipliers, e.g. Titan:1.3, E