Decompiled source of Batteries v1.1.0

Batteries.dll

Decompiled 7 months ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using BepInEx;
using BepInEx.Configuration;
using GameNetcodeStuff;
using HarmonyLib;
using LethalLib.Modules;
using Unity.Netcode;
using UnityEngine;
using UnityEngine.InputSystem;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: AssemblyTitle("Batteries")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Batteries")]
[assembly: AssemblyCopyright("Copyright ©  2024")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
[assembly: Guid("d3aee990-a08c-4376-93d1-e137bd434d45")]
[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 Batteries
{
	public class BatteryManager : MonoBehaviour
	{
		public static BatteryManager Instance { get; private set; }

		public InputAction ReloadBatteryAction { get; private set; }

		private void Awake()
		{
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			//IL_001d: Expected O, but got Unknown
			//IL_0070: Unknown result type (might be due to invalid IL or missing references)
			Instance = this;
			ReloadBatteryAction = new InputAction("ReloadBattery", (InputActionType)0, (string)null, (string)null, (string)null, (string)null);
			if (string.IsNullOrEmpty(ConfigManager.useBatteryKeybinds.Value))
			{
				ConfigManager.useBatteryKeybinds.Value = "<Keyboard>/c,<Gamepad>/dpad/up,<XRController>{RightHand}/gripButton";
			}
			string[] array = ConfigManager.useBatteryKeybinds.Value.Split(new char[1] { ',' });
			foreach (string text in array)
			{
				InputActionSetupExtensions.AddBinding(ReloadBatteryAction, text, (string)null, (string)null, (string)null);
			}
			ReloadBatteryAction.Enable();
			ReloadBatteryAction.performed += ReloadBatteryActionPerformed;
		}

		private void OnDestroy()
		{
			ReloadBatteryAction.performed -= ReloadBatteryActionPerformed;
			ReloadBatteryAction.Disable();
		}

		private static void ReloadBatteryActionPerformed(CallbackContext context)
		{
			if (!((CallbackContext)(ref context)).performed)
			{
				return;
			}
			PlayerControllerB localPlayerController = StartOfRound.Instance.localPlayerController;
			if ((Object)(object)localPlayerController.currentlyHeldObjectServer == (Object)null || localPlayerController.inSpecialInteractAnimation || !localPlayerController.currentlyHeldObjectServer.itemProperties.requiresBattery || !(localPlayerController.currentlyHeldObjectServer.insertedBattery.charge < 1f))
			{
				return;
			}
			for (int i = 0; i < localPlayerController.ItemSlots.Length; i++)
			{
				if ((Object)(object)localPlayerController.ItemSlots[i] != (Object)null && (localPlayerController.ItemSlots[i].itemProperties.itemId == 5601 || localPlayerController.ItemSlots[i].itemProperties.itemId == 5602))
				{
					((Component)localPlayerController.currentlyHeldObjectServer).GetComponent<AudioSource>().PlayOneShot(BatteriesMod.useBattery);
					localPlayerController.DestroyItemInSlotAndSync(i);
					if (ConfigManager.batteryChargeAmount.Value < 0f || ConfigManager.batteryChargeAmount.Value > 1f)
					{
						Battery insertedBattery = localPlayerController.currentlyHeldObjectServer.insertedBattery;
						insertedBattery.charge += (float)((ConfigEntryBase)ConfigManager.batteryChargeAmount).DefaultValue;
					}
					else
					{
						Battery insertedBattery2 = localPlayerController.currentlyHeldObjectServer.insertedBattery;
						insertedBattery2.charge += ConfigManager.batteryChargeAmount.Value;
					}
					if (localPlayerController.currentlyHeldObjectServer.insertedBattery.charge > 1f)
					{
						localPlayerController.currentlyHeldObjectServer.insertedBattery.charge = 1f;
					}
					if (localPlayerController.currentlyHeldObjectServer.insertedBattery.empty)
					{
						localPlayerController.currentlyHeldObjectServer.insertedBattery.empty = false;
					}
					break;
				}
			}
		}
	}
	internal class ConfigManager
	{
		public const string DEFAULT_KEYBINDS = "<Keyboard>/c,<Gamepad>/dpad/up,<XRController>{RightHand}/gripButton";

		public static ConfigEntry<bool> toolTipEnabled;

		public static ConfigEntry<bool> disableChargingCoil;

		public static ConfigEntry<string> useBatteryKeybinds;

		public static ConfigEntry<float> batteryChargeAmount;

		public static ConfigEntry<int> batteryMaxSpawns;

		public static ConfigEntry<int> batteryRarity;

		public static ConfigEntry<int> batteryScrapValue;

		public static ConfigEntry<int> batteryShopValue;

		public static void Init()
		{
			toolTipEnabled = ((BaseUnityPlugin)BatteriesMod.instance).Config.Bind<bool>("General Settings", "toolTipEnabled", true, "Allows the mod to add/remove a tool tip to battery powered items when necessary.");
			disableChargingCoil = ((BaseUnityPlugin)BatteriesMod.instance).Config.Bind<bool>("General Settings", "disableChargingCoil", false, "Disables the charging coil. Mainly for people who wish to have batteries as the only charge source.");
			useBatteryKeybinds = ((BaseUnityPlugin)BatteriesMod.instance).Config.Bind<string>("General Settings", "useBatteryKeybinds", "<Keyboard>/c,<Gamepad>/dpad/up,<XRController>{RightHand}/gripButton", "The value for the keybinds to use a battery, split by comma. Values for keybinds can be found here: https://docs.unity3d.com/Packages/[email protected]/api/UnityEngine.InputSystem.Key.html.");
			batteryChargeAmount = ((BaseUnityPlugin)BatteriesMod.instance).Config.Bind<float>("Battery Settings", "batteryChargeAmount", 0.25f, "The amount that batteries charge battery powered items. Can be set to a minimum of 0 (0% charge) and a maximum of 1 (100% charge).");
			batteryMaxSpawns = ((BaseUnityPlugin)BatteriesMod.instance).Config.Bind<int>("Battery Settings", "batteryMaxSpawns", 10, "The maximum number of batteries that can spawn per moon. Can be set to any number greater than 0.");
			batteryRarity = ((BaseUnityPlugin)BatteriesMod.instance).Config.Bind<int>("Battery Settings", "batteryRarity", 70, "How rare it is for a battery to spawn. Can be set to a minimum of 0 (cannot spawn) and a maximum of 100 (common).");
			batteryScrapValue = ((BaseUnityPlugin)BatteriesMod.instance).Config.Bind<int>("Battery Settings", "batteryScrapValue", 5, "The scrap value of batteries.");
			batteryShopValue = ((BaseUnityPlugin)BatteriesMod.instance).Config.Bind<int>("Battery Settings", "batteryShopValue", 0, "How much batteries cost in the shop. When set to 0 or less batteries will not appear in the shop.");
		}
	}
	[BepInPlugin("eXish.Batteries", "Batteries", "1.1.0")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	public class BatteriesMod : BaseUnityPlugin
	{
		private const string mGUID = "eXish.Batteries";

		private const string mName = "Batteries";

		private const string mVersion = "1.1.0";

		private readonly Harmony harmony = new Harmony("eXish.Batteries");

		internal static BatteriesMod instance;

		internal static AssetBundle bundle;

		internal static AudioClip useBattery;

		internal static Item batteryItem;

		private void Awake()
		{
			if ((Object)(object)instance == (Object)null)
			{
				instance = this;
			}
			ConfigManager.Init();
			if (string.IsNullOrEmpty(ConfigManager.useBatteryKeybinds.Value))
			{
				((BaseUnityPlugin)instance).Logger.LogWarning((object)("The value \"" + ConfigManager.useBatteryKeybinds.Value + "\" is not valid for setting \"useBatteryKeybinds\"! The default will be used instead."));
			}
			if (ConfigManager.batteryChargeAmount.Value < 0f || ConfigManager.batteryChargeAmount.Value > 1f)
			{
				((BaseUnityPlugin)instance).Logger.LogWarning((object)$"The value \"{ConfigManager.batteryChargeAmount.Value}\" is not valid for setting \"batteryChargeAmount\"! The default will be used instead.");
			}
			if (ConfigManager.batteryRarity.Value < 0 || ConfigManager.batteryRarity.Value > 100)
			{
				((BaseUnityPlugin)instance).Logger.LogWarning((object)$"The value \"{ConfigManager.batteryRarity.Value}\" is not valid for setting \"batteryRarity\"! The default will be used instead.");
			}
			if (ConfigManager.batteryMaxSpawns.Value <= 0)
			{
				((BaseUnityPlugin)instance).Logger.LogWarning((object)$"The value \"{ConfigManager.batteryMaxSpawns.Value}\" is not valid for setting \"batteryMaxSpawns\"! The default will be used instead.");
			}
			if (ConfigManager.batteryScrapValue.Value < 0)
			{
				((BaseUnityPlugin)instance).Logger.LogWarning((object)$"The value \"{ConfigManager.batteryScrapValue.Value}\" is not valid for setting \"batteryScrapValue\"! The default will be used instead.");
			}
			string text = ((BaseUnityPlugin)instance).Info.Location.TrimEnd("Batteries.dll".ToCharArray());
			bundle = AssetBundle.LoadFromFile(text + "batteries");
			if ((Object)(object)bundle != (Object)null)
			{
				useBattery = bundle.LoadAsset<AudioClip>("Assets/Batteries/UseBattery.wav");
				batteryItem = bundle.LoadAsset<Item>("Assets/Batteries/Battery.asset");
				if (ConfigManager.batteryRarity.Value != 0)
				{
					Utilities.FixMixerGroups(batteryItem.spawnPrefab);
					NetworkPrefabs.RegisterNetworkPrefab(batteryItem.spawnPrefab);
					Items.RegisterItem(batteryItem);
				}
				if (ConfigManager.batteryShopValue.Value > 0)
				{
					Item val = bundle.LoadAsset<Item>("Assets/Batteries/StoreBattery.asset");
					Utilities.FixMixerGroups(val.spawnPrefab);
					NetworkPrefabs.RegisterNetworkPrefab(val.spawnPrefab);
					TerminalNode val2 = ScriptableObject.CreateInstance<TerminalNode>();
					val2.clearPreviousText = true;
					val2.displayText = "Are you tired of having to travel all the way back to your ship to charge equipment? Well fear not! Durable's new battery line will solve all your charging needs! Get the power you deserve right when you need it!\n\nDurable is not responsible for any injury or death caused by our product. All items purchased are non-refundable.\n\n";
					Items.RegisterShopItem(val, (TerminalNode)null, (TerminalNode)null, val2, ConfigManager.batteryShopValue.Value);
				}
			}
			else
			{
				((BaseUnityPlugin)instance).Logger.LogError((object)"Unable to locate the asset file! Batteries will not spawn or appear in the shop.");
			}
			harmony.PatchAll();
			((BaseUnityPlugin)instance).Logger.LogInfo((object)"Batteries-1.1.0 loaded!");
		}
	}
}
namespace Batteries.Patches
{
	[HarmonyPatch(typeof(GrabbableObject))]
	internal class GrabbableObjectPatch
	{
		[HarmonyPatch("Update")]
		[HarmonyPostfix]
		private static void ObjUpdatePatch(ref GrabbableObject __instance)
		{
			if (__instance.itemProperties.itemId == 5601)
			{
				if (ConfigManager.batteryScrapValue.Value < 0)
				{
					__instance.SetScrapValue((int)((ConfigEntryBase)ConfigManager.batteryScrapValue).DefaultValue);
				}
				else
				{
					__instance.SetScrapValue(ConfigManager.batteryScrapValue.Value);
				}
			}
		}
	}
	[HarmonyPatch(typeof(ItemCharger))]
	internal class ItemChargerPatch
	{
		[HarmonyPatch("Update")]
		[HarmonyPostfix]
		private static void ChargerUpdatePatch(ref ItemCharger __instance)
		{
			if (((Component)__instance).gameObject.activeSelf && ConfigManager.disableChargingCoil.Value)
			{
				((Component)__instance).gameObject.SetActive(false);
			}
		}
	}
	[HarmonyPatch(typeof(PlayerControllerB))]
	internal class PlayerControllerBPatch
	{
		private static bool wasUsingController;

		[HarmonyPatch("Update")]
		[HarmonyPostfix]
		private static void PlayerUpdatePatch(ref PlayerControllerB __instance)
		{
			//IL_009e: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cc: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cd: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d6: Unknown result type (might be due to invalid IL or missing references)
			if (!((NetworkBehaviour)__instance).IsOwner || (Object)(object)__instance.currentlyHeldObjectServer == (Object)null || __instance.inSpecialInteractAnimation || !ConfigManager.toolTipEnabled.Value || !__instance.currentlyHeldObjectServer.itemProperties.requiresBattery)
			{
				return;
			}
			if (__instance.currentlyHeldObjectServer.insertedBattery.charge < 1f && (!BatteryTooltipShown() || wasUsingController != StartOfRound.Instance.localPlayerUsingController) && BatteryInInventory())
			{
				InputBinding val = ((IEnumerable<InputBinding>)(object)BatteryManager.Instance.ReloadBatteryAction.bindings).FirstOrDefault((Func<InputBinding, bool>)((InputBinding x) => ((InputBinding)(ref x)).path.ToLowerInvariant().Contains(StartOfRound.Instance.localPlayerUsingController ? "<gamepad>" : "<keyboard>")));
				string text = ((val == default(InputBinding)) ? "?" : ((InputBinding)(ref val)).ToDisplayString((DisplayStringOptions)0, (InputControl)null));
				string[] toolTips = __instance.currentlyHeldObjectServer.itemProperties.toolTips;
				string[] array = new string[toolTips.Length + 1];
				for (int i = 0; i < array.Length; i++)
				{
					if (i != array.Length - 1)
					{
						array[i] = toolTips[i];
					}
					else
					{
						array[i] = "Use Battery : [" + text + "]";
					}
				}
				__instance.currentlyHeldObjectServer.itemProperties.toolTips = array;
				HUDManager.Instance.ClearControlTips();
				__instance.currentlyHeldObjectServer.SetControlTipsForItem();
				wasUsingController = StartOfRound.Instance.localPlayerUsingController;
			}
			if (BatteryTooltipShown() && (__instance.currentlyHeldObjectServer.insertedBattery.charge >= 1f || !BatteryInInventory()))
			{
				__instance.currentlyHeldObjectServer.itemProperties.toolTips = __instance.currentlyHeldObjectServer.itemProperties.toolTips.Where((string x) => !x.StartsWith("Use Battery : [")).ToArray();
				HUDManager.Instance.ClearControlTips();
				__instance.currentlyHeldObjectServer.SetControlTipsForItem();
			}
		}

		private static bool BatteryInInventory()
		{
			return StartOfRound.Instance.localPlayerController.ItemSlots.Any((GrabbableObject x) => Object.op_Implicit((Object)(object)x) && (x.itemProperties.itemId == 5601 || x.itemProperties.itemId == 5602));
		}

		private static bool BatteryTooltipShown()
		{
			return StartOfRound.Instance.localPlayerController.currentlyHeldObjectServer.itemProperties.toolTips.Any((string tooltip) => tooltip.StartsWith("Use Battery : ["));
		}
	}
	[HarmonyPatch(typeof(RoundManager))]
	internal class RoundManagerPatch
	{
		[HarmonyPatch("SpawnScrapInLevel")]
		[HarmonyPostfix]
		private static void SpawnScrapPatch(ref RoundManager __instance)
		{
			//IL_00b5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ce: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00df: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e1: Unknown result type (might be due to invalid IL or missing references)
			int num = ConfigManager.batteryRarity.Value;
			if (num < 0 || num > 100)
			{
				num = (int)((ConfigEntryBase)ConfigManager.batteryRarity).DefaultValue;
			}
			if (num == 0)
			{
				return;
			}
			int num2 = ConfigManager.batteryMaxSpawns.Value;
			if (num2 <= 0)
			{
				num2 = (int)((ConfigEntryBase)ConfigManager.batteryMaxSpawns).DefaultValue;
			}
			for (int i = 0; i < num2; i++)
			{
				int num3 = __instance.AnomalyRandom.Next(1, 151);
				if (num3 <= num)
				{
					int num4 = __instance.AnomalyRandom.Next(0, __instance.insideAINodes.Length);
					Vector3 randomNavMeshPositionInBoxPredictable = __instance.GetRandomNavMeshPositionInBoxPredictable(__instance.insideAINodes[num4].transform.position, 8f, __instance.navHit, __instance.AnomalyRandom, -1);
					Object.Instantiate<GameObject>(BatteriesMod.batteryItem.spawnPrefab, randomNavMeshPositionInBoxPredictable, Quaternion.identity, __instance.spawnedScrapContainer).GetComponent<NetworkObject>().Spawn(false);
				}
			}
		}
	}
	[HarmonyPatch(typeof(StartOfRound))]
	internal class StartOfRoundPatch
	{
		[HarmonyPatch("Start")]
		[HarmonyPostfix]
		private static void OnStartOfRoundStart(StartOfRound __instance)
		{
			((Component)__instance).gameObject.AddComponent<BatteryManager>();
		}
	}
}