Decompiled source of ScreamCounter v1.0.2

ScreamCounter.dll

Decompiled 10 months ago
using System;
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 BepInEx;
using BepInEx.Configuration;
using Dissonance;
using GameNetcodeStuff;
using HarmonyLib;
using LC_API.GameInterfaceAPI.Features;
using Microsoft.CodeAnalysis;
using Network;
using ScreamCounter;
using TMPro;
using Unity.Netcode;
using UnityEngine;

[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("ScreamCounter")]
[assembly: AssemblyConfiguration("Debug")]
[assembly: AssemblyDescription("YourModDescriptionGoesHere")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0+9cde83bf2a79cd4ad0f2ec7070215edb39dd3be6")]
[assembly: AssemblyProduct("ScreamCounter")]
[assembly: AssemblyTitle("ScreamCounter")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.0.0.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
internal class <Module>
{
	static <Module>()
	{
	}
}
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 ScreamCounter
{
	[BepInPlugin("frsk.Scream_Counter", "ScreamCounter", "1.0.0")]
	public class ScreamCounter : BaseUnityPlugin
	{
		[HarmonyPatch(typeof(GameNetworkManager))]
		internal class GameNetworkManagerPatch
		{
			[HarmonyPatch("SaveGameValues")]
			[HarmonyPostfix]
			private static void SaveGameValuesPatch(ref GameNetworkManager __instance)
			{
				if (__instance.isHostingGame && StartOfRound.Instance.inShipPhase)
				{
					ES3.Save<int>("Stats_ScreamCounter", screamCounter, __instance.currentSaveFileName);
					Debug.Log((object)"Scream Counter Successfully saved. Current value is: ");
				}
			}

			[HarmonyPatch("ResetSaveGameValues")]
			private static void ResetSaveGameValuesPatch(ref GameNetworkManager _instance)
			{
				if (_instance.isHostingGame)
				{
					screamCounter = 0;
					ES3.Save<int>("Stats_ScreamCounter", 0, _instance.currentSaveFileName);
				}
			}
		}

		[HarmonyPatch(typeof(StartOfRound))]
		internal class StartOfRoundPatch
		{
			[HarmonyPatch("SetTimeAndPlanetToSavedSettings")]
			[HarmonyPostfix]
			private static void SetTimeAndPlanetToSavedSettingsPatchServerRpc(ref StartOfRound __instance)
			{
				string currentSaveFileName = GameNetworkManager.Instance.currentSaveFileName;
				if (ES3.KeyExists("Stats_ScreamCounter"))
				{
					screamCounter = ES3.Load<int>("Stats_ScreamCounter", currentSaveFileName, 0);
					Debug.Log((object)("Scream Counter Successfully loaded. Current value is: " + screamCounter));
				}
			}

			[HarmonyPatch("DetectVoiceChatAmplitude")]
			[HarmonyPostfix]
			private static void DetectVoiceChatAmplitudePatch(ref StartOfRound __instance)
			{
				//IL_00f7: Unknown result type (might be due to invalid IL or missing references)
				PlayerControllerB localPlayerController = GameNetworkManager.Instance.localPlayerController;
				if ((Object)(object)localPlayerController == (Object)null)
				{
					throw new Exception("pc is null");
				}
				float value = Traverse.Create((object)__instance).Field<float>("voiceChatNoiseCooldown").Value;
				VoicePlayerState val = __instance.voiceChatModule.FindPlayer(__instance.voiceChatModule.LocalPlayerName);
				bool flag = false;
				float num = val.Amplitude / Mathf.Clamp(__instance.averageVoiceAmplitude, 0.008f, 0.5f);
				if (!val.IsSpeaking || !(averageDetectCooldown <= 0f) || !(num > 3f))
				{
					flag = true;
				}
				if (averageCount > 5 && !localPlayerController.isPlayerDead && __instance.shipHasLanded && screamCooldown <= 0f)
				{
					if (val.Amplitude / averageSpeechAmplitude > screamFromAveragePercentage.Value)
					{
						CustomNetworkHandler.Instance.AddToScreamCounterServerRpc(NetworkBehaviourReference.op_Implicit((NetworkBehaviour)(object)localPlayerController));
						screamCooldown = 10f;
						flag = true;
					}
				}
				else if (screamCooldown > 0f)
				{
					screamCooldown -= Time.deltaTime;
				}
				if (!flag)
				{
					averageCount++;
					totalSpeechAmplitude += val.Amplitude;
					averageSpeechAmplitude = totalSpeechAmplitude / (float)averageCount;
					Debug.Log((object)("Added amplitude to average. Current average: " + averageSpeechAmplitude));
					averageDetectCooldown = 2f;
				}
				averageDetectCooldown -= Time.deltaTime;
			}

			[HarmonyPatch("WritePlayerNotes")]
			[HarmonyPostfix]
			private static void WritePlayerNotesPatch(ref StartOfRound __instance)
			{
				IOrderedEnumerable<KeyValuePair<PlayerControllerB, int>> source = currentPerPlayerScreams.OrderByDescending(delegate(KeyValuePair<PlayerControllerB, int> entry)
				{
					KeyValuePair<PlayerControllerB, int> keyValuePair = entry;
					return keyValuePair.Value;
				});
				PlayerControllerB key = source.FirstOrDefault().Key;
				if (source.FirstOrDefault().Value > 2)
				{
					__instance.gameStats.allPlayerStats[key.playerClientId].playerNotes.Add("Screamed the most");
				}
			}

			[HarmonyPatch("EndGameServerRpc")]
			[HarmonyPostfix]
			private static void EndGameServerRpc(ref StartOfRound __instance)
			{
				//IL_0029: 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)
				NetworkBehaviourReference[] array = (NetworkBehaviourReference[])(object)new NetworkBehaviourReference[currentPerPlayerScreams.Count];
				for (int i = 0; i < array.Length; i++)
				{
					array[i] = new NetworkBehaviourReference((NetworkBehaviour)(object)currentPerPlayerScreams.Keys.ToArray()[i]);
				}
				int[] values = currentPerPlayerScreams.Values.ToArray();
				CustomNetworkHandler.Instance.SendRoundScreamStatsClientRpc(array, values);
			}

			[HarmonyPatch("FirePlayersAfterDeadlineClientRpc")]
			[HarmonyPostfix]
			private static void FirePlayersAfterDeadlineClientRpcPatch(ref StartOfRound __instance, int[] endGameStats)
			{
				((TMP_Text)HUDManager.Instance.EndOfRunStatsText).text = $"Days on the job: {endGameStats[0]}\n" + $"Scrap value collected: {endGameStats[1]}\n" + $"Deaths: {endGameStats[2]}\n" + $"Steps taken: {endGameStats[3] + $"\nScreams: {endGameStats[4]}"}";
				screamCounter = 0;
			}

			[HarmonyPatch("ResetStats")]
			[HarmonyPostfix]
			private static void ResetStatsPatch()
			{
				currentPerPlayerScreams.Clear();
			}

			[HarmonyPatch("Start")]
			[HarmonyPrefix]
			private static void StartResetCounter(ref StartOfRound __instance)
			{
				if (((NetworkBehaviour)__instance).IsServer)
				{
					screamCounter = 0;
				}
			}

			[HarmonyPatch("GetEndgameStatsInOrder")]
			[HarmonyPrefix]
			private static bool GetEndgameStatsInOrderPatch(ref StartOfRound __instance, ref int[] __result)
			{
				__result = new int[5]
				{
					__instance.gameStats.daysSpent,
					__instance.gameStats.scrapValueCollected,
					__instance.gameStats.deaths,
					__instance.gameStats.allStepsTaken,
					screamCounter
				};
				return false;
			}
		}

		private const string modGUID = "frsk.Scream_Counter";

		private const string modName = "ScreamCounter";

		private const string modVersion = "1.0.0";

		public static ConfigEntry<float> screamFromAveragePercentage;

		private Harmony harmony = new Harmony("frsk.Scream_Counter");

		public static ScreamCounter Instance;

		public static int screamCounter = 0;

		public static int averageCount = 0;

		public static float averageSpeechAmplitude;

		public static float totalSpeechAmplitude;

		public static int currentPlayerCheck = 0;

		public static float screamCooldown = 0f;

		public static float averageDetectCooldown = 0f;

		public static bool corRunning = false;

		public static Dictionary<PlayerControllerB, int> currentPerPlayerScreams = new Dictionary<PlayerControllerB, int>();

		private void Awake()
		{
			if ((Object)(object)Instance == (Object)null)
			{
				Instance = this;
			}
			screamFromAveragePercentage = ((BaseUnityPlugin)this).Config.Bind<float>("General", "ScreamFromAveragePercentage", 1.5f, "");
			int[] array = new int[0];
			((BaseUnityPlugin)this).Logger.LogInfo((object)"Plugin frsk.Scream_Counter is loaded!");
			Type[] types = Assembly.GetExecutingAssembly().GetTypes();
			Type[] array2 = types;
			foreach (Type type in array2)
			{
				MethodInfo[] methods = type.GetMethods(BindingFlags.Instance | BindingFlags.Static | BindingFlags.NonPublic);
				MethodInfo[] array3 = methods;
				foreach (MethodInfo methodInfo in array3)
				{
					object[] customAttributes = methodInfo.GetCustomAttributes(typeof(RuntimeInitializeOnLoadMethodAttribute), inherit: false);
					if (customAttributes.Length != 0)
					{
						methodInfo.Invoke(null, null);
					}
				}
			}
			harmony.PatchAll();
		}
	}
	public static class PluginInfo
	{
		public const string PLUGIN_GUID = "ScreamCounter";

		public const string PLUGIN_NAME = "ScreamCounter";

		public const string PLUGIN_VERSION = "1.0.0";
	}
}
namespace Network
{
	[HarmonyPatch(typeof(Player))]
	public class PlayerPatch
	{
		private static readonly string BUNDLE_PATH = Path.Combine(Paths.PluginPath, "2018-LC_API", "Bundles", "networking");

		private const string PLAYER_NETWORKING_ASSET_LOCATION = "assets/lc_api/playernetworkingprefab.prefab";

		private static GameObject networkPrefab;

		[HarmonyPatch(typeof(GameNetworkManager), "Start")]
		[HarmonyPostfix]
		[HarmonyPriority(1)]
		public static void Init()
		{
			GameObject value = Traverse.Create(typeof(Player)).Property("PlayerNetworkPrefab", (object[])null).GetValue<GameObject>();
			value.AddComponent<CustomNetworkHandler>();
		}

		[HarmonyPatch("Start")]
		[HarmonyPostfix]
		public static void Init(ref Player __instance)
		{
		}
	}
	public class CustomNetworkHandler : NetworkBehaviour
	{
		public static CustomNetworkHandler Instance { get; private set; }

		public override void OnNetworkSpawn()
		{
			Instance = this;
			((NetworkBehaviour)this).OnNetworkSpawn();
		}

		[ClientRpc]
		public void SendRoundScreamStatsClientRpc(NetworkBehaviourReference[] controllers, int[] values)
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Invalid comparison between Unknown and I4
			//IL_0122: Unknown result type (might be due to invalid IL or missing references)
			//IL_012c: Invalid comparison between Unknown and I4
			//IL_005f: 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_0088: Unknown result type (might be due to invalid IL or missing references)
			//IL_008e: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ac: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b2: Unknown result type (might be due to invalid IL or missing references)
			//IL_0112: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fd: 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)base.__rpc_exec_stage != 2 && (networkManager.IsServer || networkManager.IsHost))
			{
				ClientRpcParams val = default(ClientRpcParams);
				FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendClientRpc(388944433u, val, (RpcDelivery)0);
				bool flag = controllers != null;
				((FastBufferWriter)(ref val2)).WriteValueSafe<bool>(ref flag, default(ForPrimitives));
				if (flag)
				{
					((FastBufferWriter)(ref val2)).WriteValueSafe<NetworkBehaviourReference>(controllers, default(ForNetworkSerializable));
				}
				bool flag2 = values != null;
				((FastBufferWriter)(ref val2)).WriteValueSafe<bool>(ref flag2, default(ForPrimitives));
				if (flag2)
				{
					((FastBufferWriter)(ref val2)).WriteValueSafe<int>(values, default(ForPrimitives));
				}
				((NetworkBehaviour)this).__endSendClientRpc(ref val2, 388944433u, val, (RpcDelivery)0);
			}
			if ((int)base.__rpc_exec_stage == 2 && (networkManager.IsClient || networkManager.IsHost))
			{
				PlayerControllerB key = default(PlayerControllerB);
				for (int i = 0; i < controllers.Length; i++)
				{
					((NetworkBehaviourReference)(ref controllers[i])).TryGet<PlayerControllerB>(ref key, (NetworkManager)null);
					global::ScreamCounter.ScreamCounter.currentPerPlayerScreams[key] = values[i];
				}
			}
		}

		[ServerRpc(RequireOwnership = false)]
		public void AddToScreamCounterServerRpc(NetworkBehaviourReference playerref)
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Invalid comparison between Unknown and I4
			//IL_00a7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b1: Invalid comparison between Unknown and I4
			//IL_005f: 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_007d: 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_0097: 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)base.__rpc_exec_stage != 1 && (networkManager.IsClient || networkManager.IsHost))
			{
				ServerRpcParams val = default(ServerRpcParams);
				FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendServerRpc(76070574u, val, (RpcDelivery)0);
				((FastBufferWriter)(ref val2)).WriteValueSafe<NetworkBehaviourReference>(ref playerref, default(ForNetworkSerializable));
				((NetworkBehaviour)this).__endSendServerRpc(ref val2, 76070574u, val, (RpcDelivery)0);
			}
			if ((int)base.__rpc_exec_stage == 1 && (networkManager.IsServer || networkManager.IsHost))
			{
				PlayerControllerB val3 = default(PlayerControllerB);
				((NetworkBehaviourReference)(ref playerref)).TryGet<PlayerControllerB>(ref val3, (NetworkManager)null);
				if (global::ScreamCounter.ScreamCounter.currentPerPlayerScreams.ContainsKey(val3))
				{
					global::ScreamCounter.ScreamCounter.currentPerPlayerScreams[val3] = global::ScreamCounter.ScreamCounter.currentPerPlayerScreams[val3] + 1;
				}
				else
				{
					global::ScreamCounter.ScreamCounter.currentPerPlayerScreams[val3] = 1;
				}
				if (global::ScreamCounter.ScreamCounter.screamCooldown <= 0f)
				{
					global::ScreamCounter.ScreamCounter.screamCounter++;
					global::ScreamCounter.ScreamCounter.screamCooldown = 10f;
				}
				else
				{
					global::ScreamCounter.ScreamCounter.screamCooldown -= Time.deltaTime;
				}
				Debug.Log((object)$"player {((Object)val3).name} added to scream counter. His counter: {global::ScreamCounter.ScreamCounter.currentPerPlayerScreams[val3]}, General: {global::ScreamCounter.ScreamCounter.screamCounter}");
			}
		}

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

		[RuntimeInitializeOnLoadMethod]
		internal static void InitializeRPCS_CustomNetworkHandler()
		{
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_001b: Expected O, but got Unknown
			//IL_002c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0036: Expected O, but got Unknown
			NetworkManager.__rpc_func_table.Add(388944433u, new RpcReceiveHandler(__rpc_handler_388944433));
			NetworkManager.__rpc_func_table.Add(76070574u, new RpcReceiveHandler(__rpc_handler_76070574));
		}

		private static void __rpc_handler_388944433(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams)
		{
			//IL_002f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0035: Unknown result type (might be due to invalid IL or missing references)
			//IL_0074: Unknown result type (might be due to invalid IL or missing references)
			//IL_007a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0058: 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_00b3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d1: Unknown result type (might be due to invalid IL or missing references)
			//IL_009d: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a3: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = target.NetworkManager;
			if (networkManager != null && networkManager.IsListening)
			{
				bool flag = default(bool);
				((FastBufferReader)(ref reader)).ReadValueSafe<bool>(ref flag, default(ForPrimitives));
				NetworkBehaviourReference[] controllers = null;
				if (flag)
				{
					((FastBufferReader)(ref reader)).ReadValueSafe<NetworkBehaviourReference>(ref controllers, default(ForNetworkSerializable));
				}
				bool flag2 = default(bool);
				((FastBufferReader)(ref reader)).ReadValueSafe<bool>(ref flag2, default(ForPrimitives));
				int[] values = null;
				if (flag2)
				{
					((FastBufferReader)(ref reader)).ReadValueSafe<int>(ref values, default(ForPrimitives));
				}
				target.__rpc_exec_stage = (__RpcExecStage)2;
				((CustomNetworkHandler)(object)target).SendRoundScreamStatsClientRpc(controllers, values);
				target.__rpc_exec_stage = (__RpcExecStage)0;
			}
		}

		private static void __rpc_handler_76070574(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams)
		{
			//IL_002f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0035: Unknown result type (might be due to invalid IL or missing references)
			//IL_0044: Unknown result type (might be due to invalid IL or missing references)
			//IL_004f: 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)
			NetworkManager networkManager = target.NetworkManager;
			if (networkManager != null && networkManager.IsListening)
			{
				NetworkBehaviourReference playerref = default(NetworkBehaviourReference);
				((FastBufferReader)(ref reader)).ReadValueSafe<NetworkBehaviourReference>(ref playerref, default(ForNetworkSerializable));
				target.__rpc_exec_stage = (__RpcExecStage)1;
				((CustomNetworkHandler)(object)target).AddToScreamCounterServerRpc(playerref);
				target.__rpc_exec_stage = (__RpcExecStage)0;
			}
		}

		protected internal override string __getTypeName()
		{
			return "CustomNetworkHandler";
		}
	}
}