Decompiled source of ScaledFallDamageV81 v1.0.6

BepInEx\plugins\ScaledFallDamage\windblownleaves.scaledfalldamage.dll

Decompiled 12 hours ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Serialization.Formatters.Binary;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using GameNetcodeStuff;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using Unity.Collections;
using Unity.Netcode;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[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.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace ScaledFallDamage
{
	[Serializable]
	public class Config : SyncedInstance<Config>
	{
		[HarmonyPatch(typeof(PlayerControllerB))]
		public class PlayerInitPatch
		{
			[CompilerGenerated]
			private static class <>O
			{
				public static HandleNamedMessageDelegate <0>__OnRequestSync;

				public static HandleNamedMessageDelegate <1>__OnReceiveSync;
			}

			internal static Config BoundConfig { get; private set; }

			[HarmonyPatch("ConnectClientToPlayerObject")]
			[HarmonyPostfix]
			private static void InitializeLocalPlayer()
			{
				//IL_006c: Unknown result type (might be due to invalid IL or missing references)
				//IL_0071: Unknown result type (might be due to invalid IL or missing references)
				//IL_0077: Expected O, but got Unknown
				//IL_0035: Unknown result type (might be due to invalid IL or missing references)
				//IL_003a: Unknown result type (might be due to invalid IL or missing references)
				//IL_0040: Expected O, but got Unknown
				BoundConfig = new Config(((BaseUnityPlugin)ScaledFallDamage.Instance).Config);
				if (SyncedInstance<Config>.IsHost)
				{
					CustomMessagingManager messageManager = SyncedInstance<Config>.MessageManager;
					object obj = <>O.<0>__OnRequestSync;
					if (obj == null)
					{
						HandleNamedMessageDelegate val = OnRequestSync;
						<>O.<0>__OnRequestSync = val;
						obj = (object)val;
					}
					messageManager.RegisterNamedMessageHandler("ScaledFallDamage_OnRequestConfigSync", (HandleNamedMessageDelegate)obj);
					SyncedInstance<Config>.Synced = true;
					return;
				}
				SyncedInstance<Config>.Synced = false;
				CustomMessagingManager messageManager2 = SyncedInstance<Config>.MessageManager;
				object obj2 = <>O.<1>__OnReceiveSync;
				if (obj2 == null)
				{
					HandleNamedMessageDelegate val2 = OnReceiveSync;
					<>O.<1>__OnReceiveSync = val2;
					obj2 = (object)val2;
				}
				messageManager2.RegisterNamedMessageHandler("ScaledFallDamage_OnReceiveConfigSync", (HandleNamedMessageDelegate)obj2);
				RequestSync();
			}
		}

		[NonSerialized]
		public readonly ConfigEntry<bool> modifySafeFallingHeight;

		[NonSerialized]
		public readonly ConfigEntry<float> tuningParameter;

		public bool modifySafeFallingHeightValue;

		public float tuningParameterValue;

		public Config(ConfigFile cfg)
		{
			InitInstance(this);
			cfg.SaveOnConfigSet = false;
			modifySafeFallingHeight = cfg.Bind<bool>("FallDamage", "ModifySafeFallingHeight", true, "Whether to lower the safe falling height at higher loads (at 0 load, it's the same as vanilla). If this is disabled, damage is still modified, but you won't take damage from shorter falls than normal.");
			tuningParameter = cfg.Bind<float>("FallDamage", "TuningParameter", 0.4f, "A constant by which the damage formula is multiplied. Setting this higher will cause more fall damage, setting this lower will cause less fall damage.");
			modifySafeFallingHeightValue = modifySafeFallingHeight.Value;
			tuningParameterValue = tuningParameter.Value;
			ClearOrphanedEntries(cfg);
			cfg.Save();
			cfg.SaveOnConfigSet = true;
		}

		private static void ClearOrphanedEntries(ConfigFile cfg)
		{
			((Dictionary<ConfigDefinition, string>)AccessTools.Property(typeof(ConfigFile), "OrphanedEntries").GetValue(cfg)).Clear();
		}

		public static void RequestSync()
		{
			//IL_0022: 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("ScaledFallDamage_OnRequestConfigSync", 0uL, val, (NetworkDelivery)4);
			}
			finally
			{
				((FastBufferWriter)(ref val)).Dispose();
			}
		}

		public static void OnRequestSync(ulong clientId, FastBufferReader _)
		{
			//IL_0065: Unknown result type (might be due to invalid IL or missing references)
			//IL_006b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0086: Unknown result type (might be due to invalid IL or missing references)
			if (!SyncedInstance<Config>.IsHost)
			{
				return;
			}
			ScaledFallDamage.Logger.LogInfo((object)$"Config sync request received from client: {clientId}");
			byte[] array = SyncedInstance<Config>.SerializeToBytes(SyncedInstance<Config>.Instance);
			if (array == null)
			{
				ScaledFallDamage.Logger.LogError((object)$"Could not serialize config to sync with client: {clientId}");
				return;
			}
			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("ScaledFallDamage_OnReceiveConfigSync", clientId, val, (NetworkDelivery)4);
			}
			catch (Exception arg)
			{
				ScaledFallDamage.Logger.LogInfo((object)$"Error occurred syncing config with client: {clientId}\n{arg}");
			}
			finally
			{
				((FastBufferWriter)(ref val)).Dispose();
			}
		}

		public static void OnReceiveSync(ulong _, FastBufferReader reader)
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002a: Unknown result type (might be due to invalid IL or missing references)
			if (!((FastBufferReader)(ref reader)).TryBeginRead(SyncedInstance<Config>.IntSize))
			{
				ScaledFallDamage.Logger.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))
			{
				ScaledFallDamage.Logger.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);
			ScaledFallDamage.Logger.LogInfo((object)"Successfully synced config with host.");
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(GameNetworkManager), "StartDisconnect")]
		public static void PlayerLeave()
		{
			SyncedInstance<Config>.RevertSync();
		}
	}
	[BepInPlugin("windblownleaves.scaledfalldamage", "ScaledFallDamage", "1.0.6")]
	public class ScaledFallDamage : BaseUnityPlugin
	{
		public static ScaledFallDamage Instance { get; private set; }

		public static ManualLogSource Logger { get; private set; }

		internal static Harmony Harmony { get; set; }

		internal static Config BoundConfig { get; private set; }

		private void Awake()
		{
			BoundConfig = new Config(((BaseUnityPlugin)this).Config);
			Logger = ((BaseUnityPlugin)this).Logger;
			Instance = this;
			Patch();
			Logger.LogInfo((object)"windblownleaves.scaledfalldamage v1.0.6 by Cpt.Dristyler has loaded! (config-sync NRE fixed for v81)");
		}

		internal static void Patch()
		{
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0016: Expected O, but got Unknown
			if (Harmony == null)
			{
				Harmony = new Harmony("windblownleaves.scaledfalldamage");
			}
			Logger.LogDebug((object)"Patching...");
			Harmony.PatchAll(Assembly.GetExecutingAssembly());
			Logger.LogDebug((object)"Finished patching!");
		}

		internal static void Unpatch()
		{
			Logger.LogDebug((object)"Unpatching...");
			Harmony harmony = Harmony;
			if (harmony != null)
			{
				harmony.UnpatchSelf();
			}
			Logger.LogDebug((object)"Finished unpatching!");
		}
	}
	[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)
			{
				ScaledFallDamage.Logger.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)
			{
				ScaledFallDamage.Logger.LogError((object)$"Error deserializing instance: {arg}");
				return default(T);
			}
		}
	}
	public static class MyPluginInfo
	{
		public const string PLUGIN_GUID = "windblownleaves.scaledfalldamage";

		public const string PLUGIN_NAME = "ScaledFallDamage";

		public const string PLUGIN_VERSION = "1.0.6";
	}
}
namespace ScaledFallDamage.Patches
{
	[HarmonyPatch(typeof(PlayerControllerB))]
	internal class PlayerControllerBPatch
	{
		public static float logTimer;

		[HarmonyPatch("PlayerHitGroundEffects")]
		[HarmonyPrefix]
		public static void BeforeHitGround(ref float ___carryWeight, ref float ___fallValueUncapped, ref float ___fallValue, ref bool ___takingFallDamage)
		{
			if (SyncedInstance<Config>.Instance.modifySafeFallingHeightValue)
			{
				___takingFallDamage = true;
			}
			float tuningParameterValue = SyncedInstance<Config>.Instance.tuningParameterValue;
			float num = 1f + tuningParameterValue * (___carryWeight - 1f);
			if (___fallValueUncapped < -15f)
			{
				___fallValueUncapped *= num;
				___fallValue *= num;
			}
		}
	}
}