Decompiled source of SprintFaster v1.0.0

SprintFaster.dll

Decompiled 4 months ago
using System;
using System.Diagnostics;
using System.IO;
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 SprintFaster.Configuration;
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("SprintFaster")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("SprintFaster")]
[assembly: AssemblyCopyright("Copyright ©  2024")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
[assembly: Guid("f0589f83-d171-4f28-a6f5-83b031fa3123")]
[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")]
namespace SprintFaster
{
	[BepInPlugin("SprintFaster", "SprintFaster", "1.0.0")]
	public class SprintFasterBase : BaseUnityPlugin
	{
		public static PluginLogger logger = new PluginLogger();

		private static SprintFasterBase Instance;

		public static GameObject NetPrefab;

		public static Config Config { get; internal set; }

		private void Awake()
		{
			PatchNetcode();
			if ((Object)(object)Instance == (Object)null)
			{
				Instance = this;
			}
			CreateNetworkPrefab();
			Harmony.CreateAndPatchAll(Assembly.GetExecutingAssembly(), "SprintFaster");
			Config = new Config(((BaseUnityPlugin)this).Config);
			logger.LogInfo("Plugin has awoken");
		}

		private static void PatchNetcode()
		{
			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)
				{
					if (methodInfo.GetCustomAttributes(typeof(RuntimeInitializeOnLoadMethodAttribute), inherit: false).Length != 0)
					{
						methodInfo.Invoke(null, null);
					}
				}
			}
		}

		private void CreateNetworkPrefab()
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_0010: Expected O, but got Unknown
			NetPrefab = new GameObject("Networking");
			NetworkObject val = NetPrefab.AddComponent<NetworkObject>();
			val.AutoObjectParentSync = false;
			val.DontDestroyWithOwner = true;
		}
	}
	public class PluginInfo
	{
		public const string PLUGIN_GUID = "SprintFaster";

		public const string PLUGIN_NAME = "SprintFaster";

		public const string PLUGIN_VERSION = "1.0.0";
	}
	public class PluginLogger
	{
		private static ManualLogSource mls = Logger.CreateLogSource("SprintFaster");

		private static bool ShouldLog = true;

		public void EnableLogging(bool status)
		{
			ShouldLog = status;
		}

		public void LogInfo(object data)
		{
			if (ShouldLog)
			{
				mls.LogInfo(data);
			}
		}

		public void LogError(object data)
		{
			if (ShouldLog)
			{
				mls.LogError(data);
			}
		}
	}
}
namespace SprintFaster.Patches
{
	[HarmonyPatch(typeof(GameNetworkManager))]
	internal class GameNetworkManagerPatch
	{
		[HarmonyPatch("Start")]
		[HarmonyPostfix]
		public static void Start_Postfix(ref GameNetworkManager __instance)
		{
			((Component)__instance).GetComponent<NetworkManager>().AddNetworkPrefab(SprintFasterBase.NetPrefab);
		}

		[HarmonyPatch("StartDisconnect")]
		[HarmonyPostfix]
		public static void StartDisconnect_Postfix()
		{
			SyncedInstance<Config>.RevertSync();
		}
	}
	[HarmonyPatch(typeof(PlayerControllerB))]
	internal class PlayerControllerBPatches
	{
		[HarmonyPatch("ConnectClientToPlayerObject")]
		[HarmonyPostfix]
		public static void ConnectClientToPlayerObject_Postfix()
		{
			//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("SprintFaster_OnRequestConfigSync", new HandleNamedMessageDelegate(Config.OnRequestSync));
				SyncedInstance<Config>.Synced = true;
			}
			else
			{
				SyncedInstance<Config>.Synced = false;
				SyncedInstance<Config>.MessageManager.RegisterNamedMessageHandler("SprintFaster_OnReceiveConfigSync", new HandleNamedMessageDelegate(Config.OnReceiveSync));
				Config.RequestSync();
			}
		}

		[HarmonyPatch("Update")]
		[HarmonyPostfix]
		private static void Update_Postfix(ref PlayerControllerB __instance)
		{
			bool flag = ((NetworkBehaviour)RoundManager.Instance).IsHost || ((NetworkBehaviour)RoundManager.Instance).IsServer;
			if (__instance.isSprinting && __instance.isPlayerControlled && ((SyncedInstance<Config>.Synced && SyncedInstance<Config>.Instance.SyncPlayers) || (flag && SyncedInstance<Config>.Synced)))
			{
				FieldInfo fieldInfo = AccessTools.Field(typeof(PlayerControllerB), "sprintMultiplier");
				if (fieldInfo != null)
				{
					fieldInfo.SetValue(__instance, SyncedInstance<Config>.Instance.SpeedMultiplier);
				}
				else
				{
					SprintFasterBase.logger.LogInfo("Error finding field 'sprintMultiplier' because it is null");
				}
			}
		}
	}
	[HarmonyPatch(typeof(StartOfRound), "Start")]
	internal class StartOfRoundPatch
	{
		public static void Postfix(ref StartOfRound __instance)
		{
			if (((NetworkBehaviour)__instance).IsHost)
			{
				GameObject val = Object.Instantiate<GameObject>(SprintFasterBase.NetPrefab);
				val.GetComponent<NetworkObject>().Spawn(false);
			}
		}
	}
}
namespace SprintFaster.Configuration
{
	[Serializable]
	public class Config : SyncedInstance<Config>
	{
		public bool SyncPlayers;

		public float SpeedMultiplier;

		public Config(ConfigFile cfg)
		{
			InitInstance(this);
			ConfigEntry<bool> val = cfg.Bind<bool>("General", "Logging", true, (ConfigDescription)null);
			ConfigEntry<bool> val2 = cfg.Bind<bool>("General", "Sync Configs", true, "Whether or not players should be sync. If this is disabled on host, or if the host doesn't have the mod, the player will run at normal speed.");
			ConfigEntry<float> val3 = cfg.Bind<float>("General", "Speed Multiplier", 1f, "How much faster should the player run? Setting this to 2 will make the player run twice as fast.");
			SprintFasterBase.logger.EnableLogging(val.Value);
			SyncPlayers = val2.Value;
			SpeedMultiplier = val3.Value;
		}

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

		public static void OnRequestSync(ulong playerClientId, FastBufferReader _)
		{
			//IL_0053: Unknown result type (might be due to invalid IL or missing references)
			//IL_0059: Unknown result type (might be due to invalid IL or missing references)
			//IL_0077: Unknown result type (might be due to invalid IL or missing references)
			if (!SyncedInstance<Config>.IsHost)
			{
				return;
			}
			SprintFasterBase.logger.LogInfo($"Player with the client id {playerClientId} requested config sync.");
			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("SprintFaster_OnReceiveConfigSync", playerClientId, val, (NetworkDelivery)3);
			}
			catch (Exception arg)
			{
				SprintFasterBase.logger.LogInfo($"Something went wrong when trying to sync config with client id {playerClientId}\nException: {arg}");
			}
		}

		public static void OnReceiveSync(ulong _, FastBufferReader reader)
		{
			//IL_002d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0033: Unknown result type (might be due to invalid IL or missing references)
			if (!((FastBufferReader)(ref reader)).TryBeginRead(SyncedInstance<Config>.IntSize))
			{
				SprintFasterBase.logger.LogError("Something went wrong when attempting to begin reading the buffer.");
				return;
			}
			int num = default(int);
			((FastBufferReader)(ref reader)).ReadValueSafe<int>(ref num, default(ForPrimitives));
			if (!((FastBufferReader)(ref reader)).TryBeginRead(num))
			{
				SprintFasterBase.logger.LogError("An error occured when attempting to sync with host.");
				return;
			}
			byte[] data = new byte[num];
			((FastBufferReader)(ref reader)).ReadBytesSafe(ref data, num, 0);
			SyncedInstance<Config>.SyncInstance(data);
			SprintFasterBase.logger.LogInfo("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 i)
		{
			Default = i;
			Instance = i;
			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();
			MemoryStream memoryStream = new MemoryStream();
			try
			{
				binaryFormatter.Serialize(memoryStream, val);
				return memoryStream.ToArray();
			}
			catch (Exception arg)
			{
				SprintFasterBase.logger.LogError($"Failed to serialize. Exception: {arg}");
				return null;
			}
		}

		public static T DeserializeFromBytes(byte[] data)
		{
			BinaryFormatter binaryFormatter = new BinaryFormatter();
			MemoryStream serializationStream = new MemoryStream(data);
			try
			{
				return (T)binaryFormatter.Deserialize(serializationStream);
			}
			catch (Exception arg)
			{
				SprintFasterBase.logger.LogError($"Failed to deserialize. Exception: {arg}");
				return default(T);
			}
		}
	}
}