Decompiled source of Ambient Soundtrack v1.1.1

AmbientMod.dll

Decompiled 10 months ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using AmbientMod.Patches;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using GameNetcodeStuff;
using HarmonyLib;
using LC_API.ServerAPI;
using Microsoft.CodeAnalysis;
using Unity.Netcode;
using UnityEngine;
using UnityEngine.Networking;

[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("AmbientMod")]
[assembly: AssemblyConfiguration("Debug")]
[assembly: AssemblyDescription("My first plugin")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0")]
[assembly: AssemblyProduct("AmbientMod")]
[assembly: AssemblyTitle("AmbientMod")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.0.0.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.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 AmbientMod
{
	public class Config
	{
		public static ConfigEntry<int> musicChance;

		public static ConfigEntry<bool> replaceVanillaSoundtrack;

		public static ConfigEntry<bool> forceMusicToPlay;

		public Config(ConfigFile cfg)
		{
			musicChance = cfg.Bind<int>("General", "MusicChance", 20, "A percent chance that ambient music will play on landing. [0 - 100]");
			replaceVanillaSoundtrack = cfg.Bind<bool>("General", "ReplaceVanillaSoundtrack", false, "This changes if the vanilla soundtrack will be 'added' or 'replaced' by the modded soundtrack.");
			forceMusicToPlay = cfg.Bind<bool>("Debug", "ForceMusicToPlay", false, "Forces music to play when you land on a moon");
		}
	}
	[BepInPlugin("gogozooom.AmbientMod", "Ambient Soundtrack", "1.1.1")]
	public class Plugin : BaseUnityPlugin
	{
		public const string PLUGIN_GUID = "gogozooom.AmbientMod";

		public const string PLUGIN_NAME = "Ambient Soundtrack";

		public const string PLUGIN_VERSION = "1.1.1";

		public const string PLUGIN_PATH = "/Gogozooom-Ambient_Soundtrack";

		public static string PLUGIN_PATH_FULL;

		private readonly Harmony harmony = new Harmony("gogozooom.AmbientMod");

		public static Plugin Instance;

		public static ManualLogSource _Logger;

		public static Config _Config;

		public static Action<ulong> songAction;

		public static List<AudioClip> daytimeMusic = new List<AudioClip>();

		public static List<AudioClip> eveningMusic = new List<AudioClip>();

		private bool continueFlag;

		private float waitBeforeFail = 3f;

		private Coroutine coroutine1;

		private Coroutine coroutine2;

		private void Awake()
		{
			if ((Object)(object)Instance == (Object)null)
			{
				Instance = this;
				Object.DontDestroyOnLoad((Object)(object)Instance);
			}
			_Logger = Logger.CreateLogSource("gogozooom.AmbientMod");
			_Config = new Config(((BaseUnityPlugin)this).Config);
			PLUGIN_PATH_FULL = Paths.PluginPath + "/Gogozooom-Ambient_Soundtrack";
			if (!Directory.Exists(PLUGIN_PATH_FULL))
			{
				_Logger.LogError((object)"Plugin gogozooom.AmbientMod v1.1.1 failed to load! Reason: PLUGIN_PATH INVALID");
				return;
			}
			LoadAllMusic();
			harmony.PatchAll(typeof(SoundManagerPatch));
			harmony.PatchAll(typeof(TimeOfDayPatch));
			Networking.GetInt = (Action<int, string>)Delegate.Combine(Networking.GetInt, new Action<int, string>(SyncingPatch.GetNetworkIntBrodcast));
			_Logger.LogInfo((object)"Plugin gogozooom.AmbientMod v1.1.1 is succsessfully loaded!");
		}

		public void LoadAllMusic()
		{
			daytimeMusic = new List<AudioClip>();
			eveningMusic = new List<AudioClip>();
			((MonoBehaviour)this).StartCoroutine(LoadMusic("/DaytimeMusic"));
			((MonoBehaviour)this).StartCoroutine(LoadMusic("/EveningMusic", isDaytimeMusic: false));
		}

		private IEnumerator wait1(FileInfo file)
		{
			yield return (object)new WaitForSeconds(waitBeforeFail);
			_Logger.LogError((object)$"Could not load {file.Name}! time of {waitBeforeFail} seconds has expired! Trying again...");
			continueFlag = false;
		}

		private IEnumerator wait2(UnityWebRequest web)
		{
			yield return web.SendWebRequest();
			continueFlag = false;
		}

		private IEnumerator LoadMusic(string folder, bool isDaytimeMusic = true)
		{
			if (!Directory.Exists(PLUGIN_PATH_FULL + folder))
			{
				Directory.CreateDirectory(PLUGIN_PATH_FULL + folder);
			}
			DirectoryInfo dI = new DirectoryInfo(PLUGIN_PATH_FULL);
			FileInfo[] sFS = dI.GetFiles("*.mp3");
			FileInfo[] array = sFS;
			foreach (FileInfo songFile in array)
			{
				string[] prefix = songFile.Name.Split("_");
				if (prefix[0] == "D")
				{
					songFile.MoveTo(PLUGIN_PATH_FULL + "/DaytimeMusic/" + prefix[1]);
				}
				else if (prefix[0] == "E")
				{
					songFile.MoveTo(PLUGIN_PATH_FULL + "/EveningMusic/" + prefix[1]);
				}
			}
			DirectoryInfo directoryInfo = new DirectoryInfo(PLUGIN_PATH_FULL + folder);
			FileInfo[] songFiles = directoryInfo.GetFiles("*.mp3");
			FileInfo[] array2 = songFiles;
			foreach (FileInfo print in array2)
			{
				_Logger.LogInfo((object)$"songFile: {print}");
			}
			if (songFiles.Length == 0)
			{
				_Logger.LogInfo((object)("No Songs In Folder: '" + PLUGIN_PATH_FULL + folder + "' Skipping..."));
				yield break;
			}
			FileInfo[] array3 = songFiles;
			foreach (FileInfo songFile2 in array3)
			{
				_Logger.LogInfo((object)("Trying to read " + songFile2.FullName + "..."));
				string songName = songFile2.FullName.ToString();
				string url = $"file://{songName}";
				UnityWebRequest web = UnityWebRequestMultimedia.GetAudioClip(url, (AudioType)13);
				try
				{
					while ((int)web.result != 1)
					{
						coroutine1 = ((MonoBehaviour)this).StartCoroutine(wait1(songFile2));
						coroutine2 = ((MonoBehaviour)this).StartCoroutine(wait2(web));
						continueFlag = true;
						while (continueFlag)
						{
							yield return (object)new WaitForSecondsRealtime(0.2f);
							_Logger.LogMessage((object)("[" + songFile2.Name + "] Waiting tick..."));
						}
						((MonoBehaviour)this).StopCoroutine(coroutine1);
						((MonoBehaviour)this).StopCoroutine(coroutine2);
					}
					string[] splitURL = url.Split("\\");
					_Logger.LogInfo((object)$"Read '{splitURL[^1]}' With Result: {web.result}");
					if ((int)web.result != 1)
					{
						continue;
					}
					AudioClip clip = DownloadHandlerAudioClip.GetContent(web);
					if ((Object)(object)clip != (Object)null)
					{
						((Object)clip).name = splitURL[^1];
						if (isDaytimeMusic)
						{
							daytimeMusic.Add(clip);
						}
						else
						{
							eveningMusic.Add(clip);
						}
					}
				}
				finally
				{
					((IDisposable)web)?.Dispose();
				}
			}
			_Logger.LogInfo((object)"Finished looping through soundtrack files!");
			if (Object.op_Implicit((Object)(object)SoundManager.Instance))
			{
				SoundManager soundManager = SoundManager.Instance;
				_Logger.LogInfo((object)"Found Instance, Loading Again...!");
				_Logger.LogInfo((object)$"Old DaytimeMusic Length: [{soundManager.DaytimeMusic.Length}]");
				_Logger.LogInfo((object)$"Old EveningMusic Length: [{soundManager.EveningMusic.Length}]");
				_Logger.LogInfo((object)"Loading Daytime Music...");
				soundManager.DaytimeMusic = SoundManagerPatch.UpdateMusic(SoundManagerPatch.vanillaDaytimeMusic, daytimeMusic);
				_Logger.LogInfo((object)"Loading Evening Music...");
				soundManager.EveningMusic = SoundManagerPatch.UpdateMusic(SoundManagerPatch.vanillaEveningMusic, eveningMusic);
				_Logger.LogInfo((object)$"New DaytimeMusic Length: [{soundManager.DaytimeMusic.Length}]");
				_Logger.LogInfo((object)$"New EveningMusic Length: [{soundManager.EveningMusic.Length}]");
			}
		}
	}
	public static class MyPluginInfo
	{
		public const string PLUGIN_GUID = "AmbientMod";

		public const string PLUGIN_NAME = "AmbientMod";

		public const string PLUGIN_VERSION = "1.0.0";
	}
}
namespace AmbientMod.Patches
{
	[HarmonyPatch(typeof(SoundManager))]
	internal class SoundManagerPatch
	{
		public static bool landingMusicPlayed;

		public static AudioClip[] vanillaDaytimeMusic;

		public static AudioClip[] vanillaEveningMusic;

		[HarmonyPatch("Awake")]
		[HarmonyPostfix]
		private static void patchAwake(ref AudioClip[] ___DaytimeMusic, ref AudioClip[] ___EveningMusic)
		{
			Plugin._Logger.LogInfo((object)"SoundManager has awaketh!");
			vanillaDaytimeMusic = ___DaytimeMusic;
			vanillaEveningMusic = ___EveningMusic;
			bool flag = false;
			DirectoryInfo directoryInfo = new DirectoryInfo(Plugin.PLUGIN_PATH_FULL + "/DaytimeMusic");
			FileInfo[] files = directoryInfo.GetFiles("*.mp3");
			DirectoryInfo directoryInfo2 = new DirectoryInfo(Plugin.PLUGIN_PATH_FULL + "/EveningMusic");
			FileInfo[] files2 = directoryInfo2.GetFiles("*.mp3");
			if (Config.replaceVanillaSoundtrack.Value)
			{
				if (files.Length != Plugin.daytimeMusic.Count)
				{
					flag = true;
				}
				if (files2.Length != Plugin.eveningMusic.Count)
				{
					flag = true;
				}
			}
			else
			{
				if (files.Length + SoundManager.Instance.DaytimeMusic.Length != Plugin.daytimeMusic.Count)
				{
					flag = true;
				}
				if (files2.Length + SoundManager.Instance.EveningMusic.Length != Plugin.eveningMusic.Count)
				{
					flag = true;
				}
			}
			if (flag)
			{
				Plugin._Logger.LogWarning((object)$"Unloaded Music Detected! {files.Length} != {Plugin.daytimeMusic.Count} || {files2.Length} > {Plugin.eveningMusic.Count} Attempting To Load Again!");
				if ((Object)(object)Plugin.Instance == (Object)null)
				{
					Plugin._Logger.LogError((object)"Could not find 'Plugin.Instance' make sure to set BepInEx.Config.HideManagerGameObject = true! This will prevent unity from destroying it!");
				}
				else
				{
					Plugin.Instance.LoadAllMusic();
				}
			}
		}

		[HarmonyPatch("Start")]
		[HarmonyPrefix]
		private static void patchStart(ref AudioClip[] ___DaytimeMusic, ref AudioClip[] ___EveningMusic)
		{
			Plugin._Logger.LogInfo((object)"SoundManager has starteth!");
			Plugin._Logger.LogInfo((object)$"Old DaytimeMusic Length: [{___DaytimeMusic.Length}]");
			Plugin._Logger.LogInfo((object)$"Old EveningMusic Length: [{___EveningMusic.Length}]");
			Plugin._Logger.LogInfo((object)"Loading Daytime Music...");
			___DaytimeMusic = UpdateMusic(vanillaDaytimeMusic, Plugin.daytimeMusic);
			Plugin._Logger.LogInfo((object)"Loading Evening Music...");
			___EveningMusic = UpdateMusic(vanillaEveningMusic, Plugin.eveningMusic);
			Plugin._Logger.LogInfo((object)$"New DaytimeMusic Length: [{___DaytimeMusic.Length}]");
			Plugin._Logger.LogInfo((object)$"New EveningMusic Length: [{___EveningMusic.Length}]");
		}

		[HarmonyPatch("PlayRandomOutsideMusic")]
		[HarmonyPrefix]
		private static void patchPlayRandomOutsideMusic(ref AudioClip[] ___DaytimeMusic, ref AudioClip[] ___EveningMusic)
		{
			//IL_0037: Unknown result type (might be due to invalid IL or missing references)
			//IL_003d: Invalid comparison between Unknown and I4
			bool isHost = ((NetworkBehaviour)GameNetworkManager.Instance.localPlayerController).IsHost;
			Plugin._Logger.LogMessage((object)$"PlayRandomOutsideMusic Called! IsHost[{isHost}]");
			if (isHost)
			{
				bool flag = (int)TimeOfDay.Instance.dayMode >= 2;
				int clipid = Random.Range(0, ___DaytimeMusic.Length);
				if (flag)
				{
					clipid = Random.Range(0, ___EveningMusic.Length);
				}
				brodcastPlayMusic(clipid);
			}
		}

		public static void brodcastPlayMusic(int clipid)
		{
			Plugin._Logger.LogMessage((object)$"Broadcasting Outside Music: Clip:[{clipid}]");
			Networking.Broadcast(clipid, "gogozooom.AmbientMod.playMusic");
			SyncingPatch.GetNetworkIntBrodcast(clipid, "gogozooom.AmbientMod.playMusic");
		}

		public static bool playerExitedShip()
		{
			PlayerControllerB[] allPlayerScripts = GameNetworkManager.Instance.localPlayerController.playersManager.allPlayerScripts;
			PlayerControllerB[] array = allPlayerScripts;
			foreach (PlayerControllerB val in array)
			{
				if (!val.isInHangarShipRoom)
				{
					return true;
				}
			}
			return false;
		}

		public static AudioClip[] UpdateMusic(AudioClip[] VanillaMusic, List<AudioClip> ModdedMusic)
		{
			List<AudioClip> list = new List<AudioClip>();
			int num = 0;
			if (!Config.replaceVanillaSoundtrack.Value)
			{
				foreach (AudioClip val in VanillaMusic)
				{
					Plugin._Logger.LogInfo((object)("Inserting Song: " + ((Object)val).name));
					list.Add(val);
					num++;
				}
			}
			foreach (AudioClip item in ModdedMusic)
			{
				Plugin._Logger.LogInfo((object)("Inserting Song '" + ((Object)item).name + "' into "));
				list.Add(item);
				num++;
			}
			return list.ToArray();
		}
	}
	[HarmonyPatch(typeof(TimeOfDay))]
	internal class TimeOfDayPatch
	{
		[HarmonyPatch("PlayTimeMusicDelayed")]
		[HarmonyPrefix]
		private static void patchPlaySoundDelayed(AudioClip clip, float delay, bool playRandomDaytimeMusic)
		{
			TimeOfDay instance = TimeOfDay.Instance;
			Coroutine value = Traverse.Create((object)instance).Field("playDelayedMusicCoroutine").GetValue<Coroutine>();
			if (value != null)
			{
				Debug.Log((object)"Already playing music; cancelled starting new music");
			}
			else
			{
				Traverse.Create((object)instance).Field("playDelayedMusicCoroutine").SetValue((object)((MonoBehaviour)instance).StartCoroutine(localPlaySoundDelayed(clip, delay, playRandomDaytimeMusic)));
			}
		}

		private static IEnumerator localPlaySoundDelayed(AudioClip clip, float delay, bool playRandomDaytimeMusic)
		{
			Plugin._Logger.LogMessage((object)$"localPlaySoudnDelayed {((Object)clip).name}, {delay}, {playRandomDaytimeMusic}");
			bool isHost = ((NetworkBehaviour)GameNetworkManager.Instance.localPlayerController).IsHost;
			TimeOfDay _this = TimeOfDay.Instance;
			Plugin._Logger.LogMessage((object)"Play time of day sfx (New)");
			yield return (object)new WaitForSeconds(delay);
			_this.TimeOfDayMusic.PlayOneShot(clip, 1f);
			Plugin._Logger.LogMessage((object)$"Play music!; {_this.TimeOfDayMusic.clip}; {_this.TimeOfDayMusic.volume}");
			if (!playRandomDaytimeMusic || !_this.currentLevel.planetHasTime)
			{
				yield break;
			}
			yield return (object)new WaitForSeconds(Random.Range(5f, 11f));
			bool playMusic = false;
			if (!Config.forceMusicToPlay.Value)
			{
				if (_this.insideLighting || GameNetworkManager.Instance.localPlayerController.isInHangarShipRoom || StartOfRound.Instance.fearLevel > 0.03f)
				{
					yield break;
				}
				if (Random.Range(0, 100) <= Config.musicChance.Value)
				{
					playMusic = true;
				}
			}
			else
			{
				playMusic = true;
			}
			if (playMusic && isHost)
			{
				SoundManager.Instance.PlayRandomOutsideMusic((int)_this.dayMode >= 2);
			}
			Traverse.Create((object)_this).Field("playDelayedMusicCoroutine").SetValue((object)null);
		}
	}
	internal class SyncingPatch
	{
		public static void GetNetworkIntBrodcast(int clipid, string messageid)
		{
			//IL_0063: Unknown result type (might be due to invalid IL or missing references)
			//IL_0069: Invalid comparison between Unknown and I4
			Plugin._Logger.LogMessage((object)("Got 'GetNetworkIntBrodcast': " + messageid));
			if (messageid != "gogozooom.AmbientMod.playMusic")
			{
				return;
			}
			SoundManager instance = SoundManager.Instance;
			float value = Traverse.Create((object)instance).Field("timeSincePlayingLastMusic").GetValue<float>();
			if (value < 200f)
			{
				return;
			}
			if ((int)TimeOfDay.Instance.dayMode >= 2)
			{
				if (instance.EveningMusic.Length == 0)
				{
					Plugin._Logger.LogWarning((object)"No EveningMusic! Skipping.");
					return;
				}
				instance.musicSource.clip = instance.EveningMusic[clipid];
			}
			else
			{
				instance.musicSource.clip = instance.DaytimeMusic[clipid];
			}
			instance.musicSource.Play();
			instance.playingOutsideMusic = true;
			Traverse.Create((object)instance).Field("timeSincePlayingLastMusic").SetValue((object)0f);
		}
	}
}