Decompiled source of TemporalStorm v0.0.1

BepInEx/plugins/TemporalStormWeather.dll

Decompiled 4 hours ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using BasedDecorPlacement.API;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Configuration;
using BepInEx.Logging;
using BrutalCompanyMinus;
using BrutalCompanyMinus.Minus;
using BrutalCompanyMinus.Minus.Handlers.Modded;
using Coroner;
using CullFactory;
using CullFactory.Extenders;
using Cysharp.Threading.Tasks;
using Cysharp.Threading.Tasks.CompilerServices;
using Dawn;
using GameNetcodeStuff;
using HarmonyLib;
using HatLib.Tools;
using Microsoft.CodeAnalysis;
using PathfindingLib.API.SmartPathfinding;
using PathfindingLib.Utilities;
using TMPro;
using TemporalStormWeather.API;
using TemporalStormWeather.Compat;
using TemporalStormWeather.Compat.BCMERCompat;
using TemporalStormWeather.Compat.BCMERCompat.Events.LocustSwarm;
using TemporalStormWeather.Compat.BCMERCompat.Events.RusticAllItems;
using TemporalStormWeather.Compat.BCMERCompat.Events.TemporalAllItems;
using TemporalStormWeather.Compat.BCMERCompat.Events.WorldOfRust;
using TemporalStormWeather.Enemies;
using TemporalStormWeather.Hazards;
using TemporalStormWeather.Items;
using TemporalStormWeather.NetcodePatcher;
using TemporalStormWeather.Patches;
using TemporalStormWeather.TemporalStormManagers;
using TemporalStormWeather.TemporalStormManagers.Helpers;
using TemporalStormWeather.TemporalStormManagers.RustLightning;
using TemporalStormWeather.Unlockables;
using TemporalStormWeather.Utils;
using Unity.Netcode;
using UnityEngine;
using UnityEngine.AI;
using UnityEngine.Animations;
using UnityEngine.Events;
using UnityEngine.Experimental.Rendering;
using UnityEngine.LowLevel;
using UnityEngine.Rendering;
using UnityEngine.Rendering.HighDefinition;
using UnityEngine.SceneManagement;

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

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

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

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

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace TemporalStormWeather
{
	internal static class ConfigManager
	{
		private static readonly DuskConfigInjector DuskConfig = new DuskConfigInjector("MrHat.TemporalStormWeather");

		internal static ConfigEntry<bool> TemporalRiftSkipDisabledEnemies { get; private set; } = null;

		internal static ConfigEntry<bool> TemporalRiftRespectEnemyMaxCount { get; private set; } = null;

		internal static ConfigEntry<bool> TemporalRiftUseCurrentMoonEnemyList { get; private set; } = null;

		internal static ConfigEntry<bool> TemporalRiftUnrestrictEnemySpawns { get; private set; } = null;

		internal static ConfigEntry<float> TemporalRiftLocustOnlyRiftChance { get; private set; } = null;

		internal static ConfigEntry<int> TemporalRiftMinimumLocustSpawnCount { get; private set; } = null;

		internal static ConfigEntry<int> TemporalRiftMaximumLocustSpawnCount { get; private set; } = null;

		internal static ConfigEntry<float> TemporalRiftMinimumEnemyPowerBudget { get; private set; } = null;

		internal static ConfigEntry<float> TemporalRiftMaximumEnemyPowerBudget { get; private set; } = null;

		internal static ConfigEntry<string> TemporalRiftInsideEnemyBlacklist { get; private set; } = null;

		internal static ConfigEntry<string> TemporalRiftOutsideEnemyBlacklist { get; private set; } = null;

		internal static ConfigEntry<bool> EntityGlitchEnabled { get; private set; } = null;

		internal static ConfigEntry<bool> EntityGlitchPlayerModels { get; private set; } = null;

		internal static ConfigEntry<string> EntityGlitchEnemyBlacklist { get; private set; } = null;

		internal static ConfigEntry<bool> AudioPitchingEnabled { get; private set; } = null;

		internal static void BindConfigs()
		{
			TemporalRiftSkipDisabledEnemies = DuskConfig.Bind<bool>("Temporal Rift Options", "Skip disabled enemies", true, "If true, temporal rifts will not spawn enemies marked as spawning disabled");
			TemporalRiftRespectEnemyMaxCount = DuskConfig.Bind<bool>("Temporal Rift Options", "Respect enemy max count", false, "If true, temporal rifts will not spawn an enemy after its max count allowed on the moon is reached");
			TemporalRiftUseCurrentMoonEnemyList = DuskConfig.Bind<bool>("Temporal Rift Options", "Use current moon enemy list", true, "If true, temporal rifts can only spawn enemies from the current moon's spawnable enemy lists. This option respects 'Inside/Outside enemy blacklists'");
			TemporalRiftUnrestrictEnemySpawns = DuskConfig.Bind<bool>("Temporal Rift Options", "Unrestrict enemy spawns", false, "If true and StarlancerAIFix is installed, temporal rifts ignore inside/outside enemy location restrictions. This option respects 'Use current moon enemy list' and 'Inside/Outside enemy blacklists'");
			TemporalRiftLocustOnlyRiftChance = DuskConfig.Bind<float>("Temporal Rift Options", "Locust only rift chance", 0.85f, "Chance for a temporal rift to only spawn locust enemies, e.g 0.8 = 85% chance");
			TemporalRiftMinimumLocustSpawnCount = DuskConfig.Bind<int>("Temporal Rift Options", "Min locust spawn count", 1, "Minimum number of locusts spawned at once by a locust only rift");
			TemporalRiftMaximumLocustSpawnCount = DuskConfig.Bind<int>("Temporal Rift Options", "Max locust spawn count", 3, "Maximum number of locusts spawned at once by a locust only rift");
			TemporalRiftMinimumEnemyPowerBudget = DuskConfig.Bind<float>("Temporal Rift Options", "Minimum enemy power budget", 2f, "Minimum enemy power budget assigned to a temporal rift");
			TemporalRiftMaximumEnemyPowerBudget = DuskConfig.Bind<float>("Temporal Rift Options", "Maximum enemy power budget", 4f, "Maximum enemy power budget assigned to a temporal rift");
			TemporalRiftInsideEnemyBlacklist = DuskConfig.Bind<string>("Temporal Rift Options", "Inside enemy blacklist", "lethal_company:butler_bees,lethal_company:girl", "DawnLib enemy namespaced keys that inside temporal rifts cannot spawn, separated by commas");
			TemporalRiftOutsideEnemyBlacklist = DuskConfig.Bind<string>("Temporal Rift Options", "Outside enemy blacklist", "lethal_company:red_locust_bees,lethal_company:manticoil,lethal_company:docile_locust_bees,lethal_company:feiopar,lethal_company:giantkiwi,lethal_company:bush_wolf,lethallib:sparktower,code_rebirth:tornado,code_rebirth:guardsman", "DawnLib enemy namespaced keys that outside temporal rifts cannot spawn, separated by commas");
			EntityGlitchEnabled = DuskConfig.Bind<bool>("Temporal Storm Visual Options", "Entity Glitch Enabled", true, "If true, temporal instability can apply glitch materials to entities");
			EntityGlitchPlayerModels = DuskConfig.Bind<bool>("Temporal Storm Visual Options", "Player models glitch", true, "If true, temporal instability can apply glitch materials to other player models");
			EntityGlitchEnemyBlacklist = DuskConfig.Bind<string>("Temporal Storm Visual Options", "Enemy Blacklist", "lethal_company:girl,lethal_company:blob,lethal_company:clay_surgeon,surfaced:mantis_shrimp,surfaced:urchin,surfaced:horse,surfaced:scary,lethallib:shrimp,lethallib:sparktower,lethallib:tourist,lethallib:tour_bus,code_rebirth:tornado,code_rebirth:mistress", "DawnLib enemy namespaced keys that cannot receive temporal glitch effects, separated by commas");
			AudioPitchingEnabled = DuskConfig.Bind<bool>("Temporal Storm Audio Options", "Audio Pitching Enabled", true, "If true, temporal instability can pitch and filter active audio sources");
		}
	}
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInPlugin("MrHat.TemporalStormWeather.Internals", "TemporalStormWeather", "0.0.1")]
	internal class Plugin : BaseUnityPlugin
	{
		private const string DawnLibGUID = "com.github.teamxiaolan.dawnlib";

		private const string DuskGUID = "com.github.teamxiaolan.dawnlib.dusk";

		private const string PathfindingLibGUID = "Zaggy1024.PathfindingLib";

		private const string HatLibGUID = "MrHat.Lib";

		private const string BasedDecorPlacementGUID = "MrHat.BasedDecorPlacement";

		private const string CullFactoryGUID = "com.fumiko.CullFactory";

		private const string BrutalCompanyMinusExtraRebornGUID = "SoftDiamond.BrutalCompanyMinusExtraReborn";

		private const string StarlancerAIFixGUID = "AudioKnight.StarlancerAIFix";

		private const string CoronerGUID = "com.elitemastereric.coroner";

		internal const string modGUID = "MrHat.TemporalStormWeather.Internals";

		internal const string modName = "TemporalStormWeather";

		internal const string modVersion = "0.0.1";

		internal static ManualLogSource? mls;

		internal static bool hasBasedDecorPlacement;

		internal static bool hasCullFactory;

		internal static bool hasBCMER;

		internal static bool hasStarlancerAIFix;

		internal static bool hasCoroner;

		private readonly Harmony _harmony = new Harmony("MrHat.TemporalStormWeather.Internals");

		internal static Plugin? Instance { get; private set; }

		private void Awake()
		{
			//IL_0142: Unknown result type (might be due to invalid IL or missing references)
			//IL_0147: Unknown result type (might be due to invalid IL or missing references)
			Instance = this;
			mls = Logger.CreateLogSource("MrHat.TemporalStormWeather.Internals");
			Log.Info("                   +++     +++");
			Log.Info("            ++     ++++   ++++     ++");
			Log.Info("           +++++ +++++++++++++++ +++++");
			Log.Info("            +++++++++++++++++++++++++");
			Log.Info("      ++++++++++++++++++++++++++++++++++++++");
			Log.Info("      +++++++++++++++++++++++++++++++++++++");
			Log.Info("        +++++++++++    ++++    +++++++++++");
			Log.Info("  ++++++++++++++       ++++       ++++++++++++++");
			Log.Info(" +++++++++++++         ++++         +++++++++++++");
			Log.Info("     +++++++++++++   ++++++++   +++++++++++++");
			Log.Info("    ++++++++ ++++++++++++++++++++++++ ++++++++");
			Log.Info("+++++++++++     +++++++     ++++++     +++++++++++");
			Log.Info("+++++++++++      ++++        ++++      +++++++++++");
			Log.Info("    +++++++      ++++        ++++      +++++++");
			Log.Info("    +++++++     ++++++      ++++++     +++++++");
			Log.Info("++++++++++++ ++++++++++++++++++++++++ ++++++++++++");
			Log.Info(" ++++++++++++++++    ++++++++    ++++++++++++++++");
			Log.Info("     +++++++++         ++++         +++++++++");
			Log.Info("     +++++++++++       ++++        ++++++++++");
			Log.Info("   +++++++++++++++     ++++     +++++++++++++++");
			Log.Info("    +++  ++++++++++++++++++++++++++++++++  +++");
			Log.Info("          ++++++++++++++++++++++++++++++");
			Log.Info("         ++++++++++++++++++++++++++++++++");
			Log.Info("          ++    ++++++++++++++++++    ++");
			Log.Info("                ++++   ++++   ++++");
			Log.Info("                 ++    ++++    ++");
			if (!PlayerLoopHelper.IsInjectedUniTaskPlayerLoop())
			{
				PlayerLoopSystem currentPlayerLoop = PlayerLoop.GetCurrentPlayerLoop();
				PlayerLoopHelper.Initialize(ref currentPlayerLoop, (InjectPlayerLoopTimings)65535);
			}
			hasBasedDecorPlacement = Chainloader.PluginInfos.ContainsKey("MrHat.BasedDecorPlacement");
			hasCullFactory = Chainloader.PluginInfos.ContainsKey("com.fumiko.CullFactory");
			hasBCMER = Chainloader.PluginInfos.ContainsKey("SoftDiamond.BrutalCompanyMinusExtraReborn");
			hasStarlancerAIFix = Chainloader.PluginInfos.ContainsKey("AudioKnight.StarlancerAIFix");
			hasCoroner = Chainloader.PluginInfos.ContainsKey("com.elitemastereric.coroner");
			ConfigManager.BindConfigs();
			DawnSaveManager.HookItemEffectSave();
			InitialiseNetworkBehaviour(typeof(BellEnemyAI));
			InitialiseNetworkBehaviour(typeof(LocustEnemyBase));
			InitialiseNetworkBehaviour(typeof(LocustEnemyAI));
			InitialiseNetworkBehaviour(typeof(SawbladeLocustEnemyAI));
			InitialiseNetworkBehaviour(typeof(CorruptLocustEnemyAI));
			InitialiseNetworkBehaviour(typeof(GearPileHazard));
			InitialiseNetworkBehaviour(typeof(TemporalRift));
			InitialiseNetworkBehaviour(typeof(TemporalGearItem));
			InitialiseNetworkBehaviour(typeof(ResonatorSurface));
			InitialiseNetworkBehaviour(typeof(RustHazardManager));
			InitialiseNetworkBehaviour(typeof(TemporalInstabilityManager));
			Log.Info("TemporalStormWeather 0.0.1 loaded");
			_harmony.PatchAll(typeof(EnemyAIPatches));
			_harmony.PatchAll(typeof(FlashlightItemPatches));
			_harmony.PatchAll(typeof(GameNetworkManagerPatches));
			_harmony.PatchAll(typeof(GrabbableObjectPatches));
			_harmony.PatchAll(typeof(HUDManagerPatches));
			_harmony.PatchAll(typeof(LungPropPatches));
			_harmony.PatchAll(typeof(NetworkManagerPatches));
			_harmony.PatchAll(typeof(PlayerControllerBPatches));
			_harmony.PatchAll(typeof(SoundManagerPatches));
			_harmony.PatchAll(typeof(StartOfRoundPatches));
			_harmony.PatchAll(typeof(ChatGlitchManager));
			_harmony.PatchAll(typeof(TimeOfDayPatches));
			if (hasBasedDecorPlacement)
			{
				Log.Debug("Running BasedDecorPlacement compatibility");
				BasedDecorPlacementCompat.RegisterSurfaceExtensions();
				Log.Info("BasedDecorPlacement compatibility enabled");
			}
			if (hasCullFactory)
			{
				Log.Debug("Running CullFactory compatibility");
				_harmony.PatchAll(typeof(CullFactoryCompat));
				Log.Info("CullFactory compatibility enabled");
			}
			if (hasBCMER)
			{
				Log.Debug("Running Brutal Company Minus Extra Reborn compatibility");
				BCMERCompatibility.RegisterEvents();
				_harmony.PatchAll(typeof(BCMERCompatibility));
				Log.Info("Brutal Company Minus Extra Reborn compatibility enabled");
			}
			if (hasCoroner)
			{
				Log.Debug("Running Coroner compatibility");
				CoronerCompat.Register();
				Log.Info("Coroner compatibility enabled");
			}
		}

		private void InitialiseNetworkBehaviour(Type type)
		{
			MethodInfo[] methods = type.GetMethods(BindingFlags.Instance | BindingFlags.Static | BindingFlags.NonPublic);
			MethodInfo[] array = methods;
			foreach (MethodInfo methodInfo in array)
			{
				object[] customAttributes = methodInfo.GetCustomAttributes(typeof(RuntimeInitializeOnLoadMethodAttribute), inherit: false);
				if (customAttributes.Length != 0)
				{
					methodInfo.Invoke(null, null);
				}
			}
		}
	}
	public static class MyPluginInfo
	{
		public const string PLUGIN_GUID = "TemporalStormWeather";

		public const string PLUGIN_NAME = "TemporalStormWeather";

		public const string PLUGIN_VERSION = "0.0.1";
	}
}
namespace TemporalStormWeather.Utils
{
	internal static class Keys
	{
		public const string DuskGUID = "MrHat.TemporalStormWeather";

		public const string AssetBundleName = "temporalstormotherassets";

		public const string TemporalInstabilityNetworkPrefabPath = "Assets/LethalCompany/Mods/plugins/TemporalStormWeather/Content/Temporal Storm/TemporalInstabilityNetwork.prefab";

		public const string TemporalStormAmbienceLibraryPath = "Assets/LethalCompany/Mods/plugins/TemporalStormWeather/Content/Temporal Storm/TemporalStormAmbienceLibrary.asset";

		public const string Namespace = "temporalstorm";

		public const string TemporalStorm = "temporal_storm";

		public const string TemporalRift = "temporal_rift";

		public const string ItemEffects = "item_effects";

		public const string GearsPile = "gears_pile";

		public const string LargeSpikesPile = "large_spikes_pile";

		public const string MediumSpikesPile = "medium_spikes_pile";

		public const string SmallSpikesPile = "small_spikes_pile";

		public const string SpikesOne = "spikesone";

		public const string SpikesTwo = "spikestwo";

		public const string SpikesThree = "spikesthree";

		public const string TinySpikesPile = "tiny_spikes_pile";

		public const string TemporalGear = "temporal_gear";

		public const string MadnessGear = "madness_gear";

		public const string LocustEnemy = "locust_enemy";

		public const string SawbladeLocustEnemy = "sawblade_locust_enemy";

		public const string CorruptLocustEnemy = "corrupt_locust_enemy";

		public static readonly NamespacedKey<DawnWeatherEffectInfo> TemporalStormWeather = NamespacedKey<DawnWeatherEffectInfo>.From("temporalstorm", "temporal_storm");

		public static readonly NamespacedKey<DawnMapObjectInfo> TemporalRiftMapObject = NamespacedKey<DawnMapObjectInfo>.From("temporalstorm", "temporal_rift");

		public static readonly NamespacedKey ItemEffectsSaveData = NamespacedKey.From("temporalstorm", "item_effects");

		public static readonly NamespacedKey<DawnMapObjectInfo> GearsPileMapObject = NamespacedKey<DawnMapObjectInfo>.From("temporalstorm", "gears_pile");

		public static readonly NamespacedKey<DawnMapObjectInfo> LargeSpikesPileMapObject = NamespacedKey<DawnMapObjectInfo>.From("temporalstorm", "large_spikes_pile");

		public static readonly NamespacedKey<DawnMapObjectInfo> MediumSpikesPileMapObject = NamespacedKey<DawnMapObjectInfo>.From("temporalstorm", "medium_spikes_pile");

		public static readonly NamespacedKey<DawnMapObjectInfo> SmallSpikesPileMapObject = NamespacedKey<DawnMapObjectInfo>.From("temporalstorm", "small_spikes_pile");

		public static readonly NamespacedKey<DawnMapObjectInfo> SpikesOneMapObject = NamespacedKey<DawnMapObjectInfo>.From("temporalstorm", "spikesone");

		public static readonly NamespacedKey<DawnMapObjectInfo> SpikesTwoMapObject = NamespacedKey<DawnMapObjectInfo>.From("temporalstorm", "spikestwo");

		public static readonly NamespacedKey<DawnMapObjectInfo> SpikesThreeMapObject = NamespacedKey<DawnMapObjectInfo>.From("temporalstorm", "spikesthree");

		public static readonly NamespacedKey<DawnMapObjectInfo> TinySpikesPileMapObject = NamespacedKey<DawnMapObjectInfo>.From("temporalstorm", "tiny_spikes_pile");

		public static readonly NamespacedKey<DawnItemInfo> TemporalGearItem = NamespacedKey<DawnItemInfo>.From("temporalstorm", "temporal_gear");

		public static readonly NamespacedKey<DawnItemInfo> MadnessGearItem = NamespacedKey<DawnItemInfo>.From("temporalstorm", "madness_gear");

		public static readonly NamespacedKey<DawnEnemyInfo> LocustEnemyInfo = NamespacedKey<DawnEnemyInfo>.From("temporalstorm", "locust_enemy");

		public static readonly NamespacedKey<DawnEnemyInfo> SawbladeLocustEnemyInfo = NamespacedKey<DawnEnemyInfo>.From("temporalstorm", "sawblade_locust_enemy");

		public static readonly NamespacedKey<DawnEnemyInfo> CorruptLocustEnemyInfo = NamespacedKey<DawnEnemyInfo>.From("temporalstorm", "corrupt_locust_enemy");

		public static readonly NamespacedKey<DawnMapObjectInfo>[] TemporalRustMapObjects = new NamespacedKey<DawnMapObjectInfo>[7] { LargeSpikesPileMapObject, MediumSpikesPileMapObject, SmallSpikesPileMapObject, SpikesOneMapObject, SpikesTwoMapObject, SpikesThreeMapObject, TinySpikesPileMapObject };
	}
	internal static class Log
	{
		public static void Debug(string message)
		{
			Write((LogLevel)32, message);
		}

		public static void Info(string message)
		{
			Write((LogLevel)16, message);
		}

		public static void Warn(string message)
		{
			Write((LogLevel)4, message);
		}

		public static void Error(string message)
		{
			Write((LogLevel)2, message);
		}

		public static void Fatal(string message)
		{
			Write((LogLevel)1, message);
		}

		private static void Write(LogLevel logLevel, string message)
		{
			//IL_0014: Unknown result type (might be due to invalid IL or missing references)
			if (Plugin.mls != null)
			{
				Plugin.mls.Log(logLevel, (object)message);
			}
		}
	}
	internal static class Utility
	{
		public static void BindPositionConstraint(PositionConstraint positionConstraint, Transform sourceTransform)
		{
			//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_0039: Unknown result type (might be due to invalid IL or missing references)
			if (positionConstraint.sourceCount > 0)
			{
				ConstraintSource source = positionConstraint.GetSource(0);
				if (!((Object)(object)((ConstraintSource)(ref source)).sourceTransform == (Object)(object)sourceTransform))
				{
					((ConstraintSource)(ref source)).sourceTransform = sourceTransform;
					positionConstraint.SetSource(0, source);
				}
			}
		}

		public static float ClampInstability(float value)
		{
			return Mathf.Clamp(value, 0f, 100f);
		}

		public static float InstabilityProgress(float temporalInstabilityLevel, float startLevel, float fullLevel)
		{
			return Mathf.InverseLerp(startLevel, fullLevel, temporalInstabilityLevel);
		}

		public static bool ShouldRunWeatherLifecycle()
		{
			return (Object)(object)StartOfRound.Instance != (Object)null && (Object)(object)RoundManager.Instance?.currentLevel != (Object)null && (Object)(object)TimeOfDay.Instance != (Object)null;
		}

		public static PlayerControllerB LocalPlayer()
		{
			return GameNetworkManager.Instance.localPlayerController;
		}

		public static Camera? LocalViewCamera()
		{
			PlayerControllerB val = LocalPlayer();
			if (val != null && val.isPlayerDead && (Object)(object)StartOfRound.Instance?.spectateCamera != (Object)null)
			{
				return StartOfRound.Instance.spectateCamera;
			}
			return val?.gameplayCamera;
		}

		public static Transform? LocalViewTransform()
		{
			Camera? obj = LocalViewCamera();
			return (obj != null) ? ((Component)obj).transform : null;
		}

		public static bool LocalViewIsInsideFactory()
		{
			PlayerControllerB val = LocalPlayer();
			if (val != null && val.isPlayerDead && (Object)(object)val.spectatedPlayerScript != (Object)null)
			{
				return val.spectatedPlayerScript.isInsideFactory;
			}
			return val?.isInsideFactory ?? false;
		}

		public static bool IsPlayerActive(PlayerControllerB? player)
		{
			return player != null && player.isPlayerControlled && !player.isPlayerDead;
		}

		public static float RandomRange(Random random, float minimum, float maximum)
		{
			return Mathf.Lerp(minimum, maximum, (float)random.NextDouble());
		}

		public static float RandomRange(Random random, Vector2 range)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			return RandomRange(random, range.x, range.y);
		}
	}
	internal static class MapSpawnUtils
	{
		public static bool MatchesOutsideFloorTags(Collider collider, string[] spawnableFloorTags)
		{
			if (spawnableFloorTags == null || spawnableFloorTags.Length == 0)
			{
				return true;
			}
			for (int i = 0; i < spawnableFloorTags.Length; i++)
			{
				if (((Component)collider).CompareTag(spawnableFloorTags[i]))
				{
					return true;
				}
			}
			return false;
		}

		public static bool TryRaycastClosest(Vector3 origin, Vector3 direction, RaycastHit[] hits, float maxDistance, int layerMask, QueryTriggerInteraction queryTriggerInteraction, out RaycastHit closestHit)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_0017: 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_0029: Unknown result type (might be due to invalid IL or missing references)
			//IL_005b: Unknown result type (might be due to invalid IL or missing references)
			//IL_005c: Unknown result type (might be due to invalid IL or missing references)
			int num = Physics.RaycastNonAlloc(origin, direction, hits, maxDistance, layerMask, queryTriggerInteraction);
			float num2 = float.MaxValue;
			closestHit = default(RaycastHit);
			for (int i = 0; i < num; i++)
			{
				RaycastHit val = hits[i];
				if (!((Object)(object)((RaycastHit)(ref val)).collider == (Object)null) && !(((RaycastHit)(ref val)).distance >= num2))
				{
					num2 = ((RaycastHit)(ref val)).distance;
					closestHit = val;
				}
			}
			return (Object)(object)((RaycastHit)(ref closestHit)).collider != (Object)null;
		}

		public static bool IsDeniedOutsidePosition(Vector3 position, float objectWidth, EntranceTeleport[] entranceTeleports, Transform[] shipSpawnPathPoints, GameObject[] spawnDenialPoints, GameObject itemShipLandingNode)
		{
			//IL_0025: Unknown result type (might be due to invalid IL or missing references)
			//IL_0026: Unknown result type (might be due to invalid IL or missing references)
			//IL_002b: Unknown result type (might be due to invalid IL or missing references)
			//IL_002c: Unknown result type (might be due to invalid IL or missing references)
			//IL_002d: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0033: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ae: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b3: Unknown result type (might be due to invalid IL or missing references)
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0140: Unknown result type (might be due to invalid IL or missing references)
			//IL_0145: Unknown result type (might be due to invalid IL or missing references)
			//IL_0100: Unknown result type (might be due to invalid IL or missing references)
			//IL_0105: Unknown result type (might be due to invalid IL or missing references)
			Collider shipBounds = StartOfRound.Instance.shipBounds;
			if ((Object)(object)shipBounds != (Object)null)
			{
				float num = Mathf.Max(0f, objectWidth);
				Vector3 val = shipBounds.ClosestPoint(position);
				Vector3 val2 = val - position;
				if (((Vector3)(ref val2)).sqrMagnitude <= num * num)
				{
					return true;
				}
			}
			if (shipSpawnPathPoints != null)
			{
				for (int i = 0; i < shipSpawnPathPoints.Length; i++)
				{
					if (Vector3.Distance(shipSpawnPathPoints[i].position, position) < objectWidth + 6f)
					{
						return true;
					}
				}
			}
			for (int j = 0; j < entranceTeleports.Length; j++)
			{
				if (Vector3.Distance(((Component)entranceTeleports[j]).transform.position, position) < objectWidth + 6f)
				{
					return true;
				}
			}
			if (spawnDenialPoints != null)
			{
				for (int k = 0; k < spawnDenialPoints.Length; k++)
				{
					if (Vector3.Distance(spawnDenialPoints[k].transform.position, position) < objectWidth)
					{
						return true;
					}
				}
			}
			return (Object)(object)itemShipLandingNode != (Object)null && Vector3.Distance(itemShipLandingNode.transform.position, position) < objectWidth;
		}

		public static void DestroyTreesAroundOutsideObject(SpawnableOutsideObject spawnableObject, Vector3 position)
		{
			//IL_0028: Unknown result type (might be due to invalid IL or missing references)
			//IL_002d: Unknown result type (might be due to invalid IL or missing references)
			//IL_004d: Unknown result type (might be due to invalid IL or missing references)
			if (!spawnableObject.destroyTrees)
			{
				return;
			}
			GameObject[] array = GameObject.FindGameObjectsWithTag("Tree");
			for (int i = 0; i < array.Length; i++)
			{
				if (Vector3.Distance(array[i].transform.position, position) < (float)spawnableObject.objectWidth)
				{
					RoundManager.Instance.DestroyTreeAtPosition(array[i].transform.position, 5f);
				}
			}
		}
	}
	internal readonly struct OriginalMaterialPropertyIds
	{
		public readonly int Texture;

		public readonly int Color;

		public readonly int AlphaClipThreshold;

		public readonly int NormalTexture;

		public readonly int NormalScale;

		public readonly int Smoothness;

		public readonly int Metallic;

		public OriginalMaterialPropertyIds(int texture, int color, int alphaClipThreshold, int normalTexture, int normalScale, int smoothness, int metallic = -1)
		{
			Texture = texture;
			Color = color;
			AlphaClipThreshold = alphaClipThreshold;
			NormalTexture = normalTexture;
			NormalScale = normalScale;
			Smoothness = smoothness;
			Metallic = metallic;
		}
	}
	internal readonly struct EffectMaterialPropertyIds
	{
		public readonly int BaseTexture;

		public readonly int BaseColorTint;

		public readonly int AlphaClipThreshold;

		public readonly int NormalTexture;

		public readonly int NormalScale;

		public readonly int Smoothness;

		public readonly int Metallic;

		public EffectMaterialPropertyIds(int baseTexture, int baseColorTint, int alphaClipThreshold, int normalTexture, int normalScale, int smoothness, int metallic = -1)
		{
			BaseTexture = baseTexture;
			BaseColorTint = baseColorTint;
			AlphaClipThreshold = alphaClipThreshold;
			NormalTexture = normalTexture;
			NormalScale = normalScale;
			Smoothness = smoothness;
			Metallic = metallic;
		}
	}
	internal enum MaterialPropertyCopyKind
	{
		Float,
		Color,
		Texture
	}
	internal static class MaterialUtils
	{
		private static readonly int alphaCutoffEnablePropertyId = Shader.PropertyToID("_AlphaCutoffEnable");

		private static readonly int emissiveColorPropertyId = Shader.PropertyToID("_EmissiveColor");

		private static readonly int emissionColorPropertyId = Shader.PropertyToID("_EmissionColor");

		private static readonly int surfaceTypePropertyId = Shader.PropertyToID("_SurfaceType");

		private static readonly int blendModePropertyId = Shader.PropertyToID("_BlendMode");

		private static readonly int zWritePropertyId = Shader.PropertyToID("_ZWrite");

		private static readonly int transparentZWritePropertyId = Shader.PropertyToID("_TransparentZWrite");

		private static readonly int[] copiedFloatPropertyIds = new int[35]
		{
			Shader.PropertyToID("_SurfaceType"),
			Shader.PropertyToID("_BlendMode"),
			Shader.PropertyToID("_AlphaSrcBlend"),
			Shader.PropertyToID("_AlphaDstBlend"),
			Shader.PropertyToID("_SrcBlend"),
			Shader.PropertyToID("_DstBlend"),
			Shader.PropertyToID("_ZWrite"),
			Shader.PropertyToID("_TransparentZWrite"),
			Shader.PropertyToID("_ZTest"),
			Shader.PropertyToID("_CullMode"),
			Shader.PropertyToID("_CullModeForward"),
			Shader.PropertyToID("_TransparentCullMode"),
			Shader.PropertyToID("_AlphaCutoffEnable"),
			Shader.PropertyToID("_DoubleSidedEnable"),
			Shader.PropertyToID("_TransparentDepthPrepassEnable"),
			Shader.PropertyToID("_TransparentDepthPostpassEnable"),
			Shader.PropertyToID("_TransparentWritesMotionVec"),
			Shader.PropertyToID("_EnableFogOnTransparent"),
			Shader.PropertyToID("_ReceivesSSR"),
			Shader.PropertyToID("_ReceivesSSRTransparent"),
			Shader.PropertyToID("_TransparentSortPriority"),
			Shader.PropertyToID("_EnableBlendModePreserveSpecularLighting"),
			Shader.PropertyToID("_SpecularOcclusionMode"),
			Shader.PropertyToID("_MaterialID"),
			Shader.PropertyToID("_DisplacementMode"),
			Shader.PropertyToID("_RefractionModel"),
			Shader.PropertyToID("_RefractionSSRayModel"),
			Shader.PropertyToID("_ReceivesDecals"),
			Shader.PropertyToID("_GeometricSpecularAA"),
			Shader.PropertyToID("_UseShadowThreshold"),
			Shader.PropertyToID("_PreRefractionPass"),
			Shader.PropertyToID("_RenderingPass"),
			Shader.PropertyToID("_EmissiveIntensity"),
			Shader.PropertyToID("_EmissiveExposureWeight"),
			Shader.PropertyToID("_AlbedoAffectEmissive")
		};

		private static readonly int[] copiedColorPropertyIds = new int[1] { Shader.PropertyToID("_TransmittanceColor") };

		private static readonly int[] copiedTexturePropertyIds = new int[7]
		{
			Shader.PropertyToID("_MaskMap"),
			Shader.PropertyToID("_BentNormalMap"),
			Shader.PropertyToID("_CoatMaskMap"),
			Shader.PropertyToID("_DetailMap"),
			Shader.PropertyToID("_EmissiveColorMap"),
			Shader.PropertyToID("_EmissionMap"),
			Shader.PropertyToID("_TransmittanceColorMap")
		};

		private static readonly string[] copiedMaterialKeywords = new string[12]
		{
			"_ALPHATEST_ON", "_SURFACE_TYPE_TRANSPARENT", "_BLENDMODE_ALPHA", "_BLENDMODE_ADD", "_BLENDMODE_PRE_MULTIPLY", "_BLENDMODE_PRESERVE_SPECULAR_LIGHTING", "_ENABLE_FOG_ON_TRANSPARENT", "_ENABLE_SSR_TRANSPARENT", "_DOUBLESIDED_ON", "_NORMALMAP_TANGENT_SPACE",
			"_EMISSION", "_EMISSIVE_COLOR_MAP"
		};

		public static bool IsCreatedEffectMaterial(Material? material, Material[]? originalMaterials, int materialIndex)
		{
			return (Object)(object)material != (Object)null && (originalMaterials == null || materialIndex >= originalMaterials.Length || (Object)(object)material != (Object)(object)originalMaterials[materialIndex]);
		}

		public static float CopyOriginalMaterialProperties(Material originalMaterial, Material effectMaterial, OriginalMaterialPropertyIds originalIds, EffectMaterialPropertyIds effectIds, float defaultAlphaClipThreshold)
		{
			//IL_0008: 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_01be: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b0: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c3: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f9: Unknown result type (might be due to invalid IL or missing references)
			//IL_01fe: Unknown result type (might be due to invalid IL or missing references)
			//IL_0200: Unknown result type (might be due to invalid IL or missing references)
			//IL_020d: Unknown result type (might be due to invalid IL or missing references)
			//IL_021b: Unknown result type (might be due to invalid IL or missing references)
			//IL_022b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0238: Unknown result type (might be due to invalid IL or missing references)
			//IL_0246: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ec: Unknown result type (might be due to invalid IL or missing references)
			//IL_01df: Unknown result type (might be due to invalid IL or missing references)
			//IL_0290: Unknown result type (might be due to invalid IL or missing references)
			//IL_0278: Unknown result type (might be due to invalid IL or missing references)
			//IL_0284: Unknown result type (might be due to invalid IL or missing references)
			//IL_0286: Unknown result type (might be due to invalid IL or missing references)
			effectMaterial.SetColor(effectIds.BaseColorTint, Color.white);
			float num = defaultAlphaClipThreshold;
			if ((Object)(object)originalMaterial == (Object)null)
			{
				return num;
			}
			effectMaterial.renderQueue = originalMaterial.renderQueue;
			effectMaterial.doubleSidedGI = originalMaterial.doubleSidedGI;
			effectMaterial.globalIlluminationFlags = originalMaterial.globalIlluminationFlags;
			effectMaterial.enableInstancing = originalMaterial.enableInstancing;
			string tag = originalMaterial.GetTag("RenderType", false, string.Empty);
			if (!string.IsNullOrEmpty(tag))
			{
				effectMaterial.SetOverrideTag("RenderType", tag);
			}
			string tag2 = originalMaterial.GetTag("Queue", false, string.Empty);
			if (!string.IsNullOrEmpty(tag2))
			{
				effectMaterial.SetOverrideTag("Queue", tag2);
			}
			for (int i = 0; i < copiedMaterialKeywords.Length; i++)
			{
				string text = copiedMaterialKeywords[i];
				if (originalMaterial.IsKeywordEnabled(text))
				{
					effectMaterial.EnableKeyword(text);
				}
				else
				{
					effectMaterial.DisableKeyword(text);
				}
			}
			string[] shaderKeywords = originalMaterial.shaderKeywords;
			for (int j = 0; j < shaderKeywords.Length; j++)
			{
				effectMaterial.EnableKeyword(shaderKeywords[j]);
			}
			CopyMatchingProperties(originalMaterial, effectMaterial, copiedFloatPropertyIds, MaterialPropertyCopyKind.Float);
			CopyMatchingProperties(originalMaterial, effectMaterial, copiedColorPropertyIds, MaterialPropertyCopyKind.Color);
			CopyMatchingProperties(originalMaterial, effectMaterial, copiedTexturePropertyIds, MaterialPropertyCopyKind.Texture);
			CopyTextureProperties(originalMaterial, effectMaterial, originalIds.Texture, effectIds.BaseTexture, (Texture?)(object)Texture2D.whiteTexture);
			bool flag = (originalMaterial.HasProperty(alphaCutoffEnablePropertyId) && originalMaterial.GetFloat(alphaCutoffEnablePropertyId) > 0.5f) || originalMaterial.IsKeywordEnabled("_ALPHATEST_ON");
			Color val = (originalMaterial.HasProperty(originalIds.Color) ? originalMaterial.GetColor(originalIds.Color) : Color.white);
			Color val2 = (originalMaterial.HasProperty(emissiveColorPropertyId) ? originalMaterial.GetColor(emissiveColorPropertyId) : (originalMaterial.HasProperty(emissionColorPropertyId) ? originalMaterial.GetColor(emissionColorPropertyId) : Color.black));
			float num2 = val.r * 0.2126f + val.g * 0.7152f + val.b * 0.0722f;
			float num3 = val2.r * 0.2126f + val2.g * 0.7152f + val2.b * 0.0722f;
			bool flag2 = num2 <= 0.035f && num3 > 0.035f;
			if (flag2)
			{
				val2.a = val.a;
				val = val2;
			}
			effectMaterial.SetColor(effectIds.BaseColorTint, val);
			if (originalMaterial.HasProperty(originalIds.AlphaClipThreshold) && effectMaterial.HasProperty(effectIds.AlphaClipThreshold))
			{
				num = (flag ? originalMaterial.GetFloat(originalIds.AlphaClipThreshold) : 0f);
				effectMaterial.SetFloat(effectIds.AlphaClipThreshold, num);
			}
			else if (effectMaterial.HasProperty(effectIds.AlphaClipThreshold))
			{
				num = (flag ? defaultAlphaClipThreshold : 0f);
				effectMaterial.SetFloat(effectIds.AlphaClipThreshold, num);
			}
			if (!flag)
			{
				SetFloatIfPresent(effectMaterial, alphaCutoffEnablePropertyId, 0f);
				effectMaterial.DisableKeyword("_ALPHATEST_ON");
			}
			CopyTextureProperties(originalMaterial, effectMaterial, originalIds.NormalTexture, effectIds.NormalTexture);
			if (originalMaterial.HasProperty(originalIds.NormalScale) && effectMaterial.HasProperty(effectIds.NormalScale))
			{
				effectMaterial.SetFloat(effectIds.NormalScale, originalMaterial.GetFloat(originalIds.NormalScale));
			}
			if (originalMaterial.HasProperty(originalIds.Smoothness) && effectMaterial.HasProperty(effectIds.Smoothness))
			{
				effectMaterial.SetFloat(effectIds.Smoothness, flag2 ? 0.045f : originalMaterial.GetFloat(originalIds.Smoothness));
			}
			if (originalIds.Metallic >= 0 && effectIds.Metallic >= 0 && originalMaterial.HasProperty(originalIds.Metallic) && effectMaterial.HasProperty(effectIds.Metallic))
			{
				effectMaterial.SetFloat(effectIds.Metallic, flag2 ? 0f : originalMaterial.GetFloat(originalIds.Metallic));
			}
			return num;
		}

		public static void ForceOpaqueCutout(Material material)
		{
			material.renderQueue = 2450;
			material.SetOverrideTag("RenderType", "TransparentCutout");
			material.SetOverrideTag("Queue", "AlphaTest");
			material.DisableKeyword("_SURFACE_TYPE_TRANSPARENT");
			material.DisableKeyword("_BLENDMODE_ALPHA");
			material.DisableKeyword("_BLENDMODE_ADD");
			material.DisableKeyword("_BLENDMODE_PRE_MULTIPLY");
			SetFloatIfPresent(material, surfaceTypePropertyId, 0f);
			SetFloatIfPresent(material, blendModePropertyId, 0f);
			SetFloatIfPresent(material, zWritePropertyId, 1f);
			SetFloatIfPresent(material, transparentZWritePropertyId, 1f);
		}

		public static void DestroyMaterials(Material[]? materials, Material[]? originalMaterials = null)
		{
			if (materials == null)
			{
				return;
			}
			for (int i = 0; i < materials.Length; i++)
			{
				Material val = materials[i];
				if (IsCreatedEffectMaterial(val, originalMaterials, i))
				{
					Object.Destroy((Object)(object)val);
				}
			}
		}

		public static void SetFloatOnCreatedMaterials(Material[]? materials, Material[]? originalMaterials, int propertyId, float value)
		{
			if (materials == null)
			{
				return;
			}
			for (int i = 0; i < materials.Length; i++)
			{
				Material val = materials[i];
				if (IsCreatedEffectMaterial(val, originalMaterials, i))
				{
					val.SetFloat(propertyId, value);
				}
			}
		}

		public static void CopyFromFirstProperty(Material? sourceMaterial, Material targetMaterial, int[] sourcePropertyIds, int targetPropertyId, MaterialPropertyCopyKind propertyKind, Texture? defaultTexture = null)
		{
			//IL_0079: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ad: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bc: Unknown result type (might be due to invalid IL or missing references)
			if (!targetMaterial.HasProperty(targetPropertyId))
			{
				return;
			}
			if ((Object)(object)sourceMaterial != (Object)null)
			{
				foreach (int num in sourcePropertyIds)
				{
					if (!sourceMaterial.HasProperty(num))
					{
						continue;
					}
					switch (propertyKind)
					{
					case MaterialPropertyCopyKind.Float:
						targetMaterial.SetFloat(targetPropertyId, sourceMaterial.GetFloat(num));
						return;
					case MaterialPropertyCopyKind.Color:
						targetMaterial.SetColor(targetPropertyId, sourceMaterial.GetColor(num));
						return;
					case MaterialPropertyCopyKind.Texture:
					{
						Texture texture = sourceMaterial.GetTexture(num);
						if ((Object)(object)texture == (Object)null)
						{
							break;
						}
						targetMaterial.SetTexture(targetPropertyId, texture);
						targetMaterial.SetTextureScale(targetPropertyId, sourceMaterial.GetTextureScale(num));
						targetMaterial.SetTextureOffset(targetPropertyId, sourceMaterial.GetTextureOffset(num));
						return;
					}
					}
				}
			}
			if (propertyKind == MaterialPropertyCopyKind.Texture && (Object)(object)defaultTexture != (Object)null)
			{
				targetMaterial.SetTexture(targetPropertyId, defaultTexture);
			}
		}

		private static void CopyTextureProperties(Material originalMaterial, Material effectMaterial, int originalPropertyId, int effectPropertyId, Texture? defaultTexture = null)
		{
			//IL_0062: 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)
			if (!effectMaterial.HasProperty(effectPropertyId))
			{
				return;
			}
			Texture val = (originalMaterial.HasProperty(originalPropertyId) ? originalMaterial.GetTexture(originalPropertyId) : null);
			if (!((Object)(object)val == (Object)null) || !((Object)(object)defaultTexture == (Object)null))
			{
				effectMaterial.SetTexture(effectPropertyId, val ?? defaultTexture);
				if (originalMaterial.HasProperty(originalPropertyId))
				{
					effectMaterial.SetTextureScale(effectPropertyId, originalMaterial.GetTextureScale(originalPropertyId));
					effectMaterial.SetTextureOffset(effectPropertyId, originalMaterial.GetTextureOffset(originalPropertyId));
				}
			}
		}

		private static void SetFloatIfPresent(Material material, int propertyId, float value)
		{
			if (material.HasProperty(propertyId))
			{
				material.SetFloat(propertyId, value);
			}
		}

		private static void CopyMatchingProperties(Material originalMaterial, Material effectMaterial, int[] propertyIds, MaterialPropertyCopyKind propertyKind)
		{
			//IL_005a: Unknown result type (might be due to invalid IL or missing references)
			//IL_008b: Unknown result type (might be due to invalid IL or missing references)
			//IL_009a: Unknown result type (might be due to invalid IL or missing references)
			foreach (int num in propertyIds)
			{
				if (!originalMaterial.HasProperty(num) || !effectMaterial.HasProperty(num))
				{
					continue;
				}
				switch (propertyKind)
				{
				case MaterialPropertyCopyKind.Float:
					effectMaterial.SetFloat(num, originalMaterial.GetFloat(num));
					break;
				case MaterialPropertyCopyKind.Color:
					effectMaterial.SetColor(num, originalMaterial.GetColor(num));
					break;
				case MaterialPropertyCopyKind.Texture:
				{
					Texture texture = originalMaterial.GetTexture(num);
					if (!((Object)(object)texture == (Object)null))
					{
						effectMaterial.SetTexture(num, texture);
						effectMaterial.SetTextureScale(num, originalMaterial.GetTextureScale(num));
						effectMaterial.SetTextureOffset(num, originalMaterial.GetTextureOffset(num));
					}
					break;
				}
				}
			}
		}
	}
	internal static class ParticleUtils
	{
		public static void SetEmissionRateAndPlayback(ParticleSystem particleSystem, float rate, ParticleSystemStopBehavior stopBehavior)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_000b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0046: Unknown result type (might be due to invalid IL or missing references)
			EmissionModule emission = particleSystem.emission;
			((EmissionModule)(ref emission)).rateOverTime = MinMaxCurve.op_Implicit(rate);
			if (rate > 0.001f)
			{
				if (!particleSystem.isPlaying)
				{
					particleSystem.Play(true);
				}
			}
			else if (particleSystem.isPlaying)
			{
				particleSystem.Stop(true, stopBehavior);
			}
		}
	}
	internal enum DawnItemPersistenceMode
	{
		PersistShip,
		Restore
	}
	internal static class DawnConfigUtils
	{
		public static HashSet<NamespacedKey<TInfo>> ParseNamespacedKeySet<TInfo>(string configuredKeys) where TInfo : INamespaced
		{
			HashSet<NamespacedKey<TInfo>> hashSet = new HashSet<NamespacedKey<TInfo>>();
			if (string.IsNullOrWhiteSpace(configuredKeys))
			{
				return hashSet;
			}
			string[] array = configuredKeys.Split(new char[4] { ',', ';', '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries);
			NamespacedKey val = default(NamespacedKey);
			for (int i = 0; i < array.Length; i++)
			{
				string text = array[i].Trim();
				if (NamespacedKey.TryParse(text, ref val))
				{
					hashSet.Add(val.AsTyped<TInfo>());
				}
			}
			return hashSet;
		}

		public static bool CanUseDawnItem(GrabbableObject item, bool includeNonConductive, DawnItemPersistenceMode persistenceMode)
		{
			return (Object)(object)item?.itemProperties != (Object)null && (item.itemProperties.isConductiveMetal || includeNonConductive) && (Object)(object)((Component)item).GetComponent<TemporalGearItem>() == (Object)null && ItemExtensions.GetDawnInfo(item.itemProperties) != null && (persistenceMode != DawnItemPersistenceMode.PersistShip || item.isInShipRoom) && !item.isHeld && (Object)(object)item.playerHeldBy == (Object)null && !item.isHeldByEnemy;
		}
	}
	internal static class ItemUtils
	{
		public static bool IsHeldByLocalPlayer(GrabbableObject item)
		{
			return (Object)(object)item?.playerHeldBy != (Object)null && (Object)(object)item.playerHeldBy == (Object)(object)Utility.LocalPlayer();
		}

		public static uint BuildItemSeed(GrabbableObject item)
		{
			ulong networkObjectId = ((NetworkBehaviour)item).NetworkObject.NetworkObjectId;
			uint num = 2166136261u;
			num = (num ^ (uint)(int)networkObjectId) * 16777619;
			num = (num ^ (uint)(int)(networkObjectId >> 32)) * 16777619;
			return (num ^ (uint)item.itemProperties.itemId) * 16777619;
		}

		public static uint Mix(uint value)
		{
			value ^= value >> 16;
			value *= 2246822519u;
			value ^= value >> 13;
			value *= 3266489917u;
			value ^= value >> 16;
			return value;
		}
	}
	internal static class TemporalMaterialUtils
	{
		public static void SetTemporalState(Renderer renderer, MaterialPropertyBlock propertyBlock, float glowStrength, float rustAmount)
		{
			renderer.GetPropertyBlock(propertyBlock);
			propertyBlock.SetFloat("_TemporalGlowStrength", glowStrength);
			propertyBlock.SetFloat("_TemporalRustAmount", rustAmount);
			renderer.SetPropertyBlock(propertyBlock);
		}
	}
	internal static class NetworkUtils
	{
		public static bool IsServer()
		{
			NetworkManager singleton = NetworkManager.Singleton;
			return singleton != null && singleton.IsServer;
		}

		public static bool IsServerOrNotNetworked()
		{
			NetworkManager singleton = NetworkManager.Singleton;
			return !singleton.IsListening || singleton.IsServer;
		}
	}
	internal static class AudioUtils
	{
		public static bool Configure2DAudioSource(AudioSource? audioSource, bool loop, float volume = 0f)
		{
			if ((Object)(object)audioSource == (Object)null)
			{
				return false;
			}
			audioSource.spatialBlend = 0f;
			audioSource.loop = loop;
			audioSource.playOnAwake = false;
			audioSource.volume = volume;
			return true;
		}

		public static void PlayOneShot(AudioSource? audioSource, AudioClip? audioClip, float volume)
		{
			if (!((Object)(object)audioSource == (Object)null) && !((Object)(object)audioClip == (Object)null))
			{
				audioSource.PlayOneShot(audioClip, volume);
			}
		}

		public static void LoadAudioClips(params AudioClip?[] audioClips)
		{
			int num = 0;
			foreach (AudioClip val in audioClips)
			{
				if (AudioTools.Load(val))
				{
					num++;
				}
			}
			if (num > 0)
			{
				Log.Info($"Loaded {num} audio clips");
			}
		}

		public static void UnloadAudioClips(params AudioClip?[] audioClips)
		{
			int num = 0;
			foreach (AudioClip val in audioClips)
			{
				if (AudioTools.Unload(val))
				{
					num++;
				}
			}
			if (num > 0)
			{
				Log.Info($"Unloaded {num} audio clips");
			}
		}
	}
	internal static class WeatherUtils
	{
		public static bool IsTemporalStormWeatherSelectedOrActive(bool checkSelected = true, bool checkActive = true)
		{
			//IL_0074: Unknown result type (might be due to invalid IL or missing references)
			//IL_007b: Expected I4, but got Unknown
			if ((Object)(object)TimeOfDay.Instance == (Object)null || (!checkSelected && !checkActive))
			{
				return false;
			}
			if (checkSelected)
			{
				SelectableLevel currentLevel = TimeOfDay.Instance.currentLevel;
				if ((Object)(object)currentLevel == (Object)null && (Object)(object)RoundManager.Instance != (Object)null)
				{
					currentLevel = RoundManager.Instance.currentLevel;
				}
				if ((Object)(object)currentLevel != (Object)null)
				{
					int num = (int)currentLevel.currentWeather;
					if (num >= 0 && num < TimeOfDay.Instance.effects.Length)
					{
						WeatherEffect val = TimeOfDay.Instance.effects[num];
						GameObject effectObject = val.effectObject;
						GameObject effectPermanentObject = val.effectPermanentObject;
						if ((Object)(object)((effectObject != null) ? effectObject.GetComponentInChildren<VisualManager>(true) : null) != (Object)null || (Object)(object)((effectPermanentObject != null) ? effectPermanentObject.GetComponentInChildren<VisualManager>(true) : null) != (Object)null)
						{
							return true;
						}
					}
				}
			}
			if (!checkActive)
			{
				return false;
			}
			for (int i = 0; i < TimeOfDay.Instance.effects.Length; i++)
			{
				WeatherEffect val2 = TimeOfDay.Instance.effects[i];
				GameObject effectObject2 = val2.effectObject;
				GameObject effectPermanentObject2 = val2.effectPermanentObject;
				if ((val2.effectEnabled || (effectObject2 != null && effectObject2.activeInHierarchy) || (effectPermanentObject2 != null && effectPermanentObject2.activeInHierarchy)) && ((Object)(object)((effectObject2 != null) ? effectObject2.GetComponentInChildren<VisualManager>(true) : null) != (Object)null || (Object)(object)((effectPermanentObject2 != null) ? effectPermanentObject2.GetComponentInChildren<VisualManager>(true) : null) != (Object)null))
				{
					return true;
				}
			}
			return false;
		}
	}
}
namespace TemporalStormWeather.Unlockables
{
	public class ResonatorSurface : PlaceableObjectsSurface
	{
		private static readonly WaitForSeconds PlaceCheckWait = new WaitForSeconds(0.1f);

		private const float RestoreSearchRadius = 12f;

		[Header("Cylinder")]
		[SerializeField]
		private Transform cylinderPlacement = null;

		[SerializeField]
		private ScanNodeProperties scanNodeProperties = null;

		[SerializeField]
		private BoxCollider playingInteractCollider = null;

		[Header("Hover")]
		[SerializeField]
		private InteractTrigger resonatorStartInteractTrigger = null;

		private const string NoTuningCylinderHoverTip = "[No Tuning Cylinder inserted]";

		private const string ResonatorActiveHoverTip = "[Resonator already active]";

		private const string TemporalInstabilityShutdownHoverTip = "[Temporal instability too high]";

		[Header("Animation")]
		[SerializeField]
		private Animator resonatorAnimator = null;

		[SerializeField]
		private string animationBoolName = "isPlaying";

		[SerializeField]
		private float animationSpeedTransitionSeconds = 1f;

		[Header("Audio")]
		[SerializeField]
		private AudioSource resonatorAudioSource = null;

		[SerializeField]
		private AudioClip cylinderPlacedClip = null;

		[SerializeField]
		private AudioClip cylinderRemovedClip = null;

		[SerializeField]
		private AudioClip resonatorStartedClip = null;

		[Header("Audio Reaction")]
		[SerializeField]
		private Transform audioReactiveScaleTarget = null;

		[SerializeField]
		private float minimumAudioReactiveScale = 1f;

		[SerializeField]
		private float maximumAudioReactiveScale = 1.5f;

		[SerializeField]
		private float audioReactiveStrength = 1.5f;

		[SerializeField]
		private float audioReactiveSmoothingSeconds = 0.08f;

		[Header("Temporal Instability Shutdown")]
		[SerializeField]
		[Range(0f, 100f)]
		private float temporalInstabilityStopThreshold = 90f;

		[SerializeField]
		[Min(0.01f)]
		private float temporalInstabilityStopSeconds = 0.85f;

		private TuningCylinderItem storedCylinder = null;

		private DawnContractSync? cylinderSync;

		private Coroutine? watchCylinderCoroutine;

		private Coroutine? animationSpeedCoroutine;

		private Coroutine? resonatorStartCoroutine;

		private Coroutine? audioReactionCoroutine;

		private Coroutine? temporalInstabilityStopCoroutine;

		private bool resonatorPlaying;

		private Vector3 audioReactiveBaseScale;

		private readonly float[] audioSamples = new float[64];

		private float audioReactiveCurrentScale;

		private void Start()
		{
			//IL_002c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0031: Unknown result type (might be due to invalid IL or missing references)
			resonatorAnimator.speed = 0f;
			resonatorAnimator.SetBool(animationBoolName, false);
			audioReactiveBaseScale = audioReactiveScaleTarget.localScale;
			audioReactiveCurrentScale = minimumAudioReactiveScale;
			RefreshStartInteractTrigger();
			RegisterContractSync();
		}

		public override void OnDestroy()
		{
			DawnContractSync? obj = cylinderSync;
			if (obj != null)
			{
				obj.Disable();
			}
			((NetworkBehaviour)this).OnDestroy();
		}

		private void RegisterContractSync()
		{
			PlaceableShipObject val = ((Component)base.parentTo).GetComponentInChildren<PlaceableShipObject>() ?? ((Component)this).GetComponentInParent<PlaceableShipObject>();
			if ((Object)(object)val == (Object)null)
			{
				Log.Warn("Resonator could not find its ship object");
				return;
			}
			UnlockableItem val2 = StartOfRound.Instance.unlockablesList.unlockables[val.unlockableID];
			NamespacedKey typedKey = (NamespacedKey)(object)((DawnBaseInfo<DawnUnlockableItemInfo>)(object)UnlockableItemExtensions.GetDawnInfo(val2)).TypedKey;
			cylinderSync = DawnContractSync.Register(typedKey, (Func<string>)WriteStoredCylinderData, (Action<string>)RestoreStoredCylinder, false);
		}

		public void StartResonator()
		{
			if (HasStoredCylinder() && !resonatorPlaying && !IsTemporalInstabilityShutdownActive())
			{
				RequestStartResonatorRpc();
			}
		}

		[Rpc(/*Could not decode attribute arguments.*/)]
		private void RequestStartResonatorRpc()
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Invalid comparison between Unknown and I4
			//IL_009a: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a4: Invalid comparison between Unknown and I4
			//IL_0043: Unknown result type (might be due to invalid IL or missing references)
			//IL_004b: Unknown result type (might be due to invalid IL or missing references)
			//IL_005f: 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_0072: Unknown result type (might be due to invalid IL or missing references)
			//IL_0081: Unknown result type (might be due to invalid IL or missing references)
			//IL_0085: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b3: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager;
			if (networkManager == null || !networkManager.IsListening)
			{
				return;
			}
			if ((int)((NetworkBehaviour)this).__rpc_exec_stage != 1)
			{
				RpcAttributeParams val = new RpcAttributeParams
				{
					RequireOwnership = false
				};
				RpcParams val3 = default(RpcParams);
				FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendRpc(4145759038u, val3, val, (SendTo)2, (RpcDelivery)0);
				((NetworkBehaviour)this).__endSendRpc(ref val2, 4145759038u, val3, val, (SendTo)2, (RpcDelivery)0);
			}
			if ((int)((NetworkBehaviour)this).__rpc_exec_stage == 1)
			{
				((NetworkBehaviour)this).__rpc_exec_stage = (__RpcExecStage)0;
				if (HasStoredCylinder() && !resonatorPlaying && !IsTemporalInstabilityShutdownActive())
				{
					ConfirmStartResonatorRpc();
				}
			}
		}

		[Rpc(/*Could not decode attribute arguments.*/)]
		private void ConfirmStartResonatorRpc()
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Invalid comparison between Unknown and I4
			//IL_008c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0096: Invalid comparison between Unknown and I4
			//IL_0043: Unknown result type (might be due to invalid IL or missing references)
			//IL_004b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0051: Unknown result type (might be due to invalid IL or missing references)
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0064: Unknown result type (might be due to invalid IL or missing references)
			//IL_0073: Unknown result type (might be due to invalid IL or missing references)
			//IL_0077: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a5: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager;
			if (networkManager != null && networkManager.IsListening)
			{
				if ((int)((NetworkBehaviour)this).__rpc_exec_stage != 1)
				{
					RpcAttributeParams val = default(RpcAttributeParams);
					RpcParams val3 = default(RpcParams);
					FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendRpc(858130537u, val3, val, (SendTo)7, (RpcDelivery)0);
					((NetworkBehaviour)this).__endSendRpc(ref val2, 858130537u, val3, val, (SendTo)7, (RpcDelivery)0);
				}
				if ((int)((NetworkBehaviour)this).__rpc_exec_stage == 1)
				{
					((NetworkBehaviour)this).__rpc_exec_stage = (__RpcExecStage)0;
					StartResonatorLocal();
				}
			}
		}

		private void StartResonatorLocal()
		{
			if (HasStoredCylinder() && !resonatorPlaying && !IsTemporalInstabilityShutdownActive())
			{
				resonatorPlaying = true;
				RefreshStartInteractTrigger();
				((Collider)playingInteractCollider).enabled = false;
				resonatorAnimator.SetBool(animationBoolName, true);
				AudioTools.PlayOneShot(resonatorAudioSource, resonatorStartedClip);
				CoroutineTools.Restart((MonoBehaviour)(object)this, ref resonatorStartCoroutine, StartCylinderSongAfterResonatorClip(storedCylinder));
				CoroutineTools.Restart((MonoBehaviour)(object)this, ref animationSpeedCoroutine, RampAnimatorSpeed(1f, flipBoolWhenStopped: false));
			}
		}

		public void PlaceObject(PlayerControllerB playerWhoTriggered)
		{
			TuningCylinderItem tuningCylinderItem = default(TuningCylinderItem);
			if (playerWhoTriggered != null && playerWhoTriggered.isHoldingObject && !playerWhoTriggered.isGrabbingObjectAnimation && !((Object)(object)playerWhoTriggered.currentlyHeldObjectServer == (Object)null) && ((Component)playerWhoTriggered.currentlyHeldObjectServer).TryGetComponent<TuningCylinderItem>(ref tuningCylinderItem) && !HasStoredCylinder())
			{
				RequestPlaceRpc((int)playerWhoTriggered.playerClientId, ((NetworkBehaviour)tuningCylinderItem).NetworkObjectId);
			}
		}

		internal bool CanPlaceHeldTuningCylinder(PlayerControllerB player)
		{
			int result;
			if (!HasStoredCylinder() && player.isHoldingObject && !player.isGrabbingObjectAnimation)
			{
				GrabbableObject currentlyHeldObjectServer = player.currentlyHeldObjectServer;
				TuningCylinderItem tuningCylinderItem = default(TuningCylinderItem);
				result = ((currentlyHeldObjectServer != null && ((Component)currentlyHeldObjectServer).TryGetComponent<TuningCylinderItem>(ref tuningCylinderItem)) ? 1 : 0);
			}
			else
			{
				result = 0;
			}
			return (byte)result != 0;
		}

		internal bool TryGetDisabledHoverTip(PlayerControllerB player, InteractTrigger trigger, out string disabledHoverTip)
		{
			if ((Object)(object)trigger == (Object)(object)base.triggerScript && !CanPlaceHeldTuningCylinder(player))
			{
				disabledHoverTip = trigger.disabledHoverTip;
				return true;
			}
			disabledHoverTip = string.Empty;
			return false;
		}

		[Rpc(/*Could not decode attribute arguments.*/)]
		private void RequestPlaceRpc(int playerWhoTriggered, ulong itemNetworkId)
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Invalid comparison between Unknown and I4
			//IL_00b4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00be: Invalid comparison between Unknown and I4
			//IL_0043: Unknown result type (might be due to invalid IL or missing references)
			//IL_004b: Unknown result type (might be due to invalid IL or missing references)
			//IL_005f: 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_0072: Unknown result type (might be due to invalid IL or missing references)
			//IL_0076: Unknown result type (might be due to invalid IL or missing references)
			//IL_0083: Unknown result type (might be due to invalid IL or missing references)
			//IL_009b: 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_00cd: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager;
			if (networkManager == null || !networkManager.IsListening)
			{
				return;
			}
			if ((int)((NetworkBehaviour)this).__rpc_exec_stage != 1)
			{
				RpcAttributeParams val = new RpcAttributeParams
				{
					RequireOwnership = false
				};
				RpcParams val3 = default(RpcParams);
				FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendRpc(3113508334u, val3, val, (SendTo)2, (RpcDelivery)0);
				BytePacker.WriteValueBitPacked(val2, playerWhoTriggered);
				BytePacker.WriteValueBitPacked(val2, itemNetworkId);
				((NetworkBehaviour)this).__endSendRpc(ref val2, 3113508334u, val3, val, (SendTo)2, (RpcDelivery)0);
			}
			if ((int)((NetworkBehaviour)this).__rpc_exec_stage != 1)
			{
				return;
			}
			((NetworkBehaviour)this).__rpc_exec_stage = (__RpcExecStage)0;
			if (base.parentTo.IsSpawned && !HasStoredCylinder())
			{
				PlaceableShipObject componentInChildren = ((Component)base.parentTo).gameObject.GetComponentInChildren<PlaceableShipObject>();
				if (componentInChildren != null)
				{
					componentInChildren.lastTimeScrapWasPlaced = Time.realtimeSinceStartup;
				}
				ConfirmPlaceRpc(playerWhoTriggered, itemNetworkId);
			}
		}

		[Rpc(/*Could not decode attribute arguments.*/)]
		private void ConfirmPlaceRpc(int playerId, ulong itemNetworkId)
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Invalid comparison between Unknown and I4
			//IL_00a6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b0: Invalid comparison between Unknown and I4
			//IL_0043: Unknown result type (might be due to invalid IL or missing references)
			//IL_004b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0051: Unknown result type (might be due to invalid IL or missing references)
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0064: Unknown result type (might be due to invalid IL or missing references)
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			//IL_0075: Unknown result type (might be due to invalid IL or missing references)
			//IL_008d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0091: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bf: Unknown result type (might be due to invalid IL or missing references)
			//IL_011b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0120: Unknown result type (might be due to invalid IL or missing references)
			//IL_0125: Unknown result type (might be due to invalid IL or missing references)
			//IL_012e: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager;
			if (networkManager == null || !networkManager.IsListening)
			{
				return;
			}
			if ((int)((NetworkBehaviour)this).__rpc_exec_stage != 1)
			{
				RpcAttributeParams val = default(RpcAttributeParams);
				RpcParams val3 = default(RpcParams);
				FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendRpc(2610774658u, val3, val, (SendTo)7, (RpcDelivery)0);
				BytePacker.WriteValueBitPacked(val2, playerId);
				BytePacker.WriteValueBitPacked(val2, itemNetworkId);
				((NetworkBehaviour)this).__endSendRpc(ref val2, 2610774658u, val3, val, (SendTo)7, (RpcDelivery)0);
			}
			if ((int)((NetworkBehaviour)this).__rpc_exec_stage == 1)
			{
				((NetworkBehaviour)this).__rpc_exec_stage = (__RpcExecStage)0;
				PlayerControllerB val4 = Utility.LocalPlayer();
				if ((Object)(object)val4 != (Object)null && (int)val4.playerClientId == playerId && val4.isHoldingObject && !val4.isGrabbingObjectAnimation && (Object)(object)val4.currentlyHeldObjectServer != (Object)null)
				{
					Vector3 val5 = ((Component)base.parentTo).transform.InverseTransformPoint(cylinderPlacement.position);
					val4.DiscardHeldObject(true, base.parentTo, val5, false);
				}
				((MonoBehaviour)this).StartCoroutine(WaitAndAttachPlacedCylinder(itemNetworkId));
			}
		}

		private IEnumerator WaitAndAttachPlacedCylinder(ulong itemNetworkId)
		{
			NetworkManager networkManager = NetworkManager.Singleton;
			TuningCylinderItem cylinder = default(TuningCylinderItem);
			for (int i = 0; i < 60; i++)
			{
				yield return PlaceCheckWait;
				if (((networkManager != null) ? networkManager.SpawnManager : null) != null && networkManager.SpawnManager.SpawnedObjects.TryGetValue(itemNetworkId, out var itemNetworkObject) && !((Object)(object)itemNetworkObject == (Object)null) && ((Component)itemNetworkObject).TryGetComponent<TuningCylinderItem>(ref cylinder) && !((GrabbableObject)cylinder).isHeld && !((Object)(object)((GrabbableObject)cylinder).playerHeldBy != (Object)null) && !((GrabbableObject)cylinder).isHeldByEnemy)
				{
					AttachCylinder(cylinder, saveItem: true, playPlacedSound: true);
					break;
				}
			}
		}

		private void AttachCylinder(TuningCylinderItem cylinder, bool saveItem, bool playPlacedSound)
		{
			storedCylinder = cylinder;
			((GrabbableObject)cylinder).parentObject = null;
			((Component)cylinder).transform.SetParent(((Component)base.parentTo).transform, true);
			cylinder.LoadSong();
			ApplyCylinderTransform(cylinder);
			scanNodeProperties.subText = string.Empty;
			((Collider)((Component)base.triggerScript).GetComponent<BoxCollider>()).enabled = false;
			if (playPlacedSound)
			{
				AudioTools.PlayOneShot(resonatorAudioSource, cylinderPlacedClip);
			}
			CoroutineTools.Restart((MonoBehaviour)(object)this, ref watchCylinderCoroutine, WatchStoredCylinder(cylinder));
			RefreshStartInteractTrigger();
			if (saveItem)
			{
				SaveStoredCylinder();
			}
		}

		private IEnumerator WatchStoredCylinder(TuningCylinderItem cylinder)
		{
			while ((Object)(object)cylinder != (Object)null)
			{
				if (((GrabbableObject)cylinder).isHeld || (Object)(object)((GrabbableObject)cylinder).playerHeldBy != (Object)null || ((GrabbableObject)cylinder).isHeldByEnemy)
				{
					DetachCylinder(cylinder, saveItem: true);
					yield break;
				}
				ApplyCylinderTransform(cylinder);
				yield return null;
			}
			StopTemporalInstabilityShutdown();
			StopResonatorAnimation();
			StopAudioReaction();
			scanNodeProperties.subText = string.Empty;
			storedCylinder = null;
			RefreshStartInteractTrigger();
			((Collider)((Component)base.triggerScript).GetComponent<BoxCollider>()).enabled = true;
			ClearStoredCylinderSave();
			watchCylinderCoroutine = null;
		}

		private void DetachCylinder(TuningCylinderItem cylinder, bool saveItem)
		{
			cylinder.StopSong();
			cylinder.UnloadSong();
			AudioTools.PlayOneShot(resonatorAudioSource, cylinderRemovedClip);
			StopTemporalInstabilityShutdown();
			StopResonatorAnimation();
			StopAudioReaction();
			scanNodeProperties.subText = string.Empty;
			if ((Object)(object)storedCylinder == (Object)(object)cylinder)
			{
				storedCylinder = null;
			}
			((Collider)((Component)base.triggerScript).GetComponent<BoxCollider>()).enabled = true;
			watchCylinderCoroutine = null;
			RefreshStartInteractTrigger();
			if (saveItem)
			{
				ClearStoredCylinderSave();
			}
		}

		private string WriteStoredCylinderData()
		{
			if (!HasStoredCylinder())
			{
				return string.Empty;
			}
			return ((object)FindItems.DawnKey((GrabbableObject)(object)storedCylinder))?.ToString() ?? string.Empty;
		}

		private void RestoreStoredCylinder(string rawItemKey)
		{
			//IL_0085: Unknown result type (might be due to invalid IL or missing references)
			if (HasStoredCylinder() || string.IsNullOrWhiteSpace(rawItemKey))
			{
				return;
			}
			NamespacedKey val = default(NamespacedKey);
			if (!NamespacedKey.TryParse(rawItemKey, ref val))
			{
				if (((NetworkBehaviour)this).IsServer)
				{
					ClearStoredCylinderSave();
				}
				Log.Warn("Resonator cylinder save data could not be read");
				return;
			}
			NamespacedKey<DawnItemInfo> val2 = val.AsTyped<DawnItemInfo>();
			List<GrabbableObject> list = FindItems.Active((Func<GrabbableObject, bool>)((GrabbableObject item) => item is TuningCylinderItem && !item.isHeld && (Object)(object)item.playerHeldBy == (Object)null && !item.isHeldByEnemy));
			GrabbableObject val3 = FindItems.ClosestTo(val2, cylinderPlacement.position, 12f, (IReadOnlyList<GrabbableObject>)list, (Func<GrabbableObject, bool>)null);
			TuningCylinderItem cylinder = default(TuningCylinderItem);
			if ((Object)(object)val3 == (Object)null || !((Component)val3).TryGetComponent<TuningCylinderItem>(ref cylinder))
			{
				if (((NetworkBehaviour)this).IsServer)
				{
					ClearStoredCylinderSave();
				}
			}
			else
			{
				AttachCylinder(cylinder, saveItem: false, playPlacedSound: false);
				Log.Debug("Resonator cylinder restored");
			}
		}

		private void SaveStoredCylinder()
		{
			if (((NetworkBehaviour)this).IsServer && cylinderSync != null)
			{
				string value = WriteStoredCylinderData();
				if (string.IsNullOrWhiteSpace(value))
				{
					ClearStoredCylinderSave();
					return;
				}
				cylinderSync.SaveAndPublish();
				Log.Debug("Resonator cylinder save updated");
			}
		}

		private void ClearStoredCylinderSave()
		{
			if (((NetworkBehaviour)this).IsServer && cylinderSync != null)
			{
				cylinderSync.Delete();
				cylinderSync.Publish();
				Log.Debug("Resonator cylinder save cleared");
			}
		}

		private bool HasStoredCylinder()
		{
			TuningCylinderItem tuningCylinderItem = storedCylinder;
			return tuningCylinderItem != null && !((GrabbableObject)tuningCylinderItem).isHeld && (Object)(object)((GrabbableObject)storedCylinder).playerHeldBy == (Object)null && !((GrabbableObject)storedCylinder).isHeldByEnemy;
		}

		private void RefreshStartInteractTrigger()
		{
			bool flag = HasStoredCylinder();
			bool flag2 = IsTemporalInstabilityShutdownActive();
			bool flag3 = flag && !resonatorPlaying && !flag2;
			resonatorStartInteractTrigger.interactable = flag3;
			if (!flag3)
			{
				resonatorStartInteractTrigger.disabledHoverTip = ((!flag) ? "[No Tuning Cylinder inserted]" : (resonatorPlaying ? "[Resonator already active]" : (flag2 ? "[Temporal instability too high]" : "[No Tuning Cylinder inserted]")));
			}
		}

		private void ApplyCylinderTransform(TuningCylinderItem cylinder)
		{
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			//IL_001c: 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_002d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0038: Unknown result type (might be due to invalid IL or missing references)
			//IL_003d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0042: Unknown result type (might be due to invalid IL or missing references)
			//IL_0045: Unknown result type (might be due to invalid IL or missing references)
			//IL_004a: 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_005e: Unknown result type (might be due to invalid IL or missing references)
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0071: Unknown result type (might be due to invalid IL or missing references)
			//IL_007d: Unknown result type (might be due to invalid IL or missing references)
			//IL_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_0085: 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_0094: 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)
			Vector3 val = ((Component)base.parentTo).transform.InverseTransformPoint(cylinderPlacement.position);
			Quaternion val2 = Quaternion.Inverse(((Component)base.parentTo).transform.rotation) * cylinderPlacement.rotation;
			Vector3 eulerAngles = ((Quaternion)(ref val2)).eulerAngles;
			eulerAngles.x = 0f;
			((Component)cylinder).transform.SetLocalPositionAndRotation(val, Quaternion.Euler(eulerAngles));
			((Component)cylinder).transform.localScale = ((GrabbableObject)cylinder).originalScale;
			((GrabbableObject)cylinder).targetFloorPosition = val;
			((GrabbableObject)cylinder).startFallingPosition = val + Vector3.up * 0.0001f;
			((GrabbableObject)cylinder).fallTime = 1f;
			((GrabbableObject)cylinder).hasHitGround = true;
			((GrabbableObject)cylinder).reachedFloorTarget = true;
		}

		private void StopResonatorAnimation()
		{
			resonatorPlaying = false;
			if (resonatorStartCoroutine != null)
			{
				((MonoBehaviour)this).StopCoroutine(resonatorStartCoroutine);
				resonatorStartCoroutine = null;
			}
			CoroutineTools.Restart((MonoBehaviour)(object)this, ref animationSpeedCoroutine, RampAnimatorSpeed(0f, flipBoolWhenStopped: true));
		}

		private IEnumerator StartCylinderSongAfterResonatorClip(TuningCylinderItem cylinder)
		{
			yield return (object)new WaitForSeconds(resonatorStartedClip.length);
			if (resonatorPlaying && (Object)(object)storedCylinder == (Object)(object)cylinder && HasStoredCylinder())
			{
				if (IsTemporalInstabilityShutdownActive())
				{
					StopResonatorAnimation();
					resonatorStartCoroutine = null;
					yield break;
				}
				cylinder.PlaySong();
				scanNodeProperties.subText = cylinder.SongDisplayName;
				CoroutineTools.Restart((MonoBehaviour)(object)this, ref audioReactionCoroutine, ReactToCylinderAudio(cylinder));
			}
			resonatorStartCoroutine = null;
		}

		private IEnumerator RampAnimatorSpeed(float targetSpeed, bool flipBoolWhenStopped)
		{
			float startSpeed = resonatorAnimator.speed;
			float elapsedSeconds = 0f;
			while (elapsedSeconds < animationSpeedTransitionSeconds)
			{
				elapsedSeconds += Time.deltaTime;
				resonatorAnimator.speed = Mathf.Lerp(startSpeed, targetSpeed, elapsedSeconds / animationSpeedTransitionSeconds);
				yield return null;
			}
			resonatorAnimator.speed = targetSpeed;
			if (flipBoolWhenStopped)
			{
				resonatorAnimator.SetBool(animationBoolName, false);
				if (temporalInstabilityStopCoroutine == null)
				{
					((Collider)playingInteractCollider).enabled = true;
				}
				RefreshStartInteractTrigger();
			}
			animationSpeedCoroutine = null;
		}

		private IEnumerator ReactToCylinderAudio(TuningCylinderItem cylinder)
		{
			AudioSource songAudioSource = cylinder.SongAudioSource;
			while (songAudioSource.isPlaying)
			{
				if (IsTemporalInstabilityShutdownActive())
				{
					CoroutineTools.Restart((MonoBehaviour)(object)this, ref temporalInstabilityStopCoroutine, StopForTemporalInstability(cylinder));
					audioReactionCoroutine = null;
					yield break;
				}
				songAudioSource.GetOutputData(audioSamples, 0);
				float sampleTotal = 0f;
				for (int i = 0; i < audioSamples.Length; i++)
				{
					sampleTotal += Mathf.Abs(audioSamples[i]);
				}
				float audioScale = Mathf.Clamp01(sampleTotal / (float)audioSamples.Length * audioReactiveStrength);
				float targetScale = Mathf.Lerp(minimumAudioReactiveScale, maximumAudioReactiveScale, audioScale);
				float smoothing = 1f - Mathf.Exp((0f - Time.deltaTime) / Mathf.Max(0.001f, audioReactiveSmoothingSeconds));
				audioReactiveCurrentScale = Mathf.Lerp(audioReactiveCurrentScale, targetScale, smoothing);
				audioReactiveScaleTarget.localScale = audioReactiveBaseScale * audioReactiveCurrentScale;
				yield return null;
			}
			audioReactiveScaleTarget.localScale = audioReactiveBaseScale * minimumAudioReactiveScale;
			audioReactiveCurrentScale = minimumAudioReactiveScale;
			audioReactionCoroutine = null;
		}

		private IEnumerator StopForTemporalInstability(TuningCylinderItem cylinder)
		{
			StopResonatorAnimation();
			scanNodeProperties.subText = string.Empty;
			yield return cylinder.StopSongLikeVinyl(temporalInstabilityStopSeconds);
			StopAudioReaction();
			((Collider)playingInteractCollider).enabled = true;
			temporalInstabilityStopCoroutine = null;
		}

		private void StopTemporalInstabilityShutdown()
		{
			if (temporalInstabilityStopCoroutine != null)
			{
				((MonoBehaviour)this).StopCoroutine(temporalInstabilityStopCoroutine);
				temporalInstabilityStopCoroutine = null;
			}
		}

		private bool IsTemporalInstabilityShutdownActive()
		{
			float temporalInstabilityLevel;
			return TemporalInstabilityAPI.TryGetServerInstabilityLevel(out temporalInstabilityLevel) && temporalInstabilityLevel >= temporalInstabilityStopThreshold;
		}

		private void StopAudioReaction()
		{
			//IL_002b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0036: Unknown result type (might be due to invalid IL or missing references)
			if (audioReactionCoroutine != null)
			{
				((MonoBehaviour)this).StopCoroutine(audioReactionCoroutine);
				audioReactionCoroutine = null;
			}
			audioReactiveScaleTarget.localScale = audioReactiveBaseScale * minimumAudioReactiveScale;
			audioReactiveCurrentScale = minimumAudioReactiveScale;
		}

		protected override void __initializeVariables()
		{
			((PlaceableObjectsSurface)this).__initializeVariables();
		}

		protected override void __initializeRpcs()
		{
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			//IL_001c: Expected O, but got Unknown
			//IL_0029: Unknown result type (might be due to invalid IL or missing references)
			//IL_0038: Expected O, but got Unknown
			//IL_0045: Unknown result type (might be due to invalid IL or missing references)
			//IL_0054: Expected O, but got Unknown
			//IL_0061: Unknown result type (might be due to invalid IL or missing references)
			//IL_0070: Expected O, but got Unknown
			((NetworkBehaviour)this).__registerRpc(4145759038u, new RpcReceiveHandler(__rpc_handler_4145759038), "RequestStartResonatorRpc");
			((NetworkBehaviour)this).__registerRpc(858130537u, new RpcReceiveHandler(__rpc_handler_858130537), "ConfirmStartResonatorRpc");
			((NetworkBehaviour)this).__registerRpc(3113508334u, new RpcReceiveHandler(__rpc_handler_3113508334), "RequestPlaceRpc");
			((NetworkBehaviour)this).__registerRpc(2610774658u, new RpcReceiveHandler(__rpc_handler_2610774658), "ConfirmPlaceRpc");
			((PlaceableObjectsSurface)this).__initializeRpcs();
		}

		private static void __rpc_handler_4145759038(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams)
		{
			//IL_0029: Unknown result type (might be due to invalid IL or missing references)
			//IL_003f: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = target.NetworkManager;
			if (networkManager != null && networkManager.IsListening)
			{
				target.__rpc_exec_stage = (__RpcExecStage)1;
				((ResonatorSurface)(object)target).RequestStartResonatorRpc();
				target.__rpc_exec_stage = (__RpcExecStage)0;
			}
		}

		private static void __rpc_handler_858130537(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams)
		{
			//IL_0029: Unknown result type (might be due to invalid IL or missing references)
			//IL_003f: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = target.NetworkManager;
			if (networkManager != null && networkManager.IsListening)
			{
				target.__rpc_exec_stage = (__RpcExecStage)1;
				((ResonatorSurface)(object)target).ConfirmStartResonatorRpc();
				target.__rpc_exec_stage = (__RpcExecStage)0;
			}
		}

		private static void __rpc_handler_3113508334(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams)
		{
			//IL_0023: 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_0043: 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)
			NetworkManager networkManager = target.NetworkManager;
			if (networkManager != null && networkManager.IsListening)
			{
				int playerWhoTriggered = default(int);
				ByteUnpacker.ReadValueBitPacked(reader, ref playerWhoTriggered);
				ulong itemNetworkId = default(ulong);
				ByteUnpacker.ReadValueBitPacked(reader, ref itemNetworkId);
				target.__rpc_exec_stage = (__RpcExecStage)1;
				((ResonatorSurface)(object)target).RequestPlaceRpc(playerWhoTriggered, itemNetworkId);
				target.__rpc_exec_stage = (__RpcExecStage)0;
			}
		}

		private static void __rpc_handler_2610774658(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams)
		{
			//IL_0023: 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_0043: 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)
			NetworkManager networkManager = target.NetworkManager;
			if (networkManager != null && networkManager.IsListening)
			{
				int playerId = default(int);
				ByteUnpacker.ReadValueBitPacked(reader, ref playerId);
				ulong itemNetworkId = default(ulong);
				ByteUnpacker.ReadValueBitPacked(reader, ref itemNetworkId);
				target.__rpc_exec_stage = (__RpcExecStage)1;
				((ResonatorSurface)(object)target).ConfirmPlaceRpc(playerId, itemNetworkId);
				target.__rpc_exec_stage = (__RpcExecStage)0;
			}
		}

		protected internal override string __getTypeName()
		{
			return "ResonatorSurface";
		}
	}
}
namespace TemporalStormWeather.TemporalStormManagers
{
	internal class AudioManager : MonoBehaviour, ITemporalInstability
	{
		[Serializable]
		private class InstabilityLoop
		{
			public AudioSource AudioSource = null;

			public AudioClip AudioClip = null;
		}

		private const float CrossfadeSeconds = 1f;

		private static readonly NamespacedKey<DawnEnemyInfo>[] locustEnemyKeys = new NamespacedKey<DawnEnemyInfo>[3]
		{
			Keys.LocustEnemyInfo,
			Keys.SawbladeLocustEnemyInfo,
			Keys.CorruptLocustEnemyInfo
		};

		[Header("Volume")]
		[SerializeField]
		[Range(0f, 1f)]
		private float maximumAudioVolume = 1f;

		[SerializeField]
		[Range(0f, 100f)]
		private float volumeIncreaseStartInstability = 0f;

		[SerializeField]
		[Range(0f, 100f)]
		private float maximumVolumeInstability = 90f;

		[Header("Low Instability")]
		[SerializeField]
		private InstabilityLoop lowInstability = new InstabilityLoop();

		[Header("Medium Instability")]
		[SerializeField]
		private InstabilityLoop mediumInstability = new InstabilityLoop();

		[Header("High Instability")]
		[SerializeField]
		private InstabilityLoop highInstability = new InstabilityLoop();

		[Header("Extreme Instability")]
		[SerializeField]
		private InstabilityLoop extremeInstability = new InstabilityLoop();

		private Coroutine? crossfadeCoroutine;

		private InstabilityLoop[] instabilityLoops = Array.Empty<InstabilityLoop>();

		private InstabilityLoop? activeLoop;

		private float temporalInstabilityLevel;

		private bool weatherFlowActive;

		private bool audioSourcesReady;

		private void Awake()
		{
			instabilityLoops = new InstabilityLoop[4] { lowInstability, mediumInstability, highInstability, extremeInstability };
			audioSourcesReady = true;
			for (int i = 0; i < instabilityLoops.Length; i++)
			{
				InstabilityLoop instabilityLoop = instabilityLoops[i];
				if (!AudioUtils.Configure2DAudioSource(instabilityLoop.AudioSource, loop: true))
				{
					audioSourcesReady = false;
					continue;
				}
				AudioTools.SwapClip(instabilityLoop.AudioSource, instabilityLoop.AudioClip, false);
				AudioTools.Stop(instabilityLoop.AudioSource, true);
			}
		}

		private void OnEnable()
		{
			if (audioSourcesReady && Utility.ShouldRunWeatherLifecycle())
			{
				AudioUtils.LoadAudioClips(WeatherAudioClips());
				weatherFlowActive = true;
				TemporalInstabilityAPI.Register(this, TemporalInstabilityFeed.Client);
			}
		}

		private void OnDisable()
		{
			if (!weatherFlowActive)
			{
				return;
			}
			weatherFlowActive = false;
			TemporalInstabilityAPI.Unregister(this);
			CoroutineTools.Stop((MonoBehaviour)(object)this, ref crossfadeCoroutine);
			for (int i = 0; i < instabilityLoops.Length; i++)
			{
				AudioSource audioSource = instabilityLoops[i].AudioSource;
				if (!((Object)(object)audioSource == (Object)null))
				{
					AudioTools.Stop(audioSource, true);
				}
			}
			activeLoop = null;
			temporalInstabilityLevel = 0f;
			AudioUtils.UnloadAudioClips(WeatherAudioClips());
		}

		public void SetTemporalInstabilityLevel(float value)
		{
			temporalInstabilityLevel = Utility.ClampInstability(value);
			InstabilityLoop instabilityLoop = ((temporalInstabilityLevel < 25f) ? lowInstability : ((temporalInstabilityLevel < 55f) ? mediumInstability : ((temporalInstabilityLevel < 90f) ? highInstability : extremeInstability)));
			if (instabilityLoop == activeLoop)
			{
				if (activeLoop != null && crossfadeCoroutine == null)
				{
					StopInactiveLoops(activeLoop);
					activeLoop.AudioSource.volume = (((Object)(object)activeLoop.AudioClip != (Object)null) ? WantedVolume() : 0f);
				}
			}
			else
			{
				StopInactiveLoops(activeLoop, instabilityLoop);
				CoroutineTools.Restart((MonoBehaviour)(object)this, ref crossfadeCoroutine, CrossfadeToLoop(instabilityLoop));
			}
		}

		private IEnumerator CrossfadeToLoop(InstabilityLoop newLoop)
		{
			InstabilityLoop previousLoop = activeLoop;
			activeLoop = newLoop;
			AudioSource previousSource = previousLoop?.AudioSource;
			AudioSource newSource = newLoop.AudioSource;
			float previousStartVolume = ((previousSource != null) ? previousSource.volume : 0f);
			float newStartVolume = ((newSource != null) ? newSource.volume : 0f);
			if ((Object)(object)newLoop.AudioClip != (Object)null && (Object)(object)newSource != (Object)null)
			{
				AudioTools.SwapClip(newSource, newLoop.AudioClip, false);
				if (!newSource.isPlaying)
				{
					newSource.time = 0f;
					newSource.Play();
				}
			}
			float elapsedSeconds = 0f;
			while (elapsedSeconds < 1f)
			{
				elapsedSeconds += Time.deltaTime;
				float fadeAmount = Mathf.SmoothStep(0f, 1f, elapsedSeconds / 1f);
				if (previousSource != null)
				{
					previousSource.volume = Mathf.Lerp(previousStartVolume, 0f, fadeAmount);
				}
				if (newSource != null)
				{
					newSource.volume = (((Object)(object)newLoop.AudioClip != (Object)null) ? Mathf.Lerp(newStartVolume, WantedVolume(), fadeAmount) : 0f);
				}
				yield return null;
			}
			if ((Object)(object)previousSource != (Object)null)
			{
				AudioTools.Stop(previousSource, true);
			}
			if (newSource != null)
			{
				newSource.volume = (((Object)(object)newLoop.AudioClip != (Object)null) ? WantedVolume() : 0f);
			}
			StopInactiveLoops(newLoop);
			crossfadeCoroutine = null;
		}

		private float WantedVolume()
		{
			if (temporalInstabilityLevel < volumeIncreaseStartInstability)
			{
				return 0f;
			}
			float fullLevel = Mathf.Max(volumeIncreaseStartInstability + 0.01f, maximumVolumeInstability);
			float num = Mathf.Lerp(0.1f, 1f, Utility.InstabilityProgress(temporalInstabilityLevel, volumeIncreaseStartInstability, fullLevel));
			return num * maximumAudioVolume;
		}

		private AudioClip?[] WeatherAudioClips()
		{
			WarningManager warningManager = Object.FindFirstObjectByType<WarningManager>((FindObjectsInactive)1);
			ThunderlordAnimationEvents thunderlordAnimationEvents = Object.FindFirstObjectByType<ThunderlordAnimationEvents>((FindObjectsInactive)1);
			List<AudioClip> list = new List<AudioClip>();
			list.Add(lowInstability.AudioClip);
			list.Add(mediumInstability.AudioClip);
			list.Add(highInstability.AudioClip);
			list.Add(extremeInstability.AudioClip);
			list.AddRange(TemporalStormAmbience.GetAudioClips());
			list.AddRange(warningManager?.AudioClips ?? Array.Empty<AudioClip>());
			list.AddRange(thunderlordAnimationEvents?.AudioClips ?? Array.Empty<AudioClip>());
			list.AddRange(RiftAudioClips());
			list.AddRange(LocustAudioClips());
			return list.ToArray();
		}

		private static AudioClip?[] RiftAudioClips()
		{
			DawnMapObjectInfo val = default(DawnMapObjectInfo);
			if (!((Registry<DawnMapObjectInfo>)(object)LethalContent.MapObjects).TryGetValue(Keys.TemporalRiftMapObject, ref val))
			{
				return Array.Empty<AudioClip>();
			}
			DawnInsideMapObjectInfo insideInfo = val.InsideInfo;
			GameObject riftPrefab = (((Object)(object)((insideInfo != null) ? insideInfo.IndoorMapHazardType : null) != (Object)null) ? val.InsideInfo.IndoorMapHazardType.prefabToSpawn : null);
			DawnOutsideMapObjectInfo outsideInfo = val.OutsideInfo;
			GameObject riftPrefab2 = (((Object)(object)((outsideInfo != null) ? outsideInfo.SpawnableOutsideObject : null) != (Object)null) ? val.OutsideInfo.SpawnableOutsideObject.prefabToSpawn : null);
			AudioClip[] array = RiftAudioClips(riftPrefab);
			AudioClip[] array2 = RiftAudioClips(riftPrefab2);
			int num = 0;
			AudioClip[] array3 = (AudioClip[])(object)new AudioClip[array.Length + array2.Length];
			ReadOnlySpan<AudioClip> readOnlySpan = new ReadOnlySpan<AudioClip>(array);
			readOnlySpan.CopyTo(new Span<AudioClip>(array3).Slice(num, readOnlySpan.Length));
			num += readOnlySpan.Length;
			ReadOnlySpan<AudioClip> readOnlySpan2 = new ReadOnlySpan<AudioClip>(array2);
			readOnlySpan2.CopyTo(new Span<AudioClip>(array3).Slice(num, readOnlySpan2.Length));
			num += readOnlySpan2.Length;
			return array3;
		}

		private static AudioClip?[] RiftAudioClips(GameObject? riftPrefab)
		{
			return ((riftPrefab != null) ? riftPrefab.GetComponentInChildren<TemporalRift>(true) : null)?.AudioClips ?? Array.Empty<AudioClip>();
		}

		private static AudioClip?[] LocustAudioClips()
		{
			AudioClip[] array = LocustAudioClips(locustEnemyKeys[0]);
			AudioClip[] array2 = LocustAudioClips(locustEnemyKeys[1]);
			AudioClip[] array3 = LocustAudioClips(locustEnemyKeys[2]);
			int num = 0;
			AudioClip[] array4 = (AudioClip[])(object)new AudioClip[array.Length + array2.Length + array3.Length];
			ReadOnlySpan<AudioClip> readOnlySpan = new ReadOnlySpan<AudioClip>(array);
			readOnlySpan.CopyTo(new Span<AudioClip>(array4).Slice(num, readOnlySpan.Length));
			num += readOnlySpan.Length;
			ReadOnlySpan<AudioClip> readOnlySpan2 = new ReadOnlySpan<AudioClip>(array2);
			readOnlySpan2.CopyTo(new Span<AudioClip>(array4).Slice(num, readOnlySpan2.Length));
			num += readOnlySpan2.Length;
			ReadOnlySpan<AudioClip> readOnlySpan3 = new ReadOnlySpan<AudioClip>(array3);
			readOnlySpan3.CopyTo(new Span<AudioClip>(array4).Slice(num, readOnlySpan3.Length));
			num += readOnlySpan3.Length;
			return array4;
		}

		private static AudioClip?[] LocustAudioClips(NamespacedKey<DawnEnemyInfo> enemyKey)
		{
			DawnEnemyInfo val = default(DawnEnemyInfo);
			if (!((Registry<DawnEnemyInfo>)(object)LethalContent.Enemies).TryGetValue(enemyKey, ref val) || (Object)(object)val.EnemyType?.enemyPrefab == (Object)null)
			{
				return Array.Empty<AudioClip>();
			}
			return val.EnemyType.enemyPrefab.GetComponent<LocustEnemyBase>()?.AudioClips ?? Array.Empty<AudioClip>();
		}

		private void StopInactiveLoops(InstabilityLoop? firstKeptLoop = null, InstabilityLoop? secondKeptLoop = null)
		{
			for (int i = 0; i < instabilityLoops.Length; i++)
			{
				InstabilityLoop instabilityLoop = instabilityLoops[i];
				if (instabilityLoop != firstKeptLoop && instabilityLoop != secondKeptLoop)
				{
					AudioSource audioSource = instabilityLoop.AudioSource;
					if (!((Object)(object)audioSource == (Object)null))
					{
						AudioTools.Stop(audioSource, true);
					}
				}
			}
		}
	}
	internal class ChatGlitchManager : ITemporalInstability
	{
		private const float ChatCorruptionStartInstability = 90f;

		private static readonly ChatGlitchManager Receiver = new ChatGlitchManager();

		private static bool registered;

		private static bool active;

		public void SetTemporalInstabilityLevel(float temporalInstabilityLevel)
		{
			active = temporalInstabilityLevel >= 90f;
		}

		public static void CorruptMessage(ref string chatMessage)
		{
			Register();
			if (!active || string.IsNullOrEmpty(chatMessage))
			{
				return;
			}
			StringBuilder stringBuilder = new StringBuilder(chatMessage.Length * 2);
			for (int i = 0; i < chatMessage.Length; i++)
			{
				char c = chatMessage[i];
				if (!char.IsWhiteSpace(c))
				{
					stringBuilder.Append(c);
					stringBuilder.Append('□');
				}
				else
				{
					stringBuilder.Append(c);
				}
			}
			chatMessage = stringBuilder.ToString();
		}

		public static void Reset()
		{
			TemporalInstabilityAPI.Unregister(Receiver);
			registered = false;
			active = false;
		}

		private static void Register()
		{
			if (!registered)
			{
				registered = true;
				TemporalInstabilityAPI.Register(Receiver, TemporalInstabilityFeed.Server);
			}
		}
	}
	[HarmonyPatch(typeof(HUDManager), "AddTextToChatOnServer")]
	internal static class HUDManagerChatGlitchPatch
	{
		[HarmonyPrefix]
		private static void CorruptTemporalStormChat(ref string chatMessage, int playerId)
		{
			if (playerId != -1)
			{
				ChatGlitchManager.CorruptMessage(ref chatMessage);
			}
		}
	}
	[Serializable]
	internal class TemporalStormItemContractSaveData
	{
		public List<TemporalStormSavedItem> Items = new List<TemporalStormSavedItem>();
	}
	[Serializable]
	internal class TemporalStormSavedItem
	{
		public string ItemNamespacedKey = string.Empty;

		public string ItemName = string.Empty;

		public Vector3 Position;

		public uint ItemSeed;

		public int ScrapValue;

		public float RusticLevel;

		public float VisualAmount;

		public int State;

		public uint TemporalRollsConsumed;

		public bool IncludeNonConductive;
	}
	public class DawnSaveManager : MonoBehaviour
	{
		private static DawnContractSync? itemEffectSync;

		internal static void HookItemEffectSave()
		{
			if (itemEffectSync == null)
			{
				itemEffectSync = DawnContractSync.Register(Keys.ItemEffectsSaveData, (Func<string>)BuildCurrentSaveDataJson, (Action<string>)LoadSavedItems, true);
			}
		}

		private static string BuildCurrentSaveDataJson()
		{
			TemporalStormItemContractSaveData temporalStormItemContractSaveData = BuildCurrentSaveData();
			return (temporalStormItemContractSaveData.Items.Count == 0) ? string.Empty : JsonUtility.ToJson((object)temporalStormItemContractSaveData);
		}

		private static void LoadSavedItems(string rawSaveData)
		{
			LoadSavedItems(ReadItemContractSaveData(rawSaveData));
		}

		private static TemporalStormItemContractSaveData BuildCurrentSaveData()
		{
			TemporalStormItemContractSaveData temporalStormItemContractSaveData = new TemporalStormItemContractSaveData();
			ItemEffect[] array = Object.FindObjectsByType<ItemEffect>((FindObjectsInactive)0, (FindObjectsSortMode)0);
			foreach (ItemEffect itemEffect in array)
			{
				if (itemEffect.WriteDawnSaveEntry(out TemporalStormSavedItem savedItem))
				{
					temporalStormItemContractSaveData.Items.Add(savedItem);
				}
			}
			return temporalStormItemContractSaveData;
		}

		private static List<GrabbableObject> GatherRestoreCandidates()
		{
			return FindItems.Active((Func<GrabbableObject, bool>)((GrabbableObject item) => DawnConfigUtils.CanUseDawnItem(item, includeNonConductive: true, DawnItemPersistenceMode.Restore)));
		}

		private static void LoadSavedItems(TemporalStormItemContractSaveData savedData)
		{
			if (savedData.Items.Count == 0)
			{
				return;
			}
			List<GrabbableObject> list = GatherRestoreCandidates();
			for (int i = 0; i < savedData.Items.Count; i++)
			{
				TemporalStormSavedItem temporalStormSavedItem = savedData.Items[i];
				GrabbableObject val = FindClosestMatchingItem(temporalStormSavedItem, list);
				if (!((Object)(object)val == (Object)null))
				{
					list.Remove(val);
					if (ItemEffect.Attach(val, out ItemEffect itemEffect, temporalStormSavedItem.IncludeNonConductive) && !((Object)(object)itemEffect == (Object)null))
					{
						itemEffect.ReadDawnSaveEntry(temporalStormSavedItem);
					}
				}
			}
		}

		private static GrabbableObject? FindClosestMatchingItem(TemporalStormSavedItem savedItem, List<GrabbableObject> candidates)
		{
			//IL_0020: Unknown result type (might be due to invalid IL or missing references)
			NamespacedKey val = default(NamespacedKey);
			if (!NamespacedKey.TryParse(savedItem.ItemNamespacedKey, ref val))
			{
				return null;
			}
			return FindItems.ClosestTo(val.AsTyped<DawnItemInfo>(), savedItem.Position, 8f, (IReadOnlyList<GrabbableObject>)candidates, (Func<GrabbableObject, bool>)null);
		}

		private static TemporalStormItemContractSaveData ReadItemContractSaveData(string raw)
		{
			if (string.IsNullOrWhiteSpace(raw))
			{
				return new TemporalStormItemContractSaveData();
			}
			TemporalStormItemContractSaveData temporalStormItemContractSaveData = JsonUtility.FromJson<TemporalStormItemContractSaveData>(raw);
			retur