Decompiled source of CorruptedHealth v1.0.0

CorruptedHealth.dll

Decompiled a day ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using HutongGames.PlayMaker;
using Microsoft.CodeAnalysis;
using UnityEngine;
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: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("0.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.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]
	[Microsoft.CodeAnalysis.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]
	[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 CorruptedHealth
{
	[BepInPlugin("lagerthon.CorruptedHealth", "CorruptedHealth", "1.0.0")]
	public class CorruptedHealth : BaseUnityPlugin
	{
		public class CachedAudio
		{
			public AudioSource source;

			public AudioLowPassFilter lowPass;
		}

		[CompilerGenerated]
		private sealed class <DelayedFlashHealth>d__14 : IEnumerator<object>, IEnumerator, IDisposable
		{
			private int <>1__state;

			private object <>2__current;

			public CorruptedHealth <>4__this;

			object IEnumerator<object>.Current
			{
				[DebuggerHidden]
				get
				{
					return <>2__current;
				}
			}

			object IEnumerator.Current
			{
				[DebuggerHidden]
				get
				{
					return <>2__current;
				}
			}

			[DebuggerHidden]
			public <DelayedFlashHealth>d__14(int <>1__state)
			{
				this.<>1__state = <>1__state;
			}

			[DebuggerHidden]
			void IDisposable.Dispose()
			{
				<>1__state = -2;
			}

			private bool MoveNext()
			{
				//IL_0026: Unknown result type (might be due to invalid IL or missing references)
				//IL_0030: Expected O, but got Unknown
				switch (<>1__state)
				{
				default:
					return false;
				case 0:
					<>1__state = -1;
					<>2__current = (object)new WaitForSeconds(3f);
					<>1__state = 1;
					return true;
				case 1:
					<>1__state = -1;
					FlashMasks.FlashHealth(pd.health);
					keyPressed = true;
					return false;
				}
			}

			bool IEnumerator.MoveNext()
			{
				//ILSpy generated this explicit interface implementation from .override directive in MoveNext
				return this.MoveNext();
			}

			[DebuggerHidden]
			void IEnumerator.Reset()
			{
				throw new NotSupportedException();
			}
		}

		public static ConfigEntry<float> MaxSpeed;

		public static ConfigEntry<float> audioModulation;

		public static ConfigEntry<KeyboardShortcut> flashKey;

		public static bool keyPressed = false;

		private bool wasAtBench = false;

		private Coroutine delayedFlashCoroutine;

		private static bool firstSpawn = true;

		public static bool configChanged = false;

		public static PlayerData pd;

		internal static ManualLogSource Log;

		public static readonly List<CachedAudio> Cached = new List<CachedAudio>();

		private void Awake()
		{
			//IL_003a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0044: Expected O, but got Unknown
			//IL_0077: Unknown result type (might be due to invalid IL or missing references)
			//IL_0081: Expected O, but got Unknown
			//IL_00a0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c6: Unknown result type (might be due to invalid IL or missing references)
			//IL_013a: Unknown result type (might be due to invalid IL or missing references)
			Log = ((BaseUnityPlugin)this).Logger;
			MaxSpeed = ((BaseUnityPlugin)this).Config.Bind<float>("Max Speed", "Max Speed", 2f, new ConfigDescription("Sets the maximum speed of the game at full health", (AcceptableValueBase)(object)new AcceptableValueRange<float>(1.5f, 2f), Array.Empty<object>()));
			audioModulation = ((BaseUnityPlugin)this).Config.Bind<float>("Music and Audio", "Modulation intensity", 1f, new ConfigDescription("Adjusts how much the audio will modulate", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 1f), Array.Empty<object>()));
			flashKey = ((BaseUnityPlugin)this).Config.Bind<KeyboardShortcut>("Display Key", "Display Masks", new KeyboardShortcut((KeyCode)306, Array.Empty<KeyCode>()), "Temporarily displays masks (Silk required)");
			SceneManager.sceneLoaded += OnSceneLoaded;
			RebuildAudioCache(SceneManager.GetActiveScene());
			pd = PlayerData.instance;
			keyPressed = false;
			MaxSpeed.SettingChanged += delegate
			{
				configChanged = true;
			};
			audioModulation.SettingChanged += delegate
			{
				configChanged = true;
			};
			new Harmony("lagerthon.CorruptedHealth").PatchAll();
			Log.LogInfo((object)"Health and Speed Loaded");
		}

		private void Update()
		{
			//IL_00cd: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d2: Unknown result type (might be due to invalid IL or missing references)
			HeroController instance = HeroController.instance;
			PlayerData instance2 = PlayerData.instance;
			if ((Object)(object)instance == (Object)null || instance2 == null)
			{
				return;
			}
			if (firstSpawn)
			{
				firstSpawn = false;
			}
			bool atBench = instance2.atBench;
			if (atBench && !firstSpawn)
			{
				if (delayedFlashCoroutine != null)
				{
					((MonoBehaviour)this).StopCoroutine(delayedFlashCoroutine);
					delayedFlashCoroutine = null;
					FlashMasks.FlashHealth(instance2.maxHealth);
				}
			}
			else if (wasAtBench && !atBench && delayedFlashCoroutine == null)
			{
				delayedFlashCoroutine = ((MonoBehaviour)this).StartCoroutine(DelayedFlashHealth());
			}
			wasAtBench = atBench;
			KeyboardShortcut value = flashKey.Value;
			if (((KeyboardShortcut)(ref value)).IsDown())
			{
				if (instance2.silk < 3)
				{
					return;
				}
				instance.TakeSilk(3);
				FlashMasks.FlashHealth(instance2.health);
				keyPressed = true;
			}
			if (!atBench && keyPressed)
			{
				FlashMasks.HideHealth();
				if (FlashMasks.health2Timers.Count == 0)
				{
					keyPressed = false;
				}
			}
		}

		[IteratorStateMachine(typeof(<DelayedFlashHealth>d__14))]
		private IEnumerator DelayedFlashHealth()
		{
			//yield-return decompiler failed: Unexpected instruction in Iterator.Dispose()
			return new <DelayedFlashHealth>d__14(0)
			{
				<>4__this = this
			};
		}

		private void OnDestroy()
		{
			SceneManager.sceneLoaded -= OnSceneLoaded;
		}

		private void OnSceneLoaded(Scene scene, LoadSceneMode mode)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			RebuildAudioCache(scene);
			firstSpawn = true;
		}

		private static void RebuildAudioCache(Scene scene)
		{
			Cached.Clear();
			AudioSource[] array = Resources.FindObjectsOfTypeAll<AudioSource>();
			foreach (AudioSource val in array)
			{
				if (!((Object)(object)val == (Object)null) && !((Object)val).name.Contains("Audio Player Actor") && val.loop && !(val.spatialBlend > 0f) && (!((Object)(object)val.clip != (Object)null) || !(val.clip.length < 10f)))
				{
					AudioLowPassFilter val2 = ((Component)val).GetComponent<AudioLowPassFilter>();
					if ((Object)(object)val2 == (Object)null)
					{
						val2 = ((Component)val).gameObject.AddComponent<AudioLowPassFilter>();
					}
					Cached.Add(new CachedAudio
					{
						source = val,
						lowPass = val2
					});
				}
			}
		}
	}
	[HarmonyPatch]
	internal class FracturedMaskPatch
	{
		public static int fracturedMask;

		[HarmonyPatch(typeof(ToolItemManager), "GetCurrentEquippedTools")]
		[HarmonyPostfix]
		private static void PostfixFracturedMask(ref List<ToolItem> __result)
		{
			fracturedMask = 0;
			if (__result == null)
			{
				return;
			}
			foreach (ToolItem item in __result)
			{
				if ((Object)(object)item != (Object)null && item.name == "Fractured Mask")
				{
					fracturedMask = 1;
					break;
				}
			}
		}
	}
	internal class FlashMasks
	{
		public static Dictionary<GameObject, float> health2Timers = new Dictionary<GameObject, float>();

		public static HashSet<GameObject> flashedHealth2 = new HashSet<GameObject>();

		public static void FlashHealth(int health)
		{
			PlayerData instance = PlayerData.instance;
			PlayMakerFSM[] array = Resources.FindObjectsOfTypeAll<PlayMakerFSM>();
			foreach (PlayMakerFSM val in array)
			{
				if (val.FsmName != "health_display" || !((Object)((Component)val).gameObject).name.Contains("Health 2+(Clone)"))
				{
					continue;
				}
				CorruptedHealth.Log.LogInfo((object)("Found: " + ((Object)((Component)val).gameObject).name));
				FsmInt val2 = val.FsmVariables.FindFsmInt("Health Number");
				if (val2 == null)
				{
					continue;
				}
				int value = val2.Value;
				if (!flashedHealth2.Contains(((Component)val).gameObject))
				{
					flashedHealth2.Add(((Component)val).gameObject);
					health2Timers[((Component)val).gameObject] = 2f;
					if (value <= health)
					{
						val.SetState("Idle Enter");
					}
				}
			}
		}

		public static void HideHealth()
		{
			List<GameObject> list = new List<GameObject>(health2Timers.Keys);
			foreach (GameObject item in list)
			{
				health2Timers[item] -= Time.unscaledDeltaTime;
				if (health2Timers[item] <= 0f)
				{
					PlayMakerFSM component = item.GetComponent<PlayMakerFSM>();
					if ((Object)(object)component != (Object)null)
					{
						component.SetState("Inactive");
					}
					health2Timers.Remove(item);
					flashedHealth2.Remove(item);
				}
			}
		}
	}
	[HarmonyPatch(typeof(GameManager), "Update")]
	internal class Patch_GameManager_Update
	{
		private static float currentPitch = 1f;

		private static float pitchVelocity = 0f;

		private static float lastTargetPitch = 1f;

		private static float pulseTimer = 0f;

		private static float pulseSign = 1f;

		public static int fracturedMask = 0;

		private static int lastHealth = -1;

		private static int lastMaxHealth = -1;

		private static float targetTimeScale = 1f;

		private static float targetPitch = 1f;

		private static float currentTimeScale = 1f;

		private static float timeScaleVelocity = 0f;

		private static void Postfix()
		{
			if ((Object)(object)GameManager.instance != (Object)null && GameManager.instance.isPaused)
			{
				return;
			}
			PlayerData instance = PlayerData.instance;
			if (instance != null)
			{
				fracturedMask = FracturedMaskPatch.fracturedMask;
				int num = instance.health + instance.healthBlue + fracturedMask;
				int num2 = instance.maxHealth + instance.healthBlue + fracturedMask;
				if (num != lastHealth || num2 != lastMaxHealth || CorruptedHealth.configChanged)
				{
					lastHealth = num;
					lastMaxHealth = num2;
					CorruptedHealth.configChanged = false;
					RecalculateTargets(instance, num, num2);
				}
				UpdateTimeScale();
				UpdateAudio(instance);
			}
		}

		private static void RecalculateTargets(PlayerData pd, int health, int maxHealth)
		{
			float num = (float)health / (float)maxHealth;
			targetTimeScale = 1f + (CorruptedHealth.MaxSpeed.Value - 1f) * num;
			float num2 = 1f + num;
			targetPitch = 1f + (num2 - 1.9f) * CorruptedHealth.audioModulation.Value;
			if (Mathf.Abs(targetPitch - lastTargetPitch) > 0.01f)
			{
				pulseTimer = 0.5f;
				pulseSign = ((targetPitch > lastTargetPitch) ? (-1f) : 1f);
				lastTargetPitch = targetPitch;
			}
		}

		private static void UpdateTimeScale()
		{
			currentTimeScale = Mathf.SmoothDamp(currentTimeScale, targetTimeScale, ref timeScaleVelocity, 0.25f, 5f, Time.unscaledDeltaTime);
			Time.timeScale = currentTimeScale;
		}

		private static void UpdateAudio(PlayerData pd)
		{
			currentPitch = Mathf.SmoothDamp(currentPitch, lastTargetPitch, ref pitchVelocity, 0.5f, 2f, Time.unscaledDeltaTime);
			float num = 0f;
			if (pulseTimer > 0f)
			{
				pulseTimer -= Time.unscaledDeltaTime;
				float num2 = 1f - pulseTimer / 0.5f;
				float num3 = ((num2 < 0.5f) ? Mathf.InverseLerp(0f, 0.5f, num2) : (1f - Mathf.InverseLerp(0.5f, 1f, num2)));
				num = num3 * 0.2f * pulseSign;
			}
			float pitch = currentPitch + num;
			foreach (CorruptedHealth.CachedAudio item in CorruptedHealth.Cached)
			{
				if (!((Object)(object)item.source == (Object)null))
				{
					item.source.pitch = pitch;
					float num4 = Mathf.InverseLerp(0.1f, 1f, (float)pd.health / (float)pd.maxHealth);
					num4 *= num4;
					item.lowPass.cutoffFrequency = 22000f - CorruptedHealth.audioModulation.Value * (22000f - 500f * Mathf.Pow(44f, num4));
				}
			}
		}
	}
}