Decompiled source of KirbyScream v1.0.1

KirbyScream.dll

Decompiled 2 months ago
using System;
using System.Collections;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using UnityEngine;
using UnityEngine.Networking;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("KirbyScream")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0")]
[assembly: AssemblyProduct("KirbyScream")]
[assembly: AssemblyTitle("KirbyScream")]
[assembly: AssemblyVersion("1.0.0.0")]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[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 KirbyScream
{
	public class FallScreamController : MonoBehaviour
	{
		private static readonly string[] AudioExtensions = new string[3] { ".ogg", ".wav", ".mp3" };

		private static readonly FieldRef<CharacterBalloons, bool> ParachuteOpenField = MakeParachuteRef();

		private AudioSource _source;

		private AudioClip _clip;

		private Coroutine _fade;

		private bool _screaming;

		private float _notFallingFor;

		private static FieldRef<CharacterBalloons, bool> MakeParachuteRef()
		{
			try
			{
				return AccessTools.FieldRefAccess<CharacterBalloons, bool>("_isParachuteOpen");
			}
			catch (Exception ex)
			{
				Plugin.Log.LogWarning((object)("Could not bind CharacterBalloons._isParachuteOpen, falling back to parachute GameObject state. " + ex.Message));
				return null;
			}
		}

		private void Awake()
		{
			_source = ((Component)this).gameObject.AddComponent<AudioSource>();
			_source.playOnAwake = false;
			_source.spatialBlend = 0f;
			_source.priority = 0;
			((MonoBehaviour)this).StartCoroutine(LoadClip());
		}

		private static string ResolveAudioPath()
		{
			string text = Plugin.AudioFile.Value?.Trim();
			if (!string.IsNullOrEmpty(text))
			{
				string text2 = (Path.IsPathRooted(text) ? text : Path.Combine(Plugin.PluginDir, text));
				if (File.Exists(text2))
				{
					return text2;
				}
				Plugin.Log.LogWarning((object)("AudioFile '" + text + "' not found, scanning the mod folder instead."));
			}
			return (from f in Directory.GetFiles(Plugin.PluginDir)
				where AudioExtensions.Contains(Path.GetExtension(f).ToLowerInvariant())
				select f).OrderBy<string, string>((string f) => f, StringComparer.OrdinalIgnoreCase).FirstOrDefault();
		}

		private static AudioType AudioTypeFor(string path)
		{
			return (AudioType)(Path.GetExtension(path).ToLowerInvariant() switch
			{
				".ogg" => 14, 
				".wav" => 20, 
				".mp3" => 13, 
				_ => 0, 
			});
		}

		private IEnumerator LoadClip()
		{
			string path = ResolveAudioPath();
			if (path == null)
			{
				Plugin.Log.LogError((object)("No scream audio found. Put a .ogg/.wav/.mp3 in: " + Plugin.PluginDir));
				yield break;
			}
			string absoluteUri = new Uri(path).AbsoluteUri;
			Plugin.Log.LogInfo((object)("Loading scream audio: " + path));
			UnityWebRequest req = UnityWebRequestMultimedia.GetAudioClip(absoluteUri, AudioTypeFor(path));
			try
			{
				yield return req.SendWebRequest();
				if ((int)req.result != 1)
				{
					Plugin.Log.LogError((object)("Failed to load '" + path + "': " + req.error));
					yield break;
				}
				AudioClip content = DownloadHandlerAudioClip.GetContent(req);
				if ((Object)(object)content == (Object)null || content.length <= 0f)
				{
					Plugin.Log.LogError((object)("'" + path + "' loaded but produced an empty AudioClip."));
					yield break;
				}
				((Object)content).name = Path.GetFileNameWithoutExtension(path);
				_clip = content;
				_source.clip = content;
				Plugin.Log.LogInfo((object)$"Scream ready: {((Object)content).name} ({content.length:0.00}s)");
			}
			finally
			{
				((IDisposable)req)?.Dispose();
			}
		}

		private static bool IsParachuteOpen(Character c)
		{
			CharacterBalloons val = c.refs?.balloons;
			if ((Object)(object)val != (Object)null && ParachuteOpenField != null)
			{
				return ParachuteOpenField.Invoke(val);
			}
			Parachute val2 = c.refs?.parachute;
			if ((Object)(object)val2 != (Object)null)
			{
				return ((Component)val2).gameObject.activeSelf;
			}
			return false;
		}

		private void Update()
		{
			Character localCharacter = Character.localCharacter;
			if ((Object)(object)localCharacter == (Object)null || (Object)(object)localCharacter.data == (Object)null || localCharacter.refs == null)
			{
				if (_screaming)
				{
					Stop("no local character");
				}
				return;
			}
			CharacterData data = localCharacter.data;
			string text = null;
			if (data.dead)
			{
				text = "died";
			}
			else if (data.isGrounded)
			{
				text = "landed";
			}
			else if (Plugin.StopWhenClimbing.Value && data.isClimbingAnything)
			{
				text = "grabbed something";
			}
			else if (data.isCarried || (Object)(object)data.carrier != (Object)null)
			{
				text = "being carried";
			}
			else if (Plugin.StopWhenParachuteOpens.Value && IsParachuteOpen(localCharacter))
			{
				text = "parachute open";
			}
			bool flag = false;
			if (text == null && data.avarageVelocity.y < 0f - Plugin.MinDownSpeed.Value)
			{
				bool num = (Object)(object)localCharacter.refs.movement != (Object)null && localCharacter.refs.movement.FallTime() >= Plugin.MinFallTime.Value;
				bool flag2 = Plugin.TriggerOnRagdollFall.Value && data.fallSeconds > 0f;
				flag = num || flag2;
			}
			if (flag)
			{
				_notFallingFor = 0f;
				if (!_screaming)
				{
					Begin();
				}
			}
			else
			{
				if (!_screaming)
				{
					return;
				}
				if (text != null)
				{
					Stop(text);
					return;
				}
				_notFallingFor += Time.deltaTime;
				if (_notFallingFor >= Plugin.StopGraceSeconds.Value)
				{
					Stop("no longer falling");
				}
			}
		}

		private void Begin()
		{
			_screaming = true;
			if (!((Object)(object)_clip == (Object)null))
			{
				if (_fade != null)
				{
					((MonoBehaviour)this).StopCoroutine(_fade);
					_fade = null;
				}
				if (Plugin.UseGameSfxMixer.Value && (Object)(object)SFX_Player.instance != (Object)null && (Object)(object)SFX_Player.instance.defaultMixerGroup != (Object)null)
				{
					_source.outputAudioMixerGroup = SFX_Player.instance.defaultMixerGroup;
				}
				else
				{
					_source.outputAudioMixerGroup = null;
				}
				_source.loop = Plugin.Loop.Value;
				_source.volume = Plugin.Volume.Value;
				_source.time = 0f;
				_source.Play();
				if (Plugin.DebugLog.Value)
				{
					Plugin.Log.LogInfo((object)"SCREAM start");
				}
			}
		}

		private void Stop(string reason)
		{
			_screaming = false;
			_notFallingFor = 0f;
			if ((Object)(object)_clip == (Object)null || !_source.isPlaying)
			{
				return;
			}
			if (Plugin.DebugLog.Value)
			{
				Plugin.Log.LogInfo((object)("SCREAM stop (" + reason + ")"));
			}
			float value = Plugin.StopFadeSeconds.Value;
			if (value <= 0f)
			{
				_source.Stop();
				return;
			}
			if (_fade != null)
			{
				((MonoBehaviour)this).StopCoroutine(_fade);
			}
			_fade = ((MonoBehaviour)this).StartCoroutine(FadeOut(value));
		}

		private IEnumerator FadeOut(float seconds)
		{
			float start = _source.volume;
			float t = 0f;
			while (t < seconds && _source.isPlaying)
			{
				t += Time.unscaledDeltaTime;
				_source.volume = Mathf.Lerp(start, 0f, t / seconds);
				yield return null;
			}
			_source.Stop();
			_source.volume = start;
			_fade = null;
		}
	}
	[BepInPlugin("toiletking.peak.kirbyscream", "KirbyScream", "1.0.0")]
	public class Plugin : BaseUnityPlugin
	{
		public const string GUID = "toiletking.peak.kirbyscream";

		public const string NAME = "KirbyScream";

		public const string VERSION = "1.0.0";

		internal static ManualLogSource Log;

		internal static string PluginDir;

		internal static ConfigEntry<string> AudioFile;

		internal static ConfigEntry<float> Volume;

		internal static ConfigEntry<bool> Loop;

		internal static ConfigEntry<bool> UseGameSfxMixer;

		internal static ConfigEntry<float> MinFallTime;

		internal static ConfigEntry<float> MinDownSpeed;

		internal static ConfigEntry<bool> TriggerOnRagdollFall;

		internal static ConfigEntry<float> StopFadeSeconds;

		internal static ConfigEntry<float> StopGraceSeconds;

		internal static ConfigEntry<bool> StopWhenParachuteOpens;

		internal static ConfigEntry<bool> StopWhenClimbing;

		internal static ConfigEntry<bool> DebugLog;

		private void Awake()
		{
			//IL_0072: Unknown result type (might be due to invalid IL or missing references)
			//IL_007c: Expected O, but got Unknown
			//IL_00ef: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f9: Expected O, but got Unknown
			//IL_012c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0136: Expected O, but got Unknown
			//IL_0189: Unknown result type (might be due to invalid IL or missing references)
			//IL_0193: Expected O, but got Unknown
			//IL_01c6: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d0: Expected O, but got Unknown
			//IL_023a: Unknown result type (might be due to invalid IL or missing references)
			//IL_023f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0245: Expected O, but got Unknown
			//IL_0245: Unknown result type (might be due to invalid IL or missing references)
			Log = ((BaseUnityPlugin)this).Logger;
			PluginDir = Path.GetDirectoryName(((BaseUnityPlugin)this).Info.Location);
			AudioFile = ((BaseUnityPlugin)this).Config.Bind<string>("Audio", "AudioFile", "", "File name of the scream (relative to the mod folder, or an absolute path). Leave empty to use the first .ogg / .wav / .mp3 found next to the plugin dll.");
			Volume = ((BaseUnityPlugin)this).Config.Bind<float>("Audio", "Volume", 0.6f, new ConfigDescription("Playback volume.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 1f), Array.Empty<object>()));
			Loop = ((BaseUnityPlugin)this).Config.Bind<bool>("Audio", "Loop", true, "Keep looping the clip until you land or die. If false it plays once per fall.");
			UseGameSfxMixer = ((BaseUnityPlugin)this).Config.Bind<bool>("Audio", "UseGameSfxMixer", true, "Route through the game's SFX mixer so the in-game SFX volume slider applies.");
			MinFallTime = ((BaseUnityPlugin)this).Config.Bind<float>("Trigger", "MinFallTime", 0.3f, new ConfigDescription("Seconds of free fall (the game's own FallTime, which already discounts jumps and bounces) before screaming. The game uses 1.5 for fall damage; lower = earlier scream but may fire on big jumps.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 3f), Array.Empty<object>()));
			MinDownSpeed = ((BaseUnityPlugin)this).Config.Bind<float>("Trigger", "MinDownSpeed", 5f, new ConfigDescription("Minimum downward speed (m/s) required to scream. Max fall gravity is 20 m/s^2.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 30f), Array.Empty<object>()));
			TriggerOnRagdollFall = ((BaseUnityPlugin)this).Config.Bind<bool>("Trigger", "TriggerOnRagdollFall", true, "Also scream immediately when the game puts you into a ragdoll fall (tripped, thrown, knocked off), as long as you are moving downward.");
			StopFadeSeconds = ((BaseUnityPlugin)this).Config.Bind<float>("Stop", "StopFadeSeconds", 0.05f, new ConfigDescription("Fade-out length when the scream stops. 0 = hard cut on impact.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 2f), Array.Empty<object>()));
			StopGraceSeconds = ((BaseUnityPlugin)this).Config.Bind<float>("Stop", "StopGraceSeconds", 0.35f, new ConfigDescription("If you are still airborne but no longer falling fast (updraft, bounce pad, balloon...), wait this long before stopping so the scream does not stutter.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 2f), Array.Empty<object>()));
			StopWhenParachuteOpens = ((BaseUnityPlugin)this).Config.Bind<bool>("Stop", "StopWhenParachuteOpens", true, "Stop screaming once the parachute deploys.");
			StopWhenClimbing = ((BaseUnityPlugin)this).Config.Bind<bool>("Stop", "StopWhenClimbing", true, "Stop screaming if you grab a wall, rope or vine mid-fall.");
			DebugLog = ((BaseUnityPlugin)this).Config.Bind<bool>("Misc", "DebugLog", false, "Log every scream start/stop with the reason to the BepInEx console.");
			GameObject val = new GameObject("KirbyScreamController");
			Object.DontDestroyOnLoad((Object)val);
			((Object)val).hideFlags = (HideFlags)61;
			val.AddComponent<FallScreamController>();
			Log.LogInfo((object)"KirbyScream 1.0.0 loaded.");
		}
	}
}