Decompiled source of LethalDebt v1.0.0

BepInEx/plugins/LethalDebt.dll

Decompiled 2 months ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using LethalDebt.NetcodePatcher;
using LethalDebt.Patches;
using Microsoft.CodeAnalysis;
using MoreShipUpgrades.UI.Application;
using MoreShipUpgrades.UI.TerminalNodes;
using TMPro;
using Unity.Netcode;
using UnityEngine;
using UnityEngine.UI;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("LethalDebt")]
[assembly: AssemblyConfiguration("Debug")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0")]
[assembly: AssemblyProduct("LethalDebt")]
[assembly: AssemblyTitle("LethalDebt")]
[assembly: AssemblyVersion("1.0.0.0")]
[module: NetcodePatchedAssembly]
internal class <Module>
{
	static <Module>()
	{
	}
}
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

		public NullableAttribute(byte P_0)
		{
			NullableFlags = new byte[1] { P_0 };
		}

		public NullableAttribute(byte[] P_0)
		{
			NullableFlags = P_0;
		}
	}
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableContextAttribute : Attribute
	{
		public readonly byte Flag;

		public NullableContextAttribute(byte P_0)
		{
			Flag = P_0;
		}
	}
}
namespace LethalDebt
{
	internal class NetworkHelper : NetworkBehaviour
	{
		public static NetworkHelper Instance;

		private void Start()
		{
			Instance = this;
		}

		[ClientRpc]
		public void EnableClientRpc()
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Invalid comparison between Unknown and I4
			//IL_008c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0096: Invalid comparison between Unknown and I4
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_007c: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager;
			if (networkManager != null && networkManager.IsListening)
			{
				if ((int)base.__rpc_exec_stage != 2 && (networkManager.IsServer || networkManager.IsHost))
				{
					ClientRpcParams val = default(ClientRpcParams);
					FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendClientRpc(2401801619u, val, (RpcDelivery)0);
					((NetworkBehaviour)this).__endSendClientRpc(ref val2, 2401801619u, val, (RpcDelivery)0);
				}
				if ((int)base.__rpc_exec_stage == 2 && (networkManager.IsClient || networkManager.IsHost))
				{
					Plugin.Instance.LogToConsole("The host has Lethal Debt!", "debug");
					Plugin.Instance.enabled = true;
				}
			}
		}

		protected override void __initializeVariables()
		{
			((NetworkBehaviour)this).__initializeVariables();
		}

		[RuntimeInitializeOnLoadMethod]
		internal static void InitializeRPCS_NetworkHelper()
		{
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_001b: Expected O, but got Unknown
			NetworkManager.__rpc_func_table.Add(2401801619u, new RpcReceiveHandler(__rpc_handler_2401801619));
		}

		private static void __rpc_handler_2401801619(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams)
		{
			//IL_0029: 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)
			NetworkManager networkManager = target.NetworkManager;
			if (networkManager != null && networkManager.IsListening)
			{
				target.__rpc_exec_stage = (__RpcExecStage)2;
				((NetworkHelper)(object)target).EnableClientRpc();
				target.__rpc_exec_stage = (__RpcExecStage)0;
			}
		}

		protected internal override string __getTypeName()
		{
			return "NetworkHelper";
		}
	}
	[BepInPlugin("JS03.LethalDebt", "Lethal Debt", "1.0.0")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	public class Plugin : BaseUnityPlugin
	{
		private const string modGUID = "JS03.LethalDebt";

		private const string modName = "Lethal Debt";

		private const string modVersion = "1.0.0";

		private readonly Harmony harmony = new Harmony("JS03.LethalDebt");

		public static Plugin Instance;

		internal static ManualLogSource mls;

		public bool enabled;

		public const int DEBT_LIMIT = -100000000;

		public ConfigEntry<string> debtColor;

		private void Awake()
		{
			if ((Object)(object)Instance == (Object)null)
			{
				Instance = this;
			}
			mls = Logger.CreateLogSource("JS03.LethalDebt");
			mls.LogInfo((object)"Lethal Debt is awake");
			enabled = true;
			Type[] types = Assembly.GetExecutingAssembly().GetTypes();
			Type[] array = types;
			foreach (Type type in array)
			{
				MethodInfo[] methods = type.GetMethods(BindingFlags.Instance | BindingFlags.Static | BindingFlags.NonPublic);
				MethodInfo[] array2 = methods;
				foreach (MethodInfo methodInfo in array2)
				{
					object[] customAttributes = methodInfo.GetCustomAttributes(typeof(RuntimeInitializeOnLoadMethodAttribute), inherit: false);
					if (customAttributes.Length != 0)
					{
						methodInfo.Invoke(null, null);
					}
				}
			}
			GenerateConfig();
			ApplyPatches();
		}

		private void ApplyPatches()
		{
			harmony.PatchAll(typeof(TerminalPatches));
			harmony.PatchAll(typeof(StartOfRoundPatches));
			harmony.PatchAll(typeof(TimeOfDayPatches));
			harmony.PatchAll(typeof(HUDManagerPatches));
			harmony.PatchAll(typeof(GameNetworkManagerPatches));
			if (Chainloader.PluginInfos.ContainsKey("com.malco.lethalcompany.moreshipupgrades"))
			{
				harmony.PatchAll(typeof(LGUPatches));
			}
			mls.LogInfo((object)"Patches applied!");
		}

		private void GenerateConfig()
		{
			debtColor = ((BaseUnityPlugin)this).Config.Bind<string>("Customization", "Debt Color", "#ff0000", "Changes the color of the displayed credits in the terminal when they're in the negatives.\nMake sure you separate the different values with a comma and a blank space.");
			debtColor.SettingChanged += delegate
			{
				Utils.ChangeTerminalCreditsColor(debtColor.Value);
			};
		}

		public void LogToConsole(string message, string logType = "")
		{
			switch (logType.ToLower())
			{
			case "warn":
				mls.LogWarning((object)message);
				break;
			case "error":
				mls.LogError((object)message);
				break;
			case "debug":
				mls.LogDebug((object)message);
				break;
			default:
				mls.LogInfo((object)message);
				break;
			}
		}
	}
	internal class Utils
	{
		public static void ChangeTerminalCreditsColor(string htmlColor)
		{
			//IL_0026: Unknown result type (might be due to invalid IL or missing references)
			if (TerminalPatches.terminal.groupCredits < 0)
			{
				Color color = default(Color);
				ColorUtility.TryParseHtmlString(htmlColor, ref color);
				((Graphic)TerminalPatches.terminal.topRightText).color = color;
			}
		}
	}
}
namespace LethalDebt.Patches
{
	internal class GameNetworkManagerPatches
	{
		[HarmonyPatch(typeof(GameNetworkManager), "Start")]
		[HarmonyPostfix]
		private static void StartPatch(GameNetworkManager __instance)
		{
			((Component)__instance).gameObject.AddComponent<NetworkHelper>();
			((Component)__instance).gameObject.AddComponent<NetworkObject>();
			Plugin.Instance.LogToConsole("Network Helper has been added", "debug");
		}
	}
	[HarmonyPatch(typeof(HUDManager))]
	internal class HUDManagerPatches
	{
		[HarmonyPatch("ApplyPenalty")]
		[HarmonyPrefix]
		private static bool CalculatePenaltyWithDebt(HUDManager __instance, int playersDead, int bodiesInsured)
		{
			if (TerminalPatches.terminal.groupCredits < 0)
			{
				float num = 0.2f;
				int groupCredits = TerminalPatches.terminal.groupCredits;
				bodiesInsured = Mathf.Max(bodiesInsured, 0);
				for (int i = 0; i < playersDead - bodiesInsured; i++)
				{
					Terminal terminal = TerminalPatches.terminal;
					terminal.groupCredits += (int)((float)groupCredits * num);
				}
				for (int j = 0; j < bodiesInsured; j++)
				{
					Terminal terminal2 = TerminalPatches.terminal;
					terminal2.groupCredits += (int)((float)groupCredits * (num / 2.5f));
				}
				((TMP_Text)__instance.statsUIElements.penaltyAddition).text = $"{playersDead} casualties: -{500f * (float)(playersDead - bodiesInsured)}%\n({bodiesInsured} bodies recovered)";
				((TMP_Text)__instance.statsUIElements.penaltyTotal).text = $"DUE: ${groupCredits - TerminalPatches.terminal.groupCredits}";
				Debug.Log((object)$"New group credits after penalty: {TerminalPatches.terminal.groupCredits}");
				return false;
			}
			return true;
		}
	}
	internal class LGUPatches
	{
		[HarmonyPatch(typeof(UpgradeStoreApplication), "BuyUpgrade")]
		[HarmonyTranspiler]
		private static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions)
		{
			List<CodeInstruction> list = new List<CodeInstruction>(instructions);
			for (int i = 0; i < list.Count; i++)
			{
				if (list[i].opcode == OpCodes.Ldloc_S && list[i].operand.ToString().Equals("System.Boolean (6)") && list[i + 1].opcode == OpCodes.Brfalse && list[i + 2].opcode == OpCodes.Nop)
				{
					for (int j = 0; j < 16; j++)
					{
						list[i + j].opcode = OpCodes.Nop;
					}
					Plugin.Instance.LogToConsole("Removed LGU purchasing restrictions", "debug");
					break;
				}
			}
			return list.AsEnumerable();
		}

		[HarmonyPatch(typeof(UpgradeStoreApplication), "BuyUpgrade")]
		[HarmonyPrefix]
		private static bool PreventClientGriefing(CustomTerminalNode node)
		{
			if (!Plugin.Instance.enabled && TerminalPatches.terminal.groupCredits < node.GetCurrentPrice())
			{
				return false;
			}
			return true;
		}

		[HarmonyPatch(typeof(UpgradeStoreApplication), "PurchaseUpgrade")]
		[HarmonyPostfix]
		private static void UpdateCreditsColorAfterPurchase()
		{
			Utils.ChangeTerminalCreditsColor(Plugin.Instance.debtColor.Value);
		}
	}
	internal class StartOfRoundPatches
	{
		[HarmonyPatch(typeof(StartOfRound), "OnClientConnect")]
		[HarmonyPrefix]
		private static void DisableClient(StartOfRound __instance)
		{
			if (!((NetworkBehaviour)__instance).IsHost)
			{
				Plugin.Instance.enabled = false;
			}
		}

		[HarmonyPatch(typeof(StartOfRound), "OnClientConnect")]
		[HarmonyPostfix]
		private static void EnableClientDebt(StartOfRound __instance)
		{
			NetworkHelper.Instance.EnableClientRpc();
		}
	}
	[HarmonyPatch(typeof(Terminal))]
	internal class TerminalPatches
	{
		public static Terminal terminal;

		private static Color terminalCreditsColor;

		[HarmonyPatch("LoadNewNodeIfAffordable")]
		[HarmonyTranspiler]
		private static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions)
		{
			List<CodeInstruction> list = new List<CodeInstruction>(instructions);
			for (int i = 0; i < list.Count; i++)
			{
				if (list[i].opcode == OpCodes.Ldarg_0 && list[i + 1].opcode == OpCodes.Ldfld && list[i + 1].operand.ToString().Contains("groupCredits"))
				{
					for (int j = 0; j < 20; j++)
					{
						list[i + j].opcode = OpCodes.Nop;
					}
					Plugin.Instance.LogToConsole("Purchasing restrictions removed", "debug");
					break;
				}
			}
			for (int k = 0; k < list.Count; k++)
			{
				if (list[k].opcode == OpCodes.Ldc_I4_0 && list[k + 1].opcode == OpCodes.Ldc_I4 && Convert.ToInt64(list[k + 1].operand) == 10000000)
				{
					list[k].opcode = OpCodes.Ldc_I4;
					list[k].operand = -100000000;
					Plugin.Instance.LogToConsole("New min credit limit set", "debug");
				}
			}
			return list.AsEnumerable();
		}

		[HarmonyPatch("LoadNewNodeIfAffordable")]
		[HarmonyPrefix]
		private static bool PreventGriefing(TerminalNode node, Terminal __instance, ref int ___totalCostOfItems)
		{
			if (!Plugin.Instance.enabled && __instance.groupCredits < ___totalCostOfItems && (node.buyVehicleIndex == -1 || !__instance.hasWarrantyTicket))
			{
				__instance.LoadNewNode(__instance.terminalNodes.specialNodes[2]);
				return false;
			}
			if (__instance.groupCredits - ___totalCostOfItems <= -100000000)
			{
				__instance.LoadNewNode(__instance.terminalNodes.specialNodes[2]);
				return false;
			}
			return true;
		}

		[HarmonyPatch("LoadNewNodeIfAffordable")]
		[HarmonyPostfix]
		private static void ChangeCreditsColorAfterPurchase(Terminal __instance)
		{
			Utils.ChangeTerminalCreditsColor(Plugin.Instance.debtColor.Value);
		}

		[HarmonyPatch("BeginUsingTerminal")]
		[HarmonyPostfix]
		private static void ChangeCreditsColorOnTerminalOpen(Terminal __instance)
		{
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			if (terminal.groupCredits >= 0)
			{
				terminalCreditsColor = ((Graphic)terminal.topRightText).color;
			}
			Utils.ChangeTerminalCreditsColor(Plugin.Instance.debtColor.Value);
		}

		[HarmonyPatch(typeof(DepositItemsDesk), "SellItemsClientRpc")]
		[HarmonyPostfix]
		private static void ChangeCreditsColorAfterSellingClientRpc()
		{
			//IL_0020: Unknown result type (might be due to invalid IL or missing references)
			Plugin.Instance.LogToConsole("Credits color reverted to default", "debug");
			((Graphic)terminal.topRightText).color = terminalCreditsColor;
		}

		[HarmonyPatch(typeof(Terminal), "Start")]
		[HarmonyPostfix]
		private static void GetTerminal(Terminal __instance)
		{
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			terminal = __instance;
			terminalCreditsColor = ((Graphic)terminal.topRightText).color;
			Utils.ChangeTerminalCreditsColor(Plugin.Instance.debtColor.Value);
		}
	}
	internal class TimeOfDayPatches
	{
		[HarmonyPatch(typeof(TimeOfDay), "SetNewProfitQuota")]
		[HarmonyPrefix]
		private static bool FirePlayers(TimeOfDay __instance)
		{
			if (Plugin.Instance.enabled && TerminalPatches.terminal.groupCredits < 0)
			{
				GameNetworkManager.Instance.gameHasStarted = true;
				StartOfRound.Instance.firingPlayersCutsceneRunning = true;
				StartOfRound.Instance.FirePlayersAfterDeadlineClientRpc(new int[4]
				{
					StartOfRound.Instance.gameStats.daysSpent,
					StartOfRound.Instance.gameStats.scrapValueCollected,
					StartOfRound.Instance.gameStats.deaths,
					StartOfRound.Instance.gameStats.allStepsTaken
				}, false);
				return false;
			}
			return true;
		}
	}
}
namespace LethalDebt.NetcodePatcher
{
	[AttributeUsage(AttributeTargets.Module)]
	internal class NetcodePatchedAssemblyAttribute : Attribute
	{
	}
}