Decompiled source of BuyableShotgunShells v1.3.0

BuyableShotgunShells.dll

Decompiled 4 months ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
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 BepInEx.Logging;
using GameNetcodeStuff;
using HarmonyLib;
using LethalLib.Modules;
using Microsoft.CodeAnalysis;
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: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")]
[assembly: AssemblyCompany("BuyableShotgunShells")]
[assembly: AssemblyConfiguration("Debug")]
[assembly: AssemblyCopyright("Copyright © 2023 MegaPiggy")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0+d6d2c0f918043d4e4353ef5c47682e34337a1e68")]
[assembly: AssemblyProduct("BuyableShotgunShells")]
[assembly: AssemblyTitle("BuyableShotgunShells")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.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 BuyableShotgunShells
{
	[BepInDependency("evaisa.lethallib", "0.13.2")]
	[BepInPlugin("MegaPiggy.BuyableShotgunShells", "Buyable Shotgun Shells", "1.3.0")]
	public class BuyableShotgunShells : BaseUnityPlugin
	{
		public class ClonedItem : Item
		{
			public Item original;
		}

		internal class Unflagger : MonoBehaviour
		{
			public void Awake()
			{
				((Object)((Component)this).gameObject).hideFlags = (HideFlags)0;
			}
		}

		[HarmonyPatch]
		internal static class Patches
		{
			[CompilerGenerated]
			private static class <>O
			{
				public static HandleNamedMessageDelegate <0>__OnRequestSync;

				public static HandleNamedMessageDelegate <1>__OnReceiveSync;
			}

			[HarmonyPostfix]
			[HarmonyPatch(typeof(PlayerControllerB), "ConnectClientToPlayerObject")]
			public static void ServerConnect()
			{
				//IL_00a9: Unknown result type (might be due to invalid IL or missing references)
				//IL_0084: Unknown result type (might be due to invalid IL or missing references)
				//IL_0089: Unknown result type (might be due to invalid IL or missing references)
				//IL_008f: Expected O, but got Unknown
				//IL_003a: Unknown result type (might be due to invalid IL or missing references)
				//IL_003f: Unknown result type (might be due to invalid IL or missing references)
				//IL_0045: Expected O, but got Unknown
				if (IsHost)
				{
					LoggerInstance.LogInfo((object)"Started hosting, using local settings");
					CustomMessagingManager customMessagingManager = NetworkManager.Singleton.CustomMessagingManager;
					object obj = <>O.<0>__OnRequestSync;
					if (obj == null)
					{
						HandleNamedMessageDelegate val = OnRequestSync;
						<>O.<0>__OnRequestSync = val;
						obj = (object)val;
					}
					customMessagingManager.RegisterNamedMessageHandler("BuyableShotgunShells_OnRequestConfigSync", (HandleNamedMessageDelegate)obj);
					UpdateShopItemPrice();
				}
				else
				{
					LoggerInstance.LogInfo((object)"Connected to server, requesting settings");
					CustomMessagingManager customMessagingManager2 = NetworkManager.Singleton.CustomMessagingManager;
					object obj2 = <>O.<1>__OnReceiveSync;
					if (obj2 == null)
					{
						HandleNamedMessageDelegate val2 = OnReceiveSync;
						<>O.<1>__OnReceiveSync = val2;
						obj2 = (object)val2;
					}
					customMessagingManager2.RegisterNamedMessageHandler("BuyableShotgunShells_OnReceiveConfigSync", (HandleNamedMessageDelegate)obj2);
					NetworkManager.Singleton.CustomMessagingManager.SendNamedMessage("BuyableShotgunShells_OnRequestConfigSync", 0uL, new FastBufferWriter(0, (Allocator)2, -1), (NetworkDelivery)2);
				}
			}

			[HarmonyPostfix]
			[HarmonyPatch(typeof(GameNetworkManager), "Start")]
			public static void Start()
			{
				LoggerInstance.LogWarning((object)"Game network manager start");
				CloneShells();
			}

			[HarmonyPostfix]
			[HarmonyPatch(typeof(GameNetworkManager), "StartDisconnect")]
			public static void ServerDisconnect()
			{
				LoggerInstance.LogInfo((object)"Server disconnect");
				ShellPriceRemote = -1;
			}
		}

		private const string modGUID = "MegaPiggy.BuyableShotgunShells";

		private const string modName = "Buyable Shotgun Shells";

		private const string modVersion = "1.3.0";

		private readonly Harmony harmony = new Harmony("MegaPiggy.BuyableShotgunShells");

		private static BuyableShotgunShells Instance;

		private static ConfigEntry<int> ShellPriceConfig;

		internal static int ShellPriceRemote = -1;

		private static Dictionary<string, TerminalNode> infoNodes = new Dictionary<string, TerminalNode>();

		public static byte CurrentVersionByte = 1;

		private static ManualLogSource LoggerInstance => ((BaseUnityPlugin)Instance).Logger;

		public static List<Item> AllItems => Resources.FindObjectsOfTypeAll<Item>().Reverse().ToList();

		public static Item ShotgunShell => ((IEnumerable<Item>)AllItems).FirstOrDefault((Func<Item, bool>)((Item item) => ((Object)item).name.Equals("GunAmmo") && (Object)(object)item.spawnPrefab != (Object)null));

		public static ClonedItem ShotgunShellClone { get; private set; }

		public static int ShellPriceLocal => ShellPriceConfig.Value;

		public static int ShellPrice => (ShellPriceRemote > -1) ? ShellPriceRemote : ShellPriceLocal;

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

		private static ulong LocalClientId => NetworkManager.Singleton.LocalClientId;

		private void Awake()
		{
			if ((Object)(object)Instance == (Object)null)
			{
				Object.DontDestroyOnLoad((Object)(object)this);
				Instance = this;
			}
			harmony.PatchAll();
			ShellPriceConfig = ((BaseUnityPlugin)this).Config.Bind<int>("Prices", "ShotgunShellPrice", 20, "Credits needed to buy shotgun shells");
			((BaseUnityPlugin)this).Logger.LogInfo((object)"Plugin Buyable Shotgun Shells is loaded with version 1.3.0!");
		}

		private static ClonedItem CloneNonScrap(Item original, int price)
		{
			ClonedItem clonedItem = ScriptableObject.CreateInstance<ClonedItem>();
			Object.DontDestroyOnLoad((Object)(object)clonedItem);
			clonedItem.original = original;
			GameObject val = NetworkPrefabs.CloneNetworkPrefab(original.spawnPrefab, "Buyable" + ((Object)original).name);
			val.AddComponent<Unflagger>();
			Object.DontDestroyOnLoad((Object)(object)val);
			CopyFields(original, (Item)(object)clonedItem);
			val.GetComponent<GrabbableObject>().itemProperties = (Item)(object)clonedItem;
			((Item)clonedItem).spawnPrefab = val;
			((Object)clonedItem).name = "Buyable" + ((Object)original).name;
			((Item)clonedItem).creditsWorth = price;
			((Item)clonedItem).isScrap = false;
			return clonedItem;
		}

		public static void CopyFields(Item source, Item destination)
		{
			FieldInfo[] fields = typeof(Item).GetFields();
			FieldInfo[] array = fields;
			foreach (FieldInfo fieldInfo in array)
			{
				fieldInfo.SetValue(destination, fieldInfo.GetValue(source));
			}
		}

		private static TerminalNode CreateInfoNode(string name, string description)
		{
			if (infoNodes.ContainsKey(name))
			{
				return infoNodes[name];
			}
			TerminalNode val = ScriptableObject.CreateInstance<TerminalNode>();
			val.clearPreviousText = true;
			((Object)val).name = name + "InfoNode";
			val.displayText = description + "\n\n";
			infoNodes.Add(name, val);
			return val;
		}

		private static void CloneShells()
		{
			if (!((Object)(object)ShotgunShell == (Object)null) && !((Object)(object)ShotgunShellClone != (Object)null))
			{
				ShotgunShellClone = CloneNonScrap(ShotgunShell, ShellPrice);
				((Item)ShotgunShellClone).itemName = "Shells";
				AddToShop();
			}
		}

		private static void AddToShop()
		{
			ClonedItem shotgunShellClone = ShotgunShellClone;
			int shellPrice = ShellPrice;
			Items.RegisterShopItem((Item)(object)shotgunShellClone, (TerminalNode)null, (TerminalNode)null, CreateInfoNode("ShotgunShell", "Ammo for the Nutcracker's Shotgun."), shellPrice);
			LoggerInstance.LogInfo((object)$"Shotgun Shell added to Shop for {ShellPrice} credits");
		}

		private static void UpdateShopItemPrice()
		{
			((Item)ShotgunShellClone).creditsWorth = ShellPrice;
			Items.UpdateShopItemPrice((Item)(object)ShotgunShellClone, ShellPrice);
			LoggerInstance.LogInfo((object)$"Shotgun Shell price updated to {ShellPrice} credits");
		}

		public static void WriteData(FastBufferWriter writer)
		{
			((FastBufferWriter)(ref writer)).WriteByte(CurrentVersionByte);
			((FastBufferWriter)(ref writer)).WriteBytes(BitConverter.GetBytes(ShellPriceLocal), -1, 0);
		}

		public static void ReadData(FastBufferReader reader)
		{
			byte b = default(byte);
			((FastBufferReader)(ref reader)).ReadByte(ref b);
			if (b == CurrentVersionByte)
			{
				byte[] value = new byte[4];
				((FastBufferReader)(ref reader)).ReadBytes(ref value, 4, 0);
				ShellPriceRemote = BitConverter.ToInt32(value, 0);
				UpdateShopItemPrice();
				LoggerInstance.LogInfo((object)"Host config set successfully");
				return;
			}
			throw new Exception("Invalid version byte");
		}

		public static void OnRequestSync(ulong clientID, FastBufferReader reader)
		{
			//IL_0032: Unknown result type (might be due to invalid IL or missing references)
			//IL_0049: Unknown result type (might be due to invalid IL or missing references)
			if (!IsHost)
			{
				return;
			}
			LoggerInstance.LogInfo((object)("Sending config to client " + clientID));
			FastBufferWriter val = default(FastBufferWriter);
			((FastBufferWriter)(ref val))..ctor(5, (Allocator)2, 5);
			try
			{
				WriteData(val);
				NetworkManager.Singleton.CustomMessagingManager.SendNamedMessage("BuyableShotgunShells_OnReceiveConfigSync", clientID, val, (NetworkDelivery)2);
			}
			catch (Exception arg)
			{
				LoggerInstance.LogError((object)$"Failed to send config: {arg}");
			}
			finally
			{
				((FastBufferWriter)(ref val)).Dispose();
			}
		}

		public static void OnReceiveSync(ulong clientID, FastBufferReader reader)
		{
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			LoggerInstance.LogInfo((object)"Received config from host");
			try
			{
				ReadData(reader);
			}
			catch (Exception arg)
			{
				LoggerInstance.LogError((object)$"Failed to receive config: {arg}");
				ShellPriceRemote = -1;
			}
		}
	}
}