Decompiled source of OpenTheNoor v1.1.4

OpenTheNoor.dll

Decompiled 8 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.InteropServices;
using System.Runtime.Serialization.Formatters.Binary;
using System.Runtime.Versioning;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using GameNetcodeStuff;
using HarmonyLib;
using OpenTheNoor.Config;
using OpenTheNoor.Managers;
using OpenTheNoor.NetcodePatcher;
using Unity.Collections;
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: AssemblyTitle("OpenTheNoor")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("OpenTheNoor")]
[assembly: AssemblyCopyright("Copyright ©  2024")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
[assembly: Guid("b58bef91-7e8e-4613-a41d-797b02584ab7")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: TargetFramework(".NETFramework,Version=v4.7.2", FrameworkDisplayName = ".NET Framework 4.7.2")]
[assembly: AssemblyVersion("1.0.0.0")]
[module: NetcodePatchedAssembly]
internal class <Module>
{
	static <Module>()
	{
	}
}
namespace OpenTheNoor.Patches
{
	[HarmonyPatch(typeof(StartOfRound))]
	internal class StartOfRoundPatch
	{
		[HarmonyPostfix]
		[HarmonyPatch("Start")]
		private static void spawnNetManager(StartOfRound __instance)
		{
			if (((NetworkBehaviour)__instance).IsHost)
			{
				GameObject val = Object.Instantiate<GameObject>(OpenTheNoorBase.Instance.netManagerPrefab);
				val.GetComponent<NetworkObject>().Spawn(false);
			}
		}
	}
}
namespace OpenTheNoor.Managers
{
	public class NetworkManagerOpenTheNoor : NetworkBehaviour
	{
		public static NetworkManagerOpenTheNoor Instance;

		private void Awake()
		{
			if ((Object)(object)Instance == (Object)null)
			{
				Instance = this;
			}
		}

		[ServerRpc(RequireOwnership = false)]
		public void MakeOpenTheNoorNoiseServerRpc(NetworkBehaviourReference __door)
		{
			//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)
			//IL_00d8: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager;
			if (networkManager != null && networkManager.IsListening)
			{
				if ((int)base.__rpc_exec_stage != 1 && (networkManager.IsClient || networkManager.IsHost))
				{
					ServerRpcParams val = default(ServerRpcParams);
					FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendServerRpc(2313316997u, val, (RpcDelivery)0);
					((FastBufferWriter)(ref val2)).WriteValueSafe<NetworkBehaviourReference>(ref __door, default(ForNetworkSerializable));
					((NetworkBehaviour)this).__endSendServerRpc(ref val2, 2313316997u, val, (RpcDelivery)0);
				}
				if ((int)base.__rpc_exec_stage == 1 && (networkManager.IsServer || networkManager.IsHost))
				{
					MakeOpenTheNoorNoiseClientRpc(__door);
				}
			}
		}

		[ClientRpc]
		public void MakeOpenTheNoorNoiseClientRpc(NetworkBehaviourReference __door)
		{
			//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)
			//IL_00d7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00dd: 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(610924669u, val, (RpcDelivery)0);
				((FastBufferWriter)(ref val2)).WriteValueSafe<NetworkBehaviourReference>(ref __door, default(ForNetworkSerializable));
				((NetworkBehaviour)this).__endSendClientRpc(ref val2, 610924669u, val, (RpcDelivery)0);
			}
			if ((int)base.__rpc_exec_stage == 2 && (networkManager.IsClient || networkManager.IsHost))
			{
				AudioSource doorLockSFX = ((DoorLock)NetworkBehaviourReference.op_Implicit(__door)).doorLockSFX;
				if ((Object)(object)doorLockSFX != (Object)null)
				{
					PlayerControllerBPatch.playOpenTheNoorNoise(doorLockSFX, OpenTheNoorBase.SoundFX.ToArray());
				}
			}
		}

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

		[RuntimeInitializeOnLoadMethod]
		internal static void InitializeRPCS_NetworkManagerOpenTheNoor()
		{
			//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(2313316997u, new RpcReceiveHandler(__rpc_handler_2313316997));
			NetworkManager.__rpc_func_table.Add(610924669u, new RpcReceiveHandler(__rpc_handler_610924669));
		}

		private static void __rpc_handler_2313316997(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 _door = default(NetworkBehaviourReference);
				((FastBufferReader)(ref reader)).ReadValueSafe<NetworkBehaviourReference>(ref _door, default(ForNetworkSerializable));
				target.__rpc_exec_stage = (__RpcExecStage)1;
				((NetworkManagerOpenTheNoor)(object)target).MakeOpenTheNoorNoiseServerRpc(_door);
				target.__rpc_exec_stage = (__RpcExecStage)0;
			}
		}

		private static void __rpc_handler_610924669(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 _door = default(NetworkBehaviourReference);
				((FastBufferReader)(ref reader)).ReadValueSafe<NetworkBehaviourReference>(ref _door, default(ForNetworkSerializable));
				target.__rpc_exec_stage = (__RpcExecStage)2;
				((NetworkManagerOpenTheNoor)(object)target).MakeOpenTheNoorNoiseClientRpc(_door);
				target.__rpc_exec_stage = (__RpcExecStage)0;
			}
		}

		protected internal override string __getTypeName()
		{
			return "NetworkManagerOpenTheNoor";
		}
	}
}
namespace OpenTheNoor.Config
{
	[Serializable]
	public class Config : SyncedInstance<Config>
	{
		private const float VOLUME_DEFAULT = 0.5f;

		private const bool PLAY_FOR_ALL_PLAYERS_DEFAULT = true;

		public float VOLUME;

		public bool PLAY_FOR_ALL_PLAYERS;

		public Config(ConfigFile cfg)
		{
			InitInstance(this);
			VOLUME = cfg.Bind<float>("ClientSide", "volume", 0.5f, "The volume that the sound will play at for you.").Value;
			PLAY_FOR_ALL_PLAYERS = cfg.Bind<bool>("ServerSide", "playForAllPlayers", true, "Play the sound for other players.\nThis will allow all players to hear the sound when another player attempts to open a door.").Value;
		}

		public static void RequestSync()
		{
			//IL_0029: Unknown result type (might be due to invalid IL or missing references)
			if (!SyncedInstance<Config>.IsClient)
			{
				return;
			}
			FastBufferWriter val = default(FastBufferWriter);
			((FastBufferWriter)(ref val))..ctor(SyncedInstance<Config>.IntSize, (Allocator)2, -1);
			try
			{
				SyncedInstance<Config>.MessageManager.SendNamedMessage("Kolton12O.OpenTheNoor_OnRequestConfigSync", 0uL, val, (NetworkDelivery)3);
			}
			finally
			{
				((IDisposable)(FastBufferWriter)(ref val)).Dispose();
			}
		}

		public static void OnRequestSync(ulong clientId, FastBufferReader _)
		{
			//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_007c: Unknown result type (might be due to invalid IL or missing references)
			if (!SyncedInstance<Config>.IsHost)
			{
				return;
			}
			OpenTheNoorBase.Instance.mls.LogInfo((object)$"Config sync request received from client: {clientId}");
			byte[] array = SyncedInstance<Config>.SerializeToBytes(SyncedInstance<Config>.Instance);
			int num = array.Length;
			FastBufferWriter val = default(FastBufferWriter);
			((FastBufferWriter)(ref val))..ctor(num + SyncedInstance<Config>.IntSize, (Allocator)2, -1);
			try
			{
				((FastBufferWriter)(ref val)).WriteValueSafe<int>(ref num, default(ForPrimitives));
				((FastBufferWriter)(ref val)).WriteBytesSafe(array, -1, 0);
				SyncedInstance<Config>.MessageManager.SendNamedMessage("Kolton12O.OpenTheNoor_OnReceiveConfigSync", clientId, val, (NetworkDelivery)3);
			}
			catch (Exception arg)
			{
				OpenTheNoorBase.Instance.mls.LogInfo((object)$"Error occurred syncing config with client: {clientId}\n{arg}");
			}
			finally
			{
				((IDisposable)(FastBufferWriter)(ref val)).Dispose();
			}
		}

		public static void OnReceiveSync(ulong _, FastBufferReader reader)
		{
			//IL_0032: Unknown result type (might be due to invalid IL or missing references)
			//IL_0038: Unknown result type (might be due to invalid IL or missing references)
			if (!((FastBufferReader)(ref reader)).TryBeginRead(SyncedInstance<Config>.IntSize))
			{
				OpenTheNoorBase.Instance.mls.LogError((object)"Config sync error: Could not begin reading buffer.");
				return;
			}
			int num = default(int);
			((FastBufferReader)(ref reader)).ReadValueSafe<int>(ref num, default(ForPrimitives));
			if (!((FastBufferReader)(ref reader)).TryBeginRead(num))
			{
				OpenTheNoorBase.Instance.mls.LogError((object)"Config sync error: Host could not sync.");
				return;
			}
			byte[] data = new byte[num];
			((FastBufferReader)(ref reader)).ReadBytesSafe(ref data, num, 0);
			SyncedInstance<Config>.SyncInstance(data);
			OpenTheNoorBase.Instance.mls.LogInfo((object)"Successfully synced config with host.");
		}
	}
	[Serializable]
	public class SyncedInstance<T>
	{
		[NonSerialized]
		protected static int IntSize = 4;

		internal static CustomMessagingManager MessageManager => NetworkManager.Singleton.CustomMessagingManager;

		internal static bool IsClient => NetworkManager.Singleton.IsClient;

		internal static bool IsHost => NetworkManager.Singleton.IsHost;

		public static T Default { get; private set; }

		public static T Instance { get; private set; }

		public static bool Synced { get; internal set; }

		protected void InitInstance(T instance)
		{
			Default = instance;
			Instance = instance;
			IntSize = 4;
		}

		internal static void SyncInstance(byte[] data)
		{
			Instance = DeserializeFromBytes(data);
			Synced = true;
		}

		internal static void RevertSync()
		{
			Instance = Default;
			Synced = false;
		}

		public static byte[] SerializeToBytes(T val)
		{
			BinaryFormatter binaryFormatter = new BinaryFormatter();
			using MemoryStream memoryStream = new MemoryStream();
			try
			{
				binaryFormatter.Serialize(memoryStream, val);
				return memoryStream.ToArray();
			}
			catch (Exception arg)
			{
				OpenTheNoorBase.Instance.mls.LogError((object)$"Error serializing instance: {arg}");
				return null;
			}
		}

		public static T DeserializeFromBytes(byte[] data)
		{
			BinaryFormatter binaryFormatter = new BinaryFormatter();
			using MemoryStream serializationStream = new MemoryStream(data);
			try
			{
				return (T)binaryFormatter.Deserialize(serializationStream);
			}
			catch (Exception arg)
			{
				OpenTheNoorBase.Instance.mls.LogError((object)$"Error deserializing instance: {arg}");
				return default(T);
			}
		}
	}
	[HarmonyPatch(typeof(GameNetworkManager))]
	internal class GameNetworkManagerPatch
	{
		[HarmonyPostfix]
		[HarmonyPatch("Start")]
		private static void AddToPrefabs(ref GameNetworkManager __instance)
		{
			((Component)__instance).GetComponent<NetworkManager>().AddNetworkPrefab(OpenTheNoorBase.Instance.netManagerPrefab);
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(GameNetworkManager), "StartDisconnect")]
		public static void PlayerLeave()
		{
			SyncedInstance<Config>.RevertSync();
		}
	}
	[HarmonyPatch(typeof(PlayerControllerB))]
	internal class PlayerControllerBPatch
	{
		[HarmonyPatch(typeof(PlayerControllerB), "Interact_performed")]
		[HarmonyPrefix]
		private static void onInteract(PlayerControllerB __instance)
		{
			//IL_004c: Unknown result type (might be due to invalid IL or missing references)
			if (!((Object)(object)__instance.hoveringOverTrigger != (Object)null))
			{
				return;
			}
			DoorLock componentInParent = ((Component)__instance.hoveringOverTrigger).GetComponentInParent<DoorLock>();
			if (!((Object)(object)componentInParent != (Object)null) || !componentInParent.isLocked)
			{
				return;
			}
			if (SyncedInstance<Config>.Instance.PLAY_FOR_ALL_PLAYERS)
			{
				NetworkManagerOpenTheNoor.Instance.MakeOpenTheNoorNoiseServerRpc(NetworkBehaviourReference.op_Implicit((NetworkBehaviour)(object)componentInParent));
				return;
			}
			AudioSource doorLockSFX = componentInParent.doorLockSFX;
			if ((Object)(object)doorLockSFX != (Object)null)
			{
				playOpenTheNoorNoise(doorLockSFX, OpenTheNoorBase.SoundFX.ToArray());
			}
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(PlayerControllerB), "ConnectClientToPlayerObject")]
		public static void InitializeLocalPlayer()
		{
			//IL_0048: Unknown result type (might be due to invalid IL or missing references)
			//IL_0052: Expected O, but got Unknown
			//IL_001c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0026: Expected O, but got Unknown
			if (SyncedInstance<Config>.IsHost)
			{
				SyncedInstance<Config>.MessageManager.RegisterNamedMessageHandler("Kolton12O.OpenTheNoor_OnRequestConfigSync", new HandleNamedMessageDelegate(Config.OnRequestSync));
				SyncedInstance<Config>.Synced = true;
			}
			else
			{
				SyncedInstance<Config>.Synced = false;
				SyncedInstance<Config>.MessageManager.RegisterNamedMessageHandler("Kolton12O.OpenTheNoor_OnReceiveConfigSync", new HandleNamedMessageDelegate(Config.OnReceiveSync));
				Config.RequestSync();
			}
		}

		public static void playOpenTheNoorNoise(AudioSource __audioSource, AudioClip[] sounds)
		{
			RoundManager.PlayRandomClip(__audioSource, sounds, true, SyncedInstance<Config>.Default.VOLUME, 0, 1000);
		}
	}
	[BepInPlugin("Kolton12O.OpenTheNoor", "OpenTheNoor", "1.1.4")]
	public class OpenTheNoorBase : BaseUnityPlugin
	{
		public const string MOD_GUID = "Kolton12O.OpenTheNoor";

		public const string MOD_NAME = "OpenTheNoor";

		public const string MOD_VERSION = "1.1.4";

		private readonly Harmony harmony = new Harmony("Kolton12O.OpenTheNoor");

		public static OpenTheNoorBase Instance;

		internal ManualLogSource mls;

		internal static List<AudioClip> SoundFX;

		internal static AssetBundle Bundle;

		public GameObject netManagerPrefab;

		public static Config Config { get; internal set; }

		private void Awake()
		{
			if ((Object)(object)Instance == (Object)null)
			{
				Instance = this;
			}
			mls = Logger.CreateLogSource("Kolton12O.OpenTheNoor");
			Config = new Config(((BaseUnityPlugin)this).Config);
			Type[] types = Assembly.GetExecutingAssembly().GetTypes();
			Type[] array = types;
			foreach (Type type in array)
			{
				MethodInfo[] methods = type.GetMethods(BindingFlags.Instance | BindingFlags.Static | BindingFlags.NonPublic);
				MethodInfo[] array2 = methods;
				foreach (MethodInfo methodInfo in array2)
				{
					object[] customAttributes = methodInfo.GetCustomAttributes(typeof(RuntimeInitializeOnLoadMethodAttribute), inherit: false);
					if (customAttributes.Length != 0)
					{
						methodInfo.Invoke(null, null);
					}
				}
			}
			mls.LogInfo((object)"Open The Noor has awaken!");
			string location = ((BaseUnityPlugin)Instance).Info.Location;
			location = location.TrimEnd("OpenTheNoor.dll".ToCharArray());
			Bundle = AssetBundle.LoadFromFile(location + "openthenoor");
			SoundFX = new List<AudioClip>();
			if ((Object)(object)Bundle != (Object)null)
			{
				mls.LogInfo((object)"Successfully loaded asset bundle! :)");
				netManagerPrefab = Bundle.LoadAsset<GameObject>("Assets/OpenTheNoor/NetworkManagerOpenTheNoor.prefab");
				netManagerPrefab.AddComponent<NetworkManagerOpenTheNoor>();
				SoundFX = Bundle.LoadAllAssets<AudioClip>().ToList();
			}
			else
			{
				mls.LogError((object)"Failed to load asset bundle! :(");
			}
			harmony.PatchAll();
		}
	}
}
namespace OpenTheNoor.NetcodePatcher
{
	[AttributeUsage(AttributeTargets.Module)]
	internal class NetcodePatchedAssemblyAttribute : Attribute
	{
	}
}