Decompiled source of BuyableShotgun v1.3.0

BuyableShotgun.dll

Decompiled 5 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("BuyableShotgun")]
[assembly: AssemblyConfiguration("Debug")]
[assembly: AssemblyCopyright("Copyright © 2023 MegaPiggy")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0+6ba547771daa1d82ce02c67222831d51d8608dcc")]
[assembly: AssemblyProduct("BuyableShotgun")]
[assembly: AssemblyTitle("BuyableShotgun")]
[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 BuyableShotgun
{
	[BepInDependency("evaisa.lethallib", "0.13.2")]
	[BepInPlugin("MegaPiggy.BuyableShotgun", "Buyable Shotgun", "1.3.0")]
	public class BuyableShotgun : 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("BuyableShotgun_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("BuyableShotgun_OnReceiveConfigSync", (HandleNamedMessageDelegate)obj2);
					NetworkManager.Singleton.CustomMessagingManager.SendNamedMessage("BuyableShotgun_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");
				CloneShotgun();
			}

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

		private const string modGUID = "MegaPiggy.BuyableShotgun";

		private const string modName = "Buyable Shotgun";

		private const string modVersion = "1.3.0";

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

		private static BuyableShotgun Instance;

		private static ConfigEntry<int> ShotgunPriceConfig;

		internal static int ShotgunPriceRemote = -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 Shotgun => ((IEnumerable<Item>)AllItems).FirstOrDefault((Func<Item, bool>)((Item item) => ((Object)item).name.Equals("Shotgun") && (Object)(object)item.spawnPrefab != (Object)null));

		public static ClonedItem ShotgunClone { get; private set; }

		public static int ShotgunPriceLocal => ShotgunPriceConfig.Value;

		public static int ShotgunPrice => (ShotgunPriceRemote > -1) ? ShotgunPriceRemote : ShotgunPriceLocal;

		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();
			ShotgunPriceConfig = ((BaseUnityPlugin)this).Config.Bind<int>("Prices", "ShotgunPrice", 700, "Credits needed to buy shotgun");
			((BaseUnityPlugin)this).Logger.LogInfo((object)"Plugin Buyable Shotgun 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>();
			Object.DontDestroyOnLoad((Object)(object)val);
			val.clearPreviousText = true;
			((Object)val).name = name + "InfoNode";
			val.displayText = description + "\n\n";
			infoNodes.Add(name, val);
			return val;
		}

		private static void CloneShotgun()
		{
			if (!((Object)(object)Shotgun == (Object)null) && !((Object)(object)ShotgunClone != (Object)null))
			{
				ShotgunClone = CloneNonScrap(Shotgun, ShotgunPrice);
				AddToShop();
			}
		}

		private static void AddToShop()
		{
			ClonedItem shotgunClone = ShotgunClone;
			int shotgunPrice = ShotgunPrice;
			Items.RegisterShopItem((Item)(object)shotgunClone, (TerminalNode)null, (TerminalNode)null, CreateInfoNode("Shotgun", "Nutcracker's Shotgun. Can hold 2 shells. Recommended to keep safety on while not using or it might shoot randomly."), shotgunPrice);
			LoggerInstance.LogInfo((object)$"Shotgun added to Shop for {ShotgunPrice} credits");
		}

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

		public static void WriteData(FastBufferWriter writer)
		{
			((FastBufferWriter)(ref writer)).WriteByte(CurrentVersionByte);
			((FastBufferWriter)(ref writer)).WriteBytes(BitConverter.GetBytes(ShotgunPriceLocal), -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);
				ShotgunPriceRemote = 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("BuyableShotgun_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}");
				ShotgunPriceRemote = -1;
			}
		}
	}
}