Decompiled source of Bandages v1.0.2

plugins/Bandages/Bandages.dll

Decompiled 5 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 LethalLib.Modules;
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("Bandages")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Bandages")]
[assembly: AssemblyCopyright("Copyright ©  2023")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
[assembly: Guid("b7ac27c5-113a-4162-8ef7-9df5672dccdb")]
[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 Bandages;

public class BandageItem : GrabbableObject
{
	public int maxUses = 1;

	public static int healthToAdd;

	private Random random = new Random();

	public static int itemSlotID;

	public override void Start()
	{
		((GrabbableObject)this).Start();
		base.grabbable = true;
	}

	public override void ItemActivate(bool used, bool buttonDown = true)
	{
		((GrabbableObject)this).ItemActivate(used, buttonDown);
		PlayerControllerB localPlayerController = GameNetworkManager.Instance.localPlayerController;
		int value = SyncedInstance<Config>.Instance.minHealthAmount.Value;
		int value2 = SyncedInstance<Config>.Instance.maxHealthAmount.Value;
		healthToAdd = random.Next(value, value2);
		if (localPlayerController.health == 100)
		{
			maxUses++;
		}
		localPlayerController.health += healthToAdd;
		if (localPlayerController.health >= 100)
		{
			localPlayerController.health = 100;
		}
		((Component)Plugin.bandage).GetComponent<AudioSource>().PlayOneShot(Plugin.useSFX);
		maxUses--;
		if (maxUses == 0)
		{
			itemSlotID = localPlayerController.currentItemSlot;
			localPlayerController.DestroyItemInSlotAndSync(itemSlotID);
		}
	}
}
[Serializable]
public class Config : SyncedInstance<Config>
{
	public ConfigEntry<int> minHealthAmount;

	public ConfigEntry<int> maxHealthAmount;

	public Config(ConfigFile cfg)
	{
		InitInstance(this);
		minHealthAmount = cfg.Bind<int>("General", "Minimum Health Amount", 10, "Max amount of health a bandage can give");
		maxHealthAmount = cfg.Bind<int>("General", "Max Health Amount", 15, "Minimum amount of health a bandage can give");
	}

	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("Bandages_OnRequestConfigSync", 0uL, val, (NetworkDelivery)3);
		}
		finally
		{
			((IDisposable)(FastBufferWriter)(ref val)).Dispose();
		}
	}

	public static void OnRequestSync(ulong clientId, 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;
		}
		Plugin.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("Bandages_OnReceiveConfigSync", clientId, val, (NetworkDelivery)3);
		}
		catch (Exception arg)
		{
			Plugin.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_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))
		{
			Plugin.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))
		{
			Plugin.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);
		Plugin.mls.LogInfo((object)"Successfully synced config with host.");
	}

	[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("Bandages_OnRequestConfigSync", new HandleNamedMessageDelegate(OnRequestSync));
			SyncedInstance<Config>.Synced = true;
		}
		else
		{
			SyncedInstance<Config>.Synced = false;
			SyncedInstance<Config>.MessageManager.RegisterNamedMessageHandler("Bandages_OnReceiveConfigSync", new HandleNamedMessageDelegate(OnReceiveSync));
			RequestSync();
		}
	}

	[HarmonyPostfix]
	[HarmonyPatch(typeof(GameNetworkManager), "StartDisconnect")]
	public static void PlayerLeave()
	{
		SyncedInstance<Config>.RevertSync();
	}
}
[BepInPlugin("SalakStudios.Bandages", "Bandages", "1.0.2")]
public class Plugin : BaseUnityPlugin
{
	private const string modGUID = "SalakStudios.Bandages";

	private const string modName = "Bandages";

	private const string modVersion = "1.0.2";

	private readonly Harmony harmony = new Harmony("SalakStudios.Bandages");

	internal static Plugin Instance;

	public static ManualLogSource mls;

	public static bool added;

	public static Item bandageItem;

	public static AudioClip useSFX;

	public static BandageItem bandage;

	public static Config NewConfig;

	private void Awake()
	{
		if ((Object)(object)Instance == (Object)null)
		{
			Instance = this;
		}
		harmony.PatchAll();
		NewConfig = new Config(((BaseUnityPlugin)this).Config);
		mls = Logger.CreateLogSource("SalakStudios.Bandages");
		mls.LogInfo((object)"Bandages Enabled");
		AssetBundle val = AssetBundle.LoadFromFile(((BaseUnityPlugin)Instance).Info.Location.TrimEnd("Bandages.dll".ToCharArray()) + "bandages");
		bandageItem = val.LoadAsset<Item>("assets/bandages/bandage.asset");
		useSFX = val.LoadAsset<AudioClip>("assets/bandages/useaudio.wav");
		bandage = bandageItem.spawnPrefab.AddComponent<BandageItem>();
		((GrabbableObject)bandage).itemProperties = bandageItem;
		NetworkPrefabs.RegisterNetworkPrefab(bandageItem.spawnPrefab);
		Items.RegisterShopItem(bandageItem, 35);
		if ((Object)(object)bandageItem == (Object)null)
		{
			mls.LogError((object)"bandageItem Null");
		}
	}
}
[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)
		{
			Plugin.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)
		{
			Plugin.mls.LogError((object)$"Error deserializing instance: {arg}");
			return default(T);
		}
	}
}