Decompiled source of TakeItInside v1.3.2

plugins/TakeItInside/TakeItInside.dll

Decompiled 12 hours ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Runtime.CompilerServices;
using BepInEx;
using BepInEx.Configuration;
using HarmonyLib;
using UnityEngine;
using UnityEngine.Networking;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: AssemblyVersion("0.0.0.0")]
namespace TakeItInsideMusic;

[BepInPlugin("woopsy.takeitinside", "Take It Inside", "1.3.2")]
public sealed class Plugin : BaseUnityPlugin
{
	private sealed class Playback
	{
		public bool Shop;

		public bool Loop;

		public bool AppliedVolume;

		public AudioClip Original;

		public float BaseVolume;

		public float LastVolume;

		public ShopGainFilter GainFilter;
	}

	public const string Id = "woopsy.takeitinside";

	private static Plugin instance;

	private ConfigEntry<bool> shopEnabled;

	private ConfigEntry<bool> menuEnabled;

	private ConfigEntry<int> volume;

	private ConfigEntry<int> shopVolume;

	private AudioClip song;

	private Harmony harmony;

	private Type radioType;

	private float nextScan;

	private readonly List<Component> radios = new List<Component>();

	private readonly Dictionary<AudioSource, Playback> active = new Dictionary<AudioSource, Playback>();

	private readonly List<AudioSource> remove = new List<AudioSource>();

	private readonly HashSet<AudioSource> shopSources = new HashSet<AudioSource>();

	private void Awake()
	{
		//IL_006e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0078: Expected O, but got Unknown
		//IL_00a6: Unknown result type (might be due to invalid IL or missing references)
		//IL_00b0: Expected O, but got Unknown
		//IL_00f9: Unknown result type (might be due to invalid IL or missing references)
		//IL_0103: Expected O, but got Unknown
		//IL_011b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0128: Expected O, but got Unknown
		instance = this;
		shopEnabled = ((BaseUnityPlugin)this).Config.Bind<bool>("Music", "Shop Music", true, "Replace the shop soundtrack. Changes apply to active music.");
		menuEnabled = ((BaseUnityPlugin)this).Config.Bind<bool>("Music", "Main Menu Music", false, "Replace the main menu and Halloween theme. Changes apply to active music.");
		volume = ((BaseUnityPlugin)this).Config.Bind<int>("Music", "Custom Music Volume", 100, new ConfigDescription("Percentage of the game's music source volume. The game music slider still applies.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 100), new object[0]));
		shopVolume = ((BaseUnityPlugin)this).Config.Bind<int>("Music", "Shop Volume Boost", 100, new ConfigDescription("Shop-only multiplier for custom music: 100 = normal, 200 = double gain before peak limiting. The custom music and game volume settings still apply.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 200), new object[0]));
		try
		{
			radioType = AccessTools.TypeByName("ShopRadio");
			if (radioType != null)
			{
				MethodInfo methodInfo = AccessTools.Method(radioType, "Start", Type.EmptyTypes, (Type[])null);
				if (methodInfo != null)
				{
					harmony = new Harmony("woopsy.takeitinside");
					harmony.Patch((MethodBase)methodInfo, (HarmonyMethod)null, new HarmonyMethod(typeof(Plugin), "RadioStarted", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
					((BaseUnityPlugin)this).Logger.LogInfo((object)"Patched ShopRadio.Start.");
				}
			}
			if (harmony == null)
			{
				((BaseUnityPlugin)this).Logger.LogWarning((object)"ShopRadio.Start not found; using audio-source discovery fallback.");
			}
		}
		catch (Exception ex)
		{
			((BaseUnityPlugin)this).Logger.LogWarning((object)("Shop patch setup failed; using discovery: " + ex.Message));
		}
		((MonoBehaviour)this).StartCoroutine(LoadSong());
	}

	private static void RadioStarted(object __instance)
	{
		if (!((Object)(object)instance == (Object)null))
		{
			Component val = (Component)((__instance is Component) ? __instance : null);
			if ((Object)(object)val != (Object)null && !instance.radios.Contains(val))
			{
				instance.radios.Add(val);
			}
		}
	}

	private IEnumerator LoadSong()
	{
		string path = Path.Combine(Path.GetDirectoryName(((BaseUnityPlugin)this).Info.Location), "TakeItInside.ogg");
		if (!File.Exists(path))
		{
			((BaseUnityPlugin)this).Logger.LogError((object)("Song missing: " + path));
			yield break;
		}
		UnityWebRequest req = UnityWebRequestMultimedia.GetAudioClip(new Uri(path).AbsoluteUri, (AudioType)14);
		try
		{
			yield return req.SendWebRequest();
			if ((int)req.result != 1)
			{
				((BaseUnityPlugin)this).Logger.LogError((object)("Song load failed: " + req.error));
				yield break;
			}
			song = DownloadHandlerAudioClip.GetContent(req);
			if ((Object)(object)song == (Object)null)
			{
				((BaseUnityPlugin)this).Logger.LogError((object)"Song decoded to null.");
				yield break;
			}
			((Object)song).name = "TakeItInside_Custom";
			((BaseUnityPlugin)this).Logger.LogInfo((object)("Song loaded: " + song.length.ToString("F1") + " seconds."));
		}
		finally
		{
			((IDisposable)req)?.Dispose();
		}
	}

	private static object Member(object obj, string name)
	{
		if (obj == null)
		{
			return null;
		}
		FieldInfo fieldInfo = AccessTools.Field(obj.GetType(), name);
		if (fieldInfo != null)
		{
			return fieldInfo.GetValue(obj);
		}
		PropertyInfo propertyInfo = AccessTools.Property(obj.GetType(), name);
		if (!(propertyInfo == null))
		{
			return propertyInfo.GetValue(obj, null);
		}
		return null;
	}

	private static bool IsMenu(AudioClip clip)
	{
		if ((Object)(object)clip == (Object)null)
		{
			return false;
		}
		string text = ((Object)clip).name.Trim();
		if (!text.Equals("msc main menu", StringComparison.OrdinalIgnoreCase))
		{
			return text.Equals("main theme halloween", StringComparison.OrdinalIgnoreCase);
		}
		return true;
	}

	private static bool IsShop(AudioClip clip)
	{
		if ((Object)(object)clip == (Object)null)
		{
			return false;
		}
		string text = ((Object)clip).name.Trim();
		if (!text.Equals("shop music", StringComparison.OrdinalIgnoreCase))
		{
			return text.StartsWith("shop radio", StringComparison.OrdinalIgnoreCase);
		}
		return true;
	}

	private void DiscoverRadios()
	{
		if (radioType == null)
		{
			return;
		}
		Object[] array = Object.FindObjectsOfType(radioType);
		foreach (Object val in array)
		{
			Component val2 = (Component)(object)((val is Component) ? val : null);
			if ((Object)(object)val2 != (Object)null && !radios.Contains(val2))
			{
				radios.Add(val2);
			}
		}
	}

	private void UpdateShopSources()
	{
		shopSources.Clear();
		for (int num = radios.Count - 1; num >= 0; num--)
		{
			Component val = radios[num];
			if ((Object)(object)val == (Object)null)
			{
				radios.RemoveAt(num);
			}
			else if (val.gameObject.activeInHierarchy)
			{
				try
				{
					object obj = Member(val, "shopMusic");
					object obj2 = Member(obj, "Source");
					AudioSource val2 = (AudioSource)((obj2 is AudioSource) ? obj2 : null);
					if (!((Object)(object)val2 == (Object)null))
					{
						shopSources.Add(val2);
						if (shopEnabled.Value && (Object)(object)val2.clip != (Object)null)
						{
							Apply(val2, shop: true);
						}
					}
				}
				catch (Exception ex)
				{
					((BaseUnityPlugin)this).Logger.LogWarning((object)("Shop source discovery failed: " + ex.Message));
					radios.RemoveAt(num);
				}
			}
		}
	}

	private void LateUpdate()
	{
		if ((Object)(object)song == (Object)null)
		{
			return;
		}
		try
		{
			bool flag = Time.unscaledTime >= nextScan;
			if (flag)
			{
				nextScan = Time.unscaledTime + 0.15f;
				DiscoverRadios();
			}
			UpdateShopSources();
			if (flag)
			{
				AudioSource[] array = Object.FindObjectsOfType<AudioSource>();
				foreach (AudioSource val in array)
				{
					if (!((Object)(object)val == (Object)null) && val.isPlaying)
					{
						if (shopEnabled.Value && IsShop(val.clip))
						{
							Apply(val, shop: true);
						}
						else if (menuEnabled.Value && IsMenu(val.clip))
						{
							Apply(val, shop: false);
						}
					}
				}
			}
			remove.Clear();
			foreach (KeyValuePair<AudioSource, Playback> item in active)
			{
				AudioSource key = item.Key;
				Playback value = item.Value;
				if ((Object)(object)key == (Object)null)
				{
					remove.Add(key);
					continue;
				}
				if (!(value.Shop ? shopEnabled.Value : menuEnabled.Value))
				{
					Restore(key, value, resume: true);
					remove.Add(key);
					continue;
				}
				if ((Object)(object)key.clip != (Object)(object)song)
				{
					if ((Object)(object)value.GainFilter != (Object)null)
					{
						value.GainFilter.Gain = 1f;
					}
					bool num;
					if (!value.Shop)
					{
						num = IsMenu(key.clip);
					}
					else
					{
						if (IsShop(key.clip))
						{
							goto IL_01e5;
						}
						if (!shopSources.Contains(key))
						{
							goto IL_01cd;
						}
						num = (Object)(object)key.clip != (Object)null;
					}
					if (!num)
					{
						goto IL_01cd;
					}
					goto IL_01e5;
				}
				goto IL_022c;
				IL_01cd:
				Restore(key, value, resume: false);
				remove.Add(key);
				continue;
				IL_022c:
				if ((Object)(object)key.clip == (Object)(object)song)
				{
					if (value.Shop && key.isPlaying)
					{
						key.loop = true;
					}
					ApplyVolume(key, value);
				}
				continue;
				IL_01e5:
				if (key.isPlaying)
				{
					Swap(key, value);
					((BaseUnityPlugin)this).Logger.LogDebug((object)((value.Shop ? "Shop" : "Menu") + " track change intercepted: " + ((Object)value.Original).name));
				}
				goto IL_022c;
			}
			foreach (AudioSource item2 in remove)
			{
				active.Remove(item2);
			}
		}
		catch (Exception ex)
		{
			((BaseUnityPlugin)this).Logger.LogError((object)("Music update disabled after exception: " + ex));
			Cleanup();
			((Behaviour)this).enabled = false;
		}
	}

	private void Apply(AudioSource src, bool shop)
	{
		if (!active.TryGetValue(src, out var value) && src.isPlaying && !((Object)(object)src.clip == (Object)null) && !((Object)(object)src.clip == (Object)(object)song))
		{
			Playback playback = new Playback();
			playback.Shop = shop;
			playback.Original = src.clip;
			playback.Loop = src.loop;
			playback.BaseVolume = src.volume;
			value = playback;
			active.Add(src, value);
			Swap(src, value);
			((BaseUnityPlugin)this).Logger.LogInfo((object)((shop ? "Shop" : "Main menu") + " replacement active on " + ((Object)src).name + " (" + ((Object)value.Original).name + ")."));
		}
	}

	private void Swap(AudioSource src, Playback state)
	{
		if (src.isPlaying && !((Object)(object)src.clip == (Object)null) && !((Object)(object)src.clip == (Object)(object)song))
		{
			state.Original = src.clip;
			if (!src.loop)
			{
				state.Loop = false;
			}
			src.Stop();
			src.clip = song;
			src.loop = true;
			ApplyVolume(src, state);
			src.Play();
		}
	}

	private void ApplyVolume(AudioSource src, Playback state)
	{
		if (!state.AppliedVolume || !Mathf.Approximately(src.volume, state.LastVolume))
		{
			state.BaseVolume = src.volume;
		}
		float num = Mathf.Max(0f, state.BaseVolume * ((float)volume.Value / 100f) * (state.Shop ? ((float)shopVolume.Value / 100f) : 1f));
		state.LastVolume = Mathf.Clamp01(num);
		src.volume = state.LastVolume;
		state.AppliedVolume = true;
		float num2 = (state.Shop ? Mathf.Max(1f, num) : 1f);
		if (num2 > 1f && (Object)(object)state.GainFilter == (Object)null)
		{
			state.GainFilter = ((Component)src).gameObject.AddComponent<ShopGainFilter>();
		}
		if ((Object)(object)state.GainFilter != (Object)null)
		{
			state.GainFilter.Gain = num2;
		}
	}

	private void Restore(AudioSource src, Playback state, bool resume)
	{
		if ((Object)(object)state.GainFilter != (Object)null)
		{
			state.GainFilter.Gain = 1f;
			Object.Destroy((Object)(object)state.GainFilter);
			state.GainFilter = null;
		}
		if ((Object)(object)src == (Object)null)
		{
			return;
		}
		if (state.AppliedVolume && Mathf.Approximately(src.volume, state.LastVolume))
		{
			src.volume = state.BaseVolume;
		}
		if (!((Object)(object)src.clip != (Object)(object)song))
		{
			bool isPlaying = src.isPlaying;
			src.Stop();
			src.clip = state.Original;
			src.loop = state.Loop;
			if (resume && isPlaying && (Object)(object)src.clip != (Object)null && ((Behaviour)src).isActiveAndEnabled)
			{
				src.Play();
			}
		}
	}

	private void Cleanup()
	{
		foreach (KeyValuePair<AudioSource, Playback> item in active)
		{
			Restore(item.Key, item.Value, resume: false);
		}
		active.Clear();
	}

	private void OnDestroy()
	{
		Cleanup();
		if (harmony != null)
		{
			harmony.UnpatchSelf();
		}
		if ((Object)(object)song != (Object)null)
		{
			Object.Destroy((Object)(object)song);
		}
		if ((Object)(object)instance == (Object)(object)this)
		{
			instance = null;
		}
	}
}
public sealed class ShopGainFilter : MonoBehaviour
{
	public volatile float Gain = 1f;

	private float envelope = 1f;

	private void OnAudioFilterRead(float[] data, int channels)
	{
		float gain = Gain;
		if (gain <= 1f || channels <= 0)
		{
			envelope = 1f;
			return;
		}
		for (int i = 0; i < data.Length; i += channels)
		{
			int num = Math.Min(i + channels, data.Length);
			float num2 = 0f;
			for (int j = i; j < num; j++)
			{
				num2 = Math.Max(num2, Math.Abs(data[j]) * gain);
			}
			float val = ((num2 > 0.98f) ? (0.98f / num2) : 1f);
			envelope = Math.Min(val, envelope + (1f - envelope) * 0.0005f);
			float num3 = gain * envelope;
			for (int k = i; k < num; k++)
			{
				data[k] *= num3;
			}
		}
	}
}