Decompiled source of BodaciousModPack v1.1.0
plugins/BuyableShotgun.dll
Decompiled 11 months agousing 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.Logging; using HarmonyLib; using LethalLib.Modules; using Microsoft.CodeAnalysis; using UnityEngine; using UnityEngine.SceneManagement; [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")] [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 { [BepInPlugin("MegaPiggy.BuyableShotgun", "BuyableShotgun", "1.0.0")] public class BuyableShotgun : BaseUnityPlugin { private const string modGUID = "MegaPiggy.BuyableShotgun"; private const string modName = "BuyableShotgun"; private const string modVersion = "1.0.0"; private readonly Harmony harmony = new Harmony("MegaPiggy.BuyableShotgun"); private static BuyableShotgun Instance; public int ShotgunPrice; public bool added; private static ManualLogSource LoggerInstance => ((BaseUnityPlugin)Instance).Logger; public List<Item> AllItems => Resources.FindObjectsOfTypeAll<Item>().Concat(Object.FindObjectsByType<Item>((FindObjectsInactive)1, (FindObjectsSortMode)1)).ToList(); public Item Shotgun => ((IEnumerable<Item>)AllItems).FirstOrDefault((Func<Item, bool>)((Item item) => ((Object)item).name == "Shotgun")); private void Awake() { if ((Object)(object)Instance == (Object)null) { Instance = this; } harmony.PatchAll(); ShotgunPrice = ((BaseUnityPlugin)this).Config.Bind<int>("Prices", "ShotgunPrice", 700, "Credits needed to buy shotgun").Value; SceneManager.sceneLoaded += OnSceneLoaded; ((BaseUnityPlugin)this).Logger.LogInfo((object)"Plugin BuyableShotgun is loaded with version 1.0.0!"); } private void OnSceneLoaded(Scene scene, LoadSceneMode mode) { if (!added && ((Scene)(ref scene)).name == "MainMenu") { added = true; Items.RegisterShopItem(Shotgun, ShotgunPrice); } } } }
plugins/BuyableShotgunShells.dll
Decompiled 11 months agousing 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.Logging; using HarmonyLib; using LethalLib.Modules; using Microsoft.CodeAnalysis; using UnityEngine; using UnityEngine.SceneManagement; [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")] [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 { [BepInPlugin("MegaPiggy.BuyableShotgunShells", "Buyable Shotgun Shells", "1.0.1")] public class BuyableShotgunShells : BaseUnityPlugin { private const string modGUID = "MegaPiggy.BuyableShotgunShells"; private const string modName = "Buyable Shotgun Shells"; private const string modVersion = "1.0.1"; private readonly Harmony harmony = new Harmony("MegaPiggy.BuyableShotgunShells"); private static BuyableShotgunShells Instance; public int ShellPrice; public bool added; private static ManualLogSource LoggerInstance => ((BaseUnityPlugin)Instance).Logger; public List<Item> AllItems => Resources.FindObjectsOfTypeAll<Item>().Concat(Object.FindObjectsByType<Item>((FindObjectsInactive)1, (FindObjectsSortMode)1)).ToList(); public Item ShotgunShell => ((IEnumerable<Item>)AllItems).FirstOrDefault((Func<Item, bool>)((Item item) => ((Object)item).name == "GunAmmo")); private void Awake() { if ((Object)(object)Instance == (Object)null) { Instance = this; } harmony.PatchAll(); ShellPrice = ((BaseUnityPlugin)this).Config.Bind<int>("Prices", "ShotgunShellPrice", 20, "Credits needed to buy shotgun shells").Value; SceneManager.sceneLoaded += OnSceneLoaded; ((BaseUnityPlugin)this).Logger.LogInfo((object)"Plugin Buyable Shotgun Shells is loaded with version 1.0.1!"); } private void OnSceneLoaded(Scene scene, LoadSceneMode mode) { if (!added && ((Scene)(ref scene)).name == "MainMenu") { added = true; ShotgunShell.itemName = "Shells"; Items.RegisterShopItem(ShotgunShell, ShellPrice); } } } }
plugins/DoomShotgun.dll
Decompiled 11 months agousing System; 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 HarmonyLib; using LCSoundTool; using Microsoft.CodeAnalysis; 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(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")] [assembly: AssemblyCompany("DoomShotgun")] [assembly: AssemblyConfiguration("Debug")] [assembly: AssemblyDescription("Adds Doom music while holding the shotgun")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: AssemblyInformationalVersion("1.0.0")] [assembly: AssemblyProduct("DoomShotgun")] [assembly: AssemblyTitle("DoomShotgun")] [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 LethalCompanyTemplate { [BepInPlugin("DoomShotgun", "DoomShotgun", "1.0.0")] [BepInDependency(/*Could not decode attribute arguments.*/)] public class Plugin : BaseUnityPlugin { public static AudioClip doomMusic; public static ConfigEntry<float> volumeC; public static float volume; public void Awake() { //IL_0087: Unknown result type (might be due to invalid IL or missing references) //IL_008d: Expected O, but got Unknown doomMusic = SoundTool.GetAudioClip("SpyPlayer-DoomShotgun", "doom.wav"); volumeC = ((BaseUnityPlugin)this).Config.Bind<float>("General", "volume", 1f, "Set the volume of the music"); volume = volumeC.Value; if (volume > 1f) { volume = 1f; } else if (volume < 0f) { volume = 0f; } Harmony val = new Harmony("DoomShotgun"); val.PatchAll(); } } [HarmonyPatch(typeof(ShotgunItem), "Start")] public static class ShotgunPatch { public static void Postfix(ShotgunItem __instance) { AudioSource val = ((Component)__instance).gameObject.AddComponent<AudioSource>(); val.clip = Plugin.doomMusic; val.loop = true; val.volume = Plugin.volume; } } [HarmonyPatch(typeof(ShotgunItem), "EquipItem")] public static class ShotgunEquipPatch { public static void Postfix(ShotgunItem __instance) { AudioSource val = ((Component)__instance).gameObject.GetComponents<AudioSource>().First((AudioSource x) => (Object)(object)x.clip == (Object)(object)Plugin.doomMusic); val.Play(); } } [HarmonyPatch(typeof(ShotgunItem), "StopUsingGun")] public static class ShotgunStopPatch { public static void Postfix(ShotgunItem __instance) { AudioSource val = ((Component)__instance).gameObject.GetComponents<AudioSource>().First((AudioSource x) => (Object)(object)x.clip == (Object)(object)Plugin.doomMusic); val.Stop(); } } public static class PluginInfo { public const string PLUGIN_GUID = "DoomShotgun"; public const string PLUGIN_NAME = "DoomShotgun"; public const string PLUGIN_VERSION = "1.0.0"; } }
plugins/DynamicDeadline1.2.2.dll
Decompiled 11 months agousing System.Diagnostics; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Versioning; using BepInEx; using BepInEx.Configuration; using BepInEx.Logging; using DynamicDeadlineMod.Patches; using HarmonyLib; 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("DynamicDeadlineMod")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("DynamicDeadlineMod")] [assembly: AssemblyCopyright("Copyright © 2023")] [assembly: AssemblyTrademark("")] [assembly: ComVisible(false)] [assembly: Guid("78c98d39-8b11-4a2c-bccb-e32338f5bacf")] [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 DynamicDeadlineMod { [BepInPlugin("Haha.DynamicDeadline", "Dynamic Deadline", "1.2.2")] public class DynamicDeadlineMod : BaseUnityPlugin { private const string modGUID = "Haha.DynamicDeadline"; private const string modName = "Dynamic Deadline"; private const string modVersion = "1.2.2"; private readonly Harmony harmony = new Harmony("Haha.DynamicDeadline"); public static DynamicDeadlineMod Instance; internal static ConfigEntry<float> MinScrapValuePerDay; internal static ConfigEntry<bool> legacyCal; internal static ConfigEntry<float> legacyDailyValue; internal static ConfigEntry<bool> useMinMax; internal static ConfigEntry<float> setMinimumDays; internal static ConfigEntry<float> setMaximumDays; internal ManualLogSource mls; internal void Awake() { if ((Object)(object)Instance == (Object)null) { Instance = this; } mls = Logger.CreateLogSource("Dynamic Deadline"); mls.LogInfo((object)"No more short deadlines for excessive quotas."); MinScrapValuePerDay = ((BaseUnityPlugin)this).Config.Bind<float>("Customizable Values", "Minimum Daily ScrapValue", 200f, "Set this value to the minimum scrap value you should achieve per day. This will ignore the calculation for daily scrap if it's below this number."); useMinMax = ((BaseUnityPlugin)this).Config.Bind<bool>("Customizable Values", "Use Custom Deadline Range", false, "Set to true if you want to use the custom minimum/maximum deadline range."); setMinimumDays = ((BaseUnityPlugin)this).Config.Bind<float>("Customizable Values", "Minimum Deadline", 3f, "If Use Custom Deadline Range is enabled, this is the minimum deadline you will have."); setMaximumDays = ((BaseUnityPlugin)this).Config.Bind<float>("Customizable Values", "Maximum Deadline", float.MaxValue, "If use Custom Deadline Range is enabled, this is the maximum deadline you will have."); legacyCal = ((BaseUnityPlugin)this).Config.Bind<bool>("Customizeable Values - Legacy", "Legacy Calculations", false, "Set to true if you want to use the deadline calculation from 1.1.0 prior."); legacyDailyValue = ((BaseUnityPlugin)this).Config.Bind<float>("Customizeable Values - Legacy", "Daily Scrap Value", 200f, "Set this number to the value of scrap you can reasonably achieve in a single day."); harmony.PatchAll(typeof(DynamicDeadlineMod)); harmony.PatchAll(typeof(ProfitQuotaPatch)); } } } namespace DynamicDeadlineMod.Patches { [HarmonyPatch(typeof(TimeOfDay), "SyncTimeClientRpc")] public class FixTheDeadline { [HarmonyPrefix] public static void DeadlineBroke() { string currentSaveFileName = GameNetworkManager.Instance.currentSaveFileName; float num; if (ES3.KeyExists("totalOfAverage")) { num = ES3.Load<float>("totalOfAverage", currentSaveFileName, 0f); } else { ES3.Save<float>("totalOfAverage", 0f, currentSaveFileName); num = ES3.Load<float>("totalOfAverage", currentSaveFileName, 0f); } if (num < DynamicDeadlineMod.MinScrapValuePerDay.Value * (float)TimeOfDay.Instance.timesFulfilledQuota) { num = DynamicDeadlineMod.MinScrapValuePerDay.Value * (float)TimeOfDay.Instance.timesFulfilledQuota; float num2 = num / (float)TimeOfDay.Instance.timesFulfilledQuota; float num3 = Mathf.Clamp(Mathf.Ceil((float)TimeOfDay.Instance.profitQuota / num2), 3f, float.MaxValue); ES3.Save<float>("totalOfAverage", num, currentSaveFileName); TimeOfDay.Instance.timeUntilDeadline = 700f * num3; ES3.Save<float>("previousDeadline", num3, currentSaveFileName); } } } [HarmonyPatch(typeof(GameNetworkManager), "ResetSavedGameValues")] public class ResetSavedValuesPatch { [HarmonyPrefix] public static void ResetSavedValues() { string currentSaveFileName = GameNetworkManager.Instance.currentSaveFileName; ES3.Save<float>("previousDeadline", 3f, currentSaveFileName); ES3.Save<float>("totalOfAverage", 0f, currentSaveFileName); } } [HarmonyPatch(typeof(TimeOfDay), "SetNewProfitQuota")] public class ProfitQuotaPatch { private static float quotaFulfilled; [HarmonyPrefix] public static void GetQuotaFulfilled() { quotaFulfilled = TimeOfDay.Instance.quotaFulfilled; } [HarmonyPostfix] private static void DynamicDeadline(TimeOfDay __instance) { string currentSaveFileName = GameNetworkManager.Instance.currentSaveFileName; bool isHost = ((NetworkBehaviour)RoundManager.Instance).NetworkManager.IsHost; float num = TimeOfDay.Instance.timesFulfilledQuota; float num2 = ((!DynamicDeadlineMod.useMinMax.Value) ? 3f : DynamicDeadlineMod.setMinimumDays.Value); float num3 = ((!DynamicDeadlineMod.useMinMax.Value) ? float.MaxValue : DynamicDeadlineMod.setMaximumDays.Value); float num4; if (ES3.KeyExists("previousDeadline")) { num4 = ES3.Load<float>("previousDeadline", currentSaveFileName, 3f); DynamicDeadlineMod.Instance.mls.LogInfo((object)$"Successfully loaded the previous totalOfAverage variable! totalofAverage is: {num4}"); } else { ES3.Save<float>("previousDeadline", 3f, currentSaveFileName); num4 = ES3.Load<float>("previousDeadline", currentSaveFileName, 3f); DynamicDeadlineMod.Instance.mls.LogInfo((object)"Could not load previousDeadline variable as it does not exist! Creating now!"); } float num5; if (ES3.KeyExists("totalOfAverage")) { num5 = ES3.Load<float>("totalOfAverage", currentSaveFileName, 0f); DynamicDeadlineMod.Instance.mls.LogInfo((object)$"Successfully loaded the previous totalOfAverage variable! totalofAverage is: {num5}"); } else { ES3.Save<float>("totalOfAverage", 0f, currentSaveFileName); num5 = ES3.Load<float>("totalOfAverage", currentSaveFileName, 0f); DynamicDeadlineMod.Instance.mls.LogInfo((object)"Could not load totalOfAverage variable as it does not exist! Creating now!"); } if (isHost && !DynamicDeadlineMod.legacyCal.Value) { float num6 = Mathf.Clamp(Mathf.Ceil(quotaFulfilled / num4), DynamicDeadlineMod.MinScrapValuePerDay.Value, 1000f); if (num5 == 0f && num != 0f) { num5 = DynamicDeadlineMod.MinScrapValuePerDay.Value * num - 1f; } float num7 = num5 / num; float num8 = Mathf.Clamp(Mathf.Ceil((float)__instance.profitQuota / num7), num2, num3); num5 += num6; __instance.timeUntilDeadline = __instance.totalTime * num8; DynamicDeadlineMod.Instance.mls.LogInfo((object)$"This person is the host, changing deadline. DailyValue registered as {num6}, new average is {num7}, and host is currently on their {num} run!"); TimeOfDay.Instance.SyncTimeClientRpc(__instance.globalTime, (int)__instance.timeUntilDeadline); DynamicDeadlineMod.Instance.mls.LogInfo((object)$"The new deadline is {num8} days."); num4 = num8; DynamicDeadlineMod.Instance.mls.LogInfo((object)$"Did the value get assigned properly? Previous deadline is {num4}"); ES3.Save<float>("previousDeadline", num4, currentSaveFileName); ES3.Save<float>("totalOfAverage", num5, currentSaveFileName); } else if (isHost && DynamicDeadlineMod.legacyCal.Value) { __instance.timeUntilDeadline = __instance.totalTime * Mathf.Clamp(Mathf.Ceil((float)__instance.profitQuota / DynamicDeadlineMod.legacyDailyValue.Value), num2, num3); DynamicDeadlineMod.Instance.mls.LogInfo((object)"This person is the host and using the legacy difficulty calculations. Changing deadline."); TimeOfDay.Instance.SyncTimeClientRpc(__instance.globalTime, (int)__instance.timeUntilDeadline); } else { DynamicDeadlineMod.Instance.mls.LogInfo((object)"This person is not the host. Will not change deadline or send rpc."); } } } }
plugins/FlashlightToggle.dll
Decompiled 11 months agousing System; using System.Diagnostics; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using System.Security; using System.Security.Permissions; using BepInEx; using BepInEx.Logging; using GameNetcodeStuff; using HarmonyLib; using LethalCompanyInputUtils.Api; using Microsoft.CodeAnalysis; 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: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")] [assembly: AssemblyCompany("Control")] [assembly: AssemblyConfiguration("Debug")] [assembly: AssemblyDescription("My first plugin")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: AssemblyInformationalVersion("1.0.0+f52c854f4eaa270088fff99ac87504ddad49aa16")] [assembly: AssemblyProduct("Control")] [assembly: AssemblyTitle("Control")] [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 Control { public static class PluginInfo { public const string PLUGIN_GUID = "Control"; public const string PLUGIN_NAME = "Control"; public const string PLUGIN_VERSION = "1.0.0"; } } namespace Flashlight { public class FlashButton : LcInputActions { [InputAction("<Keyboard>/f", Name = "Flashlight")] public InputAction FlashKey { get; set; } } [BepInPlugin("rr.Flashlight", "Flashlight", "1.5.0")] public class Plugin : BaseUnityPlugin { internal static ManualLogSource logSource; internal static FlashButton InputActionInstance = new FlashButton(); private Harmony _harmony = new Harmony("Flashlight"); private void Awake() { _harmony.PatchAll(typeof(Plugin)); ((BaseUnityPlugin)this).Logger.LogInfo((object)"------Flashlight done.------"); logSource = ((BaseUnityPlugin)this).Logger; } [HarmonyPatch(typeof(PlayerControllerB), "KillPlayer")] [HarmonyPostfix] public static void ClearFlashlight(PlayerControllerB __instance) { __instance.pocketedFlashlight = null; } [HarmonyPatch(typeof(PlayerControllerB), "Update")] [HarmonyPostfix] public static void ReadInput(PlayerControllerB __instance) { if (((!((NetworkBehaviour)__instance).IsOwner || !__instance.isPlayerControlled || (((NetworkBehaviour)__instance).IsServer && !__instance.isHostPlayerObject)) && !__instance.isTestingPlayer) || __instance.inTerminalMenu || __instance.isTypingChat || !Application.isFocused) { return; } if (__instance.currentlyHeldObjectServer is FlashlightItem && (Object)(object)__instance.currentlyHeldObjectServer != (Object)(object)__instance.pocketedFlashlight) { __instance.pocketedFlashlight = __instance.currentlyHeldObjectServer; } if ((Object)(object)__instance.pocketedFlashlight == (Object)null || !InputActionInstance.FlashKey.triggered || !(__instance.pocketedFlashlight is FlashlightItem) || !__instance.pocketedFlashlight.isHeld) { return; } try { __instance.pocketedFlashlight.UseItemOnClient(true); if (!(__instance.currentlyHeldObjectServer is FlashlightItem)) { GrabbableObject pocketedFlashlight = __instance.pocketedFlashlight; ((Behaviour)((FlashlightItem)((pocketedFlashlight is FlashlightItem) ? pocketedFlashlight : null)).flashlightBulbGlow).enabled = false; GrabbableObject pocketedFlashlight2 = __instance.pocketedFlashlight; ((Behaviour)((FlashlightItem)((pocketedFlashlight2 is FlashlightItem) ? pocketedFlashlight2 : null)).flashlightBulb).enabled = false; GrabbableObject pocketedFlashlight3 = __instance.pocketedFlashlight; if (((pocketedFlashlight3 is FlashlightItem) ? pocketedFlashlight3 : null).isBeingUsed) { ((Behaviour)__instance.helmetLight).enabled = true; GrabbableObject pocketedFlashlight4 = __instance.pocketedFlashlight; ((FlashlightItem)((pocketedFlashlight4 is FlashlightItem) ? pocketedFlashlight4 : null)).usingPlayerHelmetLight = true; GrabbableObject pocketedFlashlight5 = __instance.pocketedFlashlight; ((FlashlightItem)((pocketedFlashlight5 is FlashlightItem) ? pocketedFlashlight5 : null)).PocketFlashlightServerRpc(true); } else { ((Behaviour)__instance.helmetLight).enabled = false; GrabbableObject pocketedFlashlight6 = __instance.pocketedFlashlight; ((FlashlightItem)((pocketedFlashlight6 is FlashlightItem) ? pocketedFlashlight6 : null)).usingPlayerHelmetLight = false; GrabbableObject pocketedFlashlight7 = __instance.pocketedFlashlight; ((FlashlightItem)((pocketedFlashlight7 is FlashlightItem) ? pocketedFlashlight7 : null)).PocketFlashlightServerRpc(false); } } } catch { } } } }
plugins/HotbarPlus.dll
Decompiled 11 months agousing System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Reflection; using System.Reflection.Emit; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Versioning; using BepInEx; using BepInEx.Configuration; using GameNetcodeStuff; using HarmonyLib; using HotbarPlus.Config; using HotbarPlus.Patches; using Unity.Collections; using Unity.Netcode; using UnityEngine; using UnityEngine.InputSystem; 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: AssemblyTitle("HotbarPlus")] [assembly: AssemblyDescription("Mod made by flipf17.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("HotbarPlus")] [assembly: AssemblyCopyright("Copyright © 2023")] [assembly: AssemblyTrademark("")] [assembly: ComVisible(false)] [assembly: Guid("fab060f0-b006-42ea-ba6f-473f4850c587")] [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 HotbarPlus { [HarmonyPatch] internal class Keybinds { private static InputAction[] quickItemShortcutActions; private static PlayerControllerB localPlayerController; private static bool setHotbarSize; [HarmonyPatch(typeof(PlayerControllerB), "ConnectClientToPlayerObject")] [HarmonyPostfix] public static void OnLocalPlayerConnect(PlayerControllerB __instance) { localPlayerController = __instance; setHotbarSize = false; if (!ConfigSettings.useOriginalKeybindsDefaultEmotes.Value) { InputActionAsset actions = IngamePlayerSettings.Instance.playerInput.actions; InputAction val = actions.FindAction("Emote1", false); InputAction val2 = actions.FindAction("Emote2", false); InputActionRebindingExtensions.ApplyBindingOverride(val, "<Keyboard>/f1", (string)null, (string)null); InputActionRebindingExtensions.ApplyBindingOverride(val2, "<Keyboard>/f2", (string)null, (string)null); } } public static void OnSetHotbarSize() { //IL_004a: Unknown result type (might be due to invalid IL or missing references) //IL_0050: Expected O, but got Unknown setHotbarSize = true; if (ConfigSettings.useHotbarNumberHotkeysConfig.Value) { quickItemShortcutActions = (InputAction[])(object)new InputAction[PlayerPatcher.newHotbarSize]; for (int i = 0; i < quickItemShortcutActions.Length; i++) { quickItemShortcutActions[i] = new InputAction((string)null, (InputActionType)0, $"<Keyboard>/{i + 1}", "Press", (string)null, (string)null); } } if (((Component)localPlayerController).gameObject.activeSelf) { SubscribeToEvents(); } } private static void SubscribeToEvents() { if (quickItemShortcutActions != null && ConfigSettings.useHotbarNumberHotkeysConfig.Value) { for (int i = 0; i < quickItemShortcutActions.Length; i++) { quickItemShortcutActions[i].Enable(); quickItemShortcutActions[i].performed += OnPressItemSlotHotkeyAction; } } } [HarmonyPatch(typeof(PlayerControllerB), "OnEnable")] [HarmonyPostfix] public static void OnEnable(PlayerControllerB __instance) { if ((Object)(object)__instance == (Object)(object)localPlayerController && setHotbarSize) { SubscribeToEvents(); } } [HarmonyPatch(typeof(PlayerControllerB), "OnDisable")] [HarmonyPostfix] public static void OnDisable(PlayerControllerB __instance) { if (quickItemShortcutActions != null && setHotbarSize && (!((Object)(object)localPlayerController != (Object)null) || !((Object)(object)__instance != (Object)(object)localPlayerController))) { for (int i = 0; i < quickItemShortcutActions.Length; i++) { quickItemShortcutActions[i].performed -= OnPressItemSlotHotkeyAction; quickItemShortcutActions[i].Disable(); } } } private static void OnPressItemSlotHotkeyAction(CallbackContext context) { if (!((Object)(object)localPlayerController == (Object)null) && ((NetworkBehaviour)localPlayerController).IsOwner && localPlayerController.isPlayerControlled && !localPlayerController.inTerminalMenu && !localPlayerController.twoHanded && (!((NetworkBehaviour)localPlayerController).IsServer || localPlayerController.isHostPlayerObject) && ((CallbackContext)(ref context)).performed) { string name = ((CallbackContext)(ref context)).control.name; if (int.TryParse(name, out var result)) { result--; HotbarSlotSync.SwapHotbarSlot(result); } } } } [HarmonyPatch] internal static class HotbarSlotSync { private static PlayerControllerB localPlayerController; [HarmonyPatch(typeof(PlayerControllerB), "ConnectClientToPlayerObject")] [HarmonyPostfix] public static void Init(PlayerControllerB __instance) { //IL_0032: Unknown result type (might be due to invalid IL or missing references) //IL_003c: Expected O, but got Unknown //IL_0061: Unknown result type (might be due to invalid IL or missing references) //IL_006b: Expected O, but got Unknown if ((Object)(object)GameNetworkManager.Instance.localPlayerController == (Object)(object)__instance) { localPlayerController = __instance; NetworkManager.Singleton.CustomMessagingManager.RegisterNamedMessageHandler("OnHotbarSlotChangeClientRpc", new HandleNamedMessageDelegate(OnHotbarSlotChangeClientRpc)); if (NetworkManager.Singleton.IsServer) { NetworkManager.Singleton.CustomMessagingManager.RegisterNamedMessageHandler("OnHotbarSlotChangeServerRpc", new HandleNamedMessageDelegate(OnHotbarSlotChangeServerRpc)); } } } private static void SendHotbarSlotChange(int hotbarSlot) { //IL_0038: Unknown result type (might be due to invalid IL or missing references) //IL_003e: Unknown result type (might be due to invalid IL or missing references) //IL_0056: Unknown result type (might be due to invalid IL or missing references) if (NetworkManager.Singleton.IsClient) { FastBufferWriter val = default(FastBufferWriter); ((FastBufferWriter)(ref val))..ctor(4, (Allocator)2, -1); try { Plugin.Log("Sending hotbar swap slot: " + hotbarSlot); ((FastBufferWriter)(ref val)).WriteValue<int>(ref hotbarSlot, default(ForPrimitives)); NetworkManager.Singleton.CustomMessagingManager.SendNamedMessage("OnHotbarSlotChangeServerRpc", 0uL, val, (NetworkDelivery)3); return; } finally { ((IDisposable)(FastBufferWriter)(ref val)).Dispose(); } } Plugin.Log("Failed to send hotbar swap index."); } private static void OnHotbarSlotChangeServerRpc(ulong clientId, 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) //IL_006f: Unknown result type (might be due to invalid IL or missing references) //IL_0075: Unknown result type (might be due to invalid IL or missing references) //IL_0082: Unknown result type (might be due to invalid IL or missing references) //IL_0088: Unknown result type (might be due to invalid IL or missing references) //IL_009e: Unknown result type (might be due to invalid IL or missing references) if (!NetworkManager.Singleton.IsServer) { return; } if (((FastBufferReader)(ref reader)).TryBeginRead(4)) { int num = default(int); ((FastBufferReader)(ref reader)).ReadValue<int>(ref num, default(ForPrimitives)); Plugin.Log("Receiving request for hotbar swap. Slot: " + num + " ClientId: " + clientId); FastBufferWriter val = default(FastBufferWriter); ((FastBufferWriter)(ref val))..ctor(12, (Allocator)2, -1); try { ((FastBufferWriter)(ref val)).WriteValueSafe<int>(ref num, default(ForPrimitives)); ((FastBufferWriter)(ref val)).WriteValueSafe<ulong>(ref clientId, default(ForPrimitives)); NetworkManager.Singleton.CustomMessagingManager.SendNamedMessageToAll("OnHotbarSlotChangeClientRpc", val, (NetworkDelivery)3); return; } finally { ((IDisposable)(FastBufferWriter)(ref val)).Dispose(); } } Plugin.Log("Failed to receive hotbar swap index from Client: " + clientId); } private static void OnHotbarSlotChangeClientRpc(ulong clientId, FastBufferReader reader) { //IL_002e: Unknown result type (might be due to invalid IL or missing references) //IL_0034: Unknown result type (might be due to invalid IL or missing references) //IL_0042: Unknown result type (might be due to invalid IL or missing references) //IL_0048: Unknown result type (might be due to invalid IL or missing references) if (!NetworkManager.Singleton.IsClient) { return; } if (((FastBufferReader)(ref reader)).TryBeginRead(12)) { int hotbarSlot = default(int); ((FastBufferReader)(ref reader)).ReadValue<int>(ref hotbarSlot, default(ForPrimitives)); ulong num = default(ulong); ((FastBufferReader)(ref reader)).ReadValue<ulong>(ref num, default(ForPrimitives)); Plugin.Log("Receiving update for hotbar swap. Slot: " + hotbarSlot + " ClientId: " + num); if (num == localPlayerController.actualClientId || UpdateClientHotbarSlot(num, hotbarSlot)) { return; } Plugin.Log("Failed to receive hotbar swap index from Client: " + num); } Plugin.Log("Failed to receive hotbar swap index from Client"); } private static bool UpdateClientHotbarSlot(ulong clientId, int hotbarSlot) { Plugin.Log("Updating hotbar slot: " + hotbarSlot + " ClientId: " + clientId); for (int i = 0; i < StartOfRound.Instance.allPlayerScripts.Length; i++) { if (StartOfRound.Instance.allPlayerScripts[i].actualClientId == clientId) { CallSwitchToItemSlotMethod(StartOfRound.Instance.allPlayerScripts[i], hotbarSlot); return true; } } return false; } public static void SwapHotbarSlot(int hotbarIndex) { if (hotbarIndex < PlayerPatcher.targetHotbarSize) { SendHotbarSlotChange(hotbarIndex); CallSwitchToItemSlotMethod(localPlayerController, hotbarIndex); } } private static void CallSwitchToItemSlotMethod(PlayerControllerB playerController, int hotbarIndex) { if (hotbarIndex < PlayerPatcher.targetHotbarSize && playerController.currentItemSlot != hotbarIndex) { ShipBuildModeManager.Instance.CancelBuildMode(true); MethodInfo method = ((object)playerController).GetType().GetMethod("SwitchToItemSlot", BindingFlags.Instance | BindingFlags.NonPublic); method.Invoke(playerController, new object[2] { hotbarIndex, null }); if ((Object)(object)playerController.currentlyHeldObjectServer != (Object)null) { ((Component)playerController.currentlyHeldObjectServer).gameObject.GetComponent<AudioSource>().PlayOneShot(playerController.currentlyHeldObjectServer.itemProperties.grabSFX, 0.6f); } } } } [BepInPlugin("FlipMods.HotbarPlus", "HotbarPlus", "1.3.5")] public class Plugin : BaseUnityPlugin { public static Plugin instance; private Harmony _harmony; private void Awake() { //IL_000d: Unknown result type (might be due to invalid IL or missing references) //IL_0017: Expected O, but got Unknown instance = this; _harmony = new Harmony("HotbarPlus"); ConfigSettings.BindConfigSettings(); _harmony.PatchAll(); ((BaseUnityPlugin)this).Logger.LogInfo((object)"HotbarPlus loaded"); } public static void Log(string message) { ((BaseUnityPlugin)instance).Logger.LogInfo((object)message); } public static void LogError(string message) { ((BaseUnityPlugin)instance).Logger.LogError((object)message); } } public static class PluginInfo { public const string PLUGIN_GUID = "FlipMods.HotbarPlus"; public const string PLUGIN_NAME = "HotbarPlus"; public const string PLUGIN_VERSION = "1.3.5"; } } namespace HotbarPlus.Patches { [HarmonyPatch] internal class HUDPatcher { public static void ResizeHotbarSlotsHUD() { //IL_002d: Unknown result type (might be due to invalid IL or missing references) //IL_0043: Unknown result type (might be due to invalid IL or missing references) //IL_0060: 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) //IL_007c: Unknown result type (might be due to invalid IL or missing references) //IL_008a: Unknown result type (might be due to invalid IL or missing references) //IL_008f: Unknown result type (might be due to invalid IL or missing references) //IL_019f: Unknown result type (might be due to invalid IL or missing references) //IL_01a5: Unknown result type (might be due to invalid IL or missing references) //IL_01bd: Unknown result type (might be due to invalid IL or missing references) //IL_01e5: Unknown result type (might be due to invalid IL or missing references) //IL_0252: Unknown result type (might be due to invalid IL or missing references) //IL_025c: Unknown result type (might be due to invalid IL or missing references) List<Image> list = new List<Image>(HUDManager.Instance.itemSlotIconFrames); List<Image> list2 = new List<Image>(HUDManager.Instance.itemSlotIcons); float num = Mathf.Abs(((Graphic)list[1]).rectTransform.anchoredPosition.x - ((Graphic)list[0]).rectTransform.anchoredPosition.x); float y = ((Component)list[0]).GetComponent<RectTransform>().anchoredPosition.y; Vector3 eulerAngles = ((Transform)((Graphic)list[0]).rectTransform).eulerAngles; Vector3 eulerAngles2 = ((Transform)((Graphic)list2[0]).rectTransform).eulerAngles; for (int i = 0; i < Mathf.Max(PlayerPatcher.targetHotbarSize, PlayerPatcher.initialHotbarSize); i++) { if (i >= PlayerPatcher.targetHotbarSize) { Object.Destroy((Object)(object)list[PlayerPatcher.targetHotbarSize]); Object.Destroy((Object)(object)list2[PlayerPatcher.targetHotbarSize]); list.RemoveAt(PlayerPatcher.targetHotbarSize); list2.RemoveAt(PlayerPatcher.targetHotbarSize); continue; } if (i >= PlayerPatcher.initialHotbarSize) { list.Insert(i, Object.Instantiate<Image>(list[i - 1], ((Component)list[0]).transform.parent)); ((Component)list[i]).transform.SetSiblingIndex(((Component)list[i - 1]).transform.GetSiblingIndex() + 1); list2.Insert(i, ((Component)((Component)list[i]).transform.GetChild(0)).GetComponent<Image>()); } ((Object)list[i]).name = $"Slot{i}"; ((Graphic)list[i]).rectTransform.anchoredPosition = Vector2.up * y; ((Transform)((Graphic)list[i]).rectTransform).eulerAngles = eulerAngles; ((Object)list2[i]).name = "Icon"; ((Transform)((Graphic)list2[i]).rectTransform).eulerAngles = eulerAngles2; } float num2 = num * (float)(PlayerPatcher.targetHotbarSize - 1); float num3 = num2 / 2f; for (int j = 0; j < PlayerPatcher.targetHotbarSize; j++) { float num4 = (float)j * num - num3; ((Graphic)list[j]).rectTransform.anchoredPosition = new Vector2(num4, ((Graphic)list[j]).rectTransform.anchoredPosition.y); } HUDManager.Instance.itemSlotIconFrames = list.ToArray(); HUDManager.Instance.itemSlotIcons = list2.ToArray(); } } [HarmonyPatch] internal class PlayerPatcher { public static PlayerControllerB localPlayerController; public static int initialHotbarSize = -1; public static int postInitialHotbarSize = -1; public static int targetHotbarSize = -1; public static int newHotbarSize = -1; private static bool droppingItem = false; [HarmonyPatch(typeof(PlayerControllerB), "Awake")] [HarmonyPostfix] public static void GetInitialHotbarSize(PlayerControllerB __instance) { if (initialHotbarSize == -1) { initialHotbarSize = __instance.ItemSlots.Length; } } [HarmonyPatch(typeof(PlayerControllerB), "ConnectClientToPlayerObject")] [HarmonyPostfix] public static void InitializeLocalPlayer(PlayerControllerB __instance) { localPlayerController = __instance; } public static void ResizeInventory() { postInitialHotbarSize = localPlayerController.ItemSlots.Length; targetHotbarSize = Mathf.Clamp(ConfigSync.instance.hotbarSize, 0, 10); newHotbarSize = Mathf.Clamp(ConfigSync.instance.hotbarSize + (postInitialHotbarSize - initialHotbarSize), 0, 10); for (int i = 0; i < StartOfRound.Instance.allPlayerScripts.Length; i++) { PlayerControllerB val = StartOfRound.Instance.allPlayerScripts[i]; val.ItemSlots = (GrabbableObject[])(object)new GrabbableObject[newHotbarSize]; } } private static int GetNextItemSlot(PlayerControllerB __instance, bool forward, int index) { int currentItemSlot = __instance.currentItemSlot; __instance.currentItemSlot = index; MethodInfo method = ((object)__instance).GetType().GetMethod("NextItemSlot", BindingFlags.Instance | BindingFlags.NonPublic); index = (int)method.Invoke(__instance, new object[1] { forward }); __instance.currentItemSlot = currentItemSlot; return index; } [HarmonyPatch(typeof(PlayerControllerB), "ScrollMouse_performed")] [HarmonyTranspiler] private static IEnumerable<CodeInstruction> PatchSwitchItemInterval(IEnumerable<CodeInstruction> instructions) { List<CodeInstruction> list = new List<CodeInstruction>(instructions); for (int i = 0; i < list.Count; i++) { if (list[i].opcode == OpCodes.Ldc_R4 && (float)list[i].operand == 0.3f) { list[i].operand = ConfigSettings.minSwapItemInterval; break; } } return list.AsEnumerable(); } [HarmonyPatch(typeof(PlayerControllerB), "ActivateItem_performed")] [HarmonyTranspiler] private static IEnumerable<CodeInstruction> PatchActivateItemInterval(IEnumerable<CodeInstruction> instructions) { List<CodeInstruction> list = new List<CodeInstruction>(instructions); for (int i = 0; i < list.Count; i++) { if (list[i].opcode == OpCodes.Ldc_R4 && (float)list[i].operand == 0.075f) { list[i].operand = ConfigSettings.minActivateItemInterval; break; } } return list.AsEnumerable(); } [HarmonyPatch(typeof(PlayerControllerB), "Discard_performed")] [HarmonyTranspiler] private static IEnumerable<CodeInstruction> PatchDiscardItemInterval(IEnumerable<CodeInstruction> instructions) { List<CodeInstruction> list = new List<CodeInstruction>(instructions); for (int i = 0; i < list.Count; i++) { if (list[i].opcode == OpCodes.Ldc_R4 && (float)list[i].operand == 0.2f) { list[i].operand = ConfigSettings.minDiscardItemInterval; } } return list.AsEnumerable(); } [HarmonyPatch(typeof(PlayerControllerB), "Interact_performed")] [HarmonyTranspiler] private static IEnumerable<CodeInstruction> PatchInteractInterval(IEnumerable<CodeInstruction> instructions) { List<CodeInstruction> list = new List<CodeInstruction>(instructions); for (int i = 0; i < list.Count; i++) { if (list[i].opcode == OpCodes.Ldc_R4 && (float)list[i].operand == 0.2f) { list[i].operand = ConfigSettings.minInteractInterval; break; } } return list.AsEnumerable(); } [HarmonyPatch(typeof(PlayerControllerB), "PerformEmote")] [HarmonyTranspiler] private static IEnumerable<CodeInstruction> PatchPerformEmoteInterval(IEnumerable<CodeInstruction> instructions) { List<CodeInstruction> list = new List<CodeInstruction>(instructions); for (int i = 0; i < list.Count; i++) { if (list[i].opcode == OpCodes.Ldc_R4 && (float)list[i].operand == 0.5f) { list[i].operand = ConfigSettings.minUseEmoteInterval; break; } } return list.AsEnumerable(); } [HarmonyPatch(typeof(PlayerControllerB), "ScrollMouse_performed")] [HarmonyTranspiler] private static IEnumerable<CodeInstruction> InvertHotbarScrollDirection(IEnumerable<CodeInstruction> instructions) { List<CodeInstruction> list = new List<CodeInstruction>(instructions); if (ConfigSettings.invertHotbarScrollDirectionConfig.Value) { for (int i = 1; i < list.Count; i++) { if (list[i].opcode == OpCodes.Ble_Un && list[i - 1].opcode == OpCodes.Ldc_R4 && (float)list[i - 1].operand == 0f) { list[i].opcode = OpCodes.Bge_Un; break; } } } return list.AsEnumerable(); } } } namespace HotbarPlus.Config { public static class ConfigSettings { public static ConfigEntry<int> hotbarSizeConfig; public static ConfigEntry<bool> useHotbarNumberHotkeysConfig; public static ConfigEntry<bool> invertHotbarScrollDirectionConfig; public static ConfigEntry<bool> useItemQuickDropConfig; public static ConfigEntry<bool> useOriginalKeybindsDefaultEmotes; public static ConfigEntry<string> rebindEmote1Config; public static ConfigEntry<string> rebindEmote2Config; public static string[] currentEntryHeaders = new string[2] { "Server-side", "Client-side" }; public static string[] currentEntryNames = new string[7] { "HotbarSize", "UseHotbarNumberHotkeys", "InvertHotbarScrollDirection", "UseItemQuickDropConfig", "RebindDefaultEmotes", "RebindEmote1", "RebindEmote2" }; public static float minSwapItemInterval = 0.05f; public static float minActivateItemInterval = 0.05f; public static float minDiscardItemInterval = 0.05f; public static float minInteractInterval = 0.05f; public static float minUseEmoteInterval = 0.25f; public static List<ConfigEntryBase> configEntries = new List<ConfigEntryBase>(); public static void BindConfigSettings() { Plugin.Log("BindingConfigs"); hotbarSizeConfig = ((BaseUnityPlugin)Plugin.instance).Config.Bind<int>("Server-side", "HotbarSize", 4, "[Host only] The amount of hotbar slots player will have. This will sync with other clients who have the mod."); useHotbarNumberHotkeysConfig = ((BaseUnityPlugin)Plugin.instance).Config.Bind<bool>("Client-side", "UseHotbarNumberHotkeys", true, "Use the quick item selection numerical hotkeys."); invertHotbarScrollDirectionConfig = ((BaseUnityPlugin)Plugin.instance).Config.Bind<bool>("Client-side", "InvertHotbarScrollDirection", true, "Inverts the direction in which you scroll on the hotbar. Does not affect the terminal scrolling direction."); useItemQuickDropConfig = ((BaseUnityPlugin)Plugin.instance).Config.Bind<bool>("Client-side", "UseItemQuickDropConfig", true, "If enabled, dropping an item will automatically swap to the next item for easier chain dropping."); useOriginalKeybindsDefaultEmotes = ((BaseUnityPlugin)Plugin.instance).Config.Bind<bool>("Client-side", "UseOriginalKeybindsDefaultEmotes", false, "If false, the default emotes will be rebound by this mod."); rebindEmote1Config = ((BaseUnityPlugin)Plugin.instance).Config.Bind<string>("Client-side", "RebindEmote1", "<Keyboard>/f1", "Sets the new keybind for the default emote 1, if RebindDefaultEmotes is true."); rebindEmote2Config = ((BaseUnityPlugin)Plugin.instance).Config.Bind<string>("Client-side", "RebindEmote2", "<Keyboard>/f2", "Sets the new keybind for the default emote 2, if RebindDefaultEmotes is true."); ((BaseUnityPlugin)Plugin.instance).Config.Reload(); RemoveOldConfigs(); ConfigSync.BuildDefaultConfig(); } public static void RemoveOldConfigs() { try { ConfigFile config = ((BaseUnityPlugin)Plugin.instance).Config; string configFilePath = config.ConfigFilePath; if (!File.Exists(configFilePath)) { return; } List<string> list = File.ReadAllLines(configFilePath).ToList(); List<string> list2 = new List<string>(); bool flag = false; bool flag2 = false; foreach (string item in list) { if (item.Length <= 0) { if (list2[list2.Count - 1].Length > 0) { list2.Add(item); } flag2 = true; continue; } if (item.StartsWith("[")) { string value = item.Trim(new char[1] { '[' }).Trim(new char[1] { ']' }); if (currentEntryHeaders.Contains(value)) { list2.Add(item); } } else if (!flag2 || item.StartsWith("#")) { list2.Add(item); } flag2 = false; } File.WriteAllLines(configFilePath, list2); config.Reload(); } catch { } } } [HarmonyPatch] public class ConfigSync { public static ConfigSync defaultConfig; public static ConfigSync instance; public static PlayerControllerB localPlayerController; public static bool isSynced; public int hotbarSize = 1; public ConfigSync() { hotbarSize = ConfigSettings.hotbarSizeConfig.Value; } public static void BuildDefaultConfig() { defaultConfig = new ConfigSync(); instance = new ConfigSync(); } [HarmonyPatch(typeof(PlayerControllerB), "ConnectClientToPlayerObject")] [HarmonyPostfix] public static void InitializeLocalPlayer(PlayerControllerB __instance) { //IL_005d: Unknown result type (might be due to invalid IL or missing references) //IL_0067: Expected O, but got Unknown //IL_002c: Unknown result type (might be due to invalid IL or missing references) //IL_0036: Expected O, but got Unknown localPlayerController = __instance; if (NetworkManager.Singleton.IsServer) { NetworkManager.Singleton.CustomMessagingManager.RegisterNamedMessageHandler("HotbarPlusOnRequestConfigSync", new HandleNamedMessageDelegate(OnReceiveConfigSyncRequest)); OnLocalClientConfigSync(); } else { isSynced = false; NetworkManager.Singleton.CustomMessagingManager.RegisterNamedMessageHandler("HotbarPlusOnReceiveConfigSync", new HandleNamedMessageDelegate(OnReceiveConfigSync)); RequestConfigSync(); } } public static void RequestConfigSync() { //IL_0037: Unknown result type (might be due to invalid IL or missing references) if (NetworkManager.Singleton.IsClient) { Plugin.Log("Sending config sync request to server."); FastBufferWriter val = default(FastBufferWriter); ((FastBufferWriter)(ref val))..ctor(16, (Allocator)2, -1); NetworkManager.Singleton.CustomMessagingManager.SendNamedMessage("HotbarPlusOnRequestConfigSync", 0uL, val, (NetworkDelivery)3); } else { Plugin.LogError("Failed to send config sync request."); } } public static void OnReceiveConfigSyncRequest(ulong clientId, FastBufferReader reader) { //IL_0048: Unknown result type (might be due to invalid IL or missing references) //IL_004e: Unknown result type (might be due to invalid IL or missing references) //IL_0065: Unknown result type (might be due to invalid IL or missing references) if (NetworkManager.Singleton.IsServer) { Plugin.Log("Receiving extra hotbar slots sync request from client with id: " + clientId + ". Sending config sync to client."); FastBufferWriter val = default(FastBufferWriter); ((FastBufferWriter)(ref val))..ctor(4, (Allocator)2, -1); ((FastBufferWriter)(ref val)).WriteValueSafe<int>(ref instance.hotbarSize, default(ForPrimitives)); NetworkManager.Singleton.CustomMessagingManager.SendNamedMessage("HotbarPlusOnReceiveConfigSync", clientId, val, (NetworkDelivery)3); } } public static void OnReceiveConfigSync(ulong clientId, FastBufferReader reader) { //IL_001f: Unknown result type (might be due to invalid IL or missing references) //IL_0025: Unknown result type (might be due to invalid IL or missing references) if (((FastBufferReader)(ref reader)).TryBeginRead(4)) { Plugin.Log("Receiving extra hotbar slots sync from server."); int num = default(int); ((FastBufferReader)(ref reader)).ReadValueSafe<int>(ref num, default(ForPrimitives)); instance.hotbarSize = num; OnLocalClientConfigSync(); } else { Plugin.LogError("Error receiving config sync from server."); } } public static void OnLocalClientConfigSync() { isSynced = true; PlayerPatcher.ResizeInventory(); HUDPatcher.ResizeHotbarSlotsHUD(); Keybinds.OnSetHotbarSize(); } } }
plugins/LC_SoundTool.dll
Decompiled 11 months agousing System; using System.CodeDom.Compiler; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Globalization; using System.IO; using System.Linq; using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using System.Security; using System.Security.Permissions; using BepInEx; using BepInEx.Configuration; using BepInEx.Logging; using HarmonyLib; using LCSoundTool.Networking; using LCSoundTool.Patches; using LCSoundTool.Resources; using LCSoundTool.Utilities; using LCSoundToolMod.Properties; using Microsoft.CodeAnalysis; using Unity.Netcode; using UnityEngine; using UnityEngine.Networking; using UnityEngine.SceneManagement; [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("LC_SoundTool")] [assembly: AssemblyConfiguration("Debug")] [assembly: AssemblyDescription("Various audio related functions. Mainly logs all sounds that are playing and what type of playback they're into the BepInEx console.")] [assembly: AssemblyFileVersion("1.4.0.0")] [assembly: AssemblyInformationalVersion("1.4.0")] [assembly: AssemblyProduct("LC_SoundTool")] [assembly: AssemblyTitle("LC_SoundTool")] [assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/no00ob/LCSoundTool")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("1.4.0.0")] [module: UnverifiableCode] [module: RefSafetyRules(11)] 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.Module, AllowMultiple = false, Inherited = false)] internal sealed class RefSafetyRulesAttribute : Attribute { public readonly int Version; public RefSafetyRulesAttribute(int P_0) { Version = P_0; } } } namespace LCSoundToolMod { public static class PluginInfo { public const string PLUGIN_GUID = "LC_SoundTool"; public const string PLUGIN_NAME = "LC_SoundTool"; public const string PLUGIN_VERSION = "1.4.0"; } } namespace LCSoundToolMod.Properties { [GeneratedCode("System.Resources.Tools.StronglyTypedResourceBuilder", "17.0.0.0")] [DebuggerNonUserCode] [CompilerGenerated] internal class Resources { private static ResourceManager resourceMan; private static CultureInfo resourceCulture; [EditorBrowsable(EditorBrowsableState.Advanced)] internal static ResourceManager ResourceManager { get { if (resourceMan == null) { ResourceManager resourceManager = new ResourceManager("LCSoundToolMod.Properties.Resources", typeof(Resources).Assembly); resourceMan = resourceManager; } return resourceMan; } } [EditorBrowsable(EditorBrowsableState.Advanced)] internal static CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } internal static byte[] soundtool { get { object @object = ResourceManager.GetObject("soundtool", resourceCulture); return (byte[])@object; } } internal Resources() { } } } namespace LCSoundTool { public class AudioSourceExtension : MonoBehaviour { public AudioSource audioSource; public bool playOnAwake = false; public bool loop = false; private bool updateHasBeenLogged = false; private bool hasPlayed = false; private void OnEnable() { if (!((Object)(object)audioSource == (Object)null) && !audioSource.isPlaying) { if (playOnAwake) { audioSource.Play(); } if (SoundTool.infoDebugging) { SoundTool.Instance.logger.LogDebug((object)$"(AudioSourceExtension) Started playback of {audioSource} with clip {audioSource.clip} in OnEnable function!"); } updateHasBeenLogged = false; hasPlayed = false; } } private void OnDisable() { if (!((Object)(object)audioSource == (Object)null) && audioSource.isPlaying) { if (playOnAwake) { audioSource.Stop(); } if (SoundTool.infoDebugging) { SoundTool.Instance.logger.LogDebug((object)$"(AudioSourceExtension) Stopped playback of {audioSource} with clip {audioSource.clip} in OnDisable function!"); } updateHasBeenLogged = false; hasPlayed = false; } } private void Update() { if ((Object)(object)audioSource == (Object)null) { return; } if ((Object)(object)audioSource.clip == (Object)null) { hasPlayed = false; } if (audioSource.isPlaying) { updateHasBeenLogged = false; } else if (!((Behaviour)audioSource).isActiveAndEnabled) { hasPlayed = false; } else { if (!playOnAwake) { return; } if ((Object)(object)audioSource.clip != (Object)null && !hasPlayed) { audioSource.Play(); if (SoundTool.infoDebugging) { SoundTool.Instance.logger.LogDebug((object)$"(AudioSourceExtension) Started playback of {audioSource} with clip {audioSource.clip} in Update function!"); } updateHasBeenLogged = false; hasPlayed = true; } else if (!updateHasBeenLogged) { updateHasBeenLogged = true; if (SoundTool.infoDebugging) { SoundTool.Instance.logger.LogDebug((object)$"(AudioSourceExtension) Can not start playback of {audioSource} with missing clip in Update function!"); } } } } } public class RandomAudioClip { public AudioClip clip; [Range(0f, 1f)] public float chance = 1f; public RandomAudioClip(AudioClip clip, float chance) { this.clip = clip; this.chance = chance; } } [BepInPlugin("LCSoundTool", "LC Sound Tool", "1.4.0")] public class SoundTool : BaseUnityPlugin { public enum AudioType { wav, ogg, mp3 } private const string PLUGIN_GUID = "LCSoundTool"; private const string PLUGIN_NAME = "LC Sound Tool"; private ConfigEntry<bool> configUseNetworking; private ConfigEntry<bool> configSyncRandomSeed; private ConfigEntry<float> configPlayOnAwakePatchRepeatDelay; private readonly Harmony harmony = new Harmony("LCSoundTool"); public static SoundTool Instance; internal ManualLogSource logger; public KeyboardShortcut toggleAudioSourceDebugLog; public KeyboardShortcut toggleIndepthDebugLog; public KeyboardShortcut toggleInformationalDebugLog; public bool wasKeyDown; public bool wasKeyDown2; public bool wasKeyDown3; public static bool debugAudioSources; public static bool indepthDebugging; public static bool infoDebugging; public static bool networkingInitialized { get; private set; } public static bool networkingAvailable { get; private set; } public static Dictionary<string, List<RandomAudioClip>> replacedClips { get; private set; } public static Dictionary<string, AudioClip> networkedClips => NetworkHandler.networkedAudioClips; public static Dictionary<string, AudioType> clipTypes { get; private set; } public static event Action ClientNetworkedAudioChanged { add { NetworkHandler.ClientNetworkedAudioChanged += value; } remove { NetworkHandler.ClientNetworkedAudioChanged -= value; } } public static event Action HostNetworkedAudioChanged { add { NetworkHandler.HostNetworkedAudioChanged += value; } remove { NetworkHandler.HostNetworkedAudioChanged -= value; } } public static bool IsDebuggingOn() { if (debugAudioSources || indepthDebugging || infoDebugging) { return true; } return false; } private void Awake() { //IL_012e: Unknown result type (might be due to invalid IL or missing references) //IL_0133: Unknown result type (might be due to invalid IL or missing references) //IL_014c: Unknown result type (might be due to invalid IL or missing references) //IL_0151: Unknown result type (might be due to invalid IL or missing references) //IL_016a: Unknown result type (might be due to invalid IL or missing references) //IL_016f: Unknown result type (might be due to invalid IL or missing references) networkingAvailable = true; if ((Object)(object)Instance == (Object)null) { Instance = this; } configUseNetworking = ((BaseUnityPlugin)this).Config.Bind<bool>("Experimental", "EnableNetworking", false, "Whether or not to use the networking built into this plugin. If set to true everyone in the lobby needs LCSoundTool installed and networking enabled to join."); configSyncRandomSeed = ((BaseUnityPlugin)this).Config.Bind<bool>("Experimental", "SyncUnityRandomSeed", false, "Whether or not to sync the default Unity randomization seed with all clients. For this feature, networking has to be set to true. Will send the UnityEngine.Random.seed from the host to all clients automatically upon loading a networked scene."); configPlayOnAwakePatchRepeatDelay = ((BaseUnityPlugin)this).Config.Bind<float>("Experimental", "NewPlayOnAwakePatchRepeatDelay", 90f, "How long to wait between checks for new playOnAwake AudioSources. Runs the same patching that is done when each scene is loaded with this delay between each run. DO NOT set too low or high. Anything below 10 or above 600 can cause issues. This time is in seconds. Set to 0 to disable rerunning the patch, but be warned that this might break runtime initialized playOnAwake AudioSources."); 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); } } } logger = Logger.CreateLogSource("LCSoundTool"); logger.LogInfo((object)"Plugin LCSoundTool is loaded!"); toggleAudioSourceDebugLog = new KeyboardShortcut((KeyCode)286, (KeyCode[])(object)new KeyCode[0]); toggleIndepthDebugLog = new KeyboardShortcut((KeyCode)286, (KeyCode[])(object)new KeyCode[1] { (KeyCode)308 }); toggleInformationalDebugLog = new KeyboardShortcut((KeyCode)286, (KeyCode[])(object)new KeyCode[1] { (KeyCode)306 }); debugAudioSources = false; indepthDebugging = false; infoDebugging = false; replacedClips = new Dictionary<string, List<RandomAudioClip>>(); clipTypes = new Dictionary<string, AudioType>(); } private void Start() { if (!configUseNetworking.Value) { networkingAvailable = false; Instance.logger.LogWarning((object)"Networking disabled. Mod in fully client side mode, but no networked actions can take place! You can safely ignore this if you want the mod to run fully client side."); } else { networkingAvailable = true; } if (configUseNetworking.Value) { logger.LogDebug((object)"Loading SoundTool AssetBundle..."); Assets.bundle = AssetBundle.LoadFromMemory(LCSoundToolMod.Properties.Resources.soundtool); if ((Object)(object)Assets.bundle == (Object)null) { logger.LogError((object)"Failed to load SoundTool AssetBundle!"); } else { logger.LogDebug((object)"Finished loading SoundTool AssetBundle!"); } } harmony.PatchAll(typeof(AudioSourcePatch)); if (configUseNetworking.Value) { harmony.PatchAll(typeof(GameNetworkManagerPatch)); harmony.PatchAll(typeof(StartOfRoundPatch)); } SceneManager.sceneLoaded += OnSceneLoaded; } private void Update() { if (configUseNetworking.Value) { if (!networkingInitialized) { if ((Object)(object)NetworkHandler.Instance != (Object)null) { networkingInitialized = true; } } else if ((Object)(object)NetworkHandler.Instance == (Object)null) { networkingInitialized = false; } } else { networkingInitialized = false; } if (((KeyboardShortcut)(ref toggleInformationalDebugLog)).IsDown() && !wasKeyDown3) { wasKeyDown3 = true; wasKeyDown2 = false; wasKeyDown = false; } if (((KeyboardShortcut)(ref toggleInformationalDebugLog)).IsUp() && wasKeyDown3) { wasKeyDown3 = false; wasKeyDown2 = false; wasKeyDown = false; infoDebugging = !infoDebugging; Instance.logger.LogDebug((object)$"Toggling informational debug logs {infoDebugging}!"); return; } if (((KeyboardShortcut)(ref toggleIndepthDebugLog)).IsDown() && !wasKeyDown2) { wasKeyDown2 = true; wasKeyDown = false; } if (((KeyboardShortcut)(ref toggleIndepthDebugLog)).IsUp() && wasKeyDown2) { wasKeyDown2 = false; wasKeyDown = false; debugAudioSources = !debugAudioSources; indepthDebugging = debugAudioSources; infoDebugging = debugAudioSources; Instance.logger.LogDebug((object)$"Toggling in-depth AudioSource debug logs {debugAudioSources}!"); return; } if (!wasKeyDown2 && !((KeyboardShortcut)(ref toggleIndepthDebugLog)).IsDown() && ((KeyboardShortcut)(ref toggleAudioSourceDebugLog)).IsDown() && !wasKeyDown) { wasKeyDown = true; wasKeyDown2 = false; } if (((KeyboardShortcut)(ref toggleAudioSourceDebugLog)).IsUp() && wasKeyDown) { wasKeyDown = false; wasKeyDown2 = false; debugAudioSources = !debugAudioSources; if (indepthDebugging && !debugAudioSources) { indepthDebugging = false; } Instance.logger.LogDebug((object)$"Toggling AudioSource debug logs {debugAudioSources}!"); } } private void OnDestroy() { SceneManager.sceneLoaded -= OnSceneLoaded; } private void OnSceneLoaded(Scene scene, LoadSceneMode mode) { //IL_0013: Unknown result type (might be due to invalid IL or missing references) //IL_0045: Unknown result type (might be due to invalid IL or missing references) if (!((Object)(object)Instance == (Object)null)) { PatchPlayOnAwakeAudio(scene); OnSceneLoadedNetworking(); if (((Scene)(ref scene)).name.ToLower().Contains("level")) { ((MonoBehaviour)this).StopAllCoroutines(); ((MonoBehaviour)this).StartCoroutine(PatchPlayOnAwakeDelayed(scene, 1f)); } } } private IEnumerator PatchPlayOnAwakeDelayed(Scene scene, float wait) { //IL_000e: Unknown result type (might be due to invalid IL or missing references) //IL_000f: Unknown result type (might be due to invalid IL or missing references) if (infoDebugging) { logger.LogDebug((object)$"Started playOnAwake patch coroutine with delay of {wait} seconds"); } yield return (object)new WaitForSecondsRealtime(wait); if (infoDebugging) { logger.LogDebug((object)"Running playOnAwake patch coroutine!"); } PatchPlayOnAwakeAudio(scene); float repeatWait = configPlayOnAwakePatchRepeatDelay.Value; if (repeatWait != 0f) { if (repeatWait < 10f) { repeatWait = 10f; } if (repeatWait > 600f) { repeatWait = 600f; } ((MonoBehaviour)this).StartCoroutine(PatchPlayOnAwakeDelayed(scene, repeatWait)); } } private void PatchPlayOnAwakeAudio(Scene scene) { if (infoDebugging) { Instance.logger.LogDebug((object)("Grabbing all playOnAwake AudioSources for loaded scene " + ((Scene)(ref scene)).name)); } AudioSource[] allPlayOnAwakeAudioSources = GetAllPlayOnAwakeAudioSources(); if (infoDebugging) { Instance.logger.LogDebug((object)$"Found a total of {allPlayOnAwakeAudioSources.Length} playOnAwake AudioSource(s)!"); Instance.logger.LogDebug((object)$"Starting setup on {allPlayOnAwakeAudioSources.Length} playOnAwake AudioSource(s)..."); } AudioSource[] array = allPlayOnAwakeAudioSources; AudioSourceExtension audioSourceExtension = default(AudioSourceExtension); foreach (AudioSource val in array) { val.Stop(); if (((Component)((Component)val).transform).TryGetComponent<AudioSourceExtension>(ref audioSourceExtension)) { audioSourceExtension.audioSource = val; audioSourceExtension.playOnAwake = true; audioSourceExtension.loop = val.loop; val.playOnAwake = false; if (infoDebugging) { Instance.logger.LogDebug((object)$"-Set- {Array.IndexOf(allPlayOnAwakeAudioSources, val) + 1} {val} done!"); } continue; } AudioSourceExtension audioSourceExtension2 = ((Component)val).gameObject.AddComponent<AudioSourceExtension>(); audioSourceExtension2.audioSource = val; audioSourceExtension2.playOnAwake = true; audioSourceExtension2.loop = val.loop; val.playOnAwake = false; if (infoDebugging) { Instance.logger.LogDebug((object)$"-Add- {Array.IndexOf(allPlayOnAwakeAudioSources, val) + 1} {val} done!"); } } if (infoDebugging) { Instance.logger.LogDebug((object)$"Done setting up {allPlayOnAwakeAudioSources.Length} playOnAwake AudioSources!"); } } private void OnSceneLoadedNetworking() { if (networkingAvailable && networkingInitialized && configSyncRandomSeed.Value) { int num = (int)DateTime.Now.Ticks; Random.InitState(num); SendUnityRandomSeed(num); } } public AudioSource[] GetAllPlayOnAwakeAudioSources() { AudioSource[] array = Object.FindObjectsOfType<AudioSource>(true); List<AudioSource> list = new List<AudioSource>(); for (int i = 0; i < array.Length; i++) { if (array[i].playOnAwake) { list.Add(array[i]); } } return list.ToArray(); } public static void ReplaceAudioClip(string originalName, AudioClip newClip) { if (string.IsNullOrEmpty(originalName)) { Instance.logger.LogWarning((object)"Plugin LCSoundTool is trying to replace an audio clip without original clip specified! This is not allowed."); return; } if ((Object)(object)newClip == (Object)null) { Instance.logger.LogWarning((object)"Plugin LCSoundTool is trying to replace an audio clip without new clip specified! This is not allowed."); return; } string name = newClip.GetName(); float num = 100f; if (name.Contains("-")) { string[] array = name.Split('-'); if (array.Length > 1) { string s = array[^1]; if (int.TryParse(s, out var result)) { num = (float)result * 0.01f; name = string.Join("-", array, 0, array.Length - 1); } } } if (replacedClips.ContainsKey(originalName) && num >= 100f) { Instance.logger.LogWarning((object)"Plugin LCSoundTool is trying to replace an audio clip that already has been replaced with 100% chance of playback! This is not allowed."); return; } num = Mathf.Clamp01(num); if (replacedClips.ContainsKey(originalName)) { replacedClips[originalName].Add(new RandomAudioClip(newClip, num)); } else { replacedClips[originalName] = new List<RandomAudioClip> { new RandomAudioClip(newClip, num) }; } float num2 = 0f; for (int i = 0; i < replacedClips[originalName].Count(); i++) { num2 += replacedClips[originalName][i].chance; } if ((num2 < 1f || num2 > 1f) && replacedClips[originalName].Count() > 1) { Instance.logger.LogDebug((object)$"The current total combined chance for replaced {replacedClips[originalName].Count()} random audio clips for audio clip {originalName} does not equal 100% (at least yet?)"); } else if (num2 == 1f && replacedClips[originalName].Count() > 1) { Instance.logger.LogDebug((object)$"The current total combined chance for replaced {replacedClips[originalName].Count()} random audio clips for audio clip {originalName} is equal to 100%"); } } public static void ReplaceAudioClip(AudioClip originalClip, AudioClip newClip) { if ((Object)(object)originalClip == (Object)null) { Instance.logger.LogWarning((object)"Plugin LCSoundTool is trying to replace an audio clip without original clip specified! This is not allowed."); } else if ((Object)(object)newClip == (Object)null) { Instance.logger.LogWarning((object)"Plugin LCSoundTool is trying to replace an audio clip without new clip specified! This is not allowed."); } else { ReplaceAudioClip(originalClip.GetName(), newClip); } } public static void ReplaceAudioClip(string originalName, AudioClip newClip, float chance) { if (string.IsNullOrEmpty(originalName)) { Instance.logger.LogWarning((object)"Plugin LCSoundTool is trying to replace an audio clip without original clip specified! This is not allowed."); return; } if ((Object)(object)newClip == (Object)null) { Instance.logger.LogWarning((object)"Plugin LCSoundTool is trying to replace an audio clip without new clip specified! This is not allowed."); return; } string name = newClip.GetName(); if (replacedClips.ContainsKey(originalName) && chance >= 100f) { Instance.logger.LogWarning((object)"Plugin LCSoundTool is trying to replace an audio clip that already has been replaced with 100% chance of playback! This is not allowed."); return; } chance = Mathf.Clamp01(chance); if (replacedClips.ContainsKey(originalName)) { replacedClips[originalName].Add(new RandomAudioClip(newClip, chance)); } else { replacedClips[originalName] = new List<RandomAudioClip> { new RandomAudioClip(newClip, chance) }; } float num = 0f; for (int i = 0; i < replacedClips[originalName].Count(); i++) { num += replacedClips[originalName][i].chance; } if ((num < 1f || num > 1f) && replacedClips[originalName].Count() > 1) { Instance.logger.LogDebug((object)$"The current total combined chance for replaced {replacedClips[originalName].Count()} random audio clips for audio clip {originalName} does not equal 100% (at least yet?)"); } else if (num == 1f && replacedClips[originalName].Count() > 1) { Instance.logger.LogDebug((object)$"The current total combined chance for replaced {replacedClips[originalName].Count()} random audio clips for audio clip {originalName} is equal to 100%"); } } public static void ReplaceAudioClip(AudioClip originalClip, AudioClip newClip, float chance) { if ((Object)(object)originalClip == (Object)null) { Instance.logger.LogWarning((object)"Plugin LCSoundTool is trying to replace an audio clip without original clip specified! This is not allowed."); } else if ((Object)(object)newClip == (Object)null) { Instance.logger.LogWarning((object)"Plugin LCSoundTool is trying to replace an audio clip without new clip specified! This is not allowed."); } else { ReplaceAudioClip(originalClip.GetName(), newClip, chance); } } public static void RemoveRandomAudioClip(string name, float chance) { if (string.IsNullOrEmpty(name)) { Instance.logger.LogWarning((object)"Plugin LCSoundTool is trying to restore an audio clip without original clip specified! This is not allowed."); } else if (!replacedClips.ContainsKey(name)) { Instance.logger.LogWarning((object)"Plugin LCSoundTool is trying to restore an audio clip that does not exist! This is not allowed."); } else { if (!(chance > 0f)) { return; } for (int i = 0; i < replacedClips[name].Count(); i++) { if (replacedClips[name][i].chance == chance) { replacedClips[name].RemoveAt(i); break; } } } } public static void RestoreAudioClip(string name) { if (string.IsNullOrEmpty(name)) { Instance.logger.LogWarning((object)"Plugin LCSoundTool is trying to restore an audio clip without original clip specified! This is not allowed."); } else if (!replacedClips.ContainsKey(name)) { Instance.logger.LogWarning((object)"Plugin LCSoundTool is trying to restore an audio clip that does not exist! This is not allowed."); } else { replacedClips.Remove(name); } } public static void RestoreAudioClip(AudioClip clip) { if ((Object)(object)clip == (Object)null) { Instance.logger.LogWarning((object)"Plugin LCSoundTool is trying to restore an audio clip without original clip specified! This is not allowed."); } else { RestoreAudioClip(clip.GetName()); } } public static AudioClip GetAudioClip(string modFolder, string soundName) { return GetAudioClip(modFolder, string.Empty, soundName); } public static AudioClip GetAudioClip(string modFolder, string subFolder, string soundName) { AudioType audioType = AudioType.wav; bool flag = true; string text = " "; string text2 = Path.Combine(Paths.PluginPath, modFolder, subFolder, soundName); string text3 = Path.Combine(Paths.PluginPath, modFolder, soundName); string path = Path.Combine(Paths.PluginPath, modFolder, subFolder); string text4 = Path.Combine(Paths.PluginPath, subFolder, soundName); string path2 = Path.Combine(Paths.PluginPath, subFolder); if (!Directory.Exists(path)) { if (!string.IsNullOrEmpty(subFolder)) { Instance.logger.LogWarning((object)("Requested directory at BepInEx/Plugins/" + modFolder + "/" + subFolder + " does not exist!")); } else { Instance.logger.LogWarning((object)("Requested directory at BepInEx/Plugins/" + modFolder + " does not exist!")); if (!modFolder.Contains("-")) { Instance.logger.LogWarning((object)"This sound mod might not be compatable with mod managers. You should contact the sound mod's author."); } } flag = false; } if (!File.Exists(text2)) { Instance.logger.LogWarning((object)("Requested audio file does not exist at path " + text2 + "!")); flag = false; Instance.logger.LogDebug((object)("Looking for audio file from mod root instead at " + text3 + "...")); if (File.Exists(text3)) { Instance.logger.LogDebug((object)("Found audio file at path " + text3 + "!")); text2 = text3; flag = true; } else { Instance.logger.LogWarning((object)("Requested audio file does not exist at mod root path " + text3 + "!")); } } if (Directory.Exists(path2)) { if (!string.IsNullOrEmpty(subFolder)) { Instance.logger.LogWarning((object)("Legacy directory location at BepInEx/Plugins/" + subFolder + " found!")); } else if (!modFolder.Contains("-")) { Instance.logger.LogWarning((object)"Legacy directory location at BepInEx/Plugins found!"); } } if (File.Exists(text4)) { Instance.logger.LogWarning((object)("Legacy path contains the requested audio file at path " + text4 + "!")); text = " legacy "; text2 = text4; flag = true; } string[] array = soundName.Split('.'); if (array[^1].ToLower().Contains("ogg")) { audioType = AudioType.ogg; Instance.logger.LogDebug((object)"File detected as an Ogg Vorbis file!"); } else if (array[^1].ToLower().Contains("mp3")) { audioType = AudioType.mp3; Instance.logger.LogDebug((object)"File detected as a MPEG MP3 file!"); } AudioClip val = null; if (flag) { Instance.logger.LogDebug((object)("Loading AudioClip " + soundName + " from" + text + "path: " + text2)); switch (audioType) { case AudioType.wav: val = WavUtility.LoadFromDiskToAudioClip(text2); break; case AudioType.ogg: val = OggUtility.LoadFromDiskToAudioClip(text2); break; case AudioType.mp3: val = Mp3Utility.LoadFromDiskToAudioClip(text2); break; } Instance.logger.LogDebug((object)$"Finished loading AudioClip {soundName} with length of {val.length}!"); } else { Instance.logger.LogWarning((object)("Failed to load AudioClip " + soundName + " from invalid" + text + "path at " + text2 + "!")); } if (string.IsNullOrEmpty(val.GetName())) { string empty = string.Empty; string[] array2 = new string[0]; switch (audioType) { case AudioType.wav: empty = soundName.Replace(".wav", ""); array2 = empty.Split('/'); if (array2.Length <= 1) { array2 = empty.Split('\\'); } empty = array2[^1]; ((Object)val).name = empty; break; case AudioType.ogg: empty = soundName.Replace(".ogg", ""); array2 = empty.Split('/'); if (array2.Length <= 1) { array2 = empty.Split('\\'); } empty = array2[^1]; ((Object)val).name = empty; break; case AudioType.mp3: empty = soundName.Replace(".mp3", ""); array2 = empty.Split('/'); if (array2.Length <= 1) { array2 = empty.Split('\\'); } empty = array2[^1]; ((Object)val).name = empty; break; } } if ((Object)(object)val != (Object)null) { clipTypes.Add(val.GetName(), audioType); } return val; } public static AudioClip GetAudioClip(string modFolder, string soundName, AudioType audioType) { return GetAudioClip(modFolder, string.Empty, soundName, audioType); } public static AudioClip GetAudioClip(string modFolder, string subFolder, string soundName, AudioType audioType) { bool flag = true; string text = " "; string text2 = Path.Combine(Paths.PluginPath, modFolder, subFolder, soundName); string text3 = Path.Combine(Paths.PluginPath, modFolder, soundName); string path = Path.Combine(Paths.PluginPath, modFolder, subFolder); string text4 = Path.Combine(Paths.PluginPath, subFolder, soundName); string path2 = Path.Combine(Paths.PluginPath, subFolder); if (!Directory.Exists(path)) { if (!string.IsNullOrEmpty(subFolder)) { Instance.logger.LogWarning((object)("Requested directory at BepInEx/Plugins/" + modFolder + "/" + subFolder + " does not exist!")); } else { Instance.logger.LogWarning((object)("Requested directory at BepInEx/Plugins/" + modFolder + " does not exist!")); if (!modFolder.Contains("-")) { Instance.logger.LogWarning((object)"This sound mod might not be compatable with mod managers. You should contact the sound mod's author."); } } flag = false; } if (!File.Exists(text2)) { Instance.logger.LogWarning((object)("Requested audio file does not exist at path " + text2 + "!")); flag = false; Instance.logger.LogDebug((object)("Looking for audio file from mod root instead at " + text3 + "...")); if (File.Exists(text3)) { Instance.logger.LogDebug((object)("Found audio file at path " + text3 + "!")); text2 = text3; flag = true; } else { Instance.logger.LogWarning((object)("Requested audio file does not exist at mod root path " + text3 + "!")); } } if (Directory.Exists(path2)) { if (!string.IsNullOrEmpty(subFolder)) { Instance.logger.LogWarning((object)("Legacy directory location at BepInEx/Plugins/" + subFolder + " found!")); } else if (!modFolder.Contains("-")) { Instance.logger.LogWarning((object)"Legacy directory location at BepInEx/Plugins found!"); } } if (File.Exists(text4)) { Instance.logger.LogWarning((object)("Legacy path contains the requested audio file at path " + text4 + "!")); text = " legacy "; text2 = text4; flag = true; } switch (audioType) { case AudioType.wav: Instance.logger.LogDebug((object)"File defined as a WAV file!"); break; case AudioType.ogg: Instance.logger.LogDebug((object)"File defined as an Ogg Vorbis file!"); break; case AudioType.mp3: Instance.logger.LogDebug((object)"File defined as a MPEG MP3 file!"); break; } AudioClip val = null; if (flag) { Instance.logger.LogDebug((object)("Loading AudioClip " + soundName + " from" + text + "path: " + text2)); switch (audioType) { case AudioType.wav: val = WavUtility.LoadFromDiskToAudioClip(text2); break; case AudioType.ogg: val = OggUtility.LoadFromDiskToAudioClip(text2); break; case AudioType.mp3: val = Mp3Utility.LoadFromDiskToAudioClip(text2); break; } Instance.logger.LogDebug((object)$"Finished loading AudioClip {soundName} with length of {val.length}!"); } else { Instance.logger.LogWarning((object)("Failed to load AudioClip " + soundName + " from invalid" + text + "path at " + text2 + "!")); } if (string.IsNullOrEmpty(val.GetName())) { string empty = string.Empty; string[] array = new string[0]; switch (audioType) { case AudioType.wav: empty = soundName.Replace(".wav", ""); array = empty.Split('/'); if (array.Length <= 1) { array = empty.Split('\\'); } empty = array[^1]; ((Object)val).name = empty; break; case AudioType.ogg: empty = soundName.Replace(".ogg", ""); array = empty.Split('/'); if (array.Length <= 1) { array = empty.Split('\\'); } empty = array[^1]; ((Object)val).name = empty; break; case AudioType.mp3: empty = soundName.Replace(".mp3", ""); array = empty.Split('/'); if (array.Length <= 1) { array = empty.Split('\\'); } empty = array[^1]; ((Object)val).name = empty; break; } } if ((Object)(object)val != (Object)null) { clipTypes.Add(val.GetName(), audioType); } return val; } public static void SendNetworkedAudioClip(AudioClip audioClip) { if (!Instance.configUseNetworking.Value) { Instance.logger.LogWarning((object)$"Networking disabled! Failed to send {audioClip}!"); return; } if ((Object)(object)audioClip == (Object)null) { Instance.logger.LogWarning((object)$"audioClip variable of SendAudioClip not assigned! Failed to send {audioClip}!"); return; } if ((Object)(object)Instance == (Object)null || (Object)(object)GameNetworkManagerPatch.networkHandlerHost == (Object)null || (Object)(object)NetworkHandler.Instance == (Object)null) { Instance.logger.LogWarning((object)$"Instance of SoundTool not found or networking has not finished initializing. Failed to send {audioClip}! If you're sending things in Awake or in a scene such as the main menu it might be too early, please try some of the other built-in Unity methods and make sure your networked audio runs only after the player setups a networked connection!"); return; } string name = audioClip.GetName(); if (clipTypes.ContainsKey(name)) { if (clipTypes[name] == AudioType.ogg) { NetworkHandler.Instance.SendAudioClipServerRpc(name, OggUtility.AudioClipToByteArray(audioClip, out var _)); return; } if (clipTypes[name] == AudioType.mp3) { NetworkHandler.Instance.SendAudioClipServerRpc(name, Mp3Utility.AudioClipToByteArray(audioClip, out var _)); return; } } NetworkHandler.Instance.SendAudioClipServerRpc(name, WavUtility.AudioClipToByteArray(audioClip, out var _)); } public static void RemoveNetworkedAudioClip(AudioClip audioClip) { RemoveNetworkedAudioClip(audioClip.GetName()); } public static void RemoveNetworkedAudioClip(string audioClip) { if (!Instance.configUseNetworking.Value) { Instance.logger.LogWarning((object)("Networking disabled! Failed to remove " + audioClip + "!")); } else if (string.IsNullOrEmpty(audioClip)) { Instance.logger.LogWarning((object)("audioClip variable of RemoveAudioClip not assigned! Failed to remove " + audioClip + "!")); } else if ((Object)(object)Instance == (Object)null || (Object)(object)GameNetworkManagerPatch.networkHandlerHost == (Object)null || (Object)(object)NetworkHandler.Instance == (Object)null) { Instance.logger.LogWarning((object)("Instance of SoundTool not found or networking has not finished initializing. Failed to remove " + audioClip + "! If you're removing things in Awake or in a scene such as the main menu it might be too early, please try some of the other built-in Unity methods and make sure your networked audio runs only after the player setups a networked connection!")); } else { NetworkHandler.Instance.RemoveAudioClipServerRpc(audioClip); } } public static void SyncNetworkedAudioClips() { if (!Instance.configUseNetworking.Value) { Instance.logger.LogWarning((object)"Networking disabled! Failed to sync audio clips!"); } else if ((Object)(object)Instance == (Object)null || (Object)(object)GameNetworkManagerPatch.networkHandlerHost == (Object)null || (Object)(object)NetworkHandler.Instance == (Object)null) { Instance.logger.LogWarning((object)"Instance of SoundTool not found or networking has not finished initializing. Failed to sync networked audio! If you're syncing things in Awake or in a scene such as the main menu it might be too early, please try some of the other built-in Unity methods and make sure your networked audio runs only after the player setups a networked connection!"); } else { NetworkHandler.Instance.SyncAudioClipsServerRpc(); } } public static void SendUnityRandomSeed(int seed) { if (!Instance.configUseNetworking.Value) { Instance.logger.LogWarning((object)"Networking disabled! Failed to send Unity random seed!"); } else if ((Object)(object)Instance == (Object)null || (Object)(object)GameNetworkManagerPatch.networkHandlerHost == (Object)null || (Object)(object)NetworkHandler.Instance == (Object)null) { Instance.logger.LogWarning((object)"Instance of SoundTool not found or networking has not finished initializing. Failed to send Unity Random seed! If you're sending the seed in Awake or in a scene such as the main menu it might be too early, please try some of the other built-in Unity methods and make sure your networked methods run only after the player setups a networked connection!"); } else { NetworkHandler.Instance.SendSeedToClientsServerRpc(seed); } } } } namespace LCSoundTool.Utilities { public static class Mp3Utility { public static byte[] AudioClipToByteArray(AudioClip audioClip, out float[] samples) { samples = new float[audioClip.samples * audioClip.channels]; audioClip.GetData(samples, 0); byte[] array = new byte[samples.Length * 2]; int num = 32767; for (int i = 0; i < samples.Length; i++) { short value = (short)(samples[i] * (float)num); BitConverter.GetBytes(value).CopyTo(array, i * 2); } return array; } public static AudioClip ByteArrayToAudioClip(byte[] byteArray, string clipName) { int num = 16; int num2 = num / 8; AudioClip val = AudioClip.Create(clipName, byteArray.Length / num2, 1, 44100, false); val.SetData(ConvertByteArrayToFloatArray(byteArray), 0); return val; } private static float[] ConvertByteArrayToFloatArray(byte[] byteArray) { float[] array = new float[byteArray.Length / 2]; int num = 32767; for (int i = 0; i < array.Length; i++) { short num2 = BitConverter.ToInt16(byteArray, i * 2); array[i] = (float)num2 / (float)num; } return array; } public static AudioClip LoadFromDiskToAudioClip(string path) { //IL_0027: Unknown result type (might be due to invalid IL or missing references) //IL_002d: Invalid comparison between Unknown and I4 AudioClip result = null; UnityWebRequest audioClip = UnityWebRequestMultimedia.GetAudioClip(path, (AudioType)13); try { audioClip.SendWebRequest(); try { while (!audioClip.isDone) { } if ((int)audioClip.result != 1) { SoundTool.Instance.logger.LogError((object)("Failed to load MP3 AudioClip from path: " + path + " Full error: " + audioClip.error)); } else { result = DownloadHandlerAudioClip.GetContent(audioClip); } } catch (Exception ex) { SoundTool.Instance.logger.LogError((object)(ex.Message + ", " + ex.StackTrace)); } } finally { ((IDisposable)audioClip)?.Dispose(); } return result; } } public static class OggUtility { public static byte[] AudioClipToByteArray(AudioClip audioClip, out float[] samples) { samples = new float[audioClip.samples * audioClip.channels]; audioClip.GetData(samples, 0); byte[] array = new byte[samples.Length * 2]; int num = 32767; for (int i = 0; i < samples.Length; i++) { short value = (short)(samples[i] * (float)num); BitConverter.GetBytes(value).CopyTo(array, i * 2); } return array; } public static AudioClip ByteArrayToAudioClip(byte[] byteArray, string clipName) { int num = 16; int num2 = num / 8; AudioClip val = AudioClip.Create(clipName, byteArray.Length / num2, 1, 44100, false); val.SetData(ConvertByteArrayToFloatArray(byteArray), 0); return val; } private static float[] ConvertByteArrayToFloatArray(byte[] byteArray) { float[] array = new float[byteArray.Length / 2]; int num = 32767; for (int i = 0; i < array.Length; i++) { short num2 = BitConverter.ToInt16(byteArray, i * 2); array[i] = (float)num2 / (float)num; } return array; } public static AudioClip LoadFromDiskToAudioClip(string path) { //IL_0027: Unknown result type (might be due to invalid IL or missing references) //IL_002d: Invalid comparison between Unknown and I4 AudioClip result = null; UnityWebRequest audioClip = UnityWebRequestMultimedia.GetAudioClip(path, (AudioType)14); try { audioClip.SendWebRequest(); try { while (!audioClip.isDone) { } if ((int)audioClip.result != 1) { SoundTool.Instance.logger.LogError((object)("Failed to load OGGVORBIS AudioClip from path: " + path + " Full error: " + audioClip.error)); } else { result = DownloadHandlerAudioClip.GetContent(audioClip); } } catch (Exception ex) { SoundTool.Instance.logger.LogError((object)(ex.Message + ", " + ex.StackTrace)); } } finally { ((IDisposable)audioClip)?.Dispose(); } return result; } } public static class WavUtility { public static byte[] AudioClipToByteArray(AudioClip audioClip, out float[] samples) { samples = new float[audioClip.samples * audioClip.channels]; audioClip.GetData(samples, 0); byte[] array = new byte[samples.Length * 2]; int num = 32767; for (int i = 0; i < samples.Length; i++) { short value = (short)(samples[i] * (float)num); BitConverter.GetBytes(value).CopyTo(array, i * 2); } return array; } public static AudioClip ByteArrayToAudioClip(byte[] byteArray, string clipName) { int num = 16; int num2 = num / 8; AudioClip val = AudioClip.Create(clipName, byteArray.Length / num2, 1, 44100, false); val.SetData(ConvertByteArrayToFloatArray(byteArray), 0); return val; } private static float[] ConvertByteArrayToFloatArray(byte[] byteArray) { float[] array = new float[byteArray.Length / 2]; int num = 32767; for (int i = 0; i < array.Length; i++) { short num2 = BitConverter.ToInt16(byteArray, i * 2); array[i] = (float)num2 / (float)num; } return array; } public static AudioClip LoadFromDiskToAudioClip(string path) { //IL_0027: Unknown result type (might be due to invalid IL or missing references) //IL_002d: Invalid comparison between Unknown and I4 AudioClip result = null; UnityWebRequest audioClip = UnityWebRequestMultimedia.GetAudioClip(path, (AudioType)20); try { audioClip.SendWebRequest(); try { while (!audioClip.isDone) { } if ((int)audioClip.result != 1) { SoundTool.Instance.logger.LogError((object)("Failed to load WAV AudioClip from path: " + path + " Full error: " + audioClip.error)); } else { result = DownloadHandlerAudioClip.GetContent(audioClip); } } catch (Exception ex) { SoundTool.Instance.logger.LogError((object)(ex.Message + ", " + ex.StackTrace)); } } finally { ((IDisposable)audioClip)?.Dispose(); } return result; } } } namespace LCSoundTool.Patches { [HarmonyPatch(typeof(AudioSource))] internal class AudioSourcePatch { private static Dictionary<string, AudioClip> originalClips = new Dictionary<string, AudioClip>(); [HarmonyPatch("Play", new Type[] { })] [HarmonyPrefix] public static void Play_Patch(AudioSource __instance) { RunDynamicClipReplacement(__instance); DebugPlayMethod(__instance); } [HarmonyPatch("Play", new Type[] { typeof(ulong) })] [HarmonyPrefix] public static void Play_UlongPatch(AudioSource __instance) { RunDynamicClipReplacement(__instance); DebugPlayMethod(__instance); } [HarmonyPatch("Play", new Type[] { typeof(double) })] [HarmonyPrefix] public static void Play_DoublePatch(AudioSource __instance) { RunDynamicClipReplacement(__instance); DebugPlayMethod(__instance); } [HarmonyPatch("PlayDelayed", new Type[] { typeof(float) })] [HarmonyPrefix] public static void PlayDelayed_Patch(AudioSource __instance) { RunDynamicClipReplacement(__instance); DebugPlayDelayedMethod(__instance); } [HarmonyPatch("PlayClipAtPoint", new Type[] { typeof(AudioClip), typeof(Vector3), typeof(float) })] [HarmonyPrefix] public static bool PlayClipAtPoint_Patch(AudioClip clip, Vector3 position, float volume) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_000c: Expected O, but got Unknown //IL_0012: Unknown result type (might be due to invalid IL or missing references) //IL_004b: Unknown result type (might be due to invalid IL or missing references) GameObject val = new GameObject("One shot audio"); val.transform.position = position; AudioSource val2 = val.AddComponent<AudioSource>(); val2.clip = clip; val2.spatialBlend = 1f; val2.volume = volume; RunDynamicClipReplacement(val2); val2.Play(); DebugPlayClipAtPointMethod(val2, position); Object.Destroy((Object)(object)val, clip.length * ((Time.timeScale < 0.01f) ? 0.01f : Time.timeScale)); return false; } [HarmonyPatch("PlayOneShotHelper", new Type[] { typeof(AudioSource), typeof(AudioClip), typeof(float) })] [HarmonyPrefix] public static void PlayOneShotHelper_Patch(AudioSource source, ref AudioClip clip, float volumeScale) { clip = ReplaceClipWithNew(clip); DebugPlayOneShotMethod(source, clip); } private static void DebugPlayMethod(AudioSource instance) { if ((Object)(object)instance == (Object)null) { return; } if (SoundTool.debugAudioSources && !SoundTool.indepthDebugging && (Object)(object)instance != (Object)null) { SoundTool.Instance.logger.LogDebug((object)$"{instance} at {((Component)instance).transform.root} is playing {((Object)instance.clip).name}"); } else if (SoundTool.indepthDebugging && (Object)(object)instance != (Object)null) { SoundTool.Instance.logger.LogDebug((object)$"{instance} is playing {((Object)instance.clip).name} at"); Transform val = ((Component)instance).transform; while ((Object)(object)val.parent != (Object)null || (Object)(object)val != (Object)(object)((Component)instance).transform.root) { SoundTool.Instance.logger.LogDebug((object)$"--- {val.parent}"); val = val.parent; } if ((Object)(object)val == (Object)(object)((Component)instance).transform.root) { SoundTool.Instance.logger.LogDebug((object)$"--- {((Component)instance).transform.root}"); } } } private static void DebugPlayDelayedMethod(AudioSource instance) { if ((Object)(object)instance == (Object)null) { return; } if (SoundTool.debugAudioSources && !SoundTool.indepthDebugging && (Object)(object)instance != (Object)null) { SoundTool.Instance.logger.LogDebug((object)$"{instance} at {((Component)instance).transform.root} is playing {((Object)instance.clip).name} with delay"); } else if (SoundTool.indepthDebugging && (Object)(object)instance != (Object)null) { SoundTool.Instance.logger.LogDebug((object)$"{instance} is playing {((Object)instance.clip).name} with delay at"); Transform val = ((Component)instance).transform; while ((Object)(object)val.parent != (Object)null || (Object)(object)val != (Object)(object)((Component)instance).transform.root) { SoundTool.Instance.logger.LogDebug((object)$"--- {val.parent}"); val = val.parent; } if ((Object)(object)val == (Object)(object)((Component)instance).transform.root) { SoundTool.Instance.logger.LogDebug((object)$"--- {((Component)instance).transform.root}"); } } } private static void DebugPlayClipAtPointMethod(AudioSource audioSource, Vector3 position) { //IL_0065: Unknown result type (might be due to invalid IL or missing references) //IL_00b1: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)audioSource == (Object)null) { return; } if (SoundTool.debugAudioSources && !SoundTool.indepthDebugging && (Object)(object)audioSource != (Object)null) { SoundTool.Instance.logger.LogDebug((object)$"{audioSource} at {((Component)audioSource).transform.root} is playing {((Object)audioSource.clip).name} at point {position}"); } else if (SoundTool.indepthDebugging && (Object)(object)audioSource != (Object)null) { SoundTool.Instance.logger.LogDebug((object)$"{audioSource} is playing {((Object)audioSource.clip).name} located at point {position} within "); Transform val = ((Component)audioSource).transform; while ((Object)(object)val.parent != (Object)null || (Object)(object)val != (Object)(object)((Component)audioSource).transform.root) { SoundTool.Instance.logger.LogDebug((object)$"--- {val.parent}"); val = val.parent; } if ((Object)(object)val == (Object)(object)((Component)audioSource).transform.root) { SoundTool.Instance.logger.LogDebug((object)$"--- {((Component)audioSource).transform.root}"); } } } private static void DebugPlayOneShotMethod(AudioSource source, AudioClip clip) { if ((Object)(object)source == (Object)null || (Object)(object)clip == (Object)null) { return; } if (SoundTool.debugAudioSources && !SoundTool.indepthDebugging && (Object)(object)source != (Object)null) { SoundTool.Instance.logger.LogDebug((object)$"{source} at {((Component)source).transform.root} is playing one shot {((Object)clip).name}"); } else if (SoundTool.indepthDebugging && (Object)(object)source != (Object)null) { SoundTool.Instance.logger.LogDebug((object)$"{source} is playing one shot {((Object)clip).name} at"); Transform val = ((Component)source).transform; while ((Object)(object)val.parent != (Object)null || (Object)(object)val != (Object)(object)((Component)source).transform.root) { SoundTool.Instance.logger.LogDebug((object)$"--- {val.parent}"); val = val.parent; } if ((Object)(object)val == (Object)(object)((Component)source).transform.root) { SoundTool.Instance.logger.LogDebug((object)$"--- {((Component)source).transform.root}"); } } } private static void RunDynamicClipReplacement(AudioSource instance) { if ((Object)(object)instance == (Object)null || (Object)(object)instance.clip == (Object)null) { return; } string name = instance.clip.GetName(); if (SoundTool.replacedClips.ContainsKey(name)) { if (!originalClips.ContainsKey(name)) { originalClips.Add(name, instance.clip); } List<RandomAudioClip> list = SoundTool.replacedClips[name]; float num = 0f; foreach (RandomAudioClip item in list) { num += item.chance; } float num2 = Random.Range(0f, num); { foreach (RandomAudioClip item2 in list) { if (num2 <= item2.chance) { instance.clip = item2.clip; break; } num2 -= item2.chance; } return; } } if (originalClips.ContainsKey(name)) { instance.clip = originalClips[name]; originalClips.Remove(name); } } private static AudioClip ReplaceClipWithNew(AudioClip original) { if ((Object)(object)original == (Object)null) { return original; } string name = original.GetName(); if (SoundTool.replacedClips.ContainsKey(name)) { if (!originalClips.ContainsKey(name)) { originalClips.Add(name, original); } List<RandomAudioClip> list = SoundTool.replacedClips[name]; float num = 0f; foreach (RandomAudioClip item in list) { num += item.chance; } float num2 = Random.Range(0f, num); foreach (RandomAudioClip item2 in list) { if (num2 <= item2.chance) { return item2.clip; } num2 -= item2.chance; } } else if (originalClips.ContainsKey(name)) { AudioClip result = originalClips[name]; originalClips.Remove(name); return result; } return original; } } [HarmonyPatch(typeof(GameNetworkManager))] internal class GameNetworkManagerPatch { public static GameObject networkPrefab; public static GameObject networkHandlerHost; [HarmonyPatch("Start")] [HarmonyPrefix] public static void Start_Patch() { if (!((Object)(object)networkPrefab != (Object)null)) { SoundTool.Instance.logger.LogDebug((object)"Loading NetworkHandler prefab..."); networkPrefab = Assets.bundle.LoadAsset<GameObject>("SoundToolNetworkHandler.prefab"); if ((Object)(object)networkPrefab == (Object)null) { SoundTool.Instance.logger.LogError((object)"Failed to load NetworkHandler prefab!"); } if ((Object)(object)networkPrefab != (Object)null) { NetworkManager.Singleton.AddNetworkPrefab(networkPrefab); SoundTool.Instance.logger.LogDebug((object)"Registered NetworkHandler prefab!"); } else { SoundTool.Instance.logger.LogWarning((object)"Failed to registered NetworkHandler prefab! No networking can take place."); } } } [HarmonyPatch("StartDisconnect")] [HarmonyPostfix] private static void StartDisconnect_Patch() { try { if (NetworkManager.Singleton.IsHost || NetworkManager.Singleton.IsServer) { SoundTool.Instance.logger.LogDebug((object)"Destroying NetworkHandler prefab!"); Object.Destroy((Object)(object)networkHandlerHost); networkHandlerHost = null; } } catch { SoundTool.Instance.logger.LogError((object)"Failed to destroy NetworkHandler prefab!"); } } } [HarmonyPatch(typeof(StartOfRound))] internal class StartOfRoundPatch { [HarmonyPatch("Awake")] [HarmonyPostfix] private static void SpawnNetworkHandler() { //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) try { if (NetworkManager.Singleton.IsHost || NetworkManager.Singleton.IsServer) { SoundTool.Instance.logger.LogDebug((object)"Spawning NetworkHandler prefab!"); GameNetworkManagerPatch.networkHandlerHost = Object.Instantiate<GameObject>(GameNetworkManagerPatch.networkPrefab, Vector3.zero, Quaternion.identity); GameNetworkManagerPatch.networkHandlerHost.GetComponent<NetworkObject>().Spawn(true); } } catch { SoundTool.Instance.logger.LogError((object)"Failed to spawn NetworkHandler prefab!"); } } } } namespace LCSoundTool.Networking { public class NetworkHandler : NetworkBehaviour { public static NetworkHandler Instance { get; private set; } public static Dictionary<string, AudioClip> networkedAudioClips { get; private set; } public static event Action ClientNetworkedAudioChanged; public static event Action HostNetworkedAudioChanged; public override void OnNetworkSpawn() { Debug.Log((object)"LCSoundTool - NetworkHandler created!"); NetworkHandler.ClientNetworkedAudioChanged = null; NetworkHandler.HostNetworkedAudioChanged = null; networkedAudioClips = new Dictionary<string, AudioClip>(); Instance = this; } [ClientRpc] public void ReceiveAudioClipClientRpc(string clipName, byte[] audioData) { //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Invalid comparison between Unknown and I4 //IL_0115: Unknown result type (might be due to invalid IL or missing references) //IL_011f: 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_0088: Unknown result type (might be due to invalid IL or missing references) //IL_008e: Unknown result type (might be due to invalid IL or missing references) //IL_00c6: 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_0105: Unknown result type (might be due to invalid IL or missing references) //IL_00ea: Unknown result type (might be due to invalid IL or missing references) //IL_00f0: Unknown result type (might be due to invalid IL or missing references) NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager; if (networkManager == null || !networkManager.IsListening) { return; } if ((int)base.__rpc_exec_stage != 2 && (networkManager.IsServer || networkManager.IsHost)) { ClientRpcParams val = default(ClientRpcParams); FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendClientRpc(2736638642u, val, (RpcDelivery)0); bool flag = clipName != null; ((FastBufferWriter)(ref val2)).WriteValueSafe<bool>(ref flag, default(ForPrimitives)); if (flag) { ((FastBufferWriter)(ref val2)).WriteValueSafe(clipName, false); } bool flag2 = audioData != null; ((FastBufferWriter)(ref val2)).WriteValueSafe<bool>(ref flag2, default(ForPrimitives)); if (flag2) { ((FastBufferWriter)(ref val2)).WriteValueSafe<byte>(audioData, default(ForPrimitives)); } ((NetworkBehaviour)this).__endSendClientRpc(ref val2, 2736638642u, val, (RpcDelivery)0); } if ((int)base.__rpc_exec_stage != 2 || (!networkManager.IsClient && !networkManager.IsHost)) { return; } if (!networkedAudioClips.ContainsKey(clipName)) { AudioClip val3 = null; if (SoundTool.clipTypes.ContainsKey(clipName)) { if (SoundTool.clipTypes[clipName] == SoundTool.AudioType.ogg) { val3 = OggUtility.ByteArrayToAudioClip(audioData, clipName); } else if (SoundTool.clipTypes[clipName] == SoundTool.AudioType.mp3) { val3 = Mp3Utility.ByteArrayToAudioClip(audioData, clipName); } } if ((Object)(object)val3 == (Object)null) { val3 = WavUtility.ByteArrayToAudioClip(audioData, clipName); } networkedAudioClips.Add(clipName, val3); NetworkHandler.ClientNetworkedAudioChanged?.Invoke(); } else { SoundTool.Instance.logger.LogDebug((object)("Sound " + clipName + " already exists for this client! Skipping addition of this sound for this client.")); } } [ClientRpc] public void RemoveAudioClipClientRpc(string clipName) { //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Invalid comparison between Unknown and I4 //IL_00ca: Unknown result type (might be due to invalid IL or missing references) //IL_00d4: 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_0088: Unknown result type (might be due to invalid IL or missing references) //IL_008e: Unknown result type (might be due to invalid IL or missing references) //IL_00ba: Unknown result type (might be due to invalid IL or missing references) NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager; if (networkManager == null || !networkManager.IsListening) { return; } if ((int)base.__rpc_exec_stage != 2 && (networkManager.IsServer || networkManager.IsHost)) { ClientRpcParams val = default(ClientRpcParams); FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendClientRpc(1355469546u, val, (RpcDelivery)0); bool flag = clipName != null; ((FastBufferWriter)(ref val2)).WriteValueSafe<bool>(ref flag, default(ForPrimitives)); if (flag) { ((FastBufferWriter)(ref val2)).WriteValueSafe(clipName, false); } ((NetworkBehaviour)this).__endSendClientRpc(ref val2, 1355469546u, val, (RpcDelivery)0); } if ((int)base.__rpc_exec_stage == 2 && (networkManager.IsClient || networkManager.IsHost) && networkedAudioClips.ContainsKey(clipName)) { networkedAudioClips.Remove(clipName); NetworkHandler.ClientNetworkedAudioChanged?.Invoke(); } } [ClientRpc] public void SyncAudioClipsClientRpc(Strings clipNames) { //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Invalid comparison between Unknown and I4 //IL_00a7: Unknown result type (might be due to invalid IL or missing references) //IL_00b1: 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_007d: Unknown result type (might be due to invalid IL or missing references) //IL_0083: Unknown result type (might be due to invalid IL or missing references) //IL_0097: Unknown result type (might be due to invalid IL or missing references) NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager; if (networkManager == null || !networkManager.IsListening) { return; } if ((int)base.__rpc_exec_stage != 2 && (networkManager.IsServer || networkManager.IsHost)) { ClientRpcParams val = default(ClientRpcParams); FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendClientRpc(3300200130u, val, (RpcDelivery)0); ((FastBufferWriter)(ref val2)).WriteValueSafe<Strings>(ref clipNames, default(ForNetworkSerializable)); ((NetworkBehaviour)this).__endSendClientRpc(ref val2, 3300200130u, val, (RpcDelivery)0); } if ((int)base.__rpc_exec_stage != 2 || (!networkManager.IsClient && !networkManager.IsHost)) { return; } string[] myStrings = clipNames.MyStrings; for (int i = 0; i < myStrings.Length; i++) { if (!networkedAudioClips.ContainsKey(myStrings[i])) { SendExistingAudioClipServerRpc(myStrings[i]); } } } [ClientRpc] public void ReceiveSeedClientRpc(int seed) { //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Invalid comparison between Unknown and I4 //IL_0099: Unknown result type (might be due to invalid IL or missing references) //IL_00a3: 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_0071: 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) 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(1556253924u, val, (RpcDelivery)0); BytePacker.WriteValueBitPacked(val2, seed); ((NetworkBehaviour)this).__endSendClientRpc(ref val2, 1556253924u, val, (RpcDelivery)0); } if ((int)base.__rpc_exec_stage == 2 && (networkManager.IsClient || networkManager.IsHost)) { Random.InitState(seed); SoundTool.Instance.logger.LogDebug((object)$"Client received a new Unity Random seed of {seed}!"); } } } [ServerRpc(RequireOwnership = false)] public void SendAudioClipServerRpc(string clipName, byte[] audioData) { //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Invalid comparison between Unknown and I4 //IL_0115: Unknown result type (might be due to invalid IL or missing references) //IL_011f: 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_0088: Unknown result type (might be due to invalid IL or missing references) //IL_008e: Unknown result type (might be due to invalid IL or missing references) //IL_00c6: 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_0105: Unknown result type (might be due to invalid IL or missing references) //IL_00ea: Unknown result type (might be due to invalid IL or missing references) //IL_00f0: Unknown result type (might be due to invalid IL or missing references) NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager; if (networkManager == null || !networkManager.IsListening) { return; } if ((int)base.__rpc_exec_stage != 1 && (networkManager.IsClient || networkManager.IsHost)) { ServerRpcParams val = default(ServerRpcParams); FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendServerRpc(867452943u, val, (RpcDelivery)0); bool flag = clipName != null; ((FastBufferWriter)(ref val2)).WriteValueSafe<bool>(ref flag, default(ForPrimitives)); if (flag) { ((FastBufferWriter)(ref val2)).WriteValueSafe(clipName, false); } bool flag2 = audioData != null; ((FastBufferWriter)(ref val2)).WriteValueSafe<bool>(ref flag2, default(ForPrimitives)); if (flag2) { ((FastBufferWriter)(ref val2)).WriteValueSafe<byte>(audioData, default(ForPrimitives)); } ((NetworkBehaviour)this).__endSendServerRpc(ref val2, 867452943u, val, (RpcDelivery)0); } if ((int)base.__rpc_exec_stage == 1 && (networkManager.IsServer || networkManager.IsHost)) { ReceiveAudioClipClientRpc(clipName, audioData); NetworkHandler.HostNetworkedAudioChanged?.Invoke(); } } [ServerRpc(RequireOwnership = false)] public void RemoveAudioClipServerRpc(string clipName) { //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Invalid comparison between Unknown and I4 //IL_00ca: Unknown result type (might be due to invalid IL or missing references) //IL_00d4: 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_0088: Unknown result type (might be due to invalid IL or missing references) //IL_008e: Unknown result type (might be due to invalid IL or missing references) //IL_00ba: Unknown result type (might be due to invalid IL or missing references) NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager; if (networkManager == null || !networkManager.IsListening) { return; } if ((int)base.__rpc_exec_stage != 1 && (networkManager.IsClient || networkManager.IsHost)) { ServerRpcParams val = default(ServerRpcParams); FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendServerRpc(3103497155u, val, (RpcDelivery)0); bool flag = clipName != null; ((FastBufferWriter)(ref val2)).WriteValueSafe<bool>(ref flag, default(ForPrimitives)); if (flag) { ((FastBufferWriter)(ref val2)).WriteValueSafe(clipName, false); } ((NetworkBehaviour)this).__endSendServerRpc(ref val2, 3103497155u, val, (RpcDelivery)0); } if ((int)base.__rpc_exec_stage == 1 && (networkManager.IsServer || networkManager.IsHost)) { RemoveAudioClipClientRpc(clipName); NetworkHandler.HostNetworkedAudioChanged?.Invoke(); } } [ServerRpc(RequireOwnership = false)] public void SyncAudioClipsServerRpc() { //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) { return; } if ((int)base.__rpc_exec_stage != 1 && (networkManager.IsClient || networkManager.IsHost)) { ServerRpcParams val = default(ServerRpcParams); FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendServerRpc(178607916u, val, (RpcDelivery)0); ((NetworkBehaviour)this).__endSendServerRpc(ref val2, 178607916u, val, (RpcDelivery)0); } if ((int)base.__rpc_exec_stage == 1 && (networkManager.IsServer || networkManager.IsHost)) { Strings clipNames = new Strings(networkedAudioClips.Keys.ToArray()); if (clipNames.MyStrings.Length < 1) { SoundTool.Instance.logger.LogDebug((object)"No sounds found in networkedClips. Syncing process cancelled!"); } else { SyncAudioClipsClientRpc(clipNames); } } } [ServerRpc(RequireOwnership = false)] public void SendExistingAudioClipServerRpc(string clipName) { //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Invalid comparison between Unknown and I4 //IL_00ca: Unknown result type (might be due to invalid IL or missing references) //IL_00d4: 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_0088: Unknown result type (might be due to invalid IL or missing references) //IL_008e: Unknown result type (might be due to invalid IL or missing references) //IL_00ba: Unknown result type (might be due to invalid IL or missing references) NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager; if (networkManager == null || !networkManager.IsListening) { return; } if ((int)base.__rpc_exec_stage != 1 && (networkManager.IsClient || networkManager.IsHost)) { ServerRpcParams val = default(ServerRpcParams); FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendServerRpc(4006259189u, val, (RpcDelivery)0); bool flag = clipName != null; ((FastBufferWriter)(ref val2)).WriteValueSafe<bool>(ref flag, default(ForPrimitives)); if (flag) { ((FastBufferWriter)(ref val2)).WriteValueSafe(clipName, false); } ((NetworkBehaviour)this).__endSendServerRpc(ref val2, 4006259189u, val, (RpcDelivery)0); } if ((int)base.__rpc_exec_stage != 1 || (!networkManager.IsServer && !networkManager.IsHost)) { return; } if (networkedAudioClips.ContainsKey(clipName)) { byte[] array = null; if (SoundTool.clipTypes.ContainsKey(clipName)) { if (SoundTool.clipTypes[clipName] == SoundTool.AudioType.ogg) { array = OggUtility.AudioClipToByteArray(networkedAudioClips[clipName], out var _); } else if (SoundTool.clipTypes[clipName] == SoundTool.AudioType.mp3) { array = Mp3Utility.AudioClipToByteArray(networkedAudioClips[clipName], out var _); } } if (array == null) { array = WavUtility.AudioClipToByteArray(networkedAudioClips[clipName], out var _); } ReceiveAudioClipClientRpc(clipName, array); } else { SoundTool.Instance.logger.LogWarning((object)"Trying to obtain and sync a sound from the host that does not exist in the host's game!"); } } [ServerRpc(RequireOwnership = false)] public void SendSeedToClientsServerRpc(int seed) { //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Invalid comparison between Unknown and I4 //IL_0099: Unknown result type (might be due to invalid IL or missing references) //IL_00a3: 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_0071: 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) NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager; if (networkManager != null && networkManager.IsListening) { if ((int)base.__rpc_exec_stage != 1 && (networkManager.IsClient || networkManager.IsHost)) { ServerRpcParams val = default(ServerRpcParams); FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendServerRpc(4286510828u, val, (RpcDelivery)0); BytePacker.WriteValueBitPacked(val2, seed); ((NetworkBehaviour)this).__endSendServerRpc(ref val2, 4286510828u, val, (RpcDelivery)0); } if ((int)base.__rpc_exec_stage == 1 && (networkManager.IsServer || networkManager.IsHost) && ((NetworkBehaviour)this).IsHost) { ReceiveSeedClientRpc(seed); SoundTool.Instance.logger.LogDebug((object)$"Sending a new Unity random seed of {seed} to all clients..."); } } } protected override void __initializeVariables() { ((NetworkBehaviour)this).__initializeVariables(); } [RuntimeInitializeOnLoadMethod] internal static void InitializeRPCS_NetworkHandler() { //IL_0011: Unknown result type (might be due to invalid IL or missing references) //IL_001b: Expected O, but got Unknown //IL_002c: Unknown result type (might be due to invalid IL or missing references) //IL_0036: Expected O, but got Unknown //IL_0047: Unknown result type (might be due to invalid IL or missing references) //IL_0051: Expected O, but got Unknown //IL_0062: Unknown result type (might be due to invalid IL or missing references) //IL_006c: Expected O, but got Unknown //IL_007d: Unknown result type (might be due to invalid IL or missing references) //IL_0087: Expected O, but got Unknown //IL_0098: Unknown result type (might be due to invalid IL or missing references) //IL_00a2: Expected O, but got Unknown //IL_00b3: Unknown result type (might be due to invalid IL or missing references) //IL_00bd: Expected O, but got Unknown //IL_00ce: Unknown result type (might be due to invalid IL or missing references) //IL_00d8: Expected O, but got Unknown //IL_00e9: Unknown result type (might be due to invalid IL or missing references) //IL_00f3: Expected O, but got Unknown NetworkManager.__rpc_func_table.Add(2736638642u, new RpcReceiveHandler(__rpc_handler_2736638642)); NetworkManager.__rpc_func_table.Add(1355469546u, new RpcReceiveHandler(__rpc_handler_1355469546)); NetworkManager.__rpc_func_table.Add(3300200130u, new RpcReceiveHandler(__rpc_handler_3300200130)); NetworkManager.__rpc_func_table.Add(1556253924u, new RpcReceiveHandler(__rpc_handler_1556253924)); NetworkManager.__rpc_func_table.Add(867452943u, new RpcReceiveHandler(__rpc_handler_867452943)); NetworkManager.__rpc_func_table.Add(3103497155u, new RpcReceiveHandler(__rpc_handler_3103497155)); NetworkManager.__rpc_func_table.Add(178607916u, new RpcReceiveHandler(__rpc_handler_178607916)); NetworkManager.__rpc_func_table.Add(4006259189u, new RpcReceiveHandler(__rpc_handler_4006259189)); NetworkManager.__rpc_func_table.Add(4286510828u, new RpcReceiveHandler(__rpc_handler_4286510828)); } private static void __rpc_handler_2736638642(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams) { //IL_002f: Unknown result type (might be due to invalid IL or missing references) //IL_0035: Unknown result type (might be due to invalid IL or missing references) //IL_0067: 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_00a6: Unknown result type (might be due to invalid IL or missing references) //IL_00c4: Unknown result type (might be due to invalid IL or missing references) //IL_0090: Unknown result type (might be due to invalid IL or missing references) //IL_0096: Unknown result type (might be due to invalid IL or missing references) NetworkManager networkManager = target.NetworkManager; if (networkManager != null && networkManager.IsListening) { bool flag = default(bool); ((FastBufferReader)(ref reader)).ReadValueSafe<bool>(ref flag, default(ForPrimitives)); string clipName = null; if (flag) { ((FastBufferReader)(ref reader)).ReadValueSafe(ref clipName, false); } bool flag2 = default(bool); ((FastBufferReader)(ref reader)).ReadValueSafe<bool>(ref flag2, default(ForPrimitives)); byte[] audioData = null; if (flag2) { ((FastBufferReader)(ref reader)).ReadValueSafe<byte>(ref audioData, default(ForPrimitives)); } target.__rpc_exec_stage = (__RpcExecStage)2; ((NetworkHandler)(object)target).ReceiveAudioClipClientRpc(clipName, audioData); target.__rpc_exec_stage = (__RpcExecStage)0; } } private static void __rpc_handler_1355469546(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams) { //IL_002f: Unknown result type (might be due to invalid IL or missing references) //IL_0035: Unknown result type (might be due to invalid IL or missing references) //IL_0061: Unknown result type (might be due to invalid IL or missing references) //IL_007b: Unknown result type (might be due to invalid IL or missing references) NetworkManager networkManager = target.NetworkManager; if (networkManager != null && networkManager.IsListening) { bool flag = default(bool); ((FastBufferReader)(ref reader)).ReadValueSafe<bool>(ref flag, default(ForPrimitives)); string clipName = null; if (flag) { ((FastBufferReader)(ref reader)).ReadValueSafe(ref clipName, false); } target.__rpc_exec_stage = (__RpcExecStage)2; ((NetworkHandler)(object)target).RemoveAudioClipClientRpc(clipName); target.__rpc_exec_stage = (__RpcExecStage)0; } } private static void __rpc_handler_3300200130(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams) { //IL_002f: Unknown result type (might be due to invalid IL or missing references) //IL_0035: Unknown result type (might be due to invalid IL or missing references) //IL_0044: Unknown result type (might be due to invalid IL or missing references) //IL_005e: Unknown result type (might be due to invalid IL or missing references) NetworkManager networkManager = target.NetworkManager; if (networkManager != null && networkManager.IsListening) { Strings clipNames = default(Strings); ((FastBufferReader)(ref reader)).ReadValueSafe<Strings>(ref clipNames, default(ForNetworkSerializable)); target.__rpc_exec_stage = (__RpcExecStage)2; ((NetworkHandler)(object)target).SyncAudioClipsClientRpc(clipNames); target.__rpc_exec_stage = (__RpcExecStage)0; } } private static void __rpc_handler_1556253924(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams) { //IL_0023: Unknown result type (might be due to invalid IL or missing references) //IL_0036: Unknown result type (might be due to invalid IL or missing references) //IL_0050: Unknown result type (might be due to invalid IL or missing references) NetworkManager networkManager = target.NetworkManager; if (networkManager != null && networkManager.IsListening) { int seed = default(int); ByteUnpacker.ReadValueBitPacked(reader, ref seed); target.__rpc_exec_stage = (__RpcExecStage)2; ((NetworkHandler)(object)target).ReceiveSeedClientRpc(seed); target.__rpc_exec_stage = (__RpcExecStage)0; } } private static void __rpc_handler_867452943(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams) { //IL_002f: Unknown result type (might be due to invalid IL or missing references) //IL_0035: Unknown result type (might be due to invalid IL or missing references) //IL_0067: 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_00a6: Unknown result type (might be due to invalid IL or missing references) //IL_00c4: Unknown result type (might be due to invalid IL or missing references) //IL_0090: Unknown result type (might be due to invalid IL or missing references) //IL_0096: Unknown result type (might be due to invalid IL or missing references) NetworkManager networkManager = target.NetworkManager; if (networkManager != null && networkManager.IsListening) { bool flag = default(bool); ((FastBufferReader)(ref reader)).ReadValueSafe<bool>(ref flag, default(ForPrimitives)); string clipName = null; if (flag) { ((FastBufferReader)(ref reader)).ReadValueSafe(ref clipName, false); } bool flag2 = default(bool); ((FastBufferReader)(ref reader)).ReadValueSafe<bool>(ref flag2, default(ForPrimitives)); byte[] audioData = null; if (flag2) { ((FastBufferReader)(ref reader)).ReadValueSafe<byte>(ref audioData, default(ForPrimitives)); } target.__rpc_exec_stage = (__RpcExecStage)1; ((NetworkHandler)(object)target).SendAudioClipServerRpc(clipName, audioData); target.__rpc_exec_stage = (__RpcExecStage)0; } } private static void __rpc_handler_3103497155(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams) { //IL_002f: Unknown result type (might be due to invalid IL or missing references) //IL_0035: Unknown result type (might be due to invalid IL or missing references) //IL_0061: Unknown result type (might be due to invalid IL or missing references) //IL_007b: Unknown result type (might be due to invalid IL or missing references) NetworkManager networkManager = target.NetworkManager; if (networkManager != null && networkManager.IsListening) { bool flag = default(bool); ((FastBufferReader)(ref reader)).ReadValueSafe<bool>(ref flag, default(ForPrimitives)); string clipName = null; if (flag) { ((FastBufferReader)(ref reader)).ReadValueSafe(ref clipName, false); } target.__rpc_exec_stage = (__RpcExecStage)1; ((NetworkHandler)(object)target).RemoveAudioClipServerRpc(clipName); target.__rpc_exec_stage = (__RpcExecStage)0; } } private static void __rpc_handler_178607916(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)1; ((NetworkHandler)(object)target).SyncAudioClipsServerRpc(); target.__rpc_exec_stage = (__RpcExecStage)0; } } private static void __rpc_handler_4006259189(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams) { //IL_002f: Unknown result type (might be due to invalid IL or missing references) //IL_0035: Unknown result type (might be due to invalid IL or missing references) //IL_0061: Unknown result type (might be due to invalid IL or missing references) //IL_007b: Unknown result type (might be due to invalid IL or missing references) NetworkManager networkManager = target.NetworkManager; if (networkManager != null && networkManager.IsListening) { bool flag = default(bool); ((FastBufferReader)(ref reader)).ReadValueSafe<bool>(ref flag, default(ForPrimitives)); string clipName = null; if (flag) { ((FastBufferReader)(ref reader)).ReadValueSafe(ref clipName, false); } target.__rpc_exec_stage = (__RpcExecStage)1; ((NetworkHandler)(object)target).SendExistingAudioClipServerRpc(clipName); target.__rpc_exec_stage = (__RpcExecStage)0; } } private static void __rpc_handler_4286510828(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams) { //IL_0023: Unknown result type (might be due to invalid IL or missing references) //IL_0036: Unknown result type (might be due to invalid IL or missing references) //IL_0050: Unknown result type (might be due to invalid IL or missing references) NetworkManager networkManager = target.NetworkManager; if (networkManager != null && networkManager.IsListening) { int seed = default(int); ByteUnpacker.ReadValueBitPacked(reader, ref seed); target.__rpc_exec_stage = (__RpcExecStage)1; ((NetworkHandler)(object)target).SendSeedToClientsServerRpc(seed); target.__rpc_exec_stage = (__RpcExecStage)0; } } protected internal override string __getTypeName() { return "NetworkHandler"; } } public struct Strings : INetworkSerializable { private string[] myStrings; public string[] MyStrings { get { return myStrings; } set { myStrings = value; } } public Strings(string[] myStrings) { this.myStrings = myStrings; } public void NetworkSerialize<T>(BufferSerializer<T> serializer) where T : IReaderWriter { //IL_000f: Unknown result type (might be due to invalid IL or missing references) //IL_0014: 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) //IL_002a: Unknown result type (might be due to invalid IL or missing references) //IL_0073: Unknown result type (might be due to invalid IL or missing references) //IL_0078: Unknown result type (might be due to invalid IL or missing references) //IL_0080: Unknown result type (might be due to invalid IL or missing references) //IL_0086: Unknown result type (might be due to invalid IL or missing references) if (serializer.IsWriter) { FastBufferWriter fastBufferWriter = serializer.GetFastBufferWriter(); int num = myStrings.Length; ((FastBufferWriter)(ref fastBufferWriter)).WriteValueSafe<int>(ref num, default(ForPrimitives)); for (int i = 0; i < myStrings.Length; i++) { ((FastBufferWriter)(ref fastBufferWriter)).WriteValueSafe(myStrings[i], false); } } if (serializer.IsReader) { FastBufferReader fastBufferReader = serializer.GetFastBufferReader(); int num2 = default(int); ((FastBufferReader)(ref fastBufferReader)).ReadValueSafe<int>(ref num2, default(ForPrimitives)); myStrings = new string[num2]; for (int j = 0; j < num2; j++) { ((FastBufferReader)(ref fastBufferReader)).ReadValueSafe(ref myStrings[j], false); } } } } } namespace LCSoundTool.Resources { public static class Assets { internal static AssetBundle bundle; } }
plugins/LethalCompanyInputUtils.dll
Decompiled 11 months agousing System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Reflection; using System.Reflection.Emit; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using System.Security; using System.Security.Permissions; using BepInEx; using BepInEx.Logging; using HarmonyLib; using LethalCompanyInputUtils.Api; using LethalCompanyInputUtils.Data; using LethalCompanyInputUtils.Utils; using Microsoft.CodeAnalysis; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using UnityEngine; using UnityEngine.InputSystem; using UnityEngine.SceneManagement; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")] [assembly: AssemblyCompany("LethalCompanyInputUtils")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: AssemblyInformationalVersion("1.0.0+52afbf7207fdde49ac33037091301a50725deb67")] [assembly: AssemblyProduct("LethalCompanyInputUtils")] [assembly: AssemblyTitle("LethalCompanyInputUtils")] [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.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; } } [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 LethalCompanyInputUtils { public static class LcInputActionApi { private static readonly Dictionary<string, LcInputActions> InputActionsMap = new Dictionary<string, LcInputActions>(); private static IReadOnlyCollection<LcInputActions> InputActions => InputActionsMap.Values; internal static void LoadIntoUI(KepRemapPanel panel) { //IL_013b: Unknown result type (might be due to invalid IL or missing references) //IL_0140: Unknown result type (might be due to invalid IL or missing references) //IL_0076: Unknown result type (might be due to invalid IL or missing references) //IL_0080: Unknown result type (might be due to invalid IL or missing references) //IL_0085: Unknown result type (might be due to invalid IL or missing references) //IL_0090: Unknown result type (might be due to invalid IL or missing references) //IL_0095: Unknown result type (might be due to invalid IL or missing references) //IL_009d: Unknown result type (might be due to invalid IL or missing references) //IL_00a5: Unknown result type (might be due to invalid IL or missing references) //IL_00ae: Expected O, but got Unknown //IL_00bb: Unknown result type (might be due to invalid IL or missing references) //IL_00c0: Unknown result type (might be due to invalid IL or missing references) //IL_00c8: 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_00d7: Unknown result type (might be due to invalid IL or missing references) //IL_00e0: Expected O, but got Unknown List<RemappableKey> remappableKeys = panel.remappableKeys; int num = remappableKeys.Count((RemappableKey key) => !key.gamepadOnly); foreach (LcInputActions inputAction in InputActions) { if (inputAction.Loaded) { continue; } foreach (InputActionReference actionRef in inputAction.ActionRefs) { InputBinding val = ((IEnumerable<InputBinding>)(object)actionRef.action.bindings).First(); string name = ((InputBinding)(ref val)).name; RemappableKey item = new RemappableKey { ControlName = name, currentInput = actionRef, gamepadOnly = false }; remappableKeys.Insert(num++, item); RemappableKey item2 = new RemappableKey { ControlName = name, currentInput = actionRef, rebindingIndex = 1, gamepadOnly = true }; remappableKeys.Add(item2); } inputAction.Loaded = true; } float horizontalOffset = panel.horizontalOffset; Rect rect = ((Component)((Transform)panel.keyRemapContainer).parent).GetComponent<RectTransform>().rect; float num2 = Mathf.Floor(((Rect)(ref rect)).width / horizontalOffset); panel.maxVertical = (float)num / num2; } internal static void CalculateVerticalMaxForGamepad(KepRemapPanel panel) { //IL_0042: Unknown result type (might be due to invalid IL or missing references) //IL_0047: Unknown result type (might be due to invalid IL or missing references) int num = panel.remappableKeys.Count((RemappableKey key) => key.gamepadOnly); float horizontalOffset = panel.horizontalOffset; Rect rect = ((Component)((Transform)panel.keyRemapContainer).parent).GetComponent<RectTransform>().rect; float num2 = Mathf.Floor(((Rect)(ref rect)).width / horizontalOffset); panel.maxVertical = (float)num / num2; } internal static void ResetLoadedInputActions() { foreach (LcInputActions inputAction in InputActions) { inputAction.Loaded = false; } } internal static void RegisterInputActions(LcInputActions lcInputActions, InputActionMapBuilder builder) { if (!InputActionsMap.TryAdd(lcInputActions.Id, lcInputActions)) { Logging.Logger.LogWarning((object)("The mod [" + lcInputActions.Plugin.GUID + "] instantiated an Actions class [" + lcInputActions.GetType().Name + "] more than once!\n\t These classes should be treated as singletons!, do not instantiate more than once!")); } else { lcInputActions.CreateInputActions(in builder); InputActionSetupExtensions.AddActionMap(lcInputActions.GetAsset(), builder.Build()); lcInputActions.GetAsset().Enable(); lcInputActions.OnAssetLoaded(); lcInputActions.Load(); lcInputActions.BuildActionRefs(); } } internal static void DisableForRebind() { foreach (LcInputActions inputAction in InputActions) { if (inputAction.Enabled) { inputAction.Disable(); } } } internal static void ReEnableFromRebind() { foreach (LcInputActions inputAction in InputActions) { if (inputAction.WasEnabled) { inputAction.Enable(); } } } internal static void SaveOverrides() { foreach (LcInputActions inputAction in InputActions) { inputAction.Save(); } } } [BepInPlugin("com.rune580.LethalCompanyInputUtils", "Lethal Company Input Utils", "0.4.3")] public class LethalCompanyInputUtilsPlugin : BaseUnityPlugin { public const string ModId = "com.rune580.LethalCompanyInputUtils"; public const string ModName = "Lethal Company Input Utils"; public const string ModVersion = "0.4.3"; private Harmony? _harmony; private void Awake() { Logging.SetLogSource(((BaseUnityPlugin)this).Logger); _harmony = Harmony.CreateAndPatchAll(Assembly.GetExecutingAssembly(), "com.rune580.LethalCompanyInputUtils"); SceneManager.activeSceneChanged += OnSceneChanged; FsUtils.EnsureControlsDir(); ((BaseUnityPlugin)this).Logger.LogInfo((object)"Plugin com.rune580.LethalCompanyInputUtils is loaded!"); } private static void OnSceneChanged(Scene current, Scene next) { LcInputActionApi.ResetLoadedInputActions(); } } } namespace LethalCompanyInputUtils.Utils { internal static class AssemblyUtils { public static BepInPlugin? GetBepInPlugin(this Assembly assembly) { Type[] exportedTypes = assembly.GetExportedTypes(); for (int i = 0; i < exportedTypes.Length; i++) { BepInPlugin customAttribute = ((MemberInfo)exportedTypes[i]).GetCustomAttribute<BepInPlugin>(); if (customAttribute != null) { return customAttribute; } } return null; } } internal static class FsUtils { public static string SaveDir { get; } = GetSaveDir(); public static string Pre041ControlsDir { get; } = Path.Combine(Paths.BepInExRootPath, "controls"); public static string ControlsDir { get; } = Path.Combine(Paths.ConfigPath, "controls"); private static string GetSaveDir() { string folderPath = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile); return Path.Combine(folderPath, "AppData", "LocalLow", "ZeekerssRBLX", "Lethal Company"); } public static void EnsureControlsDir() { if (!Directory.Exists(ControlsDir)) { Directory.CreateDirectory(ControlsDir); } } } internal static class Logging { private static ManualLogSource? _logSource; internal static ManualLogSource Logger { get; } = _logSource; internal static void SetLogSource(ManualLogSource logSource) { _logSource = logSource; } } } namespace LethalCompanyInputUtils.Patches { public static class InputControlPathPatches { [HarmonyPatch] public static class ToHumanReadableStringPatch { public static IEnumerable<MethodBase> TargetMethods() { return from method in AccessTools.GetDeclaredMethods(typeof(InputControlPath)) where method.Name == "ToHumanReadableString" && method.ReturnType == typeof(string) select method; } public static void Postfix(ref string __result) { string text = __result; if ((text == "<InputUtils-Gamepad-Not-Bound>" || text == "<InputUtils-Kbm-Not-Bound>") ? true : false) { __result = ""; } } } } public static class KeyRemapPanelPatches { [HarmonyPatch(typeof(KepRemapPanel), "LoadKeybindsUI")] public static class LoadKeybindsUIPatch { public static void Prefix(KepRemapPanel __instance) { LcInputActionApi.DisableForRebind(); LcInputActionApi.LoadIntoUI(__instance); } public static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions) { //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_000e: Expected O, but got Unknown //IL_0052: Unknown result type (might be due to invalid IL or missing references) //IL_0058: Expected O, but got Unknown //IL_0067: Unknown result type (might be due to invalid IL or missing references) //IL_006d: Expected O, but got Unknown //IL_008f: Unknown result type (might be due to invalid IL or missing references) //IL_0095: Expected O, but got Unknown //IL_00b7: Unknown result type (might be due to invalid IL or missing references) //IL_00bd: Expected O, but got Unknown //IL_00df: Unknown result type (might be due to invalid IL or missing references) //IL_00e5: Expected O, but got Unknown //IL_0107: Unknown result type (might be due to invalid IL or missing references) //IL_010d: Expected O, but got Unknown //IL_0122: Unknown result type (might be due to invalid IL or missing references) //IL_0128: Expected O, but got Unknown //IL_0162: Unknown result type (might be due to invalid IL or missing references) //IL_0168: Expected O, but got Unknown CodeMatcher val = new CodeMatcher(instructions, (ILGenerator)null); FieldInfo maxVerticalField = AccessTools.Field(typeof(KepRemapPanel), "maxVertical"); val.MatchForward(true, (CodeMatch[])(object)new CodeMatch[6] { new CodeMatch((Func<CodeInstruction, bool>)((CodeInstruction code) => CodeInstructionExtensions.IsLdarg(code, (int?)0)), (string)null), new CodeMatch((Func<CodeInstruction, bool>)((CodeInstruction code) => CodeInstructionExtensions.LoadsField(code, maxVerticalField, false)), (string)null), new CodeMatch((Func<CodeInstruction, bool>)((CodeInstruction code) => code.opcode == OpCodes.Ldc_R4 && (float)code.operand == 2f), (string)null), new CodeMatch((Func<CodeInstruction, bool>)((CodeInstruction code) => code.opcode == OpCodes.Add), (string)null), new CodeMatch((Func<CodeInstruction, bool>)((CodeInstruction code) => code.opcode == OpCodes.Conv_I4), (string)null), new CodeMatch((Func<CodeInstruction, bool>)((CodeInstruction code) => CodeInstructionExtensions.IsStloc(code, (LocalBuilder)null)), (string)null) }); val.InsertAndAdvance((CodeInstruction[])(object)new CodeInstruction[1] { new CodeInstruction(OpCodes.Ldarg_0, (object)null) }).InsertAndAdvance((CodeInstruction[])(object)new CodeInstruction[1] { new CodeInstruction(OpCodes.Call, (object)AccessTools.Method(typeof(LcInputActionApi), "CalculateVerticalMaxForGamepad", new Type[1] { typeof(KepRemapPanel) }, (Type[])null)) }); return val.InstructionEnumeration(); } } [HarmonyPatch(typeof(KepRemapPanel), "UnloadKeybindsUI")] public static class UnloadKeybindsUIPatch { public static void Prefix() { LcInputActionApi.SaveOverrides(); LcInputActionApi.ReEnableFromRebind(); } } } } namespace LethalCompanyInputUtils.Data { [Serializable] public struct BindingOverride { public string? action; public string? origPath; public string? path; } [Serializable] public class BindingOverrides { public List<BindingOverride> overrides; private BindingOverrides() { overrides = new List<BindingOverride>(); } public BindingOverrides(IEnumerable<InputBinding> bindings) { //IL_001b: Unknown result type (might be due to invalid IL or missing references) //IL_0020: Unknown result type (might be due to invalid IL or missing references) overrides = new List<BindingOverride>(); foreach (InputBinding binding in bindings) { InputBinding current = binding; if (((InputBinding)(ref current)).hasOverrides) { BindingOverride item = new BindingOverride { action = ((InputBinding)(ref current)).action, origPath = ((InputBinding)(ref current)).path, path = ((InputBinding)(ref current)).overridePath }; overrides.Add(item); } } } public void LoadInto(InputActionAsset asset) { foreach (BindingOverride @override in overrides) { InputAction obj = asset.FindAction(@override.action, false); if (obj != null) { InputActionRebindingExtensions.ApplyBindingOverride(obj, @override.path, (string)null, @override.origPath); } } } public static BindingOverrides FromJson(string json) { BindingOverrides bindingOverrides = new BindingOverrides(); JToken value = JsonConvert.DeserializeObject<JObject>(json).GetValue("overrides"); bindingOverrides.overrides = value.ToObject<List<BindingOverride>>(); return bindingOverrides; } } } namespace LethalCompanyInputUtils.Api { [AttributeUsage(AttributeTargets.Property)] public class InputActionAttribute : Attribute { public readonly string KbmPath; public string? ActionId { get; set; } public string? GamepadPath { get; set; } public InputActionType ActionType { get; set; } = (InputActionType)1; public string? KbmInteractions { get; set; } public string? GamepadInteractions { get; set; } public string? Name { get; set; } [Obsolete("Prefer using the named optional params instead.")] public InputActionAttribute(string action, string kbmPath, string gamepadPath) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) ActionId = action; KbmPath = kbmPath; GamepadPath = gamepadPath; } public InputActionAttribute(string kbmPath) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) KbmPath = kbmPath; } } public class InputActionBindingBuilder { private readonly InputActionMapBuilder _mapBuilder; private string? _actionId; private string? _kbmPath; private string? _gamepadPath; private string? _kbmInteractions; private string? _gamepadInteractions; private InputActionType _actionType; private string? _name; internal InputActionBindingBuilder(InputActionMapBuilder mapBuilder) { _mapBuilder = mapBuilder; } public InputActionBindingBuilder WithActionId(string actionId) { _actionId = actionId; return this; } public InputActionBindingBuilder WithKbmPath(string kbmPath) { _kbmPath = kbmPath; return this; } public InputActionBindingBuilder WithGamepadPath(string gamepadPath) { _gamepadPath = gamepadPath; return this; } public InputActionBindingBuilder WithKbmInteractions(string? kbmInteractions) { _kbmInteractions = kbmInteractions; return this; } public InputActionBindingBuilder WithGamepadInteractions(string? gamepadInteractions) { _gamepadInteractions = gamepadInteractions; return this; } public InputActionBindingBuilder WithActionType(InputActionType actionType) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0002: Unknown result type (might be due to invalid IL or missing references) _actionType = actionType; return this; } public InputActionBindingBuilder WithBindingName(string? name) { _name = name; return this; } public InputAction Finish() { //IL_001b: 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) //IL_002a: Expected O, but got Unknown //IL_005f: Unknown result type (might be due to invalid IL or missing references) //IL_0092: Unknown result type (might be due to invalid IL or missing references) if (_name == null) { _name = _actionId; } InputAction val = new InputAction(_actionId, _actionType, (string)null, (string)null, (string)null, (string)null); _mapBuilder.WithAction(val); if (_kbmPath != null) { _mapBuilder.WithBinding(new InputBinding(_kbmPath, _actionId, (string)null, (string)null, _kbmInteractions, _name)); } if (_gamepadPath != null) { _mapBuilder.WithBinding(new InputBinding(_gamepadPath, _actionId, (string)null, (string)null, _gamepadInteractions, _name)); } return val; } } public class InputActionMapBuilder { private readonly InputActionMap _actionMap = new InputActionMap(mapName); public InputActionMapBuilder(string mapName) { }//IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_000c: Expected O, but got Unknown public InputActionMapBuilder WithAction(InputAction action) { //IL_000d: Unknown result type (might be due to invalid IL or missing references) InputActionSetupExtensions.AddAction(_actionMap, action.name, action.type, (string)null, (string)null, (string)null, (string)null, (string)null); return this; } public InputActionMapBuilder WithBinding(InputBinding binding) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Unknown result type (might be due to invalid IL or missing references) InputActionSetupExtensions.AddBinding(_actionMap, binding); return this; } public InputActionBindingBuilder NewActionBinding() { return new InputActionBindingBuilder(this); } internal InputActionMap Build() { return _actionMap; } } public abstract class LcInputActions { public const string UnboundKeyboardAndMouseIdentifier = "<InputUtils-Kbm-Not-Bound>"; public const string UnboundGamepadIdentifier = "<InputUtils-Gamepad-Not-Bound>"; private readonly string _jsonPath; private readonly List<InputActionReference> _actionRefs = new List<InputActionReference>(); internal bool Loaded; private readonly Dictionary<PropertyInfo, InputActionAttribute> _inputProps; public InputActionAsset Asset { get; } internal bool WasEnabled { get; private set; } public bool Enabled => Asset.enabled; internal IReadOnlyCollection<InputActionReference> ActionRefs => _actionRefs; internal string Id => Plugin.GUID + "." + MapName; public BepInPlugin Plugin { get; } protected virtual string MapName => GetType().Name; internal InputActionAsset GetAsset() { return Asset; } protected LcInputActions() { //IL_0118: Unknown result type (might be due to invalid IL or missing references) Asset = ScriptableObject.CreateInstance<InputActionAsset>(); Plugin = Assembly.GetCallingAssembly().GetBepInPlugin() ?? throw new InvalidOperationException(); _jsonPath = Path.Combine(FsUtils.ControlsDir, Id + ".json"); InputActionMapBuilder inputActionMapBuilder = new InputActionMapBuilder(Id); PropertyInfo[] properties = GetType().GetProperties(); _inputProps = new Dictionary<PropertyInfo, InputActionAttribute>(); PropertyInfo[] array = properties; foreach (PropertyInfo propertyInfo in array) { InputActionAttribute customAttribute = propertyInfo.GetCustomAttribute<InputActionAttribute>(); if (customAttribute != null && !(propertyInfo.PropertyType != typeof(InputAction))) { InputActionAttribute inputActionAttribute = customAttribute; if (inputActionAttribute.ActionId == null) { string text = (inputActionAttribute.ActionId = propertyInfo.Name); } inputActionAttribute = customAttribute; if (inputActionAttribute.GamepadPath == null) { string text = (inputActionAttribute.GamepadPath = "<InputUtils-Gamepad-Not-Bound>"); } string kbmPath = (string.IsNullOrEmpty(customAttribute.KbmPath) ? "<InputUtils-Kbm-Not-Bound>" : customAttribute.KbmPath); inputActionMapBuilder.NewActionBinding().WithActionId(customAttribute.ActionId).WithActionType(customAttribute.ActionType) .WithBindingName(customAttribute.Name) .WithKbmPath(kbmPath) .WithGamepadPath(customAttribute.GamepadPath) .WithKbmInteractions(customAttribute.KbmInteractions) .WithGamepadInteractions(customAttribute.GamepadInteractions) .Finish(); _inputProps[propertyInfo] = customAttribute; } } LcInputActionApi.RegisterInputActions(this, inputActionMapBuilder); } public virtual void CreateInputActions(in InputActionMapBuilder builder) { } public virtual void OnAssetLoaded() { } internal void BuildActionRefs() { //IL_0061: Unknown result type (might be due to invalid IL or missing references) foreach (KeyValuePair<PropertyInfo, InputActionAttribute> inputProp in _inputProps) { inputProp.Deconstruct(out var key, out var value); PropertyInfo propertyInfo = key; InputActionAttribute inputActionAttribute = value; InputAction value2 = Asset.FindAction(inputActionAttribute.ActionId, false); propertyInfo.SetValue(this, value2); } IEnumerable<InputActionReference> collection = ((IEnumerable<InputActionMap>)(object)Asset.actionMaps).SelectMany((InputActionMap map) => (IEnumerable<InputAction>)(object)map.actions).Select((Func<InputAction, InputActionReference>)InputActionReference.Create); _actionRefs.AddRange(collection); } public void Enable() { WasEnabled = Asset.enabled; Asset.Enable(); } public void Disable() { WasEnabled = Asset.enabled; Asset.Disable(); } internal void Save() { BindingOverrides bindingOverrides = new BindingOverrides(Asset.bindings); File.WriteAllText(_jsonPath, JsonConvert.SerializeObject((object)bindingOverrides)); } internal void Load() { try { ApplyMigrations(); } catch (Exception ex) { Logging.Logger.LogError((object)"Got error when applying migrations, skipping..."); Logging.Logger.LogError((object)ex); } if (!File.Exists(_jsonPath)) { return; } try { BindingOverrides.FromJson(File.ReadAllText(_jsonPath)).LoadInto(Asset); } catch (Exception ex2) { Logging.Logger.LogError((object)ex2); } } private void ApplyMigrations() { string text = Path.Combine(FsUtils.Pre041ControlsDir, Id + ".json"); if (File.Exists(text) && !File.Exists(_jsonPath)) { File.Move(text, _jsonPath); } if (!File.Exists(_jsonPath) || !File.ReadAllText(_jsonPath).Replace(" ", "").Contains("\"origPath\":\"\"")) { return; } BindingOverrides bindingOverrides = BindingOverrides.FromJson(File.ReadAllText(_jsonPath)); for (int i = 0; i < bindingOverrides.overrides.Count; i++) { BindingOverride value = bindingOverrides.overrides[i]; if (string.IsNullOrEmpty(value.origPath) && value.path != null) { if (value.path.StartsWith("<Keyboard>") || value.path.StartsWith("<Mouse>")) { value.origPath = "<InputUtils-Kbm-Not-Bound>"; } else { value.origPath = "<InputUtils-Gamepad-Not-Bound>"; } bindingOverrides.overrides[i] = value; } } File.WriteAllText(_jsonPath, JsonConvert.SerializeObject((object)bindingOverrides)); } } }
plugins/LethalLib.dll
Decompiled 11 months agousing 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.Logging; using DunGen; using DunGen.Graph; using LethalLib.Extras; using LethalLib.Modules; using Microsoft.CodeAnalysis; using Mono.Cecil.Cil; using MonoMod.Cil; using MonoMod.RuntimeDetour; using On; 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(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")] [assembly: AssemblyCompany("LethalLib")] [assembly: AssemblyConfiguration("Debug")] [assembly: AssemblyDescription("Mod for Lethal Company")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: AssemblyInformationalVersion("1.0.0+5272a22ecea7cc9a1502e3224fcb6d6e2507c9ee")] [assembly: AssemblyProduct("LethalLib")] [assembly: AssemblyTitle("LethalLib")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("1.0.0.0")] [module: UnverifiableCode] [module: RefSafetyRules(11)] 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.Module, AllowMultiple = false, Inherited = false)] internal sealed class RefSafetyRulesAttribute : Attribute { public readonly int Version; public RefSafetyRulesAttribute(int P_0) { Version = P_0; } } } namespace LethalLib { [BepInPlugin("evaisa.lethallib", "LethalLib", "0.6.3")] public class Plugin : BaseUnityPlugin { public const string ModGUID = "evaisa.lethallib"; public const string ModName = "LethalLib"; public const string ModVersion = "0.6.3"; public static AssetBundle MainAssets; public static ManualLogSource logger; private void Awake() { //IL_003a: Unknown result type (might be due to invalid IL or missing references) //IL_0044: Expected O, but got Unknown //IL_003f: Unknown result type (might be due to invalid IL or missing references) logger = ((BaseUnityPlugin)this).Logger; ((BaseUnityPlugin)this).Logger.LogInfo((object)"LethalLib loaded!!"); new ILHook((MethodBase)typeof(StackTrace).GetMethod("AddFrames", BindingFlags.Instance | BindingFlags.NonPublic), new Manipulator(IlHook)); Enemies.Init(); Items.Init(); Unlockables.Init(); MapObjects.Init(); Dungeon.Init(); NetworkPrefabs.Init(); } private void IlHook(ILContext il) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0008: Expected O, but got Unknown ILCursor val = new ILCursor(il); val.GotoNext(new Func<Instruction, bool>[1] { (Instruction x) => ILPatternMatchingExt.MatchCallvirt(x, (MethodBase)typeof(StackFrame).GetMethod("GetFileLineNumber", BindingFlags.Instance | BindingFlags.Public)) }); val.RemoveRange(2); val.EmitDelegate<Func<StackFrame, string>>((Func<StackFrame, string>)GetLineOrIL); } private static string GetLineOrIL(StackFrame instance) { int fileLineNumber = instance.GetFileLineNumber(); if (fileLineNumber == -1 || fileLineNumber == 0) { return "IL_" + instance.GetILOffset().ToString("X4"); } return fileLineNumber.ToString(); } } } namespace LethalLib.Modules { public class Dungeon { public class CustomDungeonArchetype { public DungeonArchetype archeType; public Levels.LevelTypes LevelTypes; public int lineIndex = -1; } public class CustomGraphLine { public GraphLine graphLine; public Levels.LevelTypes LevelTypes; } public class CustomDungeon { public int rarity; public DungeonFlow dungeonFlow; public Levels.LevelTypes LevelTypes; public int dungeonIndex = -1; public AudioClip firstTimeDungeonAudio; } [CompilerGenerated] private static class <>O { public static hook_GenerateNewFloor <0>__RoundManager_GenerateNewFloor; public static hook_Start <1>__RoundManager_Start; public static hook_Start <2>__StartOfRound_Start; } public static List<CustomDungeonArchetype> customDungeonArchetypes = new List<CustomDungeonArchetype>(); public static List<CustomGraphLine> customGraphLines = new List<CustomGraphLine>(); public static Dictionary<string, TileSet> extraTileSets = new Dictionary<string, TileSet>(); public static Dictionary<string, GameObjectChance> extraRooms = new Dictionary<string, GameObjectChance>(); public static List<CustomDungeon> customDungeons = new List<CustomDungeon>(); public static void Init() { //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) //IL_001c: Expected O, but got Unknown //IL_0032: Unknown result type (might be due to invalid IL or missing references) //IL_0037: Unknown result type (might be due to invalid IL or missing references) //IL_003d: Expected O, but got Unknown //IL_0053: Unknown result type (might be due to invalid IL or missing references) //IL_0058: Unknown result type (might be due to invalid IL or missing references) //IL_005e: Expected O, but got Unknown object obj = <>O.<0>__RoundManager_GenerateNewFloor; if (obj == null) { hook_GenerateNewFloor val = RoundManager_GenerateNewFloor; <>O.<0>__RoundManager_GenerateNewFloor = val; obj = (object)val; } RoundManager.GenerateNewFloor += (hook_GenerateNewFloor)obj; object obj2 = <>O.<1>__RoundManager_Start; if (obj2 == null) { hook_Start val2 = RoundManager_Start; <>O.<1>__RoundManager_Start = val2; obj2 = (object)val2; } RoundManager.Start += (hook_Start)obj2; object obj3 = <>O.<2>__StartOfRound_Start; if (obj3 == null) { hook_Start val3 = StartOfRound_Start; <>O.<2>__StartOfRound_Start = val3; obj3 = (object)val3; } StartOfRound.Start += (hook_Start)obj3; } private static void StartOfRound_Start(orig_Start orig, StartOfRound self) { //IL_00df: Unknown result type (might be due to invalid IL or missing references) //IL_00e4: Unknown result type (might be due to invalid IL or missing references) //IL_00f5: Unknown result type (might be due to invalid IL or missing references) //IL_010b: Expected O, but got Unknown foreach (CustomDungeon dungeon in customDungeons) { SelectableLevel[] levels = self.levels; foreach (SelectableLevel val in levels) { string name = ((Object)val).name; if (Enum.IsDefined(typeof(Levels.LevelTypes), name)) { Levels.LevelTypes levelTypes = (Levels.LevelTypes)Enum.Parse(typeof(Levels.LevelTypes), name); if (dungeon.LevelTypes.HasFlag(levelTypes) && !val.dungeonFlowTypes.Any((IntWithRarity rarityInt) => rarityInt.id == dungeon.dungeonIndex)) { List<IntWithRarity> list = val.dungeonFlowTypes.ToList(); list.Add(new IntWithRarity { id = dungeon.dungeonIndex, rarity = dungeon.rarity }); val.dungeonFlowTypes = list.ToArray(); } } } } Plugin.logger.LogInfo((object)"Added custom dungeons to levels"); orig.Invoke(self); } private static void RoundManager_Start(orig_Start orig, RoundManager self) { foreach (CustomDungeon customDungeon in customDungeons) { if (self.dungeonFlowTypes.Contains(customDungeon.dungeonFlow)) { continue; } List<DungeonFlow> list = self.dungeonFlowTypes.ToList(); list.Add(customDungeon.dungeonFlow); self.dungeonFlowTypes = list.ToArray(); int dungeonIndex = self.dungeonFlowTypes.Length - 1; customDungeon.dungeonIndex = dungeonIndex; List<AudioClip> list2 = self.firstTimeDungeonAudios.ToList(); if (list2.Count != self.dungeonFlowTypes.Length - 1) { while (list2.Count < self.dungeonFlowTypes.Length - 1) { list2.Add(null); } } list2.Add(customDungeon.firstTimeDungeonAudio); self.firstTimeDungeonAudios = list2.ToArray(); } orig.Invoke(self); } private static void RoundManager_GenerateNewFloor(orig_GenerateNewFloor orig, RoundManager self) { string name = ((Object)self.currentLevel).name; if (Enum.IsDefined(typeof(Levels.LevelTypes), name)) { Levels.LevelTypes levelEnum = (Levels.LevelTypes)Enum.Parse(typeof(Levels.LevelTypes), name); int index = 0; self.dungeonGenerator.Generator.DungeonFlow.Lines.ForEach(delegate(GraphLine line) { foreach (CustomDungeonArchetype customDungeonArchetype in customDungeonArchetypes) { if (customDungeonArchetype.LevelTypes.HasFlag(levelEnum) && !line.DungeonArchetypes.Contains(customDungeonArchetype.archeType) && (customDungeonArchetype.lineIndex == -1 || customDungeonArchetype.lineIndex == index)) { line.DungeonArchetypes.Add(customDungeonArchetype.archeType); Plugin.logger.LogInfo((object)("Added " + ((Object)customDungeonArchetype.archeType).name + " to " + name)); } } foreach (DungeonArchetype dungeonArchetype in line.DungeonArchetypes) { string name2 = ((Object)dungeonArchetype).name; if (extraTileSets.ContainsKey(name2)) { TileSet val4 = extraTileSets[name2]; if (!dungeonArchetype.TileSets.Contains(val4)) { dungeonArchetype.TileSets.Add(val4); Plugin.logger.LogInfo((object)("Added " + ((Object)val4).name + " to " + name)); } } foreach (TileSet tileSet in dungeonArchetype.TileSets) { string name3 = ((Object)tileSet).name; if (extraRooms.ContainsKey(name3)) { GameObjectChance item = extraRooms[name3]; if (!tileSet.TileWeights.Weights.Contains(item)) { tileSet.TileWeights.Weights.Add(item); } } } } index++; }); foreach (CustomGraphLine customGraphLine in customGraphLines) { if (customGraphLine.LevelTypes.HasFlag(levelEnum) && !self.dungeonGenerator.Generator.DungeonFlow.Lines.Contains(customGraphLine.graphLine)) { self.dungeonGenerator.Generator.DungeonFlow.Lines.Add(customGraphLine.graphLine); } } } orig.Invoke(self); NetworkManager val = Object.FindObjectOfType<NetworkManager>(); RandomMapObject[] array = Object.FindObjectsOfType<RandomMapObject>(); RandomMapObject[] array2 = array; foreach (RandomMapObject val2 in array2) { for (int j = 0; j < val2.spawnablePrefabs.Count; j++) { string prefabName = ((Object)val2.spawnablePrefabs[j]).name; NetworkPrefab val3 = val.NetworkConfig.Prefabs.m_Prefabs.First((NetworkPrefab x) => ((Object)x.Prefab).name == prefabName); if (val3 != null && (Object)(object)val3.Prefab != (Object)(object)val2.spawnablePrefabs[j]) { val2.spawnablePrefabs[j] = val3.Prefab; } } } } public static void AddArchetype(DungeonArchetype archetype, Levels.LevelTypes levelFlags, int lineIndex = -1) { CustomDungeonArchetype customDungeonArchetype = new CustomDungeonArchetype(); customDungeonArchetype.archeType = archetype; customDungeonArchetype.LevelTypes = levelFlags; customDungeonArchetype.lineIndex = lineIndex; customDungeonArchetypes.Add(customDungeonArchetype); } public static void AddLine(GraphLine line, Levels.LevelTypes levelFlags) { CustomGraphLine customGraphLine = new CustomGraphLine(); customGraphLine.graphLine = line; customGraphLine.LevelTypes = levelFlags; customGraphLines.Add(customGraphLine); } public static void AddLine(DungeonGraphLineDef line, Levels.LevelTypes levelFlags) { AddLine(line.graphLine, levelFlags); } public static void AddTileSet(TileSet set, string archetypeName) { extraTileSets.Add(archetypeName, set); } public static void AddRoom(GameObjectChance room, string tileSetName) { extraRooms.Add(tileSetName, room); } public static void AddRoom(GameObjectChanceDef room, string tileSetName) { AddRoom(room.gameObjectChance, tileSetName); } public static void AddDungeon(DungeonDef dungeon, Levels.LevelTypes levelFlags) { AddDungeon(dungeon.dungeonFlow, dungeon.rarity, levelFlags, dungeon.firstTimeDungeonAudio); } public static void AddDungeon(DungeonFlow dungeon, int rarity, Levels.LevelTypes levelFlags, AudioClip firstTimeDungeonAudio = null) { customDungeons.Add(new CustomDungeon { dungeonFlow = dungeon, rarity = rarity, LevelTypes = levelFlags, firstTimeDungeonAudio = firstTimeDungeonAudio }); } } public class Enemies { public enum SpawnType { Default, Daytime, Outside } public class SpawnableEnemy { public EnemyType enemy; public int rarity; public Levels.LevelTypes spawnLevels; public SpawnType spawnType; public TerminalNode terminalNode; public TerminalKeyword infoKeyword; public string modName; public SpawnableEnemy(EnemyType enemy, int rarity, Levels.LevelTypes spawnLevels, SpawnType spawnType) { this.enemy = enemy; this.rarity = rarity; this.spawnLevels = spawnLevels; this.spawnType = spawnType; } } [CompilerGenerated] private static class <>O { public static hook_Awake <0>__RegisterLevelEnemies; public static hook_Start <1>__Terminal_Start; } public static List<SpawnableEnemy> spawnableEnemies = new List<SpawnableEnemy>(); public static void Init() { //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) //IL_001c: Expected O, but got Unknown //IL_0032: Unknown result type (might be due to invalid IL or missing references) //IL_0037: Unknown result type (might be due to invalid IL or missing references) //IL_003d: Expected O, but got Unknown object obj = <>O.<0>__RegisterLevelEnemies; if (obj == null) { hook_Awake val = RegisterLevelEnemies; <>O.<0>__RegisterLevelEnemies = val; obj = (object)val; } StartOfRound.Awake += (hook_Awake)obj; object obj2 = <>O.<1>__Terminal_Start; if (obj2 == null) { hook_Start val2 = Terminal_Start; <>O.<1>__Terminal_Start = val2; obj2 = (object)val2; } Terminal.Start += (hook_Start)obj2; } private static void Terminal_Start(orig_Start orig, Terminal self) { //IL_0273: Unknown result type (might be due to invalid IL or missing references) //IL_0278: Unknown result type (might be due to invalid IL or missing references) //IL_0285: Unknown result type (might be due to invalid IL or missing references) //IL_029b: Expected O, but got Unknown TerminalKeyword val = self.terminalNodes.allKeywords.First((TerminalKeyword keyword) => keyword.word == "info"); List<string> list = new List<string>(); foreach (SpawnableEnemy spawnableEnemy in spawnableEnemies) { if (list.Contains(spawnableEnemy.enemy.enemyName)) { Plugin.logger.LogInfo((object)("Skipping " + spawnableEnemy.enemy.enemyName + " because it was already added")); continue; } if ((Object)(object)spawnableEnemy.terminalNode == (Object)null) { spawnableEnemy.terminalNode = ScriptableObject.CreateInstance<TerminalNode>(); spawnableEnemy.terminalNode.displayText = spawnableEnemy.enemy.enemyName + "\n\nDanger level: Unknown\n\n[No information about this creature was found.]\n\n"; spawnableEnemy.terminalNode.clearPreviousText = true; spawnableEnemy.terminalNode.maxCharactersToType = 35; spawnableEnemy.terminalNode.creatureName = spawnableEnemy.enemy.enemyName; } if (self.enemyFiles.Any((TerminalNode x) => x.creatureName == spawnableEnemy.terminalNode.creatureName)) { Plugin.logger.LogInfo((object)("Skipping " + spawnableEnemy.enemy.enemyName + " because it was already added")); continue; } TerminalKeyword keyword2 = (((Object)(object)spawnableEnemy.infoKeyword != (Object)null) ? spawnableEnemy.infoKeyword : TerminalUtils.CreateTerminalKeyword(spawnableEnemy.terminalNode.creatureName.ToLowerInvariant().Replace(" ", "-"), isVerb: false, null, null, val)); keyword2.defaultVerb = val; List<TerminalKeyword> list2 = self.terminalNodes.allKeywords.ToList(); if (!list2.Any((TerminalKeyword x) => x.word == keyword2.word)) { list2.Add(keyword2); self.terminalNodes.allKeywords = list2.ToArray(); } List<CompatibleNoun> list3 = val.compatibleNouns.ToList(); if (!list3.Any((CompatibleNoun x) => x.noun.word == keyword2.word)) { list3.Add(new CompatibleNoun { noun = keyword2, result = spawnableEnemy.terminalNode }); } val.compatibleNouns = list3.ToArray(); spawnableEnemy.terminalNode.creatureFileID = self.enemyFiles.Count; self.enemyFiles.Add(spawnableEnemy.terminalNode); spawnableEnemy.enemy.enemyPrefab.GetComponentInChildren<ScanNodeProperties>().creatureScanID = spawnableEnemy.terminalNode.creatureFileID; } orig.Invoke(self); } private static void RegisterLevelEnemies(orig_Awake orig, StartOfRound self) { //IL_00a4: Unknown result type (might be due to invalid IL or missing references) //IL_00a9: Unknown result type (might be due to invalid IL or missing references) //IL_00bb: Unknown result type (might be due to invalid IL or missing references) //IL_00cf: Expected O, but got Unknown orig.Invoke(self); SelectableLevel[] levels = self.levels; foreach (SelectableLevel val in levels) { string name = ((Object)val).name; if (!Enum.IsDefined(typeof(Levels.LevelTypes), name)) { continue; } Levels.LevelTypes levelTypes = (Levels.LevelTypes)Enum.Parse(typeof(Levels.LevelTypes), name); foreach (SpawnableEnemy spawnableEnemy in spawnableEnemies) { if (!spawnableEnemy.spawnLevels.HasFlag(levelTypes)) { continue; } SpawnableEnemyWithRarity item = new SpawnableEnemyWithRarity { enemyType = spawnableEnemy.enemy, rarity = spawnableEnemy.rarity }; switch (spawnableEnemy.spawnType) { case SpawnType.Default: if (!val.Enemies.Any((SpawnableEnemyWithRarity x) => (Object)(object)x.enemyType == (Object)(object)spawnableEnemy.enemy)) { val.Enemies.Add(item); Plugin.logger.LogInfo((object)("Added " + ((Object)spawnableEnemy.enemy).name + " to " + name + " with SpawnType [Default]")); } break; case SpawnType.Daytime: if (!val.DaytimeEnemies.Any((SpawnableEnemyWithRarity x) => (Object)(object)x.enemyType == (Object)(object)spawnableEnemy.enemy)) { val.DaytimeEnemies.Add(item); Plugin.logger.LogInfo((object)("Added " + ((Object)spawnableEnemy.enemy).name + " to " + name + " with SpawnType [Daytime]")); } break; case SpawnType.Outside: if (!val.OutsideEnemies.Any((SpawnableEnemyWithRarity x) => (Object)(object)x.enemyType == (Object)(object)spawnableEnemy.enemy)) { val.OutsideEnemies.Add(item); Plugin.logger.LogInfo((object)("Added " + ((Object)spawnableEnemy.enemy).name + " to " + name + " with SpawnType [Outside]")); } break; } } } } public static void RegisterEnemy(EnemyType enemy, int rarity, Levels.LevelTypes levelFlags, SpawnType spawnType, TerminalNode infoNode = null, TerminalKeyword infoKeyword = null) { SpawnableEnemy spawnableEnemy = new SpawnableEnemy(enemy, rarity, levelFlags, spawnType); spawnableEnemy.terminalNode = infoNode; spawnableEnemy.infoKeyword = infoKeyword; Assembly callingAssembly = Assembly.GetCallingAssembly(); string name = callingAssembly.GetName().Name; spawnableEnemy.modName = name; spawnableEnemies.Add(spawnableEnemy); } public static void RegisterEnemy(EnemyType enemy, int rarity, Levels.LevelTypes levelFlags, TerminalNode infoNode = null, TerminalKeyword infoKeyword = null) { SpawnableEnemy spawnableEnemy = new SpawnableEnemy(enemy, rarity, levelFlags, enemy.isDaytimeEnemy ? SpawnType.Daytime : (enemy.isOutsideEnemy ? SpawnType.Outside : SpawnType.Default)); spawnableEnemy.terminalNode = infoNode; spawnableEnemy.infoKeyword = infoKeyword; Assembly callingAssembly = Assembly.GetCallingAssembly(); string name = callingAssembly.GetName().Name; spawnableEnemy.modName = name; spawnableEnemies.Add(spawnableEnemy); } } public class Items { public class ScrapItem { public Item item; public int rarity; public Levels.LevelTypes spawnLevels; public string modName; public ScrapItem(Item item, int rarity, Levels.LevelTypes spawnLevels) { this.item = item; this.rarity = rarity; this.spawnLevels = spawnLevels; } } public class PlainItem { public Item item; public string modName; public PlainItem(Item item) { this.item = item; } } public class ShopItem { public Item item; public TerminalNode buyNode1; public TerminalNode buyNode2; public TerminalNode itemInfo; public int price; public string modName; public ShopItem(Item item, TerminalNode buyNode1 = null, TerminalNode buyNode2 = null, TerminalNode itemInfo = null, int price = 0) { this.item = item; this.price = price; if ((Object)(object)buyNode1 != (Object)null) { this.buyNode1 = buyNode1; } if ((Object)(object)buyNode2 != (Object)null) { this.buyNode2 = buyNode2; } if ((Object)(object)itemInfo != (Object)null) { this.itemInfo = itemInfo; } } } [CompilerGenerated] private static class <>O { public static hook_Awake <0>__StartOfRound_Awake; public static hook_Awake <1>__Terminal_Awake; } public static List<ScrapItem> scrapItems = new List<ScrapItem>(); public static List<ShopItem> shopItems = new List<ShopItem>(); public static List<PlainItem> plainItems = new List<PlainItem>(); public static void Init() { //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) //IL_001c: Expected O, but got Unknown //IL_0032: Unknown result type (might be due to invalid IL or missing references) //IL_0037: Unknown result type (might be due to invalid IL or missing references) //IL_003d: Expected O, but got Unknown object obj = <>O.<0>__StartOfRound_Awake; if (obj == null) { hook_Awake val = StartOfRound_Awake; <>O.<0>__StartOfRound_Awake = val; obj = (object)val; } StartOfRound.Awake += (hook_Awake)obj; object obj2 = <>O.<1>__Terminal_Awake; if (obj2 == null) { hook_Awake val2 = Terminal_Awake; <>O.<1>__Terminal_Awake = val2; obj2 = (object)val2; } Terminal.Awake += (hook_Awake)obj2; } private static void Terminal_Awake(orig_Awake orig, Terminal self) { //IL_02fe: Unknown result type (might be due to invalid IL or missing references) //IL_0303: Unknown result type (might be due to invalid IL or missing references) //IL_0338: Unknown result type (might be due to invalid IL or missing references) //IL_0341: Expected O, but got Unknown //IL_0343: Unknown result type (might be due to invalid IL or missing references) //IL_0348: Unknown result type (might be due to invalid IL or missing references) //IL_037d: Unknown result type (might be due to invalid IL or missing references) //IL_0385: Expected O, but got Unknown //IL_03e9: Unknown result type (might be due to invalid IL or missing references) //IL_03ee: Unknown result type (might be due to invalid IL or missing references) //IL_03f6: Unknown result type (might be due to invalid IL or missing references) //IL_0403: Expected O, but got Unknown //IL_0497: Unknown result type (might be due to invalid IL or missing references) //IL_049c: Unknown result type (might be due to invalid IL or missing references) //IL_04a4: Unknown result type (might be due to invalid IL or missing references) //IL_04b1: Expected O, but got Unknown List<Item> list = self.buyableItemsList.ToList(); TerminalKeyword val = self.terminalNodes.allKeywords.First((TerminalKeyword keyword) => keyword.word == "buy"); TerminalNode result = val.compatibleNouns[0].result.terminalOptions[1].result; TerminalKeyword val2 = self.terminalNodes.allKeywords.First((TerminalKeyword keyword) => keyword.word == "info"); Plugin.logger.LogInfo((object)$"Adding {shopItems.Count} items to terminal"); foreach (ShopItem item in shopItems) { if (list.Any((Item x) => x.itemName == item.item.itemName)) { Plugin.logger.LogInfo((object)("Item " + item.item.itemName + " already exists in terminal, skipping")); continue; } if (item.price == -1) { item.price = item.item.creditsWorth; } else { item.item.creditsWorth = item.price; } list.Add(item.item); string itemName = item.item.itemName; char c = itemName[itemName.Length - 1]; string text = itemName; TerminalNode val3 = item.buyNode2; if ((Object)(object)val3 == (Object)null) { val3 = ScriptableObject.CreateInstance<TerminalNode>(); ((Object)val3).name = itemName.Replace(" ", "-") + "BuyNode2"; val3.displayText = "Ordered [variableAmount] " + text + ". Your new balance is [playerCredits].\n\nOur contractors enjoy fast, free shipping while on the job! Any purchased items will arrive hourly at your approximate location.\r\n\r\n"; val3.clearPreviousText = true; val3.maxCharactersToType = 15; } val3.buyItemIndex = list.Count - 1; val3.isConfirmationNode = false; val3.itemCost = item.price; val3.playSyncedClip = 0; TerminalNode val4 = item.buyNode1; if ((Object)(object)val4 == (Object)null) { val4 = ScriptableObject.CreateInstance<TerminalNode>(); ((Object)val4).name = itemName.Replace(" ", "-") + "BuyNode1"; val4.displayText = "You have requested to order " + text + ". Amount: [variableAmount].\nTotal cost of items: [totalCost].\n\nPlease CONFIRM or DENY.\r\n\r\n"; val4.clearPreviousText = true; val4.maxCharactersToType = 35; } val4.buyItemIndex = list.Count - 1; val4.isConfirmationNode = true; val4.overrideOptions = true; val4.itemCost = item.price; val4.terminalOptions = (CompatibleNoun[])(object)new CompatibleNoun[2] { new CompatibleNoun { noun = self.terminalNodes.allKeywords.First((TerminalKeyword keyword2) => keyword2.word == "confirm"), result = val3 }, new CompatibleNoun { noun = self.terminalNodes.allKeywords.First((TerminalKeyword keyword2) => keyword2.word == "deny"), result = result } }; TerminalKeyword val5 = TerminalUtils.CreateTerminalKeyword(itemName.ToLowerInvariant().Replace(" ", "-"), isVerb: false, null, null, val); List<TerminalKeyword> list2 = self.terminalNodes.allKeywords.ToList(); list2.Add(val5); self.terminalNodes.allKeywords = list2.ToArray(); List<CompatibleNoun> list3 = val.compatibleNouns.ToList(); list3.Add(new CompatibleNoun { noun = val5, result = val4 }); val.compatibleNouns = list3.ToArray(); TerminalNode val6 = item.itemInfo; if ((Object)(object)val6 == (Object)null) { val6 = ScriptableObject.CreateInstance<TerminalNode>(); ((Object)val6).name = itemName.Replace(" ", "-") + "InfoNode"; val6.displayText = "[No information about this object was found.]\n\n"; val6.clearPreviousText = true; val6.maxCharactersToType = 25; } self.terminalNodes.allKeywords = list2.ToArray(); List<CompatibleNoun> list4 = val2.compatibleNouns.ToList(); list4.Add(new CompatibleNoun { noun = val5, result = val6 }); val2.compatibleNouns = list4.ToArray(); Plugin.logger.LogInfo((object)(item.modName + " registered item: " + item.item.itemName)); } self.buyableItemsList = list.ToArray(); orig.Invoke(self); } private static void StartOfRound_Awake(orig_Awake orig, StartOfRound self) { //IL_00a1: Unknown result type (might be due to invalid IL or missing references) //IL_00a6: Unknown result type (might be due to invalid IL or missing references) //IL_00b8: Unknown result type (might be due to invalid IL or missing references) //IL_00cc: Expected O, but got Unknown orig.Invoke(self); SelectableLevel[] levels = self.levels; foreach (SelectableLevel val in levels) { string name = ((Object)val).name; if (!Enum.IsDefined(typeof(Levels.LevelTypes), name)) { continue; } Levels.LevelTypes levelTypes = (Levels.LevelTypes)Enum.Parse(typeof(Levels.LevelTypes), name); foreach (ScrapItem scrapItem in scrapItems) { if (scrapItem.spawnLevels.HasFlag(levelTypes)) { SpawnableItemWithRarity item = new SpawnableItemWithRarity { spawnableItem = scrapItem.item, rarity = scrapItem.rarity }; if (!val.spawnableScrap.Any((SpawnableItemWithRarity x) => (Object)(object)x.spawnableItem == (Object)(object)scrapItem.item)) { val.spawnableScrap.Add(item); } } } } foreach (ScrapItem scrapItem2 in scrapItems) { if (!self.allItemsList.itemsList.Contains(scrapItem2.item)) { Plugin.logger.LogInfo((object)(scrapItem2.modName + " registered item: " + scrapItem2.item.itemName)); self.allItemsList.itemsList.Add(scrapItem2.item); } } foreach (ShopItem shopItem in shopItems) { if (!self.allItemsList.itemsList.Contains(shopItem.item)) { Plugin.logger.LogInfo((object)(shopItem.modName + " registered item: " + shopItem.item.itemName)); self.allItemsList.itemsList.Add(shopItem.item); } } foreach (PlainItem plainItem in plainItems) { if (!self.allItemsList.itemsList.Contains(plainItem.item)) { Plugin.logger.LogInfo((object)(plainItem.modName + " registered item: " + plainItem.item.itemName)); self.allItemsList.itemsList.Add(plainItem.item); } } } public static void RegisterScrap(Item spawnableItem, int rarity, Levels.LevelTypes levelFlags) { ScrapItem scrapItem = new ScrapItem(spawnableItem, rarity, levelFlags); Assembly callingAssembly = Assembly.GetCallingAssembly(); string name = callingAssembly.GetName().Name; scrapItem.modName = name; scrapItems.Add(scrapItem); } public static void RegisterShopItem(Item shopItem, TerminalNode buyNode1 = null, TerminalNode buyNode2 = null, TerminalNode itemInfo = null, int price = -1) { ShopItem shopItem2 = new ShopItem(shopItem, buyNode1, buyNode2, itemInfo, price); Assembly callingAssembly = Assembly.GetCallingAssembly(); string name = callingAssembly.GetName().Name; shopItem2.modName = name; shopItems.Add(shopItem2); } public static void RegisterShopItem(Item shopItem, int price = -1) { ShopItem shopItem2 = new ShopItem(shopItem, null, null, null, price); Assembly callingAssembly = Assembly.GetCallingAssembly(); string name = callingAssembly.GetName().Name; shopItem2.modName = name; shopItems.Add(shopItem2); } public static void RegisterItem(Item plainItem) { PlainItem plainItem2 = new PlainItem(plainItem); Assembly callingAssembly = Assembly.GetCallingAssembly(); string name = callingAssembly.GetName().Name; plainItem2.modName = name; plainItems.Add(plainItem2); } } public class Levels { [Flags] public enum LevelTypes { None = 1, ExperimentationLevel = 2, AssuranceLevel = 4, VowLevel = 8, OffenseLevel = 0x10, MarchLevel = 0x20, RendLevel = 0x40, DineLevel = 0x80, TitanLevel = 0x100, All = 0x1FE } } public class MapObjects { public class RegisteredMapObject { public SpawnableMapObject mapObject; public SpawnableOutsideObjectWithRarity outsideObject; public Levels.LevelTypes levels; public Func<SelectableLevel, AnimationCurve> spawnRateFunction; } [CompilerGenerated] private static class <>O { public static hook_Awake <0>__StartOfRound_Awake; public static hook_SpawnMapObjects <1>__RoundManager_SpawnMapObjects; } public static List<RegisteredMapObject> mapObjects = new List<RegisteredMapObject>(); public static void Init() { //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) //IL_001c: Expected O, but got Unknown //IL_0032: Unknown result type (might be due to invalid IL or missing references) //IL_0037: Unknown result type (might be due to invalid IL or missing references) //IL_003d: Expected O, but got Unknown object obj = <>O.<0>__StartOfRound_Awake; if (obj == null) { hook_Awake val = StartOfRound_Awake; <>O.<0>__StartOfRound_Awake = val; obj = (object)val; } StartOfRound.Awake += (hook_Awake)obj; object obj2 = <>O.<1>__RoundManager_SpawnMapObjects; if (obj2 == null) { hook_SpawnMapObjects val2 = RoundManager_SpawnMapObjects; <>O.<1>__RoundManager_SpawnMapObjects = val2; obj2 = (object)val2; } RoundManager.SpawnMapObjects += (hook_SpawnMapObjects)obj2; } private static void RoundManager_SpawnMapObjects(orig_SpawnMapObjects orig, RoundManager self) { RandomMapObject[] array = Object.FindObjectsOfType<RandomMapObject>(); RandomMapObject[] array2 = array; foreach (RandomMapObject val in array2) { foreach (RegisteredMapObject mapObject in mapObjects) { if (mapObject.mapObject != null && !val.spawnablePrefabs.Any((GameObject prefab) => (Object)(object)prefab == (Object)(object)mapObject.mapObject.prefabToSpawn)) { val.spawnablePrefabs.Add(mapObject.mapObject.prefabToSpawn); } } } orig.Invoke(self); } private static void StartOfRound_Awake(orig_Awake orig, StartOfRound self) { orig.Invoke(self); SelectableLevel[] levels = self.levels; foreach (SelectableLevel val in levels) { string name = ((Object)val).name; if (!Enum.IsDefined(typeof(Levels.LevelTypes), name)) { continue; } Levels.LevelTypes levelTypes = (Levels.LevelTypes)Enum.Parse(typeof(Levels.LevelTypes), name); foreach (RegisteredMapObject mapObject in mapObjects) { if (!mapObject.levels.HasFlag(levelTypes)) { continue; } if (mapObject.mapObject != null) { if (!val.spawnableMapObjects.Any((SpawnableMapObject x) => (Object)(object)x.prefabToSpawn == (Object)(object)mapObject.mapObject.prefabToSpawn)) { List<SpawnableMapObject> list = val.spawnableMapObjects.ToList(); list.RemoveAll((SpawnableMapObject x) => (Object)(object)x.prefabToSpawn == (Object)(object)mapObject.mapObject.prefabToSpawn); val.spawnableMapObjects = list.ToArray(); } SpawnableMapObject mapObject2 = mapObject.mapObject; if (mapObject.spawnRateFunction != null) { mapObject2.numberToSpawn = mapObject.spawnRateFunction(val); } List<SpawnableMapObject> list2 = val.spawnableMapObjects.ToList(); list2.Add(mapObject2); val.spawnableMapObjects = list2.ToArray(); Plugin.logger.LogInfo((object)("Added " + ((Object)mapObject2.prefabToSpawn).name + " to " + name)); } else { if (mapObject.outsideObject == null) { continue; } if (!val.spawnableOutsideObjects.Any((SpawnableOutsideObjectWithRarity x) => (Object)(object)x.spawnableObject.prefabToSpawn == (Object)(object)mapObject.outsideObject.spawnableObject.prefabToSpawn)) { List<SpawnableOutsideObjectWithRarity> list3 = val.spawnableOutsideObjects.ToList(); list3.RemoveAll((SpawnableOutsideObjectWithRarity x) => (Object)(object)x.spawnableObject.prefabToSpawn == (Object)(object)mapObject.outsideObject.spawnableObject.prefabToSpawn); val.spawnableOutsideObjects = list3.ToArray(); } SpawnableOutsideObjectWithRarity outsideObject = mapObject.outsideObject; if (mapObject.spawnRateFunction != null) { outsideObject.randomAmount = mapObject.spawnRateFunction(val); } List<SpawnableOutsideObjectWithRarity> list4 = val.spawnableOutsideObjects.ToList(); list4.Add(outsideObject); val.spawnableOutsideObjects = list4.ToArray(); Plugin.logger.LogInfo((object)("Added " + ((Object)outsideObject.spawnableObject.prefabToSpawn).name + " to " + name)); } } } } public static void RegisterMapObject(SpawnableMapObjectDef mapObject, Levels.LevelTypes levels, Func<SelectableLevel, AnimationCurve> spawnRateFunction = null) { RegisterMapObject(mapObject.spawnableMapObject, levels, spawnRateFunction); } public static void RegisterMapObject(SpawnableMapObject mapObject, Levels.LevelTypes levels, Func<SelectableLevel, AnimationCurve> spawnRateFunction = null) { mapObjects.Add(new RegisteredMapObject { mapObject = mapObject, levels = levels, spawnRateFunction = spawnRateFunction }); } public static void RegisterOutsideObject(SpawnableOutsideObjectDef mapObject, Levels.LevelTypes levels, Func<SelectableLevel, AnimationCurve> spawnRateFunction = null) { RegisterOutsideObject(mapObject.spawnableMapObject, levels, spawnRateFunction); } public static void RegisterOutsideObject(SpawnableOutsideObjectWithRarity mapObject, Levels.LevelTypes levels, Func<SelectableLevel, AnimationCurve> spawnRateFunction = null) { mapObjects.Add(new RegisteredMapObject { outsideObject = mapObject, levels = levels, spawnRateFunction = spawnRateFunction }); } } public class NetworkPrefabs { [CompilerGenerated] private static class <>O { public static hook_Start <0>__GameNetworkManager_Start; } private static List<GameObject> _networkPrefabs = new List<GameObject>(); internal static void Init() { //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) //IL_001c: Expected O, but got Unknown object obj = <>O.<0>__GameNetworkManager_Start; if (obj == null) { hook_Start val = GameNetworkManager_Start; <>O.<0>__GameNetworkManager_Start = val; obj = (object)val; } GameNetworkManager.Start += (hook_Start)obj; } public static void RegisterNetworkPrefab(GameObject prefab) { _networkPrefabs.Add(prefab); } private static void GameNetworkManager_Start(orig_Start orig, GameNetworkManager self) { orig.Invoke(self); foreach (GameObject networkPrefab in _networkPrefabs) { ((Component)self).GetComponent<NetworkManager>().AddNetworkPrefab(networkPrefab); } } } public class Shaders { public static void FixShaders(GameObject gameObject) { Renderer[] componentsInChildren = gameObject.GetComponentsInChildren<Renderer>(); foreach (Renderer val in componentsInChildren) { Material[] materials = val.materials; foreach (Material val2 in materials) { if (((Object)val2.shader).name.Contains("Standard")) { val2.shader = Shader.Find("HDRP/Lit"); } } } } } public class TerminalUtils { public static TerminalKeyword CreateTerminalKeyword(string word, bool isVerb = false, CompatibleNoun[] compatibleNouns = null, TerminalNode specialKeywordResult = null, TerminalKeyword defaultVerb = null, bool accessTerminalObjects = false) { TerminalKeyword val = ScriptableObject.CreateInstance<TerminalKeyword>(); ((Object)val).name = word; val.word = word; val.isVerb = isVerb; val.compatibleNouns = compatibleNouns; val.specialKeywordResult = specialKeywordResult; val.defaultVerb = defaultVerb; val.accessTerminalObjects = accessTerminalObjects; return val; } } public enum StoreType { None, ShipUpgrade, Decor } public class Unlockables { public class RegisteredUnlockable { public UnlockableItem unlockable; public StoreType StoreType; public TerminalNode buyNode1; public TerminalNode buyNode2; public TerminalNode itemInfo; public int price; public string modName; public RegisteredUnlockable(UnlockableItem unlockable, TerminalNode buyNode1 = null, TerminalNode buyNode2 = null, TerminalNode itemInfo = null, int price = -1) { this.unlockable = unlockable; this.buyNode1 = buyNode1; this.buyNode2 = buyNode2; this.itemInfo = itemInfo; this.price = price; } } [CompilerGenerated] private static class <>O { public static hook_Awake <0>__StartOfRound_Awake; public static hook_Start <1>__Terminal_Start; public static hook_TextPostProcess <2>__Terminal_TextPostProcess; } public static List<RegisteredUnlockable> registeredUnlockables = new List<RegisteredUnlockable>(); public static void Init() { //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) //IL_001c: Expected O, but got Unknown //IL_0032: Unknown result type (might be due to invalid IL or missing references) //IL_0037: Unknown result type (might be due to invalid IL or missing references) //IL_003d: Expected O, but got Unknown //IL_0053: Unknown result type (might be due to invalid IL or missing references) //IL_0058: Unknown result type (might be due to invalid IL or missing references) //IL_005e: Expected O, but got Unknown object obj = <>O.<0>__StartOfRound_Awake; if (obj == null) { hook_Awake val = StartOfRound_Awake; <>O.<0>__StartOfRound_Awake = val; obj = (object)val; } StartOfRound.Awake += (hook_Awake)obj; object obj2 = <>O.<1>__Terminal_Start; if (obj2 == null) { hook_Start val2 = Terminal_Start; <>O.<1>__Terminal_Start = val2; obj2 = (object)val2; } Terminal.Start += (hook_Start)obj2; object obj3 = <>O.<2>__Terminal_TextPostProcess; if (obj3 == null) { hook_TextPostProcess val3 = Terminal_TextPostProcess; <>O.<2>__Terminal_TextPostProcess = val3; obj3 = (object)val3; } Terminal.TextPostProcess += (hook_TextPostProcess)obj3; } private static string Terminal_TextPostProcess(orig_TextPostProcess orig, Terminal self, string modifiedDisplayText, TerminalNode node) { if (modifiedDisplayText.Contains("[buyableItemsList]") && modifiedDisplayText.Contains("[unlockablesSelectionList]")) { int num = modifiedDisplayText.IndexOf(":"); foreach (RegisteredUnlockable registeredUnlockable in registeredUnlockables) { if (registeredUnlockable.StoreType == StoreType.ShipUpgrade) { string unlockableName = registeredUnlockable.unlockable.unlockableName; int price = registeredUnlockable.price; string value = $"\n* {unlockableName} // Price: ${price}"; modifiedDisplayText = modifiedDisplayText.Insert(num + 1, value); } } } return orig.Invoke(self, modifiedDisplayText, node); } private static void Terminal_Start(orig_Start orig, Terminal self) { //IL_0390: Unknown result type (might be due to invalid IL or missing references) //IL_0395: Unknown result type (might be due to invalid IL or missing references) //IL_03ca: Unknown result type (might be due to invalid IL or missing references) //IL_03d3: Expected O, but got Unknown //IL_03d5: Unknown result type (might be due to invalid IL or missing references) //IL_03da: Unknown result type (might be due to invalid IL or missing references) //IL_040f: Unknown result type (might be due to invalid IL or missing references) //IL_0417: Expected O, but got Unknown //IL_049e: Unknown result type (might be due to invalid IL or missing references) //IL_04a3: Unknown result type (might be due to invalid IL or missing references) //IL_04b0: Unknown result type (might be due to invalid IL or missing references) //IL_04bd: Expected O, but got Unknown //IL_0551: Unknown result type (might be due to invalid IL or missing references) //IL_0556: Unknown result type (might be due to invalid IL or missing references) //IL_0563: Unknown result type (might be due to invalid IL or missing references) //IL_0570: Expected O, but got Unknown TerminalKeyword val = self.terminalNodes.allKeywords.First((TerminalKeyword keyword) => keyword.word == "buy"); TerminalNode result = val.compatibleNouns[0].result.terminalOptions[1].result; TerminalKeyword val2 = self.terminalNodes.allKeywords.First((TerminalKeyword keyword) => keyword.word == "info"); List<RegisteredUnlockable> list = registeredUnlockables.FindAll((RegisteredUnlockable unlockable) => unlockable.price != -1).ToList(); Plugin.logger.LogInfo((object)$"Adding {list.Count} items to terminal"); foreach (RegisteredUnlockable item in list) { string unlockableName = item.unlockable.unlockableName; TerminalKeyword keyword3 = TerminalUtils.CreateTerminalKeyword(unlockableName.ToLowerInvariant().Replace(" ", "-"), isVerb: false, null, null, val); if (self.terminalNodes.allKeywords.Any((TerminalKeyword kw) => kw.word == keyword3.word)) { Plugin.logger.LogInfo((object)("Keyword " + keyword3.word + " already registed, skipping.")); continue; } int shipUnlockableID = StartOfRound.Instance.unlockablesList.unlockables.FindIndex((UnlockableItem unlockable) => unlockable.unlockableName == item.unlockable.unlockableName); StartOfRound instance = StartOfRound.Instance; if ((Object)(object)instance == (Object)null) { Debug.Log((object)"STARTOFROUND INSTANCE NOT FOUND"); } if (item.price == -1 && (Object)(object)item.buyNode1 != (Object)null) { item.price = item.buyNode1.itemCost; } char c = unlockableName[unlockableName.Length - 1]; string text = unlockableName; TerminalNode val3 = item.buyNode2; if ((Object)(object)val3 == (Object)null) { val3 = ScriptableObject.CreateInstance<TerminalNode>(); ((Object)val3).name = unlockableName.Replace(" ", "-") + "BuyNode2"; val3.displayText = "Ordered [variableAmount] " + text + ". Your new balance is [playerCredits].\n\nOur contractors enjoy fast, free shipping while on the job! Any purchased items will arrive hourly at your approximate location.\r\n\r\n"; val3.clearPreviousText = true; val3.maxCharactersToType = 15; } val3.buyItemIndex = -1; val3.shipUnlockableID = shipUnlockableID; val3.buyUnlockable = true; val3.creatureName = unlockableName; val3.isConfirmationNode = false; val3.itemCost = item.price; val3.playSyncedClip = 0; TerminalNode val4 = item.buyNode1; if ((Object)(object)val4 == (Object)null) { val4 = ScriptableObject.CreateInstance<TerminalNode>(); ((Object)val4).name = unlockableName.Replace(" ", "-") + "BuyNode1"; val4.displayText = "You have requested to order " + text + ". Amount: [variableAmount].\nTotal cost of items: [totalCost].\n\nPlease CONFIRM or DENY.\r\n\r\n"; val4.clearPreviousText = true; val4.maxCharactersToType = 35; } val4.buyItemIndex = -1; val4.shipUnlockableID = shipUnlockableID; val4.creatureName = unlockableName; val4.isConfirmationNode = true; val4.overrideOptions = true; val4.itemCost = item.price; val4.terminalOptions = (CompatibleNoun[])(object)new CompatibleNoun[2] { new CompatibleNoun { noun = self.terminalNodes.allKeywords.First((TerminalKeyword keyword2) => keyword2.word == "confirm"), result = val3 }, new CompatibleNoun { noun = self.terminalNodes.allKeywords.First((TerminalKeyword keyword2) => keyword2.word == "deny"), result = result } }; if (item.StoreType == StoreType.Decor) { item.unlockable.shopSelectionNode = val4; } else { item.unlockable.shopSelectionNode = null; } List<TerminalKeyword> list2 = self.terminalNodes.allKeywords.ToList(); list2.Add(keyword3); self.terminalNodes.allKeywords = list2.ToArray(); List<CompatibleNoun> list3 = val.compatibleNouns.ToList(); list3.Add(new CompatibleNoun { noun = keyword3, result = val4 }); val.compatibleNouns = list3.ToArray(); TerminalNode val5 = item.itemInfo; if ((Object)(object)val5 == (Object)null) { val5 = ScriptableObject.CreateInstance<TerminalNode>(); ((Object)val5).name = unlockableName.Replace(" ", "-") + "InfoNode"; val5.displayText = "[No information about this object was found.]\n\n"; val5.clearPreviousText = true; val5.maxCharactersToType = 25; } self.terminalNodes.allKeywords = list2.ToArray(); List<CompatibleNoun> list4 = val2.compatibleNouns.ToList(); list4.Add(new CompatibleNoun { noun = keyword3, result = val5 }); val2.compatibleNouns = list4.ToArray(); Plugin.logger.LogInfo((object)(item.modName + " registered item: " + item.unlockable.unlockableName)); } orig.Invoke(self); } private static void StartOfRound_Awake(orig_Awake orig, StartOfRound self) { orig.Invoke(self); Plugin.logger.LogInfo((object)$"Adding {registeredUnlockables.Count} unlockables to unlockables list"); foreach (RegisteredUnlockable unlockable in registeredUnlockables) { if (self.unlockablesList.unlockables.Any((UnlockableItem x) => x.unlockableName == unlockable.unlockable.unlockableName)) { Plugin.logger.LogInfo((object)("Unlockable " + unlockable.unlockable.unlockableName + " already exists in unlockables list, skipping")); continue; } if ((Object)(object)unlockable.unlockable.prefabObject != (Object)null) { PlaceableShipObject componentInChildren = unlockable.unlockable.prefabObject.GetComponentInChildren<PlaceableShipObject>(); if ((Object)(object)componentInChildren != (Object)null) { componentInChildren.unlockableID = self.unlockablesList.unlockables.Count; } } self.unlockablesList.unlockables.Add(unlockable.unlockable); } } public static void RegisterUnlockable(UnlockableItemDef unlockable, int price = -1, StoreType storeType = StoreType.None) { RegisterUnlockable(unlockable.unlockable, storeType, null, null, null, price); } public static void RegisterUnlockable(UnlockableItem unlockable, int price = -1, StoreType storeType = StoreType.None) { RegisterUnlockable(unlockable, storeType, null, null, null, price); } public static void RegisterUnlockable(UnlockableItemDef unlockable, StoreType storeType = StoreType.None, TerminalNode buyNode1 = null, TerminalNode buyNode2 = null, TerminalNode itemInfo = null, int price = -1) { RegisterUnlockable(unlockable.unlockable, storeType, buyNode1, buyNode2, itemInfo, price); } public static void RegisterUnlockable(UnlockableItem unlockable, StoreType storeType = StoreType.None, TerminalNode buyNode1 = null, TerminalNode buyNode2 = null, TerminalNode itemInfo = null, int price = -1) { RegisteredUnlockable registeredUnlockable = new RegisteredUnlockable(unlockable, buyNode1, buyNode2, itemInfo, price); Assembly callingAssembly = Assembly.GetCallingAssembly(); string name = callingAssembly.GetName().Name; registeredUnlockable.modName = name; registeredUnlockable.StoreType = storeType; registeredUnlockables.Add(registeredUnlockable); } } } namespace LethalLib.Extras { [CreateAssetMenu(menuName = "ScriptableObjects/DungeonDef")] public class DungeonDef : ScriptableObject { public DungeonFlow dungeonFlow; [Range(0f, 300f)] public int rarity; public AudioClip firstTimeDungeonAudio; } [CreateAssetMenu(menuName = "ScriptableObjects/DungeonGraphLine")] public class DungeonGraphLineDef : ScriptableObject { public GraphLine graphLine; } [CreateAssetMenu(menuName = "ScriptableObjects/GameObjectChance")] public class GameObjectChanceDef : ScriptableObject { public GameObjectChance gameObjectChance; } [CreateAssetMenu(menuName = "ScriptableObjects/SpawnableMapObject")] public class SpawnableMapObjectDef : ScriptableObject { public SpawnableMapObject spawnableMapObject; } [CreateAssetMenu(menuName = "ScriptableObjects/SpawnableOutsideObject")] public class SpawnableOutsideObjectDef : ScriptableObject { public SpawnableOutsideObjectWithRarity spawnableMapObject; } [CreateAssetMenu(menuName = "ScriptableObjects/UnlockableItem")] public class UnlockableItemDef : ScriptableObject { public StoreType storeType = StoreType.None; public UnlockableItem unlockable; } }
plugins/LethalProgression.dll
Decompiled 11 months agousing System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; 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.Bootstrap; using BepInEx.Configuration; using BepInEx.Logging; using GameNetcodeStuff; using HarmonyLib; using LethalProgression.Config; using LethalProgression.GUI; using LethalProgression.Patches; using LethalProgression.Skills; using Microsoft.CodeAnalysis; using Newtonsoft.Json; using TMPro; using Unity.Netcode; using UnityEngine; using UnityEngine.Events; using UnityEngine.InputSystem; 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("LethalProgression")] [assembly: AssemblyConfiguration("Debug")] [assembly: AssemblyDescription("Progression Mod")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: AssemblyInformationalVersion("1.0.0+3dc7eef442dce452b17ebbe7d003936b2d4276a3")] [assembly: AssemblyProduct("LethalProgression")] [assembly: AssemblyTitle("LethalProgression")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("1.0.0.0")] [module: UnverifiableCode] [module: RefSafetyRules(11)] internal class <Module> { static <Module>() { NetworkVariableSerializationTypes.InitializeSerializer_UnmanagedByMemcpy<float>(); NetworkVariableSerializationTypes.InitializeEqualityChecker_UnmanagedIEquatable<float>(); } } 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 LethalProgression { [HarmonyPatch] internal class LP_NetworkManager { public static GameObject xpNetworkObject; public static XP xpInstance; [HarmonyPostfix] [HarmonyPatch(typeof(GameNetworkManager), "Start")] public static void Init() { //IL_0021: Unknown result type (might be due to invalid IL or missing references) //IL_002b: Expected O, but got Unknown if (!((Object)(object)xpNetworkObject != (Object)null)) { xpNetworkObject = (GameObject)LethalPlugin.skillBundle.LoadAsset("LP_XPHandler"); xpNetworkObject.AddComponent<XP>(); NetworkManager.Singleton.AddNetworkPrefab(xpNetworkObject); } } [HarmonyPostfix] [HarmonyPatch(typeof(StartOfRound), "Awake")] private static void SpawnNetworkHandler() { //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_0029: Unknown result type (might be due to invalid IL or missing references) if (NetworkManager.Singleton.IsHost || NetworkManager.Singleton.IsServer) { GameObject val = Object.Instantiate<GameObject>(xpNetworkObject, Vector3.zero, Quaternion.identity); val.GetComponent<NetworkObject>().Spawn(false); xpInstance = val.GetComponent<XP>(); LethalPlugin.Log.LogInfo((object)"XPHandler Initialized."); } } } [BepInPlugin("Stoneman.LethalProgression", "Lethal Progression", "1.3.2")] internal class LethalPlugin : BaseUnityPlugin { private const string modGUID = "Stoneman.LethalProgression"; private const string modName = "Lethal Progression"; private const string modVersion = "1.3.2"; private const string modAuthor = "Stoneman"; public static AssetBundle skillBundle; internal static ManualLogSource Log; internal static bool ReservedSlots; public static LethalPlugin Instance { get; private set; } private void Awake() { //IL_000d: Unknown result type (might be due to invalid IL or missing references) //IL_0013: Expected O, but got Unknown Instance = this; Harmony val = new Harmony("Stoneman.LethalProgression"); val.PatchAll(Assembly.GetExecutingAssembly()); skillBundle = AssetBundle.LoadFromFile(Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "skillmenu")); Log = ((BaseUnityPlugin)this).Logger; Log.LogInfo((object)"Lethal Progression loaded."); foreach (KeyValuePair<string, PluginInfo> pluginInfo in Chainloader.PluginInfos) { if (pluginInfo.Value.Metadata.GUID.IndexOf("ReservedItem") >= 0) { ReservedSlots = true; } if (pluginInfo.Value.Metadata.GUID.IndexOf("mikestweaks") < 0) { continue; } ConfigEntryBase[] configEntries = pluginInfo.Value.Instance.Config.GetConfigEntries(); ConfigEntryBase[] array = configEntries; foreach (ConfigEntryBase val2 in array) { if (val2.Definition.Key == "ExtraItemSlots") { if (int.Parse(val2.GetSerializedValue()) > 0) { ReservedSlots = true; } break; } } } Type[] types = Assembly.GetExecutingAssembly().GetTypes(); Type[] array2 = types; foreach (Type type in array2) { MethodInfo[] methods = type.GetMethods(BindingFlags.Instance | BindingFlags.Static | BindingFlags.NonPublic); MethodInfo[] array3 = methods; foreach (MethodInfo methodInfo in array3) { object[] customAttributes = methodInfo.GetCustomAttributes(typeof(RuntimeInitializeOnLoadMethodAttribute), inherit: false); if (customAttributes.Length != 0) { methodInfo.Invoke(null, null); } } } SkillConfig.InitConfig(); } public void BindConfig<T>(string section, string key, T defaultValue, string description = "") { ((BaseUnityPlugin)this).Config.Bind<T>(section, key, defaultValue, description); } public IDictionary<string, string> GetAllConfigEntries() { return ((BaseUnityPlugin)this).Config.GetConfigEntries().ToDictionary((ConfigEntryBase entry) => entry.Definition.Key, (ConfigEntryBase entry) => entry.GetSerializedValue()); } } internal class XP : NetworkBehaviour { public NetworkVariable<int> xpPoints = new NetworkVariable<int>(0, (NetworkVariableReadPermission)0, (NetworkVariableWritePermission)0); public NetworkVariable<int> xpLevel = new NetworkVariable<int>(0, (NetworkVariableReadPermission)0, (NetworkVariableWritePermission)0); public NetworkVariable<int> profit = new NetworkVariable<int>(0, (NetworkVariableReadPermission)0, (NetworkVariableWritePermission)0); public NetworkVariable<int> xpReq = new NetworkVariable<int>(0, (NetworkVariableReadPermission)0, (NetworkVariableWritePermission)0); public NetworkVariable<float> teamLootValue = new NetworkVariable<float>(0f, (NetworkVariableReadPermission)0, (NetworkVariableWritePermission)0); public int skillPoints; public SkillList skillList; public SkillsGUI guiObj; public bool Initialized = false; public void Start() { LethalPlugin.Log.LogInfo((object)"XP Network Behavior Made!"); PlayerConnect_ServerRpc(); } public void LoadSaveData() { int num = GameNetworkManager.Instance.saveFileNum + 1; string path = Application.persistentDataPath + "/lethalprogression/save" + num + ".txt"; if (!File.Exists(path)) { Directory.CreateDirectory(Application.persistentDataPath + "/lethalprogression"); File.WriteAllText(path, ""); string text = ""; text += "0\n"; text += "0\n"; text += "0\n"; File.WriteAllText(path, text); } string[] array = File.ReadAllLines(path); LethalPlugin.Log.LogError((object)"Loading XP!"); xpLevel.Value = int.Parse(array[0]); xpPoints.Value = int.Parse(array[1]); profit.Value = int.Parse(array[2]); xpReq.Value = GetXPRequirement(); LethalPlugin.Log.LogInfo((object)GetXPRequirement().ToString()); } public int GetXPRequirement() { int connectedPlayersAmount = StartOfRound.Instance.connectedPlayersAmount; int timesFulfilledQuota = TimeOfDay.Instance.timesFulfilledQuota; int num = int.Parse(SkillConfig.hostConfig["XP Minimum"]); int num2 = int.Parse(SkillConfig.hostConfig["XP Maximum"]); int num3 = int.Parse(SkillConfig.hostConfig["Person Multiplier"]); int num4 = connectedPlayersAmount * num3; int num5 = num + num4; int num6 = int.Parse(SkillConfig.hostConfig["Quota Multiplier"]); int num7 = timesFulfilledQuota * num6; num5 += (int)((float)num5 * ((float)num7 / 100f)); if (num5 > num2) { num5 = num2; } LethalPlugin.Log.LogInfo((object)$"{connectedPlayersAmount} players, {timesFulfilledQuota} quotas, {num} initial cost, {num4} person value, {num7} quota value, {num5} total cost."); return num5; } public int GetXP() { return xpPoints.Value; } public int GetLevel() { return xpLevel.Value; } public int GetProfit() { return profit.Value; } public int GetSkillPoints() { return skillPoints; } public void SetSkillPoints(int num) { skillPoints = num; } public void AddSkillPoint() { skillPoints++; } [ServerRpc(RequireOwnership = false)] public void ChangeXPRequirement_ServerRpc() { //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 != 1 && (networkManager.IsClient || networkManager.IsHost)) { ServerRpcParams val = default(ServerRpcParams); FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendServerRpc(3672466612u, val, (RpcDelivery)0); ((NetworkBehaviour)this).__endSendServerRpc(ref val2, 3672466612u, val, (RpcDelivery)0); } if ((int)base.__rpc_exec_stage == 1 && (networkManager.IsServer || networkManager.IsHost)) { ((MonoBehaviour)this).StartCoroutine(XPRequirementCoroutine()); } } } public IEnumerator XPRequirementCoroutine() { yield return (object)new WaitForSeconds(0.5f); xpReq.Value = GetXPRequirement(); } [ServerRpc(RequireOwnership = false)] public void AddXPServerRPC(int xp) { //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Invalid comparison between Unknown and I4 //IL_0099: Unknown result type (might be due to invalid IL or missing references) //IL_00a3: 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_0071: 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) NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager; if (networkManager == null || !networkManager.IsListening) { return; } if ((int)base.__rpc_exec_stage != 1 && (networkManager.IsClient || networkManager.IsHost)) { ServerRpcParams val = default(ServerRpcParams); FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendServerRpc(3074971930u, val, (RpcDelivery)0); BytePacker.WriteValueBitPacked(val2, xp); ((NetworkBehaviour)this).__endSendServerRpc(ref val2, 3074971930u, val, (RpcDelivery)0); } if ((int)base.__rpc_exec_stage != 1 || (!networkManager.IsServer && !networkManager.IsHost)) { return; } int xP = GetXP(); NetworkVariable<int> obj = xpPoints; obj.Value += xp; NetworkVariable<int> obj2 = profit; obj2.Value += xp; int num = GetXP(); XPHUDUpdate_ClientRPC(xP, num, xp); if (num >= xpReq.Value) { int num2 = 0; while (num >= xpReq.Value) { num2++; num -= xpReq.Value; Givepoint_ClientRPC(); } xpPoints.Value = num; NetworkVariable<int> obj3 = xpLevel; obj3.Value += num2; LevelUp_ClientRPC(); } } [ClientRpc] public void XPHUDUpdate_ClientRPC(int oldXP, int newXP, int xpGained) { //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Invalid comparison between Unknown and I4 //IL_00b3: Unknown result type (might be due to invalid IL or missing references) //IL_00bd: 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_0071: Unknown result type (might be due to invalid IL or missing references) //IL_007e: Unknown result type (might be due to invalid IL or missing references) //IL_008b: Unknown result type (might be due to invalid IL or missing references) //IL_00a3: 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(3462423043u, val, (RpcDelivery)0); BytePacker.WriteValueBitPacked(val2, oldXP); BytePacker.WriteValueBitPacked(val2, newXP); BytePacker.WriteValueBitPacked(val2, xpGained); ((NetworkBehaviour)this).__endSendClientRpc(ref val2, 3462423043u, val, (RpcDelivery)0); } if ((int)base.__rpc_exec_stage == 2 && (networkManager.IsClient || networkManager.IsHost)) { HUDManagerPatch.ShowXPUpdate(oldXP, newXP, newXP - oldXP); } } } [ClientRpc] public void LevelUp_ClientRPC() { //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(820724324u, val, (RpcDelivery)0); ((NetworkBehaviour)this).__endSendClientRpc(ref val2, 820724324u, val, (RpcDelivery)0); } if ((int)base.__rpc_exec_stage == 2 && (networkManager.IsClient || networkManager.IsHost)) { HUDManagerPatch.ShowLevelUp(); } } } [ClientRpc] public void Givepoint_ClientRPC() { //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(179361894u, val, (RpcDelivery)0); ((NetworkBehaviour)this).__endSendClientRpc(ref val2, 179361894u, val, (RpcDelivery)0); } if ((int)base.__rpc_exec_stage == 2 && (networkManager.IsClient || networkManager.IsHost)) { skillPoints++; } } } public void TeamLootValueUpdate(float update, int newValue) { TeamLootValueUpdate_ServerRpc(update); } [ServerRpc(RequireOwnership = false)] public void TeamLootValueUpdate_ServerRpc(float updatedValue) { //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Invalid comparison between Unknown and I4 //IL_00a7: Unknown result type (might be due to invalid IL or missing references) //IL_00b1: 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_007d: Unknown result type (might be due to invalid IL or missing references) //IL_0083: Unknown result type (might be due to invalid IL or missing references) //IL_0097: 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 != 1 && (networkManager.IsClient || networkManager.IsHost)) { ServerRpcParams val = default(ServerRpcParams); FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendServerRpc(3281224843u, val, (RpcDelivery)0); ((FastBufferWriter)(ref val2)).WriteValueSafe<float>(ref updatedValue, default(ForPrimitives)); ((NetworkBehaviour)this).__endSendServerRpc(ref val2, 3281224843u, val, (RpcDelivery)0); } if ((int)base.__rpc_exec_stage == 1 && (networkManager.IsServer || networkManager.IsHost)) { float multiplier = LP_NetworkManager.xpInstance.skillList.skills[UpgradeType.Value].GetMultiplier(); float num = updatedValue * multiplier; NetworkVariable<float> obj = teamLootValue; obj.Value += num; LethalPlugin.Log.LogInfo((object)$"Changed team loot value by {updatedValue * multiplier} turning into {teamLootValue.Value}."); } } } [ServerRpc(RequireOwnership = false)] public void ServerHandSlots_ServerRpc(ulong playerID, int newSlots) { //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Invalid comparison between Unknown and I4 //IL_00a6: Unknown result type (might be due to invalid IL or missing references) //IL_00b0: 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_0071: Unknown result type (might be due to invalid IL or missing references) //IL_007e: Unknown result type (might be due to invalid IL or missing references) //IL_0096: 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 != 1 && (networkManager.IsClient || networkManager.IsHost)) { ServerRpcParams val = default(ServerRpcParams); FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendServerRpc(2696007838u, val, (RpcDelivery)0); BytePacker.WriteValueBitPacked(val2, playerID); BytePacker.WriteValueBitPacked(val2, newSlots); ((NetworkBehaviour)this).__endSendServerRpc(ref val2, 2696007838u, val, (RpcDelivery)0); } if ((int)base.__rpc_exec_stage == 1 && (networkManager.IsServer || networkManager.IsHost) && !LethalPlugin.ReservedSlots) { SetPlayerHandslots_ClientRpc(playerID, newSlots); } } } [ClientRpc] public void SetPlayerHandslots_ClientRpc(ulong playerID, int newSlots) { //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Invalid comparison between Unknown and I4 //IL_00a6: Unknown result type (might be due to invalid IL or missing references) //IL_00b0: 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_0071: Unknown result type (might be due to invalid IL or missing references) //IL_007e: Unknown result type (might be due to invalid IL or missing references) //IL_0096: 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(2549144616u, val, (RpcDelivery)0); BytePacker.WriteValueBitPacked(val2, playerID); BytePacker.WriteValueBitPacked(val2, newSlots); ((NetworkBehaviour)this).__endSendClientRpc(ref val2, 2549144616u, val, (RpcDelivery)0); } if ((int)base.__rpc_exec_stage == 2 && (networkManager.IsClient || networkManager.IsHost)) { SetHandSlot(playerID, newSlots); } } } public void SetHandSlot(ulong playerID, int newSlots) { PlayerControllerB[] allPlayerScripts = StartOfRound.Instance.allPlayerScripts; foreach (PlayerControllerB val in allPlayerScripts) { if (val.playerClientId != playerID) { continue; } int num = 4 + newSlots; List<GrabbableObject> list = new List<GrabbableObject>(val.ItemSlots); val.ItemSlots = (GrabbableObject[])(object)new GrabbableObject[num]; for (int j = 0; j < num; j++) { if (list.Count >= num) { val.ItemSlots[j] = list[j]; } } LethalPlugin.Log.LogInfo((object)$"Player {playerID} has {val.ItemSlots.Length} slots after setting."); break; } } [ServerRpc(RequireOwnership = false)] public void GetEveryoneHandSlots_ServerRpc() { //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) { return; } if ((int)base.__rpc_exec_stage != 1 && (networkManager.IsClient || networkManager.IsHost)) { ServerRpcParams val = default(ServerRpcParams); FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendServerRpc(2063608820u, val, (RpcDelivery)0); ((NetworkBehaviour)this).__endSendServerRpc(ref val2, 2063608820u, val, (RpcDelivery)0); } if ((int)base.__rpc_exec_stage != 1 || (!networkManager.IsServer && !networkManager.IsHost) || LethalPlugin.ReservedSlots || !LP_NetworkManager.xpInstance.skillList.IsSkillValid(UpgradeType.HandSlot)) { return; } PlayerControllerB[] allPlayerScripts = StartOfRound.Instance.allPlayerScripts; foreach (PlayerControllerB val3 in allPlayerScripts) { if (((Component)val3).gameObject.activeSelf) { ulong playerClientId = val3.playerClientId; int handSlots = val3.ItemSlots.Length - 4; SendEveryoneHandSlots_ClientRpc(playerClientId, handSlots); } } } [ClientRpc] public void SendEveryoneHandSlots_ClientRpc(ulong playerID, int handSlots) { //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Invalid comparison between Unknown and I4 //IL_00a6: Unknown result type (might be due to invalid IL or missing references) //IL_00b0: 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_0071: Unknown result type (might be due to invalid IL or missing references) //IL_007e: Unknown result type (might be due to invalid IL or missing references) //IL_0096: 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(4146414765u, val, (RpcDelivery)0); BytePacker.WriteValueBitPacked(val2, playerID); BytePacker.WriteValueBitPacked(val2, handSlots); ((NetworkBehaviour)this).__endSendClientRpc(ref val2, 4146414765u, val, (RpcDelivery)0); } if ((int)base.__rpc_exec_stage == 2 && (networkManager.IsClient || networkManager.IsHost)) { SetHandSlot(playerID, handSlots); } } } [ServerRpc(RequireOwnership = false)] public void PlayerConnect_ServerRpc() { //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 != 1 && (networkManager.IsClient || networkManager.IsHost)) { ServerRpcParams val = default(ServerRpcParams); FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendServerRpc(2203520695u, val, (RpcDelivery)0); ((NetworkBehaviour)this).__endSendServerRpc(ref val2, 2203520695u, val, (RpcDelivery)0); } if ((int)base.__rpc_exec_stage == 1 && (networkManager.IsServer || networkManager.IsHost)) { IDictionary<string, string> allConfigEntries = LethalPlugin.Instance.GetAllConfigEntries(); string serializedConfig = JsonConvert.SerializeObject((object)allConfigEntries); SendEveryoneConfigs_ClientRpc(serializedConfig); } } } [ClientRpc] public void SendEveryoneConfigs_ClientRpc(string serializedConfig) { //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Invalid comparison between Unknown and I4 //IL_00ca: Unknown result type (might be due to invalid IL or missing references) //IL_00d4: 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_0088: Unknown result type (might be due to invalid IL or missing references) //IL_008e: Unknown result type (might be due to invalid IL or missing references) //IL_00ba: Unknown result type (might be due to invalid IL or missing references) NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager; if (networkManager == null || !networkManager.IsListening) { return; } if ((int)base.__rpc_exec_stage != 2 && (networkManager.IsServer || networkManager.IsHost)) { ClientRpcParams val = default(ClientRpcParams); FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendClientRpc(2502216668u, val, (RpcDelivery)0); bool flag = serializedConfig != null; ((FastBufferWriter)(ref val2)).WriteValueSafe<bool>(ref flag, default(ForPrimitives)); if (flag) { ((FastBufferWriter)(ref val2)).WriteValueSafe(serializedConfig, false); } ((NetworkBehaviour)this).__endSendClientRpc(ref val2, 2502216668u, val, (RpcDelivery)0); } if ((int)base.__rpc_exec_stage != 2 || (!networkManager.IsClient && !networkManager.IsHost)) { return; } IDictionary<string, string> dictionary = JsonConvert.DeserializeObject<IDictionary<string, string>>(serializedConfig); foreach (KeyValuePair<string, string> item in dictionary) { SkillConfig.hostConfig[item.Key] = item.Value; LethalPlugin.Log.LogInfo((object)("Loaded host config: " + item.Key + " = " + item.Value)); } if (!Initialized) { Initialized = true; LP_NetworkManager.xpInstance = this; skillList = new SkillList(); skillList.InitializeSkills(); guiObj = new SkillsGUI(); NetworkVariable<float> obj = teamLootValue; obj.OnValueChanged = (OnValueChangedDelegate<float>)(object)Delegate.Combine((Delegate?)(object)obj.OnValueChanged, (Delegate?)(object)new OnValueChangedDelegate<float>(guiObj.TeamLootHudUpdate)); if (GameNetworkManager.Instance.isHostingGame) { LoadSaveData(); } skillPoints = xpLevel.Value + 5; GetEveryoneHandSlots_ServerRpc(); ChangeXPRequirement_ServerRpc(); } } protected override void __initializeVariables() { if (xpPoints == null) { throw new Exception("XP.xpPoints cannot be null. All NetworkVariableBase instances must be initialized."); } ((NetworkVariableBase)xpPoints).Initialize((NetworkBehaviour)(object)this); ((NetworkBehaviour)this).__nameNetworkVariable((NetworkVariableBase)(object)xpPoints, "xpPoints"); base.NetworkVariableFields.Add((NetworkVariableBase)(object)xpPoints); if (xpLevel == null) { throw new Exception("XP.xpLevel cannot be null. All NetworkVariableBase instances must be initialized."); } ((NetworkVariableBase)xpLevel).Initialize((NetworkBehaviour)(object)this); ((NetworkBehaviour)this).__nameNetworkVariable((NetworkVariableBase)(object)xpLevel, "xpLevel"); base.NetworkVariableFields.Add((NetworkVariableBase)(object)xpLevel); if (profit == null) { throw new Exception("XP.profit cannot be null. All NetworkVariableBase instances must be initialized."); } ((NetworkVariableBase)profit).Initialize((NetworkBehaviour)(object)this); ((NetworkBehaviour)this).__nameNetworkVariable((NetworkVariableBase)(object)profit, "profit"); base.NetworkVariableFields.Add((NetworkVariableBase)(object)profit); if (xpReq == null) { throw new Exception("XP.xpReq cannot be null. All NetworkVariableBase instances must be initialized."); } ((NetworkVariableBase)xpReq).Initialize((NetworkBehaviour)(object)this); ((NetworkBehaviour)this).__nameNetworkVariable((NetworkVariableBase)(object)xpReq, "xpReq"); base.NetworkVariableFields.Add((NetworkVariableBase)(object)xpReq); if (teamLootValue == null) { throw new Exception("XP.teamLootValue cannot be null. All NetworkVariableBase instances must be initialized."); } ((NetworkVariableBase)teamLootValue).Initialize((NetworkBehaviour)(object)this); ((NetworkBehaviour)this).__nameNetworkVariable((NetworkVariableBase)(object)teamLootValue, "teamLootValue"); base.NetworkVariableFields.Add((NetworkVariableBase)(object)teamLootValue); ((NetworkBehaviour)this).__initializeVariables(); } [RuntimeInitializeOnLoadMethod] internal static void InitializeRPCS_XP() { //IL_0011: Unknown result type (might be due to invalid IL or missing references) //IL_001b: Expected O, but got Unknown //IL_002c: Unknown result type (might be due to invalid IL or missing references) //IL_0036: Expected O, but got Unknown //IL_0047: Unknown result type (might be due to invalid IL or missing references) //IL_0051: Expected O, but got Unknown //IL_0062: Unknown result type (might be due to invalid IL or missing references) //IL_006c: Expected O, but got Unknown //IL_007d: Unknown result type (might be due to invalid IL or missing references) //IL_0087: Expected O, but got Unknown //IL_0098: Unknown result type (might be due to invalid IL or missing references) //IL_00a2: Expected O, but got Unknown //IL_00b3: Unknown result type (might be due to invalid IL or missing references) //IL_00bd: Expected O, but got Unknown //IL_00ce: Unknown result type (might be due to invalid IL or missing references) //IL_00d8: Expected O, but got Unknown //IL_00e9: Unknown result type (might be due to invalid IL or missing references) //IL_00f3: Expected O, but got Unknown //IL_0104: Unknown result type (might be due to invalid IL or missing references) //IL_010e: Expected O, but got Unknown //IL_011f: Unknown result type (might be due to invalid IL or missing references) //IL_0129: Expected O, but got Unknown //IL_013a: Unknown result type (might be due to invalid IL or missing references) //IL_0144: Expected O, but got Unknown NetworkManager.__rpc_func_table.Add(3672466612u, new RpcReceiveHandler(__rpc_handler_3672466612)); NetworkManager.__rpc_func_table.Add(3074971930u, new RpcReceiveHandler(__rpc_handler_3074971930)); NetworkManager.__rpc_func_table.Add(3462423043u, new RpcReceiveHandler(__rpc_handler_3462423043)); NetworkManager.__rpc_func_table.Add(820724324u, new RpcReceiveHandler(__rpc_handler_820724324)); NetworkManager.__rpc_func_table.Add(179361894u, new RpcReceiveHandler(__rpc_handler_179361894)); NetworkManager.__rpc_func_table.Add(3281224843u, new RpcReceiveHandler(__rpc_handler_3281224843)); NetworkManager.__rpc_func_table.Add(2696007838u, new RpcReceiveHandler(__rpc_handler_2696007838)); NetworkManager.__rpc_func_table.Add(2549144616u, new RpcReceiveHandler(__rpc_handler_2549144616)); NetworkManager.__rpc_func_table.Add(2063608820u, new RpcReceiveHandler(__rpc_handler_2063608820)); NetworkManager.__rpc_func_table.Add(4146414765u, new RpcReceiveHandler(__rpc_handler_4146414765)); NetworkManager.__rpc_func_table.Add(2203520695u, new RpcReceiveHandler(__rpc_handler_2203520695)); NetworkManager.__rpc_func_table.Add(2502216668u, new RpcReceiveHandler(__rpc_handler_2502216668)); } private static void __rpc_handler_3672466612(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)1; ((XP)(object)target).ChangeXPRequirement_ServerRpc(); target.__rpc_exec_stage = (__RpcExecStage)0; } } private static void __rpc_handler_3074971930(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams) { //IL_0023: Unknown result type (might be due to invalid IL or missing references) //IL_0036: Unknown result type (might be due to invalid IL or missing references) //IL_0050: Unknown result type (might be due to invalid IL or missing references) NetworkManager networkManager = target.NetworkManager; if (networkManager != null && networkManager.IsListening) { int xp = default(int); ByteUnpacker.ReadValueBitPacked(reader, ref xp); target.__rpc_exec_stage = (__RpcExecStage)1; ((XP)(object)target).AddXPServerRPC(xp); target.__rpc_exec_stage = (__RpcExecStage)0; } } private static void __rpc_handler_3462423043(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams) { //IL_0023: Unknown result type (might be due to invalid IL or missing references) //IL_0030: Unknown result type (might be due to invalid IL or missing references) //IL_003d: Unknown result type (might be due to invalid IL or missing references) //IL_0050: Unknown result type (might be due to invalid IL or missing references) //IL_0072: Unknown result type (might be due to invalid IL or missing references) NetworkManager networkManager = target.NetworkManager; if (networkManager != null && networkManager.IsListening) { int oldXP = default(int); ByteUnpacker.ReadValueBitPacked(reader, ref oldXP); int newXP = default(int); ByteUnpacker.ReadValueBitPacked(reader, ref newXP); int xpGained = default(int); ByteUnpacker.ReadValueBitPacked(reader, ref xpGained); target.__rpc_exec_stage = (__RpcExecStage)2; ((XP)(object)target).XPHUDUpdate_ClientRPC(oldXP, newXP, xpGained); target.__rpc_exec_stage = (__RpcExecStage)0; } } private static void __rpc_handler_820724324(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; ((XP)(object)target).LevelUp_ClientRPC(); target.__rpc_exec_stage = (__RpcExecStage)0; } } private static void __rpc_handler_179361894(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; ((XP)(object)target).Givepoint_ClientRPC(); target.__rpc_exec_stage = (__RpcExecStage)0; } } private static void __rpc_handler_3281224843(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams) { //IL_002f: Unknown result type (might be due to invalid IL or missing references) //IL_0035: Unknown result type (might be due to invalid IL or missing references) //IL_0044: Unknown result type (might be due to invalid IL or missing references) //IL_005e: Unknown result type (might be due to invalid IL or missing references) NetworkManager networkManager = target.NetworkManager; if (networkManager != null && networkManager.IsListening) { float updatedValue = default(float); ((FastBufferReader)(ref reader)).ReadValueSafe<float>(ref updatedValue, default(ForPrimitives)); target.__rpc_exec_stage = (__RpcExecStage)1; ((XP)(object)target).TeamLootValueUpdate_ServerRpc(updatedValue); target.__rpc_exec_stage = (__RpcExecStage)0; } } private static void __rpc_handler_2696007838(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams) { //IL_0023: Unknown result type (might be due to invalid IL or missing references) //IL_0030: Unknown result type (might be due to invalid IL or missing references) //IL_0043: Unknown result type (might be due to invalid IL or missing references) //IL_0061: Unknown result type (might be due to invalid IL or missing references) NetworkManager networkManager = target.NetworkManager; if (networkManager != null && networkManager.IsListening) { ulong playerID = default(ulong); ByteUnpacker.ReadValueBitPacked(reader, ref playerID); int newSlots = default(int); ByteUnpacker.ReadValueBitPacked(reader, ref newSlots); target.__rpc_exec_stage = (__RpcExecStage)1; ((XP)(object)target).ServerHandSlots_ServerRpc(playerID, newSlots); target.__rpc_exec_stage = (__RpcExecStage)0; } } private static void __rpc_handler_2549144616(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams) { //IL_0023: Unknown result type (might be due to invalid IL or missing references) //IL_0030: Unknown result type (might be due to invalid IL or missing references) //IL_0043: Unknown result type (might be due to invalid IL or missing references) //IL_0061: Unknown result type (might be due to invalid IL or missing references) NetworkManager networkManager = target.NetworkManager; if (networkManager != null && networkManager.IsListening) { ulong playerID = default(ulong); ByteUnpacker.ReadValueBitPacked(reader, ref playerID); int newSlots = default(int); ByteUnpacker.ReadValueBitPacked(reader, ref newSlots); target.__rpc_exec_stage = (__RpcExecStage)2; ((XP)(object)target).SetPlayerHandslots_ClientRpc(playerID, newSlots); target.__rpc_exec_stage = (__RpcExecStage)0; } } private static void __rpc_handler_2063608820(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)1; ((XP)(object)target).GetEveryoneHandSlots_ServerRpc(); target.__rpc_exec_stage = (__RpcExecStage)0; } } private static void __rpc_handler_4146414765(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams) { //IL_0023: Unknown result type (might be due to invalid IL or missing references) //IL_0030: Unknown result type (might be due to invalid IL or missing references) //IL_0043: Unknown result type (might be due to invalid IL or missing references) //IL_0061: Unknown result type (might be due to invalid IL or missing references) NetworkManager networkManager = target.NetworkManager; if (networkManager != null && networkManager.IsListening) { ulong playerID = default(ulong); ByteUnpacker.ReadValueBitPacked(reader, ref playerID); int handSlots = default(int); ByteUnpacker.ReadValueBitPacked(reader, ref handSlots); target.__rpc_exec_stage = (__RpcExecStage)2; ((XP)(object)target).SendEveryoneHandSlots_ClientRpc(playerID, handSlots); target.__rpc_exec_stage = (__RpcExecStage)0; } } private static void __rpc_handler_2203520695(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)1; ((XP)(object)target).PlayerConnect_ServerRpc(); target.__rpc_exec_stage = (__RpcExecStage)0; } } private static void __rpc_handler_2502216668(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams) { //IL_002f: Unknown result type (might be due to invalid IL or missing references) //IL_0035: Unknown result type (might be due to invalid IL or missing references) //IL_0061: Unknown result type (might be due to invalid IL or missing references) //IL_007b: Unknown result type (might be due to invalid IL or missing references) NetworkManager networkManager = target.NetworkManager; if (networkManager != null && networkManager.IsListening) { bool flag = default(bool); ((FastBufferReader)(ref reader)).ReadValueSafe<bool>(ref flag, default(ForPrimitives)); string serializedConfig = null; if (flag) { ((FastBufferReader)(ref reader)).ReadValueSafe(ref serializedConfig, false); } target.__rpc_exec_stage = (__RpcExecStage)2; ((XP)(object)target).SendEveryoneConfigs_ClientRpc(serializedConfig); target.__rpc_exec_stage = (__RpcExecStage)0; } } protected internal override string __getTypeName() { return "XP"; } } public static class MyPluginInfo { public const string PLUGIN_GUID = "LethalProgression"; public const string PLUGIN_NAME = "LethalProgression"; public const string PLUGIN_VERSION = "1.0.0"; } } namespace LethalProgression.GUI { [HarmonyPatch] internal class GUIUpdate { public static bool isMenuOpen; public static SkillsGUI guiInstance; [HarmonyPostfix] [HarmonyPatch(typeof(QuickMenuManager), "Update")] private static void SkillMenuUpdate(QuickMenuManager __instance) { //IL_00d7: Unknown result type (might be due to invalid IL or missing references) //IL_00dc: Unknown result type (might be due to invalid IL or missing references) //IL_0100: Unknown result type (might be due to invalid IL or missing references) //IL_0111: Unknown result type (might be due to invalid IL or missing references) //IL_0116: Unknown result type (might be due to invalid IL or missing references) //IL_0129: Unknown result type (might be due to invalid IL or missing references) //IL_013a: Unknown result type (might be due to invalid IL or missing references) //IL_013f: Unknown result type (might be due to invalid IL or missing references) //IL_0152: Unknown result type (might be due to invalid IL or missing references) //IL_0163: Unknown result type (might be due to invalid IL or missing references) //IL_0168: Unknown result type (might be due to invalid IL or missing references) //IL_017b: Unknown result type (might be due to invalid IL or missing references) //IL_018c: Unknown result type (might be due to invalid IL or missing references) //IL_0191: Unknown result type (might be due to invalid IL or missing references) //IL_019d: Unknown result type (might be due to invalid IL or missing references) //IL_01a7: Unknown result type (might be due to invalid IL or missing references) //IL_01be: Unknown result type (might be due to invalid IL or missing references) //IL_01c8: Unknown result type (might be due to invalid IL or missing references) if (guiInstance == null || !Object.op_Implicit((Object)(object)guiInstance.mainPanel)) { return; } if (isMenuOpen) { if (bool.Parse(SkillConfig.hostConfig["Unspec in Ship Only"]) && !bool.Parse(SkillConfig.hostConfig["Disable Unspec"])) { if (GameNetworkManager.Instance.localPlayerController.isInHangarShipRoom) { guiInstance.SetUnspec(show: true); } else { guiInstance.SetUnspec(show: false); } } if (bool.Parse(SkillConfig.hostConfig["Disable Unspec"])) { guiInstance.SetUnspec(show: false); } Vector2 val = ((InputControl<Vector2>)(object)((Pointer)Mouse.current).position).ReadValue(); GameObject gameObject = ((Component)guiInstance.mainPanel.transform.GetChild(2)).gameObject; float x = gameObject.transform.position.x; Rect rect = gameObject.GetComponent<RectTransform>().rect; float num = x - ((Rect)(ref rect)).width; float x2 = gameObject.transform.position.x; rect = gameObject.GetComponent<RectTransform>().rect; float num2 = x2 + ((Rect)(ref rect)).width; float y = gameObject.transform.position.y; rect = gameObject.GetComponent<RectTransform>().rect; float num3 = y - ((Rect)(ref rect)).height; float y2 = gameObject.transform.position.y; rect = gameObject.GetComponent<RectTransform>().rect; float num4 = y2 + ((Rect)(ref rect)).height; if (val.x >= num && val.x <= num2) { if (val.y >= num3 && val.y <= num4) { ((Component)guiInstance.mainPanel.transform.GetChild(2).GetChild(2)).gameObject.SetActive(true); } else { ((Component)guiInstance.mainPanel.transform.GetChild(2).GetChild(2)).gameObject.SetActive(false); } } else { ((Component)guiInstance.mainPanel.transform.GetChild(2).GetChild(2)).gameObject.SetActive(false); } guiInstance.mainPanel.SetActive(true); GameObject val2 = GameObject.Find("Systems/UI/Canvas/QuickMenu/MainButtons"); val2.SetActive(false); GameObject val3 = GameObject.Find("Systems/UI/Canvas/QuickMenu/PlayerList"); val3.SetActive(false); RealTimeUpdateInfo(); } else { guiInstance.mainPanel.SetActive(false); } } [HarmonyPostfix] [HarmonyPatch(typeof(QuickMenuManager), "CloseQuickMenu")] private static void SkillMenuClose(QuickMenuManager __instance) { isMenuOpen = false; } private static void RealTimeUpdateInfo() { GameObject gameObject = ((Component)guiInstance.mainPanel.transform.GetChild(2)).gameObject; gameObject = ((Component)gameObject.transform.GetChild(1)).gameObject; TextMeshProUGUI component = gameObject.GetComponent<TextMeshProUGUI>(); ((TMP_Text)component).text = LP_NetworkManager.xpInstance.GetSkillPoints().ToString(); } } internal class SkillsGUI { public GameObject mainPanel; public GameObject infoPanel; public Skill activeSkill; public GameObject templateSlot; public List<GameObject> skillButtonsList = new List<GameObject>(); public int shownSkills = 0; public SkillsGUI() { CreateSkillMenu(); GUIUpdate.guiInstance = this; } public void OpenSkillMenu() { GUIUpdate.isMenuOpen = true; mainPanel.SetActive(true); } public void CreateSkillMenu() { //IL_00b2: Unknown result type (might be due to invalid IL or missing references) //IL_00bc: Expected O, but got Unknown //IL_00cf: Unknown result type (might be due to invalid IL or missing references) //IL_00d9: Expected O, but got Unknown mainPanel = Object.Instantiate<GameObject>(LethalPlugin.skillBundle.LoadAsset<GameObject>("SkillMenu")); ((Object)mainPanel).name = "SkillMenu"; mainPanel.SetActive(false); templateSlot = Object.Instantiate<GameObject>(GameObject.Find("Systems/UI/Canvas/IngamePlayerHUD/Inventory/Slot3")); ((Object)templateSlot).name = "TemplateSlot"; templateSlot.SetActive(false); infoPanel = ((Component)mainPanel.transform.GetChild(1)).gameObject; infoPanel.SetActive(false); GameObject gameObject = ((Component)mainPanel.transform.GetChild(4)).gameObject; gameObject.GetComponent<Button>().onClick = new ButtonClickedEvent(); ((UnityEvent)gameObject.GetComponent<Button>().onClick).AddListener(new UnityAction(BackButton)); shownSkills = 0; if (LP_NetworkManager.xpInstance.skillList.skills == null) { return; } foreach (KeyValuePair<UpgradeType, Skill> skill in LP_NetworkManager.xpInstance.skillList.skills) { LethalPlugin.Log.LogInfo((object)("Creating button for " + skill.Value.GetShortName())); GameObject val = SetupUpgradeButton(skill.Value); LethalPlugin.Log.LogInfo((object)"Setup passed!"); skillButtonsList.Add(val); LethalPlugin.Log.LogInfo((object)"Added to skill list.."); LoadSkillData(skill.Value, val); } TeamLootHudUpdate(1f, 1f); } public void BackButton() { GUIUpdate.isMenuOpen = false; GameObject val = GameObject.Find("Systems/UI/Canvas/QuickMenu/MainButtons"); val.SetActive(true); GameObject val2 = GameObject.Find("Systems/UI/Canvas/QuickMenu/PlayerList"); val2.SetActive(true); } public void SetUnspec(bool show) { GameObject gameObject = ((Component)infoPanel.transform.GetChild(6)).gameObject; GameObject gameObject2 = ((Component)infoPanel.transform.GetChild(7)).gameObject; GameObject gameObject3 = ((Component)infoPanel.transform.GetChild(8)).gameObject; gameObject.SetActive(show); gameObject2.SetActive(show); gameObject3.SetActive(show); if (!bool.Parse(SkillConfig.hostConfig["Disable Unspec"])) { GameObject gameObject4 = ((Component)infoPanel.transform.GetChild(9)).gameObject; gameObject4.SetActive(!show); } } public GameObject SetupUpgradeButton(Skill skill) { //IL_01b3: Unknown result type (might be due to invalid IL or missing references) //IL_01bd: Expected O, but got Unknown //IL_01d0: Unknown result type (might be due to invalid IL or missing references) //IL_01da: Expected O, but got Unknown GameObject gameObject = ((Component)mainPanel.transform.GetChild(0)).gameObject; GameObject val = Object.Instantiate<GameObject>(gameObject); if (!Object.op_Implicit((Object)(object)gameObject)) { LethalPlugin.Log.LogError((object)"Couldn't find template button!"); return null; } ((Object)val).name = skill.GetShortName(); GameObject gameObject2 = ((Component)mainPanel.transform.GetChild(3)).gameObject; GameObject gameObject3 = ((Component)gameObject2.transform.GetChild(1)).gameObject; val.transform.SetParent(gameObject3.transform, false); shownSkills++; GameObject gameObject4 = ((Component)val.transform.GetChild(0)).gameObject; ((TMP_Text)gameObject4.GetComponent<TextMeshProUGUI>()).SetText(skill.GetShortName(), true); GameObject gameObject5 = ((Component)val.transform.GetChild(1)).gameObject; ((TMP_Text)gameObject5.GetComponent<TextMeshProUGUI>()).SetText(skill.GetLevel().ToString(), true); GameObject gameObject6 = ((Component)val.transform.GetChild(2)).gameObject; ((TMP_Text)gameObject6.GetComponent<TextMeshProUGUI>()).SetText("(" + skill.GetLevel() + " " + skill.GetAttribute() + ")", true); ((TMP_Text)val.GetComponentInChildren<TextMeshProUGUI>()).SetText(skill.GetShortName() + ":", true); val.SetActive(true); val.GetComponent<Button>().onClick = new ButtonClickedEvent(); ((UnityEvent)val.GetComponent<Button>().onClick).AddListener((UnityAction)delegate { UpdateStatInfo(skill); }); return val; } public void LoadSkillData(Skill skill, GameObject skillButton) { if (!skill._teamShared) { GameObject gameObject = ((Component)skillButton.transform.GetChild(0)).gameObject; ((TMP_Text)gameObject.GetComponent<TextMeshProUGUI>()).SetText(skill.GetShortName(), true); GameObject gameObject2 = ((Component)skillButton.transform.GetChild(1)).gameObject; ((TMP_Text)gameObject2.GetComponent<TextMeshProUGUI>()).SetText(skill.GetLevel().ToString(), true); GameObject gameObject3 = ((Component)skillButton.transform.GetChild(2)).gameObject; ((TMP_Text)gameObject3.GetComponent<TextMeshProUGUI>()).SetText("(+" + (float)skill.GetLevel() * skill.GetMultiplier() + "% " + skill.GetAttribute() + ")", true); ((TMP_Text)skillButton.GetComponentInChildren<TextMeshProUGUI>()).SetText(skill.GetShortName() + ":", true); } } public void UpdateStatInfo(Skill skill) { //IL_017d: Unknown result type (might be due to invalid IL or missing references) //IL_0187: Expected O, but got Unknown //IL_019b: Unknown result type (might be due to invalid IL or missing references) //IL_01a5: Expected O, but got Unknown //IL_01ad: Unknown result type (might be due to invalid IL or missing references) //IL_01b7: Expected O, but got Unknown //IL_01cb: Unknown result type (might be due to invalid IL or missing references) //IL_01d5: Expected O, but got Unknown //IL_01dd: Unknown result type (might be due to invalid IL or missing references) //IL_01e7: Expected O, but got Unknown //IL_01fb: Unknown result type (might be due to invalid IL or missing references) //IL_0205: Expected O, but got Unknown //IL_0255: Unknown result type (might be due to invalid IL or missing references) //IL_025f: Expected O, but got Unknown //IL_0273: Unknown result type (might be due to invalid IL or missing references) //IL_027d: Expected O, but got Unknown //IL_0285: Unknown result type (might be due to invalid IL or missing references) //IL_028f: Expected O, but got Unknown //IL_02a3: Unknown result type (might be due to invalid IL or missing references) //IL_02ad: Expected O, but got Unknown //IL_02b5: Unknown result type (might be due to invalid IL or missing references) //IL_02bf: Expected O, but got Unknown //IL_02d3: Unknown result type (might be due to invalid IL or missing references) //IL_02dd: Expected O, but got Unknown if (!infoPanel.activeSelf) { infoPanel.SetActive(true); } TextMeshProUGUI component = ((Component)infoPanel.transform.GetChild(0)).gameObject.GetComponent<TextMeshProUGUI>(); TextMeshProUGUI component2 = ((Component)infoPanel.transform.GetChild(1)).gameObject.GetComponent<TextMeshProUGUI>(); TextMeshProUGUI component3 = ((Component)infoPanel.transform.GetChild(2)).gameObject.GetComponent<TextMeshProUGUI>(); activeSkill = skill; ((TMP_Text)component).SetText(skill.GetName(), true); if (skill.GetMaxLevel() == 99999) { ((TMP_Text)component2).SetText($"{skill.GetLevel()}", true); } else { ((TMP_Text)component2).SetText($"{skill.GetLevel()} / {skill.GetMaxLevel()}", true); } ((TMP_Text)component3).SetText(skill.GetDescription(), true); GameObject gameObject = ((Component)infoPanel.transform.GetChild(3)).gameObject; GameObject gameObject2 = ((Component)infoPanel.transform.GetChild(4)).gameObject; GameObject gameObject3 = ((Component)infoPanel.transform.GetChild(5)).gameObject; gameObject.GetComponent<Button>().onClick = new ButtonClickedEvent(); ((UnityEvent)gameObject.GetComponent<Button>().onClick).AddListener((UnityAction)delegate { AddSkillPoint(skill, 5); }); gameObject2.GetComponent<Button>().onClick = new ButtonClickedEvent(); ((UnityEvent)gameObject2.GetComponent<Button>().onClick).AddListener((UnityAction)delegate { AddSkillPoint(skill, 2); }); gameObject3.GetComponent<Button>().onClick = new ButtonClickedEvent(); ((UnityEvent)gameObject3.GetComponent<Button>().onClick).AddListener((UnityAction)delegate { AddSkillPoint(skill, 1); }); GameObject gameObject4 = ((Component)infoPanel.transform.GetChild(6)).gameObject; GameObject gameObject5 = ((Component)infoPanel.transform.GetChild(7)).gameObject; GameObject gameObject6 = ((Component)infoPanel.transform.GetChild(8)).gameObject; gameObject4.GetComponent<Button>().onClick = new ButtonClickedEvent(); ((UnityEvent)gameObject4.GetComponent<Button>().onClick).AddListener((UnityAction)delegate { RemoveSkillPoint(skill, 5); }); gameObject5.GetComponent<Button>().onClick = new ButtonClickedEvent(); ((UnityEvent)gameObject5.GetComponent<Button>().onClick).AddListener((UnityAction)delegate { RemoveSkillPoint(skill, 2); }); gameObject6.GetComponent<Button>().onClick = new ButtonClickedEvent(); ((UnityEvent)gameObject6.GetComponent<Button>().onClick).AddListener((UnityAction)delegate { RemoveSkillPoint(skill, 1); }); } public void AddSkillPoint(Skill skill, int amt) { if (LP_NetworkManager.xpInstance.GetSkillPoints() <= 0) { return; } int skillPoints = LP_NetworkManager.xpInstance.GetSkillPoints(); if (skillPoints < amt) { amt = skillPoints; } if (skill.GetLevel() + amt > skill.GetMaxLevel()) { amt = skill.GetMaxLevel() - skill.GetLevel(); } skill.AddLevel(amt); LP_NetworkManager.xpInstance.SetSkillPoints(LP_NetworkManager.xpInstance.GetSkillPoints() - amt); UpdateStatInfo(skill); foreach (GameObject skillButtons in skillButtonsList) { if (((Object)skillButtons).name == skill.GetShortName()) { LoadSkillData(skill, skillButtons); } } } public void RemoveSkillPoint(Skill skill, int amt) { if (skill.GetLevel() == 0) { return; } int level = skill.GetLevel(); if (level < amt) { amt = level; } skill.AddLevel(-amt); LP_NetworkManager.xpInstance.SetSkillPoints(LP_NetworkManager.xpInstance.GetSkillPoints() + amt); UpdateStatInfo(skill); foreach (GameObject skillButtons in skillButtonsList) { if (((Object)skillButtons).name == skill.GetShortName()) { LoadSkillData(skill, skillButtons); } } } public void TeamLootHudUpdate(float oldValue, float newValue) { foreach (GameObject skillButtons in skillButtonsList) { if (((Object)skillButtons).name == "VAL") { Skill skill = LP_NetworkManager.xpInstance.skillList.skills[UpgradeType.Value]; LoadSkillData(skill, skillButtons); GameObject gameObject = ((Component)skillButtons.transform.GetChild(0)).gameObject; ((TMP_Text)gameObject.GetComponent<TextMeshProUGUI>()).SetText(skill.GetShortName(), true); GameObject gameObject2 = ((Component)skillButtons.transform.GetChild(1)).gameObject; ((TMP_Text)gameObject2.GetComponent<TextMeshProUGUI>()).SetText(skill.GetLevel().ToString(), true); ((TMP_Text)skillButtons.GetComponentInChildren<TextMeshProUGUI>()).SetText(skill.GetShortName() + ":", true); GameObject gameObject3 = ((Component)skillButtons.transform.GetChild(2)).gameObject; ((TMP_Text)gameObject3.GetComponent<TextMeshProUGUI>()).SetText("(+" + LP_NetworkManager.xpInstance.teamLootValue.Value + "% " + skill.GetAttribute() + ")", true); LethalPlugin.Log.LogInfo((object)$"Setting team value hud to {LP_NetworkManager.xpInstance.teamLootValue.Value}"); } } } } } namespace LethalProgression.Skills { public enum UpgradeType { HPRegen, Stamina, Battery, HandSlot, Value, Oxygen } internal class SkillList { public Dictionary<UpgradeType, Skill> skills = new Dictionary<UpgradeType, Skill>(); public void CreateSkill(UpgradeType upgrade, string name, string description, string shortname, string attribute, UpgradeType upgradeType, int cost, int maxLevel, float multiplier, Action<int, int> callback = null, bool teamShared = false) { Skill value = new Skill(name, description, shortname, attribute, upgradeType, cost, maxLevel, multiplier, callback, teamShared); skills.Add(upgrade, value); } public bool IsSkillListValid() { if (skills.Count == 0) { return false; } return true; } public bool IsSkillValid(UpgradeType upgrade) { if (!skills.ContainsKey(upgrade)) { LethalPlugin.Log.LogInfo((object)("Skill " + upgrade.ToString() + " is not in the skill list!")); return false; } return true; } public void InitializeSkills() { if (bool.Parse(SkillConfig.hostConfig["Health Regen Enabled"])) { LethalPlugin.Log.LogInfo((object)"HP Regen check 1"); CreateSkill(UpgradeType.HPRegen, "Health Regen", "The company installs a basic healer into your suit, letting you regenerate health slowly. Only regenerate up to 100 HP.", "HPR", "Health Regeneration", UpgradeType.HPRegen, 1, int.Parse(SkillConfig.hostConfig["Health Regen Max Level"]), float.Parse(SkillConfig.hostConfig["Health Regen Multiplier"], CultureInfo.InvariantCulture)); } if (bool.Parse(SkillConfig.hostConfig["Stamina Enabled"])) { CreateSkill(UpgradeType.Stamina, "Stamina", "Hours on that company gym finally coming into play. Allows you to run for longer.", "STM", "Stamina", UpgradeType.Stamina, 1, int.Parse(SkillConfig.hostConfig["Stamina Max Level"]), float.Parse(SkillConfig.hostConfig["Stamina Multiplier"], CultureInfo.InvariantCulture), Stamina.StaminaUpdate); } if (bool.Parse(SkillConfig.hostConfig["Battery Life Enabled"])) { CreateSkill(UpgradeType.Battery, "Battery Life", "The company provides you with better batteries. Replace your batteries AT THE SHIP'S CHARGER to see an effect.", "BAT", "Battery Life", UpgradeType.Battery, 1, int.Parse(SkillConfig.hostConfig["Battery Life Max Level"]), float.Parse(SkillConfig.hostConfig["Battery Life Multiplier"], CultureInfo.InvariantCulture)); } if (bool.Parse(SkillConfig.hostConfig["Hand Slots Enabled"]) && !LethalPlugin.ReservedSlots) { CreateSkill(UpgradeType.HandSlot, "Hand Slot", "The company finally gives you a better belt! Fit more stuff! (Reach 100% for one slot.)", "HND", "Hand Slots", UpgradeType.HandSlot, 1, int.Parse(SkillConfig.hostConfig["Hand Slots Max Level"]), float.Parse(SkillConfig.hostConfig["Hand Slots Multiplier"], CultureInfo.InvariantCulture), HandSlots.HandSlotsUpdate); } if (bool.Parse(SkillConfig.hostConfig["Loot Value Enabled"])) { CreateSkill(UpgradeType.Value, "Loot Value", "The company gives you a better pair of eyes, allowing you to see the value in things.", "VAL", "Loot Value", UpgradeType.Value, 1, int.Parse(SkillConfig.hostConfig["Loot Value Max Level"]), float.Parse(SkillConfig.hostConfig["Loot Value Multiplier"], CultureInfo.InvariantCulture), LootValue.LootValueUpdate); } if (bool.Parse(SkillConfig.hostConfig["Oxygen Enabled"])) { CreateSkill(UpgradeType.Oxygen, "Oxygen", "The company installs you with oxygen tanks. You gain extra time in the water. (Start drowning when the bar is empty.)", "OXY", "Extra Oxygen", UpgradeType.Oxygen, 1, int.Parse(SkillConfig.hostConfig["Oxygen Max Level"]), float.Parse(SkillConfig.hostConfig["Oxygen Multiplier"], CultureInfo.InvariantCulture)); } } } internal class Skill { private readonly string _shortName; private readonly string _name; private readonly string _attribute; private readonly string _description; private readonly UpgradeType _upgradeType; private readonly int _cost; private readonly int _maxLevel; private readonly float _multiplier; private readonly Action<int, int> _callback; public bool _teamShared; private int _level; public Skill(string name, string description, string shortname, string attribute, UpgradeType upgradeType, int cost, int maxLevel, float multiplier, Action<int, int> callback = null, bool teamShared = false) { _name = name; _shortName = shortname; _attribute = attribute; _description = description; _upgradeType = upgradeType; _cost = cost; _maxLevel = maxLevel; _multiplier = multiplier; _level = 0; _callback = callback; _teamShared = teamShared; } public string GetName() { return _name; } public string GetShortName() { return _shortName; } public string GetAttribute() { return _attribute; } public string GetDescription() { return _description; } public UpgradeType GetUpgradeType() { return _upgradeType; } public int GetCost() { return _cost; } public int GetMaxLevel() { return _maxLevel; } public int GetLevel() { return _level; } public float GetMultiplier() { return _multiplier; } public float GetTrueValue() { return _multiplier * (float)_level; } public void SetLevel(int level) { _level = level; } public void AddLevel(int level) { _level += level; int level2 = _level; _callback?.Invoke(level, level2); } } [HarmonyPatch] internal class BatteryLife { [HarmonyPrefix] [HarmonyPatch(typeof(GrabbableObject), "SyncBatteryServerRpc")] public static void BatteryUpdate(ref int charge) { if (LP_NetworkManager.xpInstance.skillList.IsSkillListValid() && LP_NetworkManager.xpInstance.skillList.IsSkillValid(UpgradeType.Battery) && charge == 100) { charge += (int)LP_NetworkManager.xpInstance.skillList.skills[UpgradeType.Battery].GetTrueValue(); } } } internal class HandSlots { public static int currentSlotCount = 4; public static void HandSlotsUpdate(int updateValue, int newValue) { //IL_0244: Unknown result type (might be due to invalid IL or missing references) //IL_0249: Unknown result type (might be due to invalid IL or missing references) //IL_0252: Unknown result type (might be due to invalid IL or missing references) //IL_025f: Unknown result type (might be due to invalid IL or missing references) //IL_0266: Unknown result type (might be due to invalid IL or missing references) //IL_026d: Unknown result type (might be due to invalid IL or missing references) //IL_0279: Unknown result type (might be due to invalid IL or missing references) //IL_02e2: Unknown result type (might be due to invalid IL or missing references) //IL_02e7: Unknown result type (might be due to invalid IL or missing references) //IL_02f3: Unknown result type (might be due to invalid IL or missing references) //IL_0300: Unknown result type (might be due to invalid IL or missing references) //IL_0307: Unknown result type (might be due to invalid IL or missing references) //IL_030e: Unknown result type (might be due to invalid IL or missing references) //IL_031d: Unknown result type (might be due to invalid IL or missing references) if (LethalPlugin.ReservedSlots || !LP_NetworkManager.xpInstance.skillList.IsSkillListValid() || !LP_NetworkManager.xpInstance.skillList.IsSkillValid(UpgradeType.HandSlot)) { return; } XP xpInstance = LP_NetworkManager.xpInstance; float num = xpInstance.skillList.skills[UpgradeType.HandSlot].GetTrueValue() / 100f; int num2 = 4 + (int)Math.Floor(num); int num3 = num2 - currentSlotCount; GameObject val = GameObject.Find("Systems/UI/Canvas/IngamePlayerHUD/Inventory"); List<string> list = new List<string> { "Slot0", "Slot1", "Slot2", "Slot3" }; for (int i = 0; i < val.transform.childCount; i++) { Transform child = val.transform.GetChild(i); if (!list.Contains(((Object)((Component)child).gameObject).name)) { Object.Destroy((Object)(object)((Component)child).gameObject); } } int num4 = (int)xpInstance.skillList.skills[UpgradeType.HandSlot].GetTrueValue(); int newSlots = (int)Math.Floor((double)(num4 / 100)); Image[] array = (Image[])(object)new Image[num2]; array[0] = HUDManager.Instance.itemSlotIconFrames[0]; array[1] = HUDManager.Instance.itemSlotIconFrames[1]; array[2] = HUDManager.Instance.itemSlotIconFrames[2]; array[3] = HUDManager.Instance.itemSlotIconFrames[3]; Image[] array2 = (Image[])(object)new Image[num2]; array2[0] = HUDManager.Instance.itemSlotIcons[0]; array2[1] = HUDManager.Instance.itemSlotIcons[1]; array2[2] = HUDManager.Instance.itemSlotIcons[2]; array2[3] = HUDManager.Instance.itemSlotIcons[3]; GameObject val2 = GameObject.Find("Systems/UI/Canvas/IngamePlayerHUD/Inventory/Slot3"); GameObject templateSlot = xpInstance.guiObj.templateSlot; GameObject val3 = val2; currentSlotCount = num2; for (int j = 0; j < (int)num; j++) { GameObject val4 = Object.Instantiate<GameObject>(templateSlot); ((Object)val4).name = $"Slot{3 + (j + 1)}"; val4.transform.SetParent(val.transform); Vector3 localPosition = val3.transform.localPosition; val4.transform.SetLocalPositionAndRotation(new Vector3(localPosition.x + 50f, localPosition.y, localPosition.z), val3.transform.localRotation); val3 = val4; array[3 + (j + 1)] = val4.GetComponent<Image>(); array2[3 + (j + 1)] = ((Component)val4.transform.GetChild(0)).GetComponent<Image>(); val4.SetActive(true); } for (int k = 0; k < array.Length; k++) { Vector3 localPosition2 = ((Component)array[k]).transform.localPosition; ((Component)array[k]).transform.SetLocalPositionAndRotation(new Vector3(localPosition2.x - (float)(num3 * 25), localPosition2.y, localPosition2.z), ((Component)array[k]).transform.localRotation); } HUDManager.Instance.itemSlotIconFrames = array; HUDManager.Instance.itemSlotIcons = array2; ulong playerClientId = GameNetworkManager.Instance.localPlayerController.playerClientId; xpInstance.ServerHandSlots_ServerRpc(playerClientId, newSlots); } } [HarmonyPatch] internal class HPRegen { [HarmonyPostfix] [HarmonyPatch(typeof(PlayerControllerB), "LateUpdate")] private static void HPRegenUpdate(PlayerControllerB __instance) { if (__instance.health >= 100 || !LP_NetworkManager.xpInstance.skillList.IsSkillListValid() || !LP_NetworkManager.xpInstance.skillList.IsSkillValid(UpgradeType.HPRegen) || LP_NetworkManager.xpInstance.skillList.skills[UpgradeType.HPRegen].GetLevel() == 0) { return; } if (__instance.healthRegenerateTimer <= 0f) { Skill skill = LP_NetworkManager.xpInstance.skillList.skills[UpgradeType.HPRegen]; float trueValue = skill.GetTrueValue(); __instance.healthRegenerateTimer = 1f / trueValue; __instance.health++; if (__instance.health >= 20) { __instance.MakeCriticallyInjured(false); } HUDManager.Instance.UpdateHealthUI(__instance.health, false); } else { __instance.healthRegenerateTimer -= Time.deltaTime; } } } [HarmonyPatch] internal class LootValue { [HarmonyPrefix] [HarmonyPatch(typeof(RoundManager), "SpawnScrapInLevel")] private static void AddLootValue() { if (LP_NetworkManager.xpInstance.skillList.IsSkillListValid() && LP_NetworkManager.xpInstance.skillList.IsSkillValid(UpgradeType.Value)) { RoundManager.Instance.scrapValueMultiplier = RoundManager.Instance.scrapValueMultiplier + LP_NetworkManager.xpInstance.teamLootValue.Value / 100f; } } public static void LootValueUpdate(int change, int newLevel) { if (LP_NetworkManager.xpInstance.skillList.IsSkillListValid() && LP_NetworkManager.xpInstance.skillList.IsSkillValid(UpgradeType.Value)) { LP_NetworkManager.xpInstance.TeamLootValueUpdate(change, newLevel); } } } [HarmonyPatch] internal class Oxygen { private static GameObject oxygenBar; private static float oxygen = 0f; private static float oxygenTimer = 0f; private static bool inWater = false; private static bool canDrown = true; [HarmonyPostfix] [HarmonyPatch(typeof(PlayerControllerB), "SetFaceUnderwaterClientRpc")] private static void EnteredWater(PlayerControllerB __instance) { inWater = true; } [HarmonyPostfix] [HarmonyPatch(typeof(PlayerControllerB), "SetFaceOutOfWaterClientRpc")] private static void LeftWater(PlayerControllerB __instance) { inWater = false; } [HarmonyPrefix] [HarmonyPatch(typeof(PlayerControllerB), "SetFaceUnderwaterFilters")] private static void ShouldDrown(PlayerControllerB __instance) { if (!canDrown) { StartOfRound.Instance.drowningTimer = 99f; } } [HarmonyPostfix] [HarmonyPatch(typeof(PlayerControllerB), "LateUpdate")] private static void OxygenUpdate(PlayerControllerB __instance) { if (!LP_NetworkManager.xpInstance.skillList.IsSkillListValid() || !LP_NetworkManager.xpInstance.skillList.IsSkillValid(UpgradeType.Oxygen)) { return; } if (__instance.isPlayerDead) { if (Object.op_Implicit((Object)(object)oxygenBar)) { oxygenBar.SetActive(false); } return; } if (LP_NetworkManager.xpInstance.skillList.skills[UpgradeType.Oxygen].GetLevel() == 0) { if (Object.op_Implicit((Object)(object)oxygenBar)) { oxygenBar.SetActive(false); } if (!canDrown) { canDrown = true; StartOfRound.Instance.drowningTimer = 1f; } return; } if (!Object.op_Implicit((Object)(object)oxygenBar)) { CreateOxygenBar(); } Skill skill = LP_NetworkManager.xpInstance.skillList.skills[UpgradeType.Oxygen]; float trueValue = skill.GetTrueValue(); if (inWater) { oxygenBar.SetActive(true); if (oxygenTimer <= 0f) { oxygenTimer = 0.1f; if (oxygen > 0f) { oxygen -= 0.1f; } else if (!canDrown) { canDrown = true; StartOfRound.Instance.drowningTimer = 1f; } } else { oxygenTimer -= Time.deltaTime; } } if (!inWater) { if (oxygenTimer <= 0f) { oxygenTimer = 0.1f; if (oxygen < trueValue) { oxygenBar.SetActive(true); oxygen += 0.1f; canDrown = false; } else { oxygenBar.SetActive(false); } } else { oxygenTimer -= Time.deltaTime; } } if (oxygen > trueValue) { oxygenBar.SetActive(false); oxygen = trueValue; } if (oxygenBar.activeSelf) { float fillAmount = oxygen / trueValue; ((Component)oxygenBar.transform.GetChild(0).GetChild(0)).GetComponent<Image>().fillAmount = fillAmount; } } public static void CreateOxygenBar() { oxygenBar = Object.Instantiate<GameObject>(LethalPlugin.skillBundle.LoadAsset<GameObject>("OxygenBar")); oxygenBar.SetActive(false); } } internal class Stamina { public static void StaminaUpdate(int updatedValue, int newStamina) { if (LP_NetworkManager.xpInstance.skillList.IsSkillListValid() && LP_NetworkManager.xpInstance.skillList.IsSkillValid(UpgradeType.Stamina)) { Skill skill = LP_NetworkManager.xpInstance.skillList.skills[UpgradeType.Stamina]; PlayerControllerB localPlayerController = GameNetworkManager.Instance.localPlayerController; float num = (float)updatedValue * skill.GetMultiplier() / 100f * 11f; localPlayerController.sprintTime += num; LethalPlugin.Log.LogInfo((object)$"{updatedValue} change, {newStamina} new stamina points, Adding {num} resulting in {localPlayerController.sprintTime} stamina"); } } } } namespace LethalProgression.Patches { [HarmonyPatch] internal class HUDManagerPatch { private static GameObject _tempBar; private static TextMeshProUGUI _tempText; private static float _tempBarTime; private static GameObject levelText; private static float levelTextTime; private static Dictionary<string, int> _enemyReward = new Dictionary<string, int> { { "HoarderBug (EnemyType)", 30 }, { "BaboonBird (EnemyType)", 15 }, { "MouthDog (EnemyType)", 200 }, { "Centipede (EnemyType)", 30 }, { "Flowerman (EnemyType)", 200 }, { "SandSpider (EnemyType)", 50 }, { "Crawler (EnemyType)", 50 }, { "Puffer (EnemyType)", 15 } }; [HarmonyPrefix] [HarmonyPatch(typeof(HUDManager), "AddNewScrapFoundToDisplay")] private static void GiveXPForScrap(GrabbableObject GObject) { if (GameNetworkManager.Instance.isHostingGame) { int scrapValue = GObject.scrapValue; LP_NetworkManager.xpInstance.AddXPServerRPC(scrapValue); } } [HarmonyPostfix] [HarmonyPatch(typeof(EnemyAI), "KillEnemy")] private static void GiveXPForKill(EnemyAI __instance) { string text = ((object)__instance.enemyType).ToString(); LethalPlugin.Log.LogInfo((object)("Enemy type: " + text)); int xp = 30; if (_enemyReward.ContainsKey(text)) { xp = _enemyReward[text]; } LP_NetworkManager.xpInstance.AddXPServerRPC(xp); } public static void ShowXPUpdate(int oldXP, int newXP, int xp) { if (!Object.op_Implicit((Object)(object)_tempBar)) { MakeBar(); } GameObject val = GameObject.Find("/Systems/UI/Canvas/IngamePlayerHUD/BottomMiddle/XPUpdate/XPBarProgress"); val.GetComponent<Image>().fillAmount = (float)newXP / (float)LP_NetworkManager.xpInstance.GetXPRequirement(); ((TMP_Text)_tempText).text = newXP + " / " + (float)LP_NetworkManager.xpInstance.GetXPRequirement(); _tempBarTime = 2f; if (!_tempBar.activeSelf) { ((MonoBehaviour)GameNetworkManager.Instance).StartCoroutine(XPBarCoroutine()); } } private static IEnumerator XPBarCoroutine() { _tempBar.SetActive(true); while (_tempBarTime > 0f) { float time = _tempBarTime; _tempBarTime = 0f; yield return (object)new WaitForSeconds(time); } _tempBar.SetActive(false); } public static void ShowLevelUp() { if (!Object.op_Implicit((Object)(object)levelText)) { MakeLevelUp(); } levelTextTime = 5f; if (!levelText.gameObject.activeSelf) { ((MonoBehaviour)GameNetworkManager.Instance).StartCoroutine(LevelUpCoroutine()); } } public static void MakeLevelUp() { levelText = Object.Instantiate<GameObject>(LethalPlugin.skillBundle.LoadAsset<GameObject>("LevelUp")); ((TMP_Text)((Component)levelText.transform.GetChild(0)).GetComponent<TextMeshProUGUI>()).text = "Level Up! Spend your skill points."; levelText.gameObject.SetActive(false); } private static IEnumerator LevelUpCoroutine() { levelText.gameObject.SetActive(true); while (levelTextTime > 0f) { float time = levelTextTime; levelTextTime = 0f; yield return (object)new WaitForSeconds(time); } levelText.gameObject.SetActive(false); } private static void MakeBar() { //IL_0082: Unknown result type (might be due to invalid IL or missing references) //IL_00da: 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_00eb: Unknown result type (might be due to invalid IL or missing references) //IL_00f2: Unknown result type (might be due to invalid IL or missing references) //IL_00ff: Unknown result type (might be due to invalid IL or missing references) //IL_0106: Unknown result type (might be due to invalid IL or missing references) GameObject val = GameObject.Find("/Systems/UI/Canvas/QuickMenu/XPBar"); QuickMenuManagerPatch.MakeNewXPBar(); val = GameObject.Find("/Systems/UI/Canvas/QuickMenu/XPBar"); _tempBar = Object.Instantiate<GameObject>(val); ((Object)_tempBar).name = "XPUpdate"; _tempText = _tempBar.GetComponentInChildren<TextMeshProUGUI>(); GameObject val2 = GameObject.Find("/Systems/UI/Canvas/IngamePlayerHUD/BottomMiddle"); _tempBar.transform.SetParent(val2.transform, false); _tempBar.transform.localScale = new Vector3(0.4f, 0.4f, 0.4f); GameObject val3 = GameObject.Find("/Systems/UI/Canvas/IngamePlayerHUD/BottomMiddle/XPUpdate/XPLevel"); Object.Destroy((Object)(object)val3); GameObject val4 = GameObject.Find("/Systems/UI/Canvas/IngamePlayerHUD/BottomMiddle/XPUpdate/XPProfit"); Object.Destroy((Object)(object)val4); _tempBar.transform.Translate(3.1f, -2.1f, 0f); Vector3 localPosition = _tempBar.transform.localPosition; _tempBar.transform.localPosition = new Vector3(localPosition.x, localPosition.y + 5f, localPosition.z); _tempBar.SetActive(false); } } [HarmonyPatch] internal class QuickMenuManagerPatch { [CompilerGenerated] private static class <>O { public static UnityAction <0>__OpenSkillTree; } private static GameObject _xpBar; private static GameObject _xpBarProgress; private static TextMeshProUGUI _xpText; private static TextMeshProUGUI _xpLevel; private static TextMeshProUGUI _profit; private static GameObject skillTreeButton; [HarmonyPostfix] [HarmonyPatch(typeof(QuickMenuManager), "OpenQuickMenu")] private static void QuickMenuXPBar(QuickMenuManager __instance) { if (__instance.isMenuOpen) { if (!Object.op_Implicit((Object)(object)_xpBar) || !Object.op_Implicit((Object)(object)_xpBarProgress)) { MakeNewXPBar(); } _xpBar.SetActive(true); _xpBarProgress.SetActive(true); } } [HarmonyPostfix] [HarmonyPatch(typeof(QuickMenuManager), "Update")] private static void XPMenuUpdate(QuickMenuManager __instance) { if (Object.op_Implicit((Object)(object)_xpBar) && Object.op_Implicit((Object)(object)_xpBarProgress)) { if (__instance.mainButtonsPanel.activeSelf) { _xpBar.SetActive(true); _xpBarProgress.SetActive(true); } else { _xpBar.SetActive(false); _xpBarProgress.SetActive(false); } ((TMP_Text)_xpText).text = LP_NetworkManager.xpInstance.GetXP() + " / " + LP_NetworkManager.xpInstance.xpReq.Value; ((TMP_Text)_xpLevel).text = "Level: " + LP_NetworkManager.xpInstance.GetLevel(); ((TMP_Text)_profit).text = "You've made.. " + LP_NetworkManager.xpInstance.GetProfit() + "$"; _xpBarProgress.GetComponent<Image>().fillAmount = (float)LP_NetworkManager.xpInstance.GetXP() / (float)LP_NetworkManager.xpInstance.xpReq.Value; } } public static void MakeNewXPBar() { //IL_0077: Unknown result type (might be due to invalid IL or missing references) //IL_0128: Unknown result type (might be due to invalid IL or missing references) //IL_015c: Unknown result type (might be due to invalid IL or missing references) //IL_0161: Unknown result type (might be due to invalid IL or missing references) //IL_016d: Unknown result type (might be due to invalid IL or missing references) //IL_017a: Unknown result type (might be due to invalid IL or missing references) //IL_018c: Unknown result type (might be due to invalid IL or missing references) //IL_0219: Unknown result type (might be due to invalid IL or missing references) //IL_02b9: Unknown result type (might be due to invalid IL or missing references) //IL_0359: Unknown result type (might be due to invalid IL or missing references) GameObject val = GameObject.Find("/Systems/UI/Canvas/QuickMenu"); if (!Object.op_Implicit((Object)(object)_xpBar)) { GameObject val2 = GameObject.Find("/Systems/UI/Canvas/EndgameStats/LevelUp/LevelUpBox"); _xpBar = Object.Instantiate<GameObject>(val2); ((Object)_xpBar).name = "XPBar"; _xpBar.transform.SetParent(val.transform, false); _xpBar.transform.localScale = new Vector3(0.75f, 0.75f, 0.75f); _xpBar.transform.Translate(-2f, 1f, 0f); } if (!Object.op_Implicit((Object)(object)_xpBarProgress)) { GameObject val3 = GameObject.Find("/Systems/UI/Canvas/EndgameStats/LevelUp/LevelUpMeter"); _xpBarProgress = Object.Instantiate<GameObject>(val3); ((Object)_xpBarProgress).name = "XPBarProgress"; _xpBarProgress.transform.SetParent(_xpBar.transform, false); _xpBarProgress.GetComponent<Image>().fillAmount = 0f; _xpBarProgress.transform.localScale = new Vector3(0.597f, 5.21f, 1f); _xpBarProgress.transform.Translate(-0.8f, 0.2f, 0f); Vector3 localPosition = _xpBarProgress.transform.localPosition; _xpBarProgress.transform.localPosition = new Vector3(localPosition.x + 7f, localPosition.y - 3.5f, 0f); GameObject val4 = GameObject.Find("/Systems/UI/Canvas/EndgameStats/LevelUp/Total"); _xpText = Object.Instantiate<GameObject>(val4).GetComponent<TextMeshProUGUI>(); ((Object)_xpText).name = "XPText"; ((TMP_Text)_xpText).alignment = (TextAlignmentOptions)514; ((TMP_Text)_xpText).SetText("0/1000", true); ((TMP_Text)_xpText).transform.SetParent(_xpBar.transform, false); ((Graphic)_xpText).color = new Color(1f, 0.6f, 0f, 1f); ((TMP_Text)_xpText).transform.Translate(-0.75f, 0.21f, 0f); _xpLevel = Object.Instantiate<GameObject>(val4).GetComponent<TextMeshProUGUI>(); ((Object)_xpLevel).name = "XPLevel"; ((TMP_Text)_xpLevel).alignment = (TextAlignmentOptions)514; ((TMP_Text)_xpLevel).SetText("Level: 0", true); ((TMP_Text)_xpLevel).transform.SetParent(_xpBar.transform, false); ((Graphic)_xpLevel).color = new Color(1f, 0.6f, 0f, 1f); ((TMP_Text)_xpLevel).transform.Translate(-1f, 0.4f, 0f); _profit = Object.Instantiate<GameObject>(val4).GetComponent<TextMeshProUGUI>(); ((Object)_profit).name = "XPProfit"; ((TMP_Text)_profit).alignment = (TextAlignmentOptions)514; ((TMP_Text)_profit).SetText("You've made.. 0$.", true); ((TMP_Text)_profit).transform.SetParent(_xpBar.transform, false); ((Graphic)_profit).color = new Color(1f, 0.6f, 0f, 1f); ((TMP_Text)_profit).transform.Translate(-0.8f, 0f, 0f); } } [HarmonyPostfix] [HarmonyPatch(typeof(QuickMenuManager), "OpenQuickMenu")] private static void SkillTreeAwake(QuickMenuManager __instance) { if (__instance.isMenuOpen && !Object.op_Implicit((Object)(object)skillTreeButton)) { MakeSkillTreeButton(); } } private static void MakeSkillTreeButton() { //IL_0087: Unknown result type (might be due to invalid IL or missing references) //IL_0091: Expected O, but got Unknown //IL_00b1: Unknown result type (might be due to invalid IL or missing references) //IL_00b6: Unknown result type (might be due to invalid IL or missing references) //IL_00bc: Expected O, but got Unknown GameObject val = GameObject.Find("Systems/UI/Canvas/QuickMenu/MainButtons/Resume"); skillTreeButton = Object.Instantiate<GameObject>(val); GameObject val2 = GameObject.Find("Systems/UI/Canvas/QuickMenu/MainButtons"); skillTreeButton.transform.SetParent(val2.transform, false); ((Object)skillTreeButton).name = "Skills"; ((TMP_Text)skillTreeButton.GetComponentInChildren<TextMeshProUGUI>()).text = "> Skills"; skillTreeButton.transform.Translate(0.7f, 1.1f, 0f); skillTreeButton.GetComponent<Button>().onClick = new ButtonClickedEvent(); ButtonClickedEvent onClick = skillTreeButton.GetComponent<Button>().onClick; object obj = <>O.<0>__OpenSkillTree; if (obj == null) { UnityAction val3 = OpenSkillTree; <>O.<0>__OpenSkillTree = val3; obj = (object)val3; } ((UnityEvent)onClick).AddListener((UnityAction)obj); } private static void OpenSkillTree() { LP_NetworkManager.xpInstance.guiObj.OpenSkillMenu(); } } [HarmonyPatch] internal class XPPatches { [HarmonyPostfix] [HarmonyPatch(typeof(GameNetworkManager), "SaveGameValues")] private static void SaveXPValues(GameNetworkManager __instance) { if (GameNetworkManager.Instance.isHostingGame && StartOfRound.Instance.inShipPhase) { int num = __instance.saveFileNum + 1; string path = Application.persistentDataPath + "/lethalprogression/save" + num + ".txt"; string text = ""; text = text + LP_NetworkManager.xpInstance.GetLevel() + "\n"; text = text + LP_NetworkManager.xpInstance.GetXP() + "\n"; text = text + LP_NetworkManager.xpInstance.GetProfit() + "\n"; File.WriteAllText(path, text); } } [HarmonyPostfix] [HarmonyPatch(typeof(StartOfRound), "FirePlayersAfterDeadlineClientRpc")] private static void ResetXPValues(StartOfRound __instance) { XP xpInstance = LP_NetworkManager.xpInstance; int num = GameNetworkManager.Instance.saveFileNum + 1; string path = Application.persistentDataPath + "/lethalprogression/save" + num + ".txt"; if (File.Exists(path)) { File.Delete(path); } Directory.CreateDirectory(Application.persistentDataPath + "/lethalprogression"); File.WriteAllText(path, ""); string text = ""; text += "0\n"; text += "0\n"; text += "0\n"; File.WriteAllText(path, text); xpInstance.xpReq.Value = xpInstance.GetXPRequirement(); foreach (Skill value in xpInstance.skillList.skills.Values) { value.SetLevel(0); } xpInstance.SetSkillPoints(5); xpInstance.xpLevel.Value = 0; xpInstance.xpPoints.Value = 0; xpInstance.profit.Value = 0; xpInstance.teamLootValue.Value = 0f; } [HarmonyPostfix] [HarmonyPatch(typeof(DeleteFileButton), "DeleteFile")] private static void XPFileDeleteReset() { int num = GameNetworkManager.Instance.saveFileNum + 1; string path = Application.persistentDataPath + "/lethalprogression/save" + num + ".txt"; if (File.Exists(path)) { File.Delete(path); } Directory.CreateDirectory(Application.persistentDataPath + "/lethalprogression"); File.WriteAllText(path, ""); string text = ""; text += "0\n"; text += "0\n"; text += "0\n"; File.WriteAllText(path, text); } [HarmonyPostfix] [HarmonyPatch(typeof(GameNetworkManager), "Disconnect")] private static void DisconnectXPHandler() { int level = LP_NetworkManager.xpInstance.skillList.skills[UpgradeType.HandSlot].GetLevel(); LP_NetworkManager.xpInstance.TeamLootValueUpdate(-level, 0); GUIUpdate.isMenuOpen = false; } [HarmonyPostfix] [HarmonyPatch(typeof(TimeOfDay), "SetNewProfitQuota")] private static void ProfitQuotaUpdate(TimeOfDay __instance) { if (GameNetworkManager.Instance.isHostingGame) { LP_NetworkManager.xpInstance.xpReq.Value = LP_NetworkManager.xpInstance.GetXPRequirement(); } } } } namespace LethalProgression.Config { internal class SkillConfig { public static IDictionary<string, string> hostConfig = new Dictionary<string, string>(); public static void InitConfig() { LethalPlugin.Instance.BindConfig("General", "Person Multiplier", 35, "How much does XP cost to level up go up per person?"); LethalPlugin.Instance.BindConfig("General", "Quota Multiplier", 30, "How much more XP does it cost to level up go up per quota? (Percent)"); LethalPlugin.Instance.BindConfig("General", "XP Minimum", 40, "Minimum XP to level up."); LethalPlugin.Instance.BindConfig("General", "XP Maximum", 750, "Maximum XP to level up."); LethalPlugin.Instance.BindConfig("General", "Unspec in Ship Only", defaultValue: true, "Disallows unspecing stats if you're not currently on the ship."); LethalPlugin.Instance.BindConfig("General", "Disable Unspec", defaultValue: false, "Disallows unspecing altogether."); LethalPlugin.Instance.BindConfig("Skills", "Health Regen Enabled", defaultValue: true, "Enable the Health Regen skill?"); LethalPlugin.Instance.BindConfig("Skills", "Health Regen Max Level", 20, "Maximum level for the health regen."); LethalPlugin.Instance.BindConfig("Skills", "Health Regen Multiplier", 0.05f, "How much does the health regen skill increase per level?"); LethalPlugin.Instance.BindConfig("Skills", "Stamina Enabled", defaultValue: true, "Enable the Stamina skill?"); LethalPlugin.Instance.BindConfig("Skills", "Stamina Max Level", 99999, "Maximum level for the stamina."); LethalPlugin.Instance.BindConfig("Skills", "Stamina Multiplier", 2f, "How much does the stamina skill increase per level?"); LethalPlugin.Instance.BindConfig("Skills", "Battery Life Enabled", defaultValue: true, "Enable the Battery Life skill?"); LethalPlugin.Instance.BindConfig("Skills", "Battery Life Max Level", 99999, "Maximum level for the battery life."); LethalPlugin.Instance.BindConfig("Skills", "Battery Life Multiplier", 5f, "How much does the battery life skill increase per level?"); LethalPlugin.Instance.BindConfig("Skills", "Hand Slots Enabled", defaultValue: true, "Enable the Hand Slots skill?"); LethalPlugin.Instance.BindConfig("Skills", "Hand Slots Max Level", 30, "Maximum level for the hand slots."); LethalPlugin.Instance.BindConfig("Skills", "Hand Slots Multiplier", 10f, "How much does the hand slots skill increase per level?"); LethalPlugin.Instance.BindConfig("Skills", "Loot Value Enabled", defaultValue: true, "Enable the Loot Value skill?"); LethalPlugin.Instance.BindConfig("Skills", "Loot Value Max Level", 99999, "Maximum level for the loot value."); LethalPlugin.Instance.BindConfig("Skills", "Loot Value Multiplier", 0.25f, "How much does the loot value skill increase per level?"); LethalPlugin.Instance.BindConfig("Skills", "Oxygen Enabled", defaultValue: true, "Enable the Oxygen skill?"); LethalPlugin.Instance.BindConfig("Skills", "Oxygen Max Level", 99999, "Maximum level for Oxygen."); LethalPlugin.Instance.BindConfig("Skills", "Oxygen Multiplier", 1f, "How much does the Oxygen skill increase per level?"); } } }
plugins/Nyan.LC.DeathMessages.dll
Decompiled 11 months agousing System; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using System.Security; using System.Security.Permissions; using BepInEx; using BepInEx.Logging; using GameNetcodeStuff; using HarmonyLib; using Microsoft.CodeAnalysis; using UnityEngine; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")] [assembly: AssemblyCompany("Nyan.LC.DeathMessages")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyDescription("This is a description")] [assembly: AssemblyFileVersion("0.0.2.0")] [assembly: AssemblyInformationalVersion("0.0.2+cd928ea4d2517f38e38897cb11c63d7e0817c4ba")] [assembly: AssemblyProduct("Nyan.LC.DeathMessages")] [assembly: AssemblyTitle("Nyan.LC.DeathMessages")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("0.0.2.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.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; } } [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 LCDeathMessages { public static class DeathMessages { private static List<string> Unknown { get; } = new List<string>(10) { "$$ was slain.", "$$'s soul left their body.", "$$ was murdered.", "$$ passed.", "$$ heart stopped.", "$$ went offline.", "$$'s life support was unplugged.", "$$ turned blue.", "$$'s incompetence was put on display.", "$$ expired." }; private static List<string> Bludgeoning { get; } = new List<string>(8) { "$$ experienced skull crushing defeat.", "$$'s bones were shattered.", "$$ was whacked in the head.", "$$ was bludgeoned out of their misery.", "$$ was on the wrong end of an object.", "$$ found themselves before a hard place.", "$$'s neck was pulverised.", "$$ suffered a fatal blow." }; private static List<string> Gravity { get; } = new List<string>(9) { "$$ didn't bounce.", "$$ tripped.", "$$ discovered gravity.", "$$ thought they could fly.", "$$ left a small crater.", "$$ left an average crater.", "$$ left a massive crater.", "$$ forgot to walk on solid ground.", "$$ splattered." }; private static List<string> Blast { get; } = new List<string>(8) { "$$ went boom!", "$$ went everywhere.", "$$ went out with a bang.", "$$ was blown to smithereens.", "$$ detonated.", "$$ became a cloud of dust.", "$$ was ripped piece by piece in an explosion.", "$$ was reduced to atoms." }; private static List<string> Strangulation { get; } = new List<string>(6) { "$$'s neck was tied up with a nice bow.", "$$ was choked out.", "$$ was throttled.", "$$ had their breath taken away.", "$$ lost their breathing privileges.", "$$'s neck was held in high regard." }; private static List<string> Suffocation { get; } = new List<string>(9) { "$$ couldn't breathe.", "$$ ran out of air.", "$$'s lungs were empty.", "$$ took their last breath.", "$$ suffocated in the dark", "$$'s last breath was wasted.", "$$ asphyxiated.", "$$ experienced hypoxia.", "$$'s breath left them." }; private static List<string> Mauling => new List<string>(10) { "$$ was slain.", "$$ was eviscerated.", "$$ was murdered.", "$$'s face was torn off.", "$$'s entrails were ripped out.", "$$ got massacred.", "$$ was torn in half.", "$$'s body was mangled.", "$$'s vital organs were ruptured.", "$$ was removed from " + ((Object)Plugin.RoundData.currentLevel).name + "." }; private static List<string> Gunshots { get; } = new List<string>(9) { "$$ was given some extra holes.", "$$ became partly see-through.", "$$ had lead forcefully implanted.", "$$ was target practice.", "$$ didn't hear the gunshots.", "$$ wasn't Neo.", "$$ found out that bullets hurt.", "$$ was shot down.", "$$ walked into a training range." }; private static List<string> Crushing { get; } = new List<string>(6) { "$$ found crushing defeat.", "$$ couldn't handle the pressure.", "$$'s life was crushed.", "$$ found too much weight upon them.", "$$ suffered under pressure.", "$$ discovered that gravity doesn't just make them fall." }; private static List<string> Drowning { get; } = new List<string>(7) { "$$ is shark food.", "$$ is sleeping with the fish.", "$$ drowned.", "$$ tried to drink a lake.", "$$ discovered Atlantis.", "$$ drank water the wrong way.", "$$ didn't have gills." }; private static List<string> Abandoned { get; } = new List<string>(6) { "$$ was left behind.", "$$ was forgotten.", "$$ wasn't important.", "$$ decided to stay home.", "$$ lost track of time.", "$$ forgot the last part of the mission." }; private static List<string> Electrocution { get; } = new List<string>(8) { "$$ couldn't figure out watt happened.", "$$ couldn't contain the watts.", "$$ was turned into a battery.", "$$ became a lightning rod.", "$$'s positive life force became negative.", "$$ was zapped.", "$$ touched the wrong wire.", "$$ is no longer live." }; public static string Get(CauseOfDeath cause, string username) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_003c: Expected I4, but got Unknown Random random = new Random(); return ((int)cause switch { 0 => Unknown[random.Next(0, Unknown.Count)], 1 => Bludgeoning[random.Next(0, Bludgeoning.Count)], 2 => Gravity[random.Next(0, Gravity.Count)], 3 => Blast[random.Next(0, Blast.Count)], 4 => Strangulation[random.Next(0, Strangulation.Count)], 5 => Suffocation[random.Next(0, Suffocation.Count)], 6 => Mauling[random.Next(0, Mauling.Count)], 7 => Gunshots[random.Next(0, Gunshots.Count)], 8 => Crushing[random.Next(0, Crushing.Count)], 9 => Drowning[random.Next(0, Drowning.Count)], 10 => Abandoned[random.Next(0, Abandoned.Count)], 11 => Electrocution[random.Next(0, Electrocution.Count)], _ => string.Empty, }).Replace("$$", username); } } [BepInPlugin("Nyan.LC.DeathMessages", "Nyan.LC.DeathMessages", "0.0.2")] public class Plugin : BaseUnityPlugin { public static Plugin? Instance; private readonly Harmony _harmony = new Harmony("Nyan.LC.DeathMessages"); public static StartOfRound RoundData => StartOfRound.Instance; public static ManualLogSource? Log { [return: NotNull] get; private set; } private void Awake() { if (Instance == null) { Instance = this; } ((BaseUnityPlugin)this).Logger.LogInfo((object)"Started Death Messages Plugin Successfully."); _harmony.PatchAll(typeof(Plugin)); Log = ((BaseUnityPlugin)this).Logger; } [HarmonyPatch(typeof(PlayerControllerB), "KillPlayer")] [HarmonyPostfix] private static void SendDeathMessage(PlayerControllerB __instance) { //IL_000a: Unknown result type (might be due to invalid IL or missing references) if (__instance.isPlayerDead) { string text = DeathMessages.Get(__instance.causeOfDeath, __instance.playerUsername); string text2 = "<color=#E11919>" + text + "</color>"; HUDManager.Instance.AddTextToChatOnServer(text2, -1); } } } public static class PluginInfo { public const string PLUGIN_GUID = "Nyan.LC.DeathMessages"; public const string PLUGIN_NAME = "Nyan.LC.DeathMessages"; public const string PLUGIN_VERSION = "0.0.2"; } }
plugins/QuickRestart.dll
Decompiled 11 months agousing System; using System.Diagnostics; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using System.Security; using System.Security.Permissions; using BepInEx; using BepInEx.Configuration; using GameNetcodeStuff; using HarmonyLib; using Microsoft.CodeAnalysis; using UnityEngine; using UnityEngine.EventSystems; 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: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")] [assembly: AssemblyCompany("QuickRestart")] [assembly: AssemblyConfiguration("Debug")] [assembly: AssemblyDescription("My first plugin")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: AssemblyInformationalVersion("1.0.0+a395cfe8aac0ee2687d75817f75fae451f729511")] [assembly: AssemblyProduct("QuickRestart")] [assembly: AssemblyTitle("QuickRestart")] [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 QuickRestart { [BepInPlugin("QuickRestart", "QuickRestart", "1.0.0")] public class Plugin : BaseUnityPlugin { public static bool verifying; private ConfigEntry<bool> overrideConfirmation; public static bool bypassConfirm; private Harmony harmony; private static MethodInfo chat; private void Awake() { //IL_0038: Unknown result type (might be due to invalid IL or missing references) //IL_0042: Expected O, but got Unknown overrideConfirmation = ((BaseUnityPlugin)this).Config.Bind<bool>("Config", "Override Confirmation", false, "Ignore the confirmation step of restarting."); bypassConfirm = overrideConfirmation.Value; harmony = new Harmony("QuickRestart"); harmony.PatchAll(); chat = AccessTools.Method(typeof(HUDManager), "AddChatMessage", (Type[])null, (Type[])null); ((BaseUnityPlugin)this).Logger.LogInfo((object)"QuickRestart loaded!"); } public static void SendChatMessage(string message) { chat?.Invoke(HUDManager.Instance, new object[2] { message, "" }); HUDManager.Instance.lastChatMessage = ""; } public static void ConfirmRestart() { verifying = true; SendChatMessage("Are you sure? Type CONFIRM or DENY."); } public static void AcceptRestart(StartOfRound manager) { SendChatMessage("Restart confirmed."); verifying = false; int[] array = new int[4] { manager.gameStats.daysSpent, manager.gameStats.scrapValueCollected, manager.gameStats.deaths, manager.gameStats.allStepsTaken }; manager.FirePlayersAfterDeadlineClientRpc(array, false); } public static void DeclineRestart() { SendChatMessage("Restart aborted."); verifying = false; } } public static class MyPluginInfo { public const string PLUGIN_GUID = "QuickRestart"; public const string PLUGIN_NAME = "QuickRestart"; public const string PLUGIN_VERSION = "1.0.0"; } } namespace QuickRestart.Patches { [HarmonyPatch(typeof(HUDManager), "SubmitChat_performed")] public class SubmitChat { private static bool Prefix(HUDManager __instance, ref CallbackContext context) { if (!((CallbackContext)(ref context)).performed) { return true; } if (string.IsNullOrEmpty(__instance.chatTextField.text)) { return true; } PlayerControllerB localPlayerController = GameNetworkManager.Instance.localPlayerController; if ((Object)(object)localPlayerController == (Object)null) { return true; } StartOfRound playersManager = localPlayerController.playersManager; if ((Object)(object)playersManager == (Object)null) { return true; } string text = __instance.chatTextField.text; if (Plugin.verifying) { if (text.ToLower() == "confirm") { ResetTextbox(__instance, localPlayerController); if (!localPlayerController.isInHangarShipRoom || !playersManager.inShipPhase || playersManager.travellingToNewLevel) { Plugin.SendChatMessage("Cannot restart, ship must be in orbit."); return false; } Plugin.AcceptRestart(playersManager); return false; } if (text.ToLower() == "deny") { ResetTextbox(__instance, localPlayerController); Plugin.DeclineRestart(); return false; } return true; } if (text == "/restart") { ResetTextbox(__instance, localPlayerController); if (!GameNetworkManager.Instance.isHostingGame) { Plugin.SendChatMessage("Only the host can restart."); return false; } if (!localPlayerController.isInHangarShipRoom || !playersManager.inShipPhase || playersManager.travellingToNewLevel) { Plugin.SendChatMessage("Cannot restart, ship must be in orbit."); return false; } if (Plugin.bypassConfirm) { Plugin.AcceptRestart(playersManager); } else { Plugin.ConfirmRestart(); } return false; } return true; } private static void ResetTextbox(HUDManager manager, PlayerControllerB local) { local.isTypingChat = false; manager.chatTextField.text = ""; EventSystem.current.SetSelectedGameObject((GameObject)null); manager.PingHUDElement(manager.Chat, 2f, 1f, 0.2f); ((Behaviour)manager.typingIndicator).enabled = false; } } }
plugins/ReservedFlashlightSlot.dll
Decompiled 11 months agousing System.Diagnostics; 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 ReservedFlashlightSlot.Patches; using ReservedItemSlotCore; using ReservedItemSlotCore.Networking; using ReservedItemSlotCore.Patches; 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("ReservedFlashlightSlot")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("ReservedFlashlightSlot")] [assembly: AssemblyCopyright("Copyright © 2023")] [assembly: AssemblyTrademark("")] [assembly: ComVisible(false)] [assembly: Guid("5b7d6563-4e51-4a69-bcf9-fa1dea6eff75")] [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 ReservedFlashlightSlot { public static class ConfigSettings { public static ConfigEntry<string> activateFlashlightKey; public static ConfigEntry<bool> hideFlashlightMeshShoulder; public static string activateFlashlightDisplayName; public static void BindConfigSettings() { Plugin.Log("BindingConfigs"); activateFlashlightKey = ((BaseUnityPlugin)Plugin.instance).Config.Bind<string>("ReservedItemSlotCore", "ActivateFlashlightKey", "<Keyboard>/f", "Activate flashlight keybind."); hideFlashlightMeshShoulder = ((BaseUnityPlugin)Plugin.instance).Config.Bind<bool>("ReservedItemSlotCore", "HideFlashlightOnShoulder", false, "Hides the flashlight mesh while on your shoulder."); activateFlashlightDisplayName = GetDisplayName(activateFlashlightKey.Value); } public static string GetDisplayName(string key) { key = key.Replace("<Keyboard>/", ""); key = key.Replace("<Mouse>/", ""); string text = key; text = text.Replace("leftAlt", "Alt"); text = text.Replace("rightAlt", "Alt"); text = text.Replace("leftCtrl", "Ctrl"); text = text.Replace("rightCtrl", "Ctrl"); text = text.Replace("leftShift", "Shift"); text = text.Replace("rightShift", "Shift"); text = text.Replace("leftButton", "LMB"); text = text.Replace("rightButton", "RMB"); return text.Replace("middleButton", "MMB"); } } [HarmonyPatch] internal static class Keybinds { public static PlayerControllerB localPlayerController; private static InputAction activateFlashlightAction; [HarmonyPatch(typeof(PlayerControllerB), "ConnectClientToPlayerObject")] [HarmonyPostfix] public static void OnLocalPlayerConnect(PlayerControllerB __instance) { //IL_001a: Unknown result type (might be due to invalid IL or missing references) //IL_0024: Expected O, but got Unknown localPlayerController = __instance; activateFlashlightAction = new InputAction((string)null, (InputActionType)0, ConfigSettings.activateFlashlightKey.Value, "Press", (string)null, (string)null); if (((Component)localPlayerController).gameObject.activeSelf) { SubscribeToEvents(); } } private static void SubscribeToEvents() { if (activateFlashlightAction != null) { activateFlashlightAction.Enable(); activateFlashlightAction.performed += OnActivateFlashlightPerformed; } } [HarmonyPatch(typeof(PlayerControllerB), "OnEnable")] [HarmonyPostfix] public static void OnEnable(PlayerControllerB __instance) { if ((Object)(object)__instance == (Object)(object)localPlayerController) { SubscribeToEvents(); } } [HarmonyPatch(typeof(PlayerControllerB), "OnDisable")] [HarmonyPostfix] public static void OnDisable(PlayerControllerB __instance) { if (activateFlashlightAction != null && !((Object)(object)__instance != (Object)(object)localPlayerController)) { activateFlashlightAction.performed -= OnActivateFlashlightPerformed; activateFlashlightAction.Disable(); } } private static void OnActivateFlashlightPerformed(CallbackContext context) { if ((Object)(object)localPlayerController == (Object)null || !localPlayerController.isPlayerControlled || localPlayerController.inTerminalMenu || (((NetworkBehaviour)localPlayerController).IsServer && !localPlayerController.isHostPlayerObject)) { return; } FlashlightItem mainFlashlight = ReservedFlashlightSlotPatcher.GetMainFlashlight(localPlayerController); if (((CallbackContext)(ref context)).performed && !((Object)(object)mainFlashlight == (Object)null)) { float num = (float)Traverse.Create((object)localPlayerController).Field("timeSinceSwitchingSlots").GetValue(); if (!(num < 0.075f)) { ((GrabbableObject)mainFlashlight).UseItemOnClient(!((GrabbableObject)mainFlashlight).isBeingUsed); Traverse.Create((object)localPlayerController).Field("timeSinceSwitchingSlots").SetValue((object)0); } } } } [BepInPlugin("FlipMods.ReservedFlashlightSlot", "ReservedFlashlightSlot", "1.5.0")] [BepInDependency(/*Could not decode attribute arguments.*/)] internal class Plugin : BaseUnityPlugin { public static Plugin instance; private Harmony _harmony; public static ReservedItemInfo proFlashlightInfo = new ReservedItemInfo("Pro-flashlight", 120, true, true, true, true); public static ReservedItemInfo flashlightInfo = new ReservedItemInfo("Flashlight", 120, true, true, true, true); public static ReservedItemInfo laserPointerInfo = new ReservedItemInfo("Laser pointer", 120, true, true, true, true); private void Awake() { //IL_0013: Unknown result type (might be due to invalid IL or missing references) //IL_001d: Expected O, but got Unknown instance = this; ConfigSettings.BindConfigSettings(); _harmony = new Harmony("ReservedFlashlightSlot"); _harmony.PatchAll(); ((BaseUnityPlugin)this).Logger.LogInfo((object)"ReservedFlashlightSlot loaded"); } public static void Log(string message) { ((BaseUnityPlugin)instance).Logger.LogInfo((object)message); } } public static class PluginInfo { public const string PLUGIN_GUID = "FlipMods.ReservedFlashlightSlot"; public const string PLUGIN_NAME = "ReservedFlashlightSlot"; public const string PLUGIN_VERSION = "1.5.0"; } } namespace ReservedFlashlightSlot.Patches { [HarmonyPatch] internal static class ReservedFlashlightSlotPatcher { private static Vector3 playerShoulderPositionOffset = new Vector3(0.2f, 0f, 0f); private static Vector3 playerShoulderRotationOffset = new Vector3(90f, 0f, 0f); private static string originalControlTooltip = ""; public static PlayerControllerB localPlayerController => PlayerPatcher.localPlayerController; public static PlayerControllerB GetPreviousPlayerHeldBy(FlashlightItem flashlightItem) { //IL_0015: Unknown result type (might be due to invalid IL or missing references) //IL_001b: Expected O, but got Unknown return (PlayerControllerB)Traverse.Create((object)flashlightItem).Field("previousPlayerHeldBy").GetValue(); } public static FlashlightItem GetMainFlashlight(PlayerControllerB playerController) { return GetCurrentlySelectedFlashlight(playerController) ?? GetReservedFlashlight(playerController); } public static FlashlightItem GetReservedFlashlight(PlayerControllerB playerController) { GrabbableObject obj = ((playerController != null) ? playerController.ItemSlots[Plugin.flashlightInfo.indexInInventory] : null); return (FlashlightItem)(object)((obj is FlashlightItem) ? obj : null); } public static FlashlightItem GetCurrentlySelectedFlashlight(PlayerControllerB playerController) { GrabbableObject obj = ((playerController != null) ? playerController.ItemSlots[playerController.currentItemSlot] : null); return (FlashlightItem)(object)((obj is FlashlightItem) ? obj : null); } public static bool IsFlashlightOn(PlayerControllerB playerController) { return ((GrabbableObject)(GetMainFlashlight(playerController)?)).isBeingUsed ?? false; } [HarmonyPatch(typeof(FlashlightItem), "__initializeVariables")] [HarmonyPostfix] public static void EditTooltips(FlashlightItem __instance) { if (originalControlTooltip == "") { originalControlTooltip = ((GrabbableObject)__instance).itemProperties.toolTips[((GrabbableObject)__instance).itemProperties.toolTips.Length - 1]; } ((GrabbableObject)__instance).itemProperties.toolTips[((GrabbableObject)__instance).itemProperties.toolTips.Length - 1] = $"{originalControlTooltip}[{ConfigSettings.activateFlashlightDisplayName.ToUpper()}]"; } [HarmonyPatch(typeof(MenuManager), "OnEnable")] [HarmonyPostfix] public static void ResetVariables() { Keybinds.localPlayerController = null; } [HarmonyPatch(typeof(PlayerControllerB), "ActivateItem_performed")] [HarmonyPrefix] public static bool PreventActivatingDuplicateItem(CallbackContext context, PlayerControllerB __instance) { FlashlightItem currentlySelectedFlashlight = GetCurrentlySelectedFlashlight(__instance); if ((Object)(object)__instance != (Object)(object)localPlayerController || (Object)(object)currentlySelectedFlashlight == (Object)null) { return true; } if (!((CallbackContext)(ref context)).performed) { return false; } return true; } [HarmonyPatch(typeof(FlashlightItem), "SwitchFlashlight")] [HarmonyPostfix] public static void OnSwitchOnOffFlashlight(bool on, FlashlightItem __instance) { if (!((Object)(object)((GrabbableObject)__instance).playerHeldBy == (Object)null)) { UpdateAllFlashlightStates(((GrabbableObject)__instance).playerHeldBy, on); } } [HarmonyPatch(typeof(FlashlightItem), "PocketItem")] [HarmonyPostfix] public static void OnPocketFlashlightLocal(FlashlightItem __instance) { OnPocketFlashlight(__instance, ((GrabbableObject)__instance).isBeingUsed); } [HarmonyPatch(typeof(FlashlightItem), "PocketFlashlightClientRpc")] [HarmonyPrefix] public static bool OnPocketFlashlightClientRpc(bool stillUsingFlashlight, FlashlightItem __instance) { if (!NetworkHelper.IsValidClientRpcExecStage((NetworkBehaviour)(object)__instance) || ((NetworkBehaviour)__instance).IsOwner || (Object)(object)((GrabbableObject)__instance).playerHeldBy == (Object)null || (Object)(object)((GrabbableObject)__instance).playerHeldBy == (Object)(object)localPlayerController || !NetworkHelper.IsClientExecStage((NetworkBehaviour)(object)__instance)) { return false; } OnPocketFlashlight(__instance, stillUsingFlashlight); return true; } private static void OnPocketFlashlight(FlashlightItem flashlightItem, bool stillUsingFlashlight = false) { if (!((Object)(object)((GrabbableObject)flashlightItem).playerHeldBy == (Object)null)) { FlashlightItem currentlySelectedFlashlight = GetCurrentlySelectedFlashlight(((GrabbableObject)flashlightItem).playerHeldBy); FlashlightItem reservedFlashlight = GetReservedFlashlight(((GrabbableObject)flashlightItem).playerHeldBy); bool mainFlashlightActive = stillUsingFlashlight || ((Object)(object)currentlySelectedFlashlight != (Object)null && ((GrabbableObject)currentlySelectedFlashlight).isBeingUsed); if ((Object)(object)currentlySelectedFlashlight != (Object)null && ((GrabbableObject)currentlySelectedFlashlight).isBeingUsed) { ((GrabbableObject)flashlightItem).playerHeldBy.pocketedFlashlight = null; } else if (((GrabbableObject)flashlightItem).isBeingUsed) { ((GrabbableObject)flashlightItem).playerHeldBy.pocketedFlashlight = (GrabbableObject)(object)flashlightItem; } else if ((Object)(object)reservedFlashlight != (Object)null && ((Object)(object)((GrabbableObject)flashlightItem).playerHeldBy.pocketedFlashlight == (Object)null || !((GrabbableObject)flashlightItem).playerHeldBy.pocketedFlashlight.isBeingUsed)) { ((GrabbableObject)flashlightItem).playerHeldBy.pocketedFlashlight = (GrabbableObject)(object)reservedFlashlight; } if ((Object)(object)flashlightItem == (Object)(object)reservedFlashlight) { ((GrabbableObject)flashlightItem).parentObject = ((GrabbableObject)flashlightItem).playerHeldBy.playerGlobalHead; } UpdateAllFlashlightStates(((GrabbableObject)flashlightItem).playerHeldBy, mainFlashlightActive); } } [HarmonyPatch(typeof(FlashlightItem), "EquipItem")] [HarmonyPostfix] public static void OnEquipFlashlight(FlashlightItem __instance) { if (!((Object)(object)((GrabbableObject)__instance).playerHeldBy == (Object)null)) { bool mainFlashlightActive = ((Object)(object)((GrabbableObject)__instance).playerHeldBy.pocketedFlashlight != (Object)null && ((GrabbableObject)__instance).playerHeldBy.pocketedFlashlight.isBeingUsed) || ((GrabbableObject)__instance).isBeingUsed; FlashlightItem reservedFlashlight = GetReservedFlashlight(((GrabbableObject)__instance).playerHeldBy); if (((GrabbableObject)__instance).isBeingUsed || (Object)(object)__instance == (Object)(object)((GrabbableObject)__instance).playerHeldBy.pocketedFlashlight) { ((GrabbableObject)__instance).playerHeldBy.pocketedFlashlight = null; } else if ((Object)(object)reservedFlashlight != (Object)null && ((Object)(object)((GrabbableObject)__instance).playerHeldBy.pocketedFlashlight == (Object)null || !((GrabbableObject)__instance).playerHeldBy.pocketedFlashlight.isBeingUsed)) { ((GrabbableObject)__instance).playerHeldBy.pocketedFlashlight = (GrabbableObject)(object)reservedFlashlight; } ((GrabbableObject)__instance).parentObject = (((Object)(object)((GrabbableObject)__instance).playerHeldBy == (Object)(object)localPlayerController) ? ((GrabbableObject)__instance).playerHeldBy.localItemHolder : ((GrabbableObject)__instance).playerHeldBy.serverItemHolder); UpdateAllFlashlightStates(((GrabbableObject)__instance).playerHeldBy, mainFlashlightActive); } } [HarmonyPatch(typeof(FlashlightItem), "DiscardItem")] [HarmonyPrefix] public static void ResetPocketedFlashlight(FlashlightItem __instance) { PlayerControllerB previousPlayerHeldBy = GetPreviousPlayerHeldBy(__instance); if (!((Object)(object)previousPlayerHeldBy == (Object)null)) { FlashlightItem reservedFlashlight = GetReservedFlashlight(previousPlayerHeldBy); Plugin.Log("Reserved: " + (((Object)(object)reservedFlashlight == (Object)null) ? "NULL" : "NOT NULL")); Plugin.Log("222: " + ((Object)(object)__instance == (Object)(object)previousPlayerHeldBy.pocketedFlashlight)); Plugin.Log("333: " + ((Object)(object)previousPlayerHeldBy.pocketedFlashlight == (Object)null)); if ((Object)(object)reservedFlashlight != (Object)null && ((Object)(object)__instance == (Object)(object)previousPlayerHeldBy.pocketedFlashlight || (Object)(object)previousPlayerHeldBy.pocketedFlashlight == (Object)null)) { previousPlayerHeldBy.pocketedFlashlight = (GrabbableObject)(object)reservedFlashlight; } } } [HarmonyPatch(typeof(GrabbableObject), "LateUpdate")] [HarmonyPostfix] public static void SetPositionOffset(GrabbableObject __instance) { //IL_006c: Unknown result type (might be due to invalid IL or missing references) //IL_0071: Unknown result type (might be due to invalid IL or missing references) //IL_0076: Unknown result type (might be due to invalid IL or missing references) //IL_007b: Unknown result type (might be due to invalid IL or missing references) //IL_008d: Unknown result type (might be due to invalid IL or missing references) //IL_0093: Unknown result type (might be due to invalid IL or missing references) //IL_0098: Unknown result type (might be due to invalid IL or missing references) //IL_009d: Unknown result type (might be due to invalid IL or missing references) //IL_00a2: Unknown result type (might be due to invalid IL or missing references) if (__instance is FlashlightItem && (Object)(object)__instance.playerHeldBy != (Object)null && __instance.isPocketed && (Object)(object)__instance.parentObject != (Object)null && (Object)(object)__instance != (Object)(object)GetCurrentlySelectedFlashlight(__instance.playerHeldBy)) { Transform transform = ((Component)__instance.parentObject).transform; ((Component)__instance).transform.rotation = ((Component)__instance.parentObject).transform.rotation * Quaternion.Euler(playerShoulderRotationOffset); ((Component)__instance).transform.position = transform.position + transform.rotation * playerShoulderPositionOffset; } } [HarmonyPatch(typeof(GrabbableObject), "EnableItemMeshes")] [HarmonyPrefix] public static void OnEnableItemMeshes(ref bool enable, GrabbableObject __instance) { if (__instance is FlashlightItem && (Object)(object)__instance.playerHeldBy != (Object)null && ((Object)(object)__instance == (Object)(object)GetCurrentlySelectedFlashlight(__instance.playerHeldBy) || ((Object)(object)__instance == (Object)(object)GetReservedFlashlight(__instance.playerHeldBy) && (Object)(object)__instance.playerHeldBy != (Object)(object)localPlayerController))) { enable = true; } } private static void UpdateAllFlashlightStates(PlayerControllerB playerController, bool mainFlashlightActive = true) { FlashlightItem mainFlashlight = GetMainFlashlight(playerController); if ((Object)(object)mainFlashlight == (Object)null) { ((Behaviour)playerController.helmetLight).enabled = false; mainFlashlightActive = false; } else { playerController.ChangeHelmetLight(mainFlashlight.flashlightTypeID, mainFlashlightActive && (Object)(object)playerController == (Object)(object)localPlayerController && (Object)(object)playerController.ItemSlots[playerController.currentItemSlot] != (Object)(object)mainFlashlight); } for (int i = 0; i < PlayerPatcher.combinedHotbarSize; i++) { GrabbableObject obj = playerController.ItemSlots[i]; FlashlightItem val = (FlashlightItem)(object)((obj is FlashlightItem) ? obj : null); if ((Object)(object)val != (Object)null) { UpdateFlashlightState(val, (Object)(object)val == (Object)(object)mainFlashlight && mainFlashlightActive); } } } private static void UpdateFlashlightState(FlashlightItem flashlightItem, bool active) { if (!((Object)(object)((GrabbableObject)flashlightItem).playerHeldBy == (Object)null)) { PlayerControllerB playerHeldBy = ((GrabbableObject)flashlightItem).playerHeldBy; ((GrabbableObject)flashlightItem).isBeingUsed = active; bool flag = (Object)(object)playerHeldBy != (Object)(object)localPlayerController || (Object)(object)playerHeldBy.ItemSlots[playerHeldBy.currentItemSlot] == (Object)(object)flashlightItem; ((Behaviour)flashlightItem.flashlightBulb).enabled = active && flag; ((Behaviour)flashlightItem.flashlightBulbGlow).enabled = active && flag; flashlightItem.usingPlayerHelmetLight = active && !flag; } } } }
plugins/ReservedItemSlotCore.dll
Decompiled 11 months agousing System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; 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 ReservedItemSlotCore.Networking; using ReservedItemSlotCore.Patches; using TMPro; using Unity.Collections; using Unity.Netcode; using UnityEngine; using UnityEngine.InputSystem; 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: AssemblyTitle("ReservedItemSlotCore")] [assembly: AssemblyDescription("Mod made by flipf17")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("ReservedItemSlotCore")] [assembly: AssemblyCopyright("Copyright © 2023")] [assembly: AssemblyTrademark("")] [assembly: ComVisible(false)] [assembly: Guid("238ce080-e339-46b6-9b08-992a950453a1")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: InternalsVisibleTo("ReservedFlashlightSlot")] [assembly: InternalsVisibleTo("ReservedWalkieSlot")] [assembly: TargetFramework(".NETFramework,Version=v4.7.2", FrameworkDisplayName = ".NET Framework 4.7.2")] [assembly: AssemblyVersion("1.0.0.0")] namespace ReservedItemSlotCore { public static class ConfigSettings { public static ConfigEntry<string> focusReservedHotbarHotkey; public static ConfigEntry<string> specialReservedItemUseHotkey; public static string focusReservedHotbarHotkeyDisplayName; public static void BindConfigSettings() { Plugin.Log("BindingConfigs"); focusReservedHotbarHotkey = ((BaseUnityPlugin)Plugin.instance).Config.Bind<string>("ReservedItemSlotCore", "FocusReservedItemSlotsHotkey", "<Keyboard>/leftAlt", "Which key will focus your reserved item slots hotbar to allow selcting, dropping, charging, etc."); specialReservedItemUseHotkey = ((BaseUnityPlugin)Plugin.instance).Config.Bind<string>("ReservedItemSlotCore", "SpecialReservedItemUseHotkey", "<Mouse>/middleButton", "[REMOVED] Which key will focus your reserved item slots hotbar to allow selcting, dropping, charging, etc."); focusReservedHotbarHotkeyDisplayName = GetDisplayName(focusReservedHotbarHotkey.Value); } public static string GetDisplayName(string key) { key = key.Replace("<Keyboard>/", ""); key = key.Replace("<Mouse>/", ""); string text = key; text = text.Replace("leftAlt", "Alt"); text = text.Replace("rightAlt", "Alt"); text = text.Replace("leftCtrl", "Ctrl"); text = text.Replace("rightCtrl", "Ctrl"); text = text.Replace("leftShift", "Shift"); text = text.Replace("rightShift", "Shift"); text = text.Replace("leftButton", "LMB"); text = text.Replace("rightButton", "RMB"); return text.Replace("middleButton", "MMB"); } } [HarmonyPatch] internal static class HotbarSlotSync { public static PlayerControllerB localPlayerController; [HarmonyPatch(typeof(PlayerControllerB), "ConnectClientToPlayerObject")] [HarmonyPostfix] public static void Init(PlayerControllerB __instance) { //IL_001d: Unknown result type (might be due to invalid IL or missing references) //IL_0027: Expected O, but got Unknown //IL_004c: Unknown result type (might be due to invalid IL or missing references) //IL_0056: Expected O, but got Unknown localPlayerController = __instance; NetworkManager.Singleton.CustomMessagingManager.RegisterNamedMessageHandler("OnSwapHotbarClientRpc", new HandleNamedMessageDelegate(OnSwapHotbarClientRpc)); if (NetworkManager.Singleton.IsServer) { NetworkManager.Singleton.CustomMessagingManager.RegisterNamedMessageHandler("OnSwapHotbarServerRpc", new HandleNamedMessageDelegate(OnSwapHotbarServerRpc)); } } private static void SendSwapHotbarUpdate(int hotbarSlot) { //IL_0038: Unknown result type (might be due to invalid IL or missing references) //IL_003e: Unknown result type (might be due to invalid IL or missing references) //IL_0056: Unknown result type (might be due to invalid IL or missing references) if (NetworkManager.Singleton.IsClient) { FastBufferWriter val = default(FastBufferWriter); ((FastBufferWriter)(ref val))..ctor(4, (Allocator)2, -1); try { Plugin.Log("Sending hotbar swap slot: " + hotbarSlot); ((FastBufferWriter)(ref val)).WriteValue<int>(ref hotbarSlot, default(ForPrimitives)); NetworkManager.Singleton.CustomMessagingManager.SendNamedMessage("OnSwapHotbarServerRpc", 0uL, val, (NetworkDelivery)3); return; } finally { ((IDisposable)(FastBufferWriter)(ref val)).Dispose(); } } Plugin.Log("Failed to send hotbar swap index."); } private static void OnSwapHotbarServerRpc(ulong clientId, 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) //IL_006f: Unknown result type (might be due to invalid IL or missing references) //IL_0075: Unknown result type (might be due to invalid IL or missing references) //IL_0082: Unknown result type (might be due to invalid IL or missing references) //IL_0088: Unknown result type (might be due to invalid IL or missing references) //IL_009e: Unknown result type (might be due to invalid IL or missing references) if (!NetworkManager.Singleton.IsServer) { return; } if (((FastBufferReader)(ref reader)).TryBeginRead(4)) { int num = default(int); ((FastBufferReader)(ref reader)).ReadValue<int>(ref num, default(ForPrimitives)); Plugin.Log("Receiving request for hotbar swap. Slot: " + num + " ClientId: " + clientId); FastBufferWriter val = default(FastBufferWriter); ((FastBufferWriter)(ref val))..ctor(12, (Allocator)2, -1); try { ((FastBufferWriter)(ref val)).WriteValueSafe<int>(ref num, default(ForPrimitives)); ((FastBufferWriter)(ref val)).WriteValueSafe<ulong>(ref clientId, default(ForPrimitives)); NetworkManager.Singleton.CustomMessagingManager.SendNamedMessageToAll("OnSwapHotbarClientRpc", val, (NetworkDelivery)3); return; } finally { ((IDisposable)(FastBufferWriter)(ref val)).Dispose(); } } Plugin.Log("Failed to receive hotbar swap index from Client: " + clientId); } private static void OnSwapHotbarClientRpc(ulong clientId, FastBufferReader reader) { //IL_002e: Unknown result type (might be due to invalid IL or missing references) //IL_0034: Unknown result type (might be due to invalid IL or missing references) //IL_0042: Unknown result type (might be due to invalid IL or missing references) //IL_0048: Unknown result type (might be due to invalid IL or missing references) if (!NetworkManager.Singleton.IsClient) { return; } if (((FastBufferReader)(ref reader)).TryBeginRead(12)) { int hotbarSlot = default(int); ((FastBufferReader)(ref reader)).ReadValue<int>(ref hotbarSlot, default(ForPrimitives)); ulong num = default(ulong); ((FastBufferReader)(ref reader)).ReadValue<ulong>(ref num, default(ForPrimitives)); Plugin.Log("Receiving update for hotbar swap. Slot: " + hotbarSlot + " ClientId: " + num); if (num == localPlayerController.actualClientId || UpdateClientHotbarSlot(num, hotbarSlot)) { return; } Plugin.Log("Failed to receive hotbar swap index from Client: " + num); } Plugin.Log("Failed to receive hotbar swap index from Client"); } private static bool UpdateClientHotbarSlot(ulong clientId, int hotbarSlot) { Plugin.Log("Updating hotbar slot: " + hotbarSlot + " ClientId: " + clientId); for (int i = 0; i < StartOfRound.Instance.allPlayerScripts.Length; i++) { if (StartOfRound.Instance.allPlayerScripts[i].actualClientId == clientId) { CallSwitchToItemSlotMethod(StartOfRound.Instance.allPlayerScripts[i], hotbarSlot); return true; } } return false; } public static void SwapHotbarSlot(int hotbarIndex) { SendSwapHotbarUpdate(hotbarIndex); CallSwitchToItemSlotMethod(localPlayerController, hotbarIndex); Traverse.Create((object)localPlayerController).Field("timeSinceSwitchingSlots").SetValue((object)0); } private static void CallSwitchToItemSlotMethod(PlayerControllerB playerController, int hotbarIndex) { ShipBuildModeManager.Instance.CancelBuildMode(true); MethodInfo method = ((object)playerController).GetType().GetMethod("SwitchToItemSlot", BindingFlags.Instance | BindingFlags.NonPublic); method.Invoke(playerController, new object[2] { hotbarIndex, null }); if ((Object)(object)playerController.currentlyHeldObjectServer != (Object)null) { ((Component)playerController.currentlyHeldObjectServer).gameObject.GetComponent<AudioSource>().PlayOneShot(playerController.currentlyHeldObjectServer.itemProperties.grabSFX, 0.6f); } } } [HarmonyPatch] internal static class Keybinds { public static PlayerControllerB localPlayerController; public static InputAction focusReservedHotbarAction; public static bool holdingModifierKey; [HarmonyPatch(typeof(PlayerControllerB), "ConnectClientToPlayerObject")] [HarmonyPostfix] public static void OnLocalPlayerConnect(PlayerControllerB __instance) { //IL_0016: Unknown result type (might be due to invalid IL or missing references) //IL_0020: Expected O, but got Unknown localPlayerController = __instance; focusReservedHotbarAction = new InputAction((string)null, (InputActionType)0, ConfigSettings.focusReservedHotbarHotkey.Value, (string)null, (string)null, (string)null); if (((Component)localPlayerController).gameObject.activeSelf) { SubscribeToEvents(); } } private static void SubscribeToEvents() { if (focusReservedHotbarAction != null && Plugin.numReservedItemSlots > 0) { focusReservedHotbarAction.performed += FocusReservedHotbarSlotsAction; focusReservedHotbarAction.canceled += UnfocusReservedHotbarSlotsPerformed; focusReservedHotbarAction.Enable(); } } [HarmonyPatch(typeof(PlayerControllerB), "OnEnable")] [HarmonyPostfix] public static void OnEnable(PlayerControllerB __instance) { if ((Object)(object)__instance == (Object)(object)localPlayerController) { SubscribeToEvents(); } } [HarmonyPatch(typeof(PlayerControllerB), "OnDisable")] [HarmonyPostfix] public static void OnDisable(PlayerControllerB __instance) { if (focusReservedHotbarAction != null && Plugin.numReservedItemSlots > 0 && !((Object)(object)__instance != (Object)(object)localPlayerController)) { focusReservedHotbarAction.performed -= FocusReservedHotbarSlotsAction; focusReservedHotbarAction.canceled -= UnfocusReservedHotbarSlotsPerformed; focusReservedHotbarAction.Disable(); } } private static void FocusReservedHotbarSlotsAction(CallbackContext context) { if (!((Object)(object)localPlayerController == (Object)null) && !((Object)(object)localPlayerController == (Object)null) && ((NetworkBehaviour)localPlayerController).IsOwner && localPlayerController.isPlayerControlled && (!((NetworkBehaviour)localPlayerController).IsServer || localPlayerController.isHostPlayerObject)) { holdingModifierKey = true; bool flag = (bool)Traverse.Create((object)localPlayerController).Field("throwingObject").GetValue(); if (!(localPlayerController.inTerminalMenu || localPlayerController.isPlayerDead || localPlayerController.isGrabbingObjectAnimation || localPlayerController.inSpecialInteractAnimation || flag) && !localPlayerController.isTypingChat && !localPlayerController.twoHanded && !localPlayerController.activatingItem && ((CallbackContext)(ref context)).performed) { ReservedItemPatcher.SetFocusReservedHotbarSlots(active: true); } } } private static void UnfocusReservedHotbarSlotsPerformed(CallbackContext context) { if (!((Object)(object)localPlayerController == (Object)null) && ((NetworkBehaviour)localPlayerController).IsOwner && (!((NetworkBehaviour)localPlayerController).IsServer || localPlayerController.isHostPlayerObject)) { holdingModifierKey = false; if (ReservedItemPatcher.CanSwapToReservedHotbarSlot() && ((CallbackContext)(ref context)).canceled) { ReservedItemPatcher.SetFocusReservedHotbarSlots(active: false); } } } } [BepInPlugin("FlipMods.ReservedItemSlotCore", "ReservedItemSlotCore", "1.6.0")] internal class Plugin : BaseUnityPlugin { private Harmony _harmony; public static Plugin instance; public static Dictionary<string, ReservedItemInfo> reservedItemsDict => ReservedItemInfo.reservedItemsDict; public static List<ReservedItemInfo> reservedItemsList => ReservedItemInfo.reservedItemsList; public static List<ReservedItemInfo> reservedItemSlotReps => ReservedItemInfo.reservedItemSlotReps; public static int numReservedItemSlots => ReservedItemInfo.numReservedItemSlots; private void Awake() { //IL_000d: Unknown result type (might be due to invalid IL or missing references) //IL_0017: Expected O, but got Unknown instance = this; _harmony = new Harmony("ReservedItemSlotCore"); ConfigSettings.BindConfigSettings(); _harmony.PatchAll(); ((BaseUnityPlugin)this).Logger.LogInfo((object)"ReservedItemSlotCore loaded"); } public static void Log(string message) { ((BaseUnityPlugin)instance).Logger.LogInfo((object)message); } public static bool IsReservedItem(string itemName) { return reservedItemsDict.ContainsKey(itemName); } public static ReservedItemInfo GetReservedItemInfo(string itemName) { return IsReservedItem(itemName) ? reservedItemsDict[itemName] : null; } public static ReservedItemInfo GetReservedItemInfo(GrabbableObject item) { return ((Object)(object)item != (Object)null) ? GetReservedItemInfo(item.itemProperties.itemName) : null; } public static int GetReservedItemHotbarIndex(string itemName) { return IsReservedItem(itemName) ? reservedItemsDict[itemName].indexInInventory : (-1); } } internal class ReservedItemInfo { public static Dictionary<string, ReservedItemInfo> reservedItemsDict = new Dictionary<string, ReservedItemInfo>(); public static List<ReservedItemInfo> reservedItemsList = new List<ReservedItemInfo>(); public static List<ReservedItemInfo> reservedItemSlotReps = new List<ReservedItemInfo>(); public static int defaultHotbarSlotPriority = 10; public static int currentUndefinedHotbarSlotPriority = 0; public string itemName; public int hotbarSlotPriority; private int undefinedHotbarSlotPriority = -1; public int reservedItemIndex; public bool forceUpdateCanBeGrabbedBeforeGameStart = false; public bool canBeGrabbedBeforeGameStart = false; public bool forceUpdateRequiresBattery = false; public bool requiresBattery = false; public static int numReservedItemSlots => reservedItemSlotReps.Count; public int indexInInventory => ((Object)(object)PlayerPatcher.localPlayerController != (Object)null) ? (PlayerPatcher.localPlayerController.ItemSlots.Length - (numReservedItemSlots - reservedItemIndex)) : (-1); public ReservedItemInfo(string itemName, int hotbarSlotPriority = -1, bool forceUpdateCanBeGrabbedBeforeGameStart = false, bool canBeGrabbedBeforeGameStart = false, bool forceUpdateRequiresBattery = false, bool requiresBattery = false) { this.itemName = itemName; this.forceUpdateCanBeGrabbedBeforeGameStart = forceUpdateCanBeGrabbedBeforeGameStart; this.canBeGrabbedBeforeGameStart = canBeGrabbedBeforeGameStart; this.forceUpdateRequiresBattery = forceUpdateRequiresBattery; this.requiresBattery = requiresBattery; if (hotbarSlotPriority != -1) { this.hotbarSlotPriority = hotbarSlotPriority; } else { this.hotbarSlotPriority = defaultHotbarSlotPriority; undefinedHotbarSlotPriority = ++currentUndefinedHotbarSlotPriority; } if (!reservedItemsDict.ContainsKey(this.itemName)) { reservedItemsDict.Add(this.itemName, this); reservedItemsList.Add(this); int i; for (i = 0; i < reservedItemSlotReps.Count; i++) { ReservedItemInfo reservedItemInfo = reservedItemSlotReps[i]; if (this.hotbarSlotPriority == reservedItemInfo.hotbarSlotPriority) { if (undefinedHotbarSlotPriority == reservedItemInfo.undefinedHotbarSlotPriority) { i = -1; } break; } if (this.hotbarSlotPriority > reservedItemInfo.hotbarSlotPriority) { break; } } if (i >= 0) { reservedItemIndex = i; reservedItemSlotReps.Insert(i, this); for (int j = i + 1; j < reservedItemSlotReps.Count; j++) { reservedItemSlotReps[j].reservedItemIndex = j; } } } else { Plugin.Log($"Tried to add duplicate item name to the ReservedItems list: {this.itemName}"); } } } public static class PluginInfo { public const string PLUGIN_GUID = "FlipMods.ReservedItemSlotCore"; public const string PLUGIN_NAME = "ReservedItemSlotCore"; public const string PLUGIN_VERSION = "1.6.0"; } } namespace ReservedItemSlotCore.Networking { public static class NetworkHelper { private static int NONE_EXEC_STAGE = 0; private static int SERVER_EXEC_STAGE = 1; private static int CLIENT_EXEC_STAGE = 2; public static int GetExecStage(NetworkBehaviour __instance) { return (int)Traverse.Create((object)__instance).Field("__rpc_exec_stage").GetValue(); } public static bool IsClientExecStage(NetworkBehaviour __instance) { return GetExecStage(__instance) == CLIENT_EXEC_STAGE; } public static bool IsServerExecStage(NetworkBehaviour __instance) { return GetExecStage(__instance) == SERVER_EXEC_STAGE; } public static bool IsValidClientRpcExecStage(NetworkBehaviour __instance) { NetworkManager singleton = NetworkManager.Singleton; if ((Object)(object)singleton == (Object)null || !singleton.IsListening) { return false; } int num = (int)Traverse.Create((object)__instance).Field("__rpc_exec_stage").GetValue(); if ((singleton.IsServer || singleton.IsHost) && num != 2) { return false; } return true; } } } namespace ReservedItemSlotCore.Patches { [HarmonyPatch] public static class HUDPatcher { private static CanvasScaler canvasScaler; private static AspectRatioFitter aspectRatioFitter; private static float iconWidth; private static float xPos; private static int oldHotbarSize; [HarmonyPatch(typeof(HUDManager), "Awake")] [HarmonyPrefix] public static void Initialize(HUDManager __instance) { //IL_0032: Unknown result type (might be due to invalid IL or missing references) //IL_0046: Unknown result type (might be due to invalid IL or missing references) canvasScaler = ((Component)__instance.itemSlotIconFrames[0]).GetComponentInParent<CanvasScaler>(); aspectRatioFitter = ((Component)__instance.itemSlotIconFrames[0]).GetComponentInParent<AspectRatioFitter>(); iconWidth = ((Component)__instance.itemSlotIconFrames[0]).GetComponent<RectTransform>().sizeDelta.x; xPos = canvasScaler.referenceResolution.x / 2f / aspectRatioFitter.aspectRatio - iconWidth / 4f; } [HarmonyPatch(typeof(HUDManager), "Start")] [HarmonyPostfix] public static void AddNewHotbarSlotsHud(HUDManager __instance) { //IL_0040: Unknown result type (might be due to invalid IL or missing references) //IL_005c: Unknown result type (might be due to invalid IL or missing references) //IL_0061: Unknown result type (might be due to invalid IL or missing references) //IL_0073: Unknown result type (might be due to invalid IL or missing references) //IL_0078: Unknown result type (might be due to invalid IL or missing references) //IL_00ed: Unknown result type (might be due to invalid IL or missing references) //IL_0162: Unknown result type (might be due to invalid IL or missing references) //IL_0174: Unknown result type (might be due to invalid IL or missing references) //IL_01c7: Unknown result type (might be due to invalid IL or missing references) //IL_0236: Unknown result type (might be due to invalid IL or missing references) //IL_026a: Unknown result type (might be due to invalid IL or missing references) //IL_0283: Unknown result type (might be due to invalid IL or missing references) //IL_0298: Unknown result type (might be due to invalid IL or missing references) //IL_02a5: Unknown result type (might be due to invalid IL or missing references) //IL_02af: Unknown result type (might be due to invalid IL or missing references) //IL_02c3: Unknown result type (might be due to invalid IL or missing references) //IL_02df: Unknown result type (might be due to invalid IL or missing references) if (PlayerPatcher.reservedHotbarSize > 0) { List<Image> list = new List<Image>(__instance.itemSlotIconFrames); List<Image> list2 = new List<Image>(__instance.itemSlotIcons); float y = ((Component)HUDManager.Instance.itemSlotIconFrames[0]).GetComponent<RectTransform>().sizeDelta.y; Vector3 eulerAngles = ((Transform)((Component)HUDManager.Instance.itemSlotIconFrames[0]).GetComponent<RectTransform>()).eulerAngles; Vector3 eulerAngles2 = ((Transform)((Component)HUDManager.Instance.itemSlotIcons[0]).GetComponent<RectTransform>()).eulerAngles; Plugin.Log($"Adding {ReservedItemInfo.reservedItemsList.Count} Reserved Item slots to the inventory HUD. Previous inventory HUD size: {PlayerPatcher.unreservedHotbarSize}"); for (int i = 0; i < Plugin.reservedItemSlotReps.Count; i++) { ReservedItemInfo reservedItemInfo = Plugin.reservedItemSlotReps[i]; Plugin.Log($"Adding Reserved Item slot for item types [{reservedItemInfo.itemName}]. Inventory index: {list.Count}"); float num = ((Graphic)HUDManager.Instance.itemSlotIconFrames[0]).rectTransform.anchoredPosition.y + 1.125f * y * (float)i; Image val = Object.Instantiate<Image>(HUDManager.Instance.itemSlotIconFrames[PlayerPatcher.unreservedHotbarSize - 1], ((Component)HUDManager.Instance.itemSlotIconFrames[0]).transform.parent); ((Object)val).name = $"ReservedItemSlot{i} [{reservedItemInfo.itemName}]"; ((Graphic)val).rectTransform.anchoredPosition = new Vector2(xPos, num); ((Transform)((Graphic)val).rectTransform).eulerAngles = eulerAngles; CanvasGroup val2 = ((Component)val).gameObject.AddComponent<CanvasGroup>(); val2.ignoreParentGroups = true; val2.alpha = 1f; Image component = ((Component)((Component)val).transform.GetChild(0)).GetComponent<Image>(); ((Object)component).name = "Icon"; ((Transform)((Graphic)component).rectTransform).eulerAngles = eulerAngles2; list.Add(val); list2.Add(component); } if (Plugin.numReservedItemSlots > 0) { TextMeshProUGUI component2 = new GameObject("ReservedItemSlotTooltip", new Type[2] { typeof(RectTransform), typeof(TextMeshProUGUI) }).GetComponent<TextMeshProUGUI>(); RectTransform rectTransform = ((TMP_Text)component2).rectTransform; ((Component)rectTransform).transform.parent = ((Component)list[PlayerPatcher.unreservedHotbarSize]).transform; ((Transform)rectTransform).localScale = Vector3.one; rectTransform.sizeDelta = new Vector2(((Graphic)list[0]).rectTransform.sizeDelta.x * 2f, 10f); rectTransform.pivot = Vector2.one / 2f; rectTransform.anchoredPosition3D = new Vector3(0f, (0f - rectTransform.sizeDelta.x / 2f) * 1.2f, 0f); ((TMP_Text)component2).font = ((TMP_Text)__instance.controlTipLines[0]).font; ((TMP_Text)component2).fontSize = 7f; ((TMP_Text)component2).alignment = (TextAlignmentOptions)514; ((TMP_Text)component2).text = string.Format($"Hold: [{ConfigSettings.GetDisplayName(ConfigSettings.focusReservedHotbarHotkey.Value)}]"); } __instance.itemSlotIconFrames = list.ToArray(); __instance.itemSlotIcons = list2.ToArray(); oldHotbarSize = __instance.itemSlotIconFrames.Length; Plugin.Log($"Finished adding {PlayerPatcher.reservedHotbarSize} Reserved Item slots in the inventory HUD."); } } public static void UpdateHotbarSize() { if (StartOfRound.Instance.localPlayerController.ItemSlots.Length != oldHotbarSize) { for (int i = 0; i < Plugin.numReservedItemSlots; i++) { HUDManager.Instance.itemSlotIcons[HUDManager.Instance.itemSlotIcons.Length - 1 - i].sprite = HUDManager.Instance.itemSlotIcons[oldHotbarSize - 1 - i].sprite; HUDManager.Instance.itemSlotIcons[oldHotbarSize - 1 - i].sprite = null; ((Behaviour)HUDManager.Instance.itemSlotIcons[oldHotbarSize - 1 - i]).enabled = false; ((Behaviour)HUDManager.Instance.itemSlotIcons[HUDManager.Instance.itemSlotIcons.Length - 1 - i]).enabled = (Object)(object)StartOfRound.Instance.localPlayerController.ItemSlots[HUDManager.Instance.itemSlotIcons.Length - 1 - i] != (Object)null; } oldHotbarSize = StartOfRound.Instance.localPlayerController.ItemSlots.Length; } } } [HarmonyPatch] public static class ReservedItemPatcher { public static bool isReservedHotbarFocused; public static int indexUnfocusedReservedHotbar; public static int indexFocusedReservedHotbar; internal static Dictionary<PlayerControllerB, ReservedItemInfo> grabbingReservedItemInfoDict; private static GrabbableObject previouslyHeldObjectServer; public static PlayerControllerB localPlayerController => PlayerPatcher.localPlayerController; public static int unreservedHotbarSize => PlayerPatcher.unreservedHotbarSize; public static int reservedHotbarSize => Plugin.numReservedItemSlots; public static int combinedHotbarSize => PlayerPatcher.combinedHotbarSize; internal static ReservedItemInfo grabbingReservedItemInfoLocal { get { return ((Object)(object)localPlayerController != (Object)null) ? grabbingReservedItemInfoDict[localPlayerController] : null; } set { if (!((Object)(object)localPlayerController == (Object)null)) { grabbingReservedItemInfoDict[localPlayerController] = value; } } } [HarmonyPatch(typeof(MenuManager), "OnEnable")] [HarmonyPrefix] public static void ResetVariables(MenuManager __instance) { if (grabbingReservedItemInfoDict == null) { grabbingReservedItemInfoDict = new Dictionary<PlayerControllerB, ReservedItemInfo>(); } if (grabbingReservedItemInfoDict.Count > 0) { grabbingReservedItemInfoDict.Clear(); } } [HarmonyPatch(typeof(PlayerControllerB), "ConnectClientToPlayerObject")] [HarmonyPrefix] public static void OnLocalPlayerConnect(PlayerControllerB __instance) { grabbingReservedItemInfoDict[__instance] = null; } private static GrabbableObject GetCurrentlyGrabbingObject(PlayerControllerB playerController) { //IL_0016: Unknown result type (might be due to invalid IL or missing references) //IL_001c: Expected O, but got Unknown return (GrabbableObject)Traverse.Create((object)playerController).Field("currentlyGrabbingObject").GetValue(); } private static void SetCurrentlyGrabbingObject(PlayerControllerB playerController, GrabbableObject grabbable) { Traverse.Create((object)playerController).Field("currentlyGrabbingObject").SetValue((object)grabbable); } [HarmonyPatch(typeof(PlayerControllerB), "BeginGrabObject")] [HarmonyPrefix] public static bool GrabReservedItemPrefix(PlayerControllerB __instance) { //IL_0021: Unknown result type (might be due to invalid IL or missing references) //IL_0031: Unknown result type (might be due to invalid IL or missing references) //IL_003b: Unknown result type (might be due to invalid IL or missing references) //IL_0241: Unknown result type (might be due to invalid IL or missing references) //IL_0267: Unknown result type (might be due to invalid IL or missing references) //IL_026e: Expected O, but got Unknown if (isReservedHotbarFocused) { return false; } Ray val = default(Ray); ((Ray)(ref val))..ctor(((Component)__instance.gameplayCamera).transform.position, ((Component)__instance.gameplayCamera).transform.forward); RaycastHit val2 = default(RaycastHit); if (!Physics.Raycast(val, ref val2, __instance.grabDistance, PlayerPatcher.INTERACTABLE_OBJECT_MASK) || ((Component)((RaycastHit)(ref val2)).collider).gameObject.layer == 8 || !(((Component)((RaycastHit)(ref val2)).collider).tag == "PhysicsProp") || __instance.twoHanded || __instance.sinkingValue > 0.73f) { grabbingReservedItemInfoLocal = null; return true; } GrabbableObject component = ((Component)((Component)((RaycastHit)(ref val2)).collider).transform).gameObject.GetComponent<GrabbableObject>(); grabbingReservedItemInfoLocal = Plugin.GetReservedItemInfo(component); if (grabbingReservedItemInfoLocal == null) { return true; } if (!GameNetworkManager.Instance.gameHasStarted && !component.itemProperties.canBeGrabbedBeforeGameStart && !StartOfRound.Instance.testRoom.activeSelf) { return false; } Traverse.Create((object)__instance).Field("grabInvalidated").SetValue((object)false); SetCurrentlyGrabbingObject(__instance, component); if (__instance.inSpecialInteractAnimation || component.isHeld || component.isPocketed) { return false; } NetworkObject networkObject = ((NetworkBehaviour)component).NetworkObject; if ((Object)(object)networkObject == (Object)null || !networkObject.IsSpawned) { return false; } if (grabbingReservedItemInfoLocal == null || !IsItemSlotEmpty(grabbingReservedItemInfoLocal)) { return true; } ((Behaviour)__instance.cursorIcon).enabled = false; ((TMP_Text)__instance.cursorTip).text = ""; __instance.twoHanded = component.itemProperties.twoHanded; __instance.carryWeight += Mathf.Clamp(component.itemProperties.weight - 1f, 0f, 10f); __instance.grabObjectAnimationTime = 0f; MethodInfo method = ((object)__instance).GetType().GetMethod("GrabObjectServerRpc", BindingFlags.Instance | BindingFlags.NonPublic); method.Invoke(__instance, new object[1] { NetworkObjectReference.op_Implicit(networkObject) }); Coroutine val3 = (Coroutine)Traverse.Create((object)__instance).Field("grabObjectCoroutine").GetValue(); if (val3 != null) { ((MonoBehaviour)__instance).StopCoroutine(val3); } MethodInfo method2 = ((object)__instance).GetType().GetMethod("GrabObject", BindingFlags.Instance | BindingFlags.NonPublic); val3 = ((MonoBehaviour)__instance).StartCoroutine((IEnumerator)method2.Invoke(__instance, new object[0])); Traverse.Create((object)__instance).Field("grabObjectCoroutine").SetValue((object)val3); return false; } [HarmonyPatch(typeof(PlayerControllerB), "GrabObjectClientRpc")] [HarmonyPrefix] public static bool GrabReservedItemClientRpcPrefix(bool grabValidated, NetworkObjectReference grabbedObject, PlayerControllerB __instance) { if (!NetworkHelper.IsClientExecStage((NetworkBehaviour)(object)__instance)) { return true; } if ((Object)(object)NetworkManager.Singleton != (Object)null && NetworkManager.Singleton.IsListening) { if (grabValidated) { NetworkObject val = default(NetworkObject); if (((NetworkObjectReference)(ref grabbedObject)).TryGet(ref val, (NetworkManager)null)) { GrabbableObject component = ((Component)val).GetComponent<GrabbableObject>(); ReservedItemInfo reservedItemInfo = Plugin.GetReservedItemInfo(component); if (reservedItemInfo != null && IsItemSlotEmpty(reservedItemInfo, __instance)) { __instance.ItemSlots[reservedItemInfo.indexInInventory] = component; component.playerHeldBy = __instance; component.isHeld = true; component.EnablePhysics(false); component.hasHitGround = false; component.isInFactory = __instance.isInsideFactory; component.EnableItemMeshes(false); Traverse.Create((object)component).Field("previousPlayerHeldBy").SetValue((object)__instance); component.PocketItem(); if ((Object)(object)__instance != (Object)(object)localPlayerController) { Plugin.Log("Grab object completed on player: " + ((Object)__instance).name); if ((Object)(object)component.itemProperties.grabSFX != (Object)null) { __instance.itemAudio.PlayOneShot(component.itemProperties.grabSFX, 1f); } grabbingReservedItemInfoDict[__instance] = null; } else { HUDManager.Instance.itemSlotIcons[reservedItemInfo.indexInInventory].sprite = component.itemProperties.itemIcon; ((Behaviour)HUDManager.Instance.itemSlotIcons[reservedItemInfo.indexInInventory]).enabled = true; HUDManager.Instance.PingHUDElement(HUDManager.Instance.Inventory, 1.5f, 1f, 0.13f); previouslyHeldObjectServer = localPlayerController.currentlyHeldObjectServer; localPlayerController.currentlyHeldObjectServer = component; } return false; } } } else if ((Object)(object)__instance == (Object)(object)localPlayerController) { Plugin.Log("Failed to validate ReservedItemGrab by the local player. Object id: " + ((NetworkObjectReference)(ref grabbedObject)).NetworkObjectId + "."); Traverse.Create((object)localPlayerController).Field("grabInvalidated").SetValue((object)true); } else { Plugin.Log("Failed to validate ReservedItemGrab by player with id: " + ((Object)__instance).name + ". Object id: " + ((NetworkObjectReference)(ref grabbedObject)).NetworkObjectId + "."); } } grabbingReservedItemInfoDict[__instance] = null; return true; } [HarmonyPatch(typeof(GrabbableObject), "GrabItemOnClient")] [HarmonyPrefix] public static void OnReservedItemGrabbed(GrabbableObject __instance) { if (grabbingReservedItemInfoLocal != null && !((Object)(object)__instance != (Object)(object)GetCurrentlyGrabbingObject(localPlayerController))) { OnLocalPlayerGrabbedReservedItem(); __instance.PocketItem(); } } private static void OnLocalPlayerGrabbedReservedItem() { localPlayerController.currentlyHeldObjectServer = previouslyHeldObjectServer; previouslyHeldObjectServer = null; grabbingReservedItemInfoLocal = null; } [HarmonyPatch(typeof(PlayerControllerB), "FirstEmptyItemSlot")] [HarmonyPostfix] public static void GetReservedItemSlotPlacementIndex(ref int __result, PlayerControllerB __instance) { ReservedItemInfo reservedItemInfo = grabbingReservedItemInfoDict[__instance]; if (reservedItemInfo != null) { if (__result == reservedItemInfo.indexInInventory && IsItemSlotEmpty(reservedItemInfo, __instance)) { return; } grabbingReservedItemInfoDict[__instance] = null; } if (__result < unreservedHotbarSize) { return; } __result = -1; for (int i = 0; i < unreservedHotbarSize; i++) { if ((Object)(object)__instance.ItemSlots[i] == (Object)null) { __result = i; break; } } } [HarmonyPatch(typeof(PlayerControllerB), "NextItemSlot")] [HarmonyPrefix] public static bool PreventScrollingOtherHotbar(ref int __result, bool forward, PlayerControllerB __instance) { __result = __instance.currentItemSlot; bool flag = __instance.currentItemSlot >= unreservedHotbarSize; int num = (forward ? 1 : (-1)); if (!flag) { __result = Mathf.Clamp(__result, 0, unreservedHotbarSize - 1) + num; if (__result < 0) { __result = unreservedHotbarSize - 1; } else if (__result >= unreservedHotbarSize) { __result = 0; } } else { __result = Mathf.Clamp(__result, unreservedHotbarSize, combinedHotbarSize - 1) + num; if (__result < unreservedHotbarSize) { __result = combinedHotbarSize - 1; } else if (__result >= combinedHotbarSize) { __result = unreservedHotbarSize; } } return false; } [HarmonyPatch(typeof(PlayerControllerB), "LateUpdate")] [HarmonyPrefix] public static void RefocusReservedHotbarAfterAnimation(PlayerControllerB __instance) { if (!((Object)(object)__instance != (Object)(object)localPlayerController) && Keybinds.holdingModifierKey != isReservedHotbarFocused && CanSwapToReservedHotbarSlot()) { SetFocusReservedHotbarSlots(Keybinds.holdingModifierKey); } } public static bool CanSwapToReservedHotbarSlot() { bool flag = (bool)Traverse.Create((object)localPlayerController).Field("throwingObject").GetValue(); return !(localPlayerController.inTerminalMenu || localPlayerController.isPlayerDead || localPlayerController.isGrabbingObjectAnimation || localPlayerController.inSpecialInteractAnimation || flag) && !localPlayerController.isTypingChat && !localPlayerController.twoHanded && !localPlayerController.activatingItem; } [HarmonyPatch(typeof(PlayerControllerB), "UpdateSpecialAnimationValue")] [HarmonyPostfix] public static void OnSpecialAnimationUpdate(bool specialAnimation, PlayerControllerB __instance, short yVal = 0, float timed = 0f, bool climbingLadder = false) { if (!((Object)(object)__instance != (Object)(object)localPlayerController)) { if (!specialAnimation || isReservedHotbarFocused) { } if (!specialAnimation && isReservedHotbarFocused != Keybinds.holdingModifierKey) { SetFocusReservedHotbarSlots(Keybinds.holdingModifierKey); } } } public static void SetFocusReservedHotbarSlots(bool active) { if (reservedHotbarSize <= 0 || isReservedHotbarFocused == active) { return; } Plugin.Log("SettingFocusReservedHotbar to: " + active); isReservedHotbarFocused = active; int num = localPlayerController.currentItemSlot; if (isReservedHotbarFocused && num < unreservedHotbarSize) { if (indexFocusedReservedHotbar == -1) { indexFocusedReservedHotbar = unreservedHotbarSize; } indexUnfocusedReservedHotbar = num; num = Mathf.Max(indexFocusedReservedHotbar, unreservedHotbarSize); if ((Object)(object)localPlayerController.ItemSlots[num] == (Object)null) { for (int i = 0; i < reservedHotbarSize; i++) { int num2 = unreservedHotbarSize + i; if ((Object)(object)localPlayerController.ItemSlots[num2] != (Object)null) { num = num2; break; } } } } else if (!isReservedHotbarFocused && num >= unreservedHotbarSize) { indexFocusedReservedHotbar = num; num = Mathf.Min(indexUnfocusedReservedHotbar, unreservedHotbarSize - 1); } HotbarSlotSync.SwapHotbarSlot(num); } public static bool IsItemSlotEmpty(string itemName, PlayerControllerB player = null) { return IsItemSlotEmpty(Plugin.GetReservedItemInfo(itemName), player); } internal static bool IsItemSlotEmpty(ReservedItemInfo itemInfo, PlayerControllerB player = null) { if ((Object)(object)player == (Object)null) { player = localPlayerController; } if ((Object)(object)player == (Object)null) { return false; } return itemInfo != null && itemInfo.indexInInventory < player.ItemSlots.Length && (Object)(object)player.ItemSlots[itemInfo.indexInInventory] == (Object)null; } public static GrabbableObject GetHeldReservedObject(string itemName, PlayerControllerB player = null) { if ((Object)(object)player == (Object)null) { player = localPlayerController; } if ((Object)(object)player == (Object)null) { return null; } int reservedItemHotbarIndex = Plugin.GetReservedItemHotbarIndex(itemName); return (reservedItemHotbarIndex >= 0 && reservedItemHotbarIndex < player.ItemSlots.Length && (Object)(object)player.ItemSlots[reservedItemHotbarIndex] != (Object)null) ? player.ItemSlots[reservedItemHotbarIndex] : null; } [HarmonyPatch(typeof(GrabbableObject), "Start")] [HarmonyPostfix] public static void InitializeReservedItemProperties(GrabbableObject __instance) { ReservedItemInfo reservedItemInfo = Plugin.GetReservedItemInfo(__instance.itemProperties.itemName); if (reservedItemInfo != null) { if (reservedItemInfo.forceUpdateCanBeGrabbedBeforeGameStart) { __instance.itemProperties.canBeGrabbedBeforeGameStart = reservedItemInfo.canBeGrabbedBeforeGameStart; } if (reservedItemInfo.forceUpdateRequiresBattery) { __instance.itemProperties.requiresBattery = reservedItemInfo.requiresBattery; } } } } [HarmonyPatch] public static class PlayerPatcher { public static PlayerControllerB localPlayerController; public static int vanillaHotbarSize = -1; public static int oldHotbarSize = -1; public static int INTERACTABLE_OBJECT_MASK { get; private set; } public static int unreservedHotbarSize => ((Object)(object)localPlayerController != (Object)null) ? (localPlayerController.ItemSlots.Length - reservedHotbarSize) : vanillaHotbarSize; public static int reservedHotbarSize => Plugin.numReservedItemSlots; public static int combinedHotbarSize => unreservedHotbarSize + reservedHotbarSize; [HarmonyPatch(typeof(MenuManager), "OnEnable")] [HarmonyPrefix] public static void ResetVariables(MenuManager __instance) { localPlayerController = null; vanillaHotbarSize = -1; ReservedItemPatcher.isReservedHotbarFocused = false; ReservedItemPatcher.indexUnfocusedReservedHotbar = 0; ReservedItemPatcher.indexFocusedReservedHotbar = -1; Keybinds.localPlayerController = null; Keybinds.focusReservedHotbarAction = null; Keybinds.holdingModifierKey = false; HotbarSlotSync.localPlayerController = null; } [HarmonyPatch(typeof(PlayerControllerB), "Awake")] [HarmonyPostfix] public static void InitializePlayerController(PlayerControllerB __instance) { if (vanillaHotbarSize == -1) { vanillaHotbarSize = __instance.ItemSlots.Length; } } [HarmonyPatch(typeof(PlayerControllerB), "Start")] [HarmonyPostfix] public static void InitializePlayerControllerLate(PlayerControllerB __instance) { __instance.ItemSlots = (GrabbableObject[])(object)new GrabbableObject[__instance.ItemSlots.Length + reservedHotbarSize]; } [HarmonyPatch(typeof(PlayerControllerB), "Update")] [HarmonyPostfix] public static void CheckForIncreasedInventorySize(PlayerControllerB __instance) { if ((Object)(object)__instance != (Object)(object)localPlayerController || reservedHotbarSize == 0 || __instance.ItemSlots.Length <= oldHotbarSize) { return; } PlayerControllerB[] allPlayerScripts = StartOfRound.Instance.allPlayerScripts; foreach (PlayerControllerB val in allPlayerScripts) { for (int j = 0; j < reservedHotbarSize; j++) { if ((Object)(object)val.ItemSlots[oldHotbarSize - 1 - j] != (Object)null) { val.ItemSlots[val.ItemSlots.Length - 1 - j] = val.ItemSlots[oldHotbarSize - 1 - j]; val.ItemSlots[oldHotbarSize - 1 - j] = null; } } } oldHotbarSize = __instance.ItemSlots.Length; HUDPatcher.UpdateHotbarSize(); Plugin.Log("Adjusted for new hotbar size: " + oldHotbarSize); } [HarmonyPatch(typeof(PlayerControllerB), "ConnectClientToPlayerObject")] [HarmonyPrefix] public static void OnLocalPlayerConnect(PlayerControllerB __instance) { localPlayerController = __instance; INTERACTABLE_OBJECT_MASK = (int)Traverse.Create((object)__instance).Field("interactableObjectsMask").GetValue(); oldHotbarSize = __instance.ItemSlots.Length; } } }
plugins/SkinwalkerMod.dll
Decompiled 11 months agousing System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Versioning; using BepInEx; using BepInEx.Configuration; using BepInEx.Logging; using Dissonance.Config; using HarmonyLib; using Unity.Netcode; using UnityEngine; using UnityEngine.Networking; using UnityEngine.SceneManagement; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)] [assembly: AssemblyTitle("SkinwalkerMod")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("SkinwalkerMod")] [assembly: AssemblyCopyright("Copyright © 2023")] [assembly: AssemblyTrademark("")] [assembly: ComVisible(false)] [assembly: Guid("fd4979a2-cef0-46af-8bf8-97e630b11475")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")] [assembly: AssemblyVersion("1.0.0.0")] internal class <Module> { static <Module>() { NetworkVariableSerializationTypes.InitializeSerializer_UnmanagedByMemcpy<bool>(); NetworkVariableSerializationTypes.InitializeEqualityChecker_UnmanagedIEquatable<bool>(); NetworkVariableSerializationTypes.InitializeSerializer_UnmanagedByMemcpy<float>(); NetworkVariableSerializationTypes.InitializeEqualityChecker_UnmanagedIEquatable<float>(); } } namespace SkinwalkerMod; [BepInPlugin("RugbugRedfern.SkinwalkerMod", "Skinwalker Mod", "1.0.8")] internal class PluginLoader : BaseUnityPlugin { private readonly Harmony harmony = new Harmony("RugbugRedfern.SkinwalkerMod"); private const string modGUID = "RugbugRedfern.SkinwalkerMod"; private const string modVersion = "1.0.8"; private static bool initialized; public static PluginLoader Instance { get; private set; } private void Awake() { //IL_00e0: Unknown result type (might be due to invalid IL or missing references) //IL_00e6: Expected O, but got Unknown if (initialized) { return; } initialized = true; Instance = this; harmony.PatchAll(Assembly.GetExecutingAssembly()); 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); } } } SkinwalkerLogger.Initialize("RugbugRedfern.SkinwalkerMod"); SkinwalkerLogger.Log("SKINWALKER MOD STARTING UP 1.0.8"); SkinwalkerConfig.InitConfig(); SceneManager.sceneLoaded += SkinwalkerNetworkManagerHandler.ClientConnectInitializer; GameObject val = new GameObject("Skinwalker Mod"); val.AddComponent<SkinwalkerModPersistent>(); ((Object)val).hideFlags = (HideFlags)61; Object.DontDestroyOnLoad((Object)(object)val); } public void BindConfig<T>(ref ConfigEntry<T> config, string section, string key, T defaultValue, string description = "") { config = ((BaseUnityPlugin)this).Config.Bind<T>(section, key, defaultValue, description); } } internal class SkinwalkerBehaviour : MonoBehaviour { private AudioSource audioSource; public const float PLAY_INTERVAL_MIN = 15f; public const float PLAY_INTERVAL_MAX = 40f; private const float MAX_DIST = 100f; private float nextTimeToPlayAudio; private EnemyAI ai; public void Initialize(EnemyAI ai) { this.ai = ai; audioSource = ai.creatureVoice; SetNextTime(); } private void Update() { //IL_0077: Unknown result type (might be due to invalid IL or missing references) //IL_0082: Unknown result type (might be due to invalid IL or missing references) if (!(Time.time > nextTimeToPlayAudio)) { return; } SetNextTime(); float num = -1f; if (Object.op_Implicit((Object)(object)ai) && !ai.isEnemyDead) { if ((Object)(object)GameNetworkManager.Instance == (Object)null || (Object)(object)GameNetworkManager.Instance.localPlayerController == (Object)null || (num = Vector3.Distance(((Component)GameNetworkManager.Instance.localPlayerController).transform.position, ((Component)this).transform.position)) < 100f) { AudioClip sample = SkinwalkerModPersistent.Instance.GetSample(); if (Object.op_Implicit((Object)(object)sample)) { SkinwalkerLogger.Log(((Object)this).name + " played voice line 1"); audioSource.PlayOneShot(sample); } else { SkinwalkerLogger.Log(((Object)this).name + " played voice line 0"); } } else { SkinwalkerLogger.Log(((Object)this).name + " played voice line no (too far away) " + num); } } else { SkinwalkerLogger.Log(((Object)this).name + " played voice line no (dead) EnemyAI: " + (object)ai); } } private void SetNextTime() { if (SkinwalkerNetworkManager.Instance.VoiceLineFrequency.Value <= 0f) { nextTimeToPlayAudio = Time.time + 100000000f; } else { nextTimeToPlayAudio = Time.time + Random.Range(15f, 40f) / SkinwalkerNetworkManager.Instance.VoiceLineFrequency.Value; } } private T CopyComponent<T>(T original, GameObject destination) where T : Component { Type type = ((object)original).GetType(); Component val = destination.AddComponent(type); FieldInfo[] fields = type.GetFields(); FieldInfo[] array = fields; foreach (FieldInfo fieldInfo in array) { fieldInfo.SetValue(val, fieldInfo.GetValue(original)); } return (T)(object)((val is T) ? val : null); } } internal class SkinwalkerConfig { public static ConfigEntry<bool> VoiceEnabled_BaboonHawk; public static ConfigEntry<bool> VoiceEnabled_Bracken; public static ConfigEntry<bool> VoiceEnabled_BunkerSpider; public static ConfigEntry<bool> VoiceEnabled_Centipede; public static ConfigEntry<bool> VoiceEnabled_CoilHead; public static ConfigEntry<bool> VoiceEnabled_EyelessDog; public static ConfigEntry<bool> VoiceEnabled_ForestGiant; public static ConfigEntry<bool> VoiceEnabled_GhostGirl; public static ConfigEntry<bool> VoiceEnabled_GiantWorm; public static ConfigEntry<bool> VoiceEnabled_HoardingBug; public static ConfigEntry<bool> VoiceEnabled_Hygrodere; public static ConfigEntry<bool> VoiceEnabled_Jester; public static ConfigEntry<bool> VoiceEnabled_Masked; public static ConfigEntry<bool> VoiceEnabled_Nutcracker; public static ConfigEntry<bool> VoiceEnabled_SporeLizard; public static ConfigEntry<bool> VoiceEnabled_Thumper; public static ConfigEntry<float> VoiceLineFrequency; public static void InitConfig() { PluginLoader.Instance.BindConfig(ref VoiceLineFrequency, "Voice Settings", "VoiceLineFrequency", 1f, "1 is the default, and voice lines will occur every " + 15f.ToString("0") + " to " + 40f.ToString("0") + " seconds per enemy. Setting this to 2 means they will occur twice as often, 0.5 means half as often, etc."); PluginLoader.Instance.BindConfig(ref VoiceEnabled_BaboonHawk, "Monster Voices", "Baboon Hawk", defaultValue: true); PluginLoader.Instance.BindConfig(ref VoiceEnabled_Bracken, "Monster Voices", "Bracken", defaultValue: true); PluginLoader.Instance.BindConfig(ref VoiceEnabled_BunkerSpider, "Monster Voices", "Bunker Spider", defaultValue: true); PluginLoader.Instance.BindConfig(ref VoiceEnabled_Centipede, "Monster Voices", "Centipede", defaultValue: true); PluginLoader.Instance.BindConfig(ref VoiceEnabled_CoilHead, "Monster Voices", "Coil Head", defaultValue: true); PluginLoader.Instance.BindConfig(ref VoiceEnabled_EyelessDog, "Monster Voices", "Eyeless Dog", defaultValue: true); PluginLoader.Instance.BindConfig(ref VoiceEnabled_ForestGiant, "Monster Voices", "Forest Giant", defaultValue: false); PluginLoader.Instance.BindConfig(ref VoiceEnabled_GhostGirl, "Monster Voices", "Ghost Girl", defaultValue: true); PluginLoader.Instance.BindConfig(ref VoiceEnabled_GiantWorm, "Monster Voices", "Giant Worm", defaultValue: false); PluginLoader.Instance.BindConfig(ref VoiceEnabled_HoardingBug, "Monster Voices", "Hoarding Bug", defaultValue: true); PluginLoader.Instance.BindConfig(ref VoiceEnabled_Hygrodere, "Monster Voices", "Hygrodere", defaultValue: false); PluginLoader.Instance.BindConfig(ref VoiceEnabled_Jester, "Monster Voices", "Jester", defaultValue: true); PluginLoader.Instance.BindConfig(ref VoiceEnabled_Masked, "Monster Voices", "Masked", defaultValue: true); PluginLoader.Instance.BindConfig(ref VoiceEnabled_Nutcracker, "Monster Voices", "Nutcracker", defaultValue: true); PluginLoader.Instance.BindConfig(ref VoiceEnabled_SporeLizard, "Monster Voices", "Spore Lizard", defaultValue: true); PluginLoader.Instance.BindConfig(ref VoiceEnabled_Thumper, "Monster Voices", "Thumper", defaultValue: true); SkinwalkerLogger.Log("VoiceEnabled_BaboonHawk" + $" VALUE LOADED FROM CONFIG: [{VoiceEnabled_BaboonHawk.Value}]"); SkinwalkerLogger.Log("VoiceEnabled_Bracken" + $" VALUE LOADED FROM CONFIG: [{VoiceEnabled_Bracken.Value}]"); SkinwalkerLogger.Log("VoiceEnabled_BunkerSpider" + $" VALUE LOADED FROM CONFIG: [{VoiceEnabled_BunkerSpider.Value}]"); SkinwalkerLogger.Log("VoiceEnabled_Centipede" + $" VALUE LOADED FROM CONFIG: [{VoiceEnabled_Centipede.Value}]"); SkinwalkerLogger.Log("VoiceEnabled_CoilHead" + $" VALUE LOADED FROM CONFIG: [{VoiceEnabled_CoilHead.Value}]"); SkinwalkerLogger.Log("VoiceEnabled_EyelessDog" + $" VALUE LOADED FROM CONFIG: [{VoiceEnabled_EyelessDog.Value}]"); SkinwalkerLogger.Log("VoiceEnabled_ForestGiant" + $" VALUE LOADED FROM CONFIG: [{VoiceEnabled_ForestGiant.Value}]"); SkinwalkerLogger.Log("VoiceEnabled_GhostGirl" + $" VALUE LOADED FROM CONFIG: [{VoiceEnabled_GhostGirl.Value}]"); SkinwalkerLogger.Log("VoiceEnabled_GiantWorm" + $" VALUE LOADED FROM CONFIG: [{VoiceEnabled_GiantWorm.Value}]"); SkinwalkerLogger.Log("VoiceEnabled_HoardingBug" + $" VALUE LOADED FROM CONFIG: [{VoiceEnabled_HoardingBug.Value}]"); SkinwalkerLogger.Log("VoiceEnabled_Hygrodere" + $" VALUE LOADED FROM CONFIG: [{VoiceEnabled_Hygrodere.Value}]"); SkinwalkerLogger.Log("VoiceEnabled_Jester" + $" VALUE LOADED FROM CONFIG: [{VoiceEnabled_Jester.Value}]"); SkinwalkerLogger.Log("VoiceEnabled_Masked" + $" VALUE LOADED FROM CONFIG: [{VoiceEnabled_Masked.Value}]"); SkinwalkerLogger.Log("VoiceEnabled_Nutcracker" + $" VALUE LOADED FROM CONFIG: [{VoiceEnabled_Nutcracker.Value}]"); SkinwalkerLogger.Log("VoiceEnabled_SporeLizard" + $" VALUE LOADED FROM CONFIG: [{VoiceEnabled_SporeLizard.Value}]"); SkinwalkerLogger.Log("VoiceEnabled_Thumper" + $" VALUE LOADED FROM CONFIG: [{VoiceEnabled_Thumper.Value}]"); SkinwalkerLogger.Log("VoiceLineFrequency" + $" VALUE LOADED FROM CONFIG: [{VoiceLineFrequency.Value}]"); } } internal static class SkinwalkerLogger { internal static ManualLogSource logSource; public static void Initialize(string modGUID) { logSource = Logger.CreateLogSource(modGUID); } public static void Log(object message) { logSource.LogInfo(message); } public static void LogError(object message) { logSource.LogError(message); } public static void LogWarning(object message) { logSource.LogWarning(message); } } public class SkinwalkerModPersistent : MonoBehaviour { private string audioFolder; private List<AudioClip> cachedAudio = new List<AudioClip>(); private float nextTimeToCheckFolder = 30f; private float nextTimeToCheckEnemies = 30f; private const float folderScanInterval = 8f; private const float enemyScanInterval = 5f; public static SkinwalkerModPersistent Instance { get; private set; } private void Awake() { //IL_000e: Unknown result type (might be due to invalid IL or missing references) Instance = this; ((Component)this).transform.position = Vector3.zero; SkinwalkerLogger.Log("Skinwalker Mod Object Initialized"); audioFolder = Path.Combine(Application.dataPath, "..", "Dissonance_Diagnostics"); EnableRecording(); if (!Directory.Exists(audioFolder)) { Directory.CreateDirectory(audioFolder); } } private void Start() { try { if (Directory.Exists(audioFolder)) { Directory.Delete(audioFolder, recursive: true); } } catch (Exception message) { SkinwalkerLogger.Log(message); } } private void OnApplicationQuit() { DisableRecording(); } private void EnableRecording() { DebugSettings.Instance.EnablePlaybackDiagnostics = true; DebugSettings.Instance.RecordFinalAudio = true; } private void Update() { if (Time.realtimeSinceStartup > nextTimeToCheckFolder) { nextTimeToCheckFolder = Time.realtimeSinceStartup + 8f; if (!Directory.Exists(audioFolder)) { SkinwalkerLogger.Log("Audio folder not present. Don't worry about it, it will be created automatically when you play with friends. (" + audioFolder + ")"); return; } string[] files = Directory.GetFiles(audioFolder); SkinwalkerLogger.Log($"Got audio file paths ({files.Length})"); string[] array = files; foreach (string path in array) { ((MonoBehaviour)this).StartCoroutine(LoadWavFile(path, delegate(AudioClip audioClip) { cachedAudio.Add(audioClip); })); } } if (!(Time.realtimeSinceStartup > nextTimeToCheckEnemies)) { return; } nextTimeToCheckEnemies = Time.realtimeSinceStartup + 5f; EnemyAI[] array2 = Object.FindObjectsOfType<EnemyAI>(true); EnemyAI[] array3 = array2; SkinwalkerBehaviour skinwalkerBehaviour = default(SkinwalkerBehaviour); foreach (EnemyAI val in array3) { SkinwalkerLogger.Log("IsEnemyEnabled " + ((Object)val).name + " " + IsEnemyEnabled(val)); if (IsEnemyEnabled(val) && !((Component)val).TryGetComponent<SkinwalkerBehaviour>(ref skinwalkerBehaviour)) { ((Component)val).gameObject.AddComponent<SkinwalkerBehaviour>().Initialize(val); } } } private bool IsEnemyEnabled(EnemyAI enemy) { if ((Object)(object)enemy == (Object)null) { return false; } return ((Object)((Component)enemy).gameObject).name switch { "MaskedPlayerEnemy(Clone)" => SkinwalkerNetworkManager.Instance.VoiceEnabled_Masked.Value, "NutcrackerEnemy(Clone)" => SkinwalkerNetworkManager.Instance.VoiceEnabled_Nutcracker.Value, "BaboonHawkEnemy(Clone)" => SkinwalkerNetworkManager.Instance.VoiceEnabled_BaboonHawk.Value, "Flowerman(Clone)" => SkinwalkerNetworkManager.Instance.VoiceEnabled_Bracken.Value, "SandSpider(Clone)" => SkinwalkerNetworkManager.Instance.VoiceEnabled_BunkerSpider.Value, "RedLocustBees(Clone)" => false, "Centipede(Clone)" => SkinwalkerNetworkManager.Instance.VoiceEnabled_Centipede.Value, "SpringMan(Clone)" => SkinwalkerNetworkManager.Instance.VoiceEnabled_CoilHead.Value, "MouthDog(Clone)" => SkinwalkerNetworkManager.Instance.VoiceEnabled_EyelessDog.Value, "ForestGiant(Clone)" => SkinwalkerNetworkManager.Instance.VoiceEnabled_ForestGiant.Value, "DressGirl(Clone)" => SkinwalkerNetworkManager.Instance.VoiceEnabled_GhostGirl.Value, "SandWorm(Clone)" => SkinwalkerNetworkManager.Instance.VoiceEnabled_GiantWorm.Value, "HoarderBug(Clone)" => SkinwalkerNetworkManager.Instance.VoiceEnabled_HoardingBug.Value, "Blob(Clone)" => SkinwalkerNetworkManager.Instance.VoiceEnabled_Hygrodere.Value, "JesterEnemy(Clone)" => SkinwalkerNetworkManager.Instance.VoiceEnabled_Jester.Value, "PufferEnemy(Clone)" => SkinwalkerNetworkManager.Instance.VoiceEnabled_SporeLizard.Value, "Crawler(Clone)" => SkinwalkerNetworkManager.Instance.VoiceEnabled_Thumper.Value, "DocileLocustBees(Clone)" => false, "DoublewingedBird(Clone)" => false, _ => true, }; } internal IEnumerator LoadWavFile(string path, Action<AudioClip> callback) { UnityWebRequest www = UnityWebRequestMultimedia.GetAudioClip(path, (AudioType)20); try { yield return www.SendWebRequest(); if ((int)www.result == 1) { SkinwalkerLogger.Log("Loaded clip from path " + path); AudioClip audioClip = DownloadHandlerAudioClip.GetContent(www); if (audioClip.length > 0.9f) { callback(audioClip); } try { File.Delete(path); } catch (Exception e) { SkinwalkerLogger.LogWarning(e); } } } finally { ((IDisposable)www)?.Dispose(); } } private void DisableRecording() { DebugSettings.Instance.EnablePlaybackDiagnostics = false; DebugSettings.Instance.RecordFinalAudio = false; if (Directory.Exists(audioFolder)) { Directory.Delete(audioFolder, recursive: true); } } public AudioClip GetSample() { if (cachedAudio.Count > 0) { int index = Random.Range(0, cachedAudio.Count - 1); AudioClip result = cachedAudio[index]; cachedAudio.RemoveAt(index); return result; } while (cachedAudio.Count > 200) { cachedAudio.RemoveAt(0); } return null; } public void ClearCache() { cachedAudio.Clear(); } } internal static class SkinwalkerNetworkManagerHandler { internal static void ClientConnectInitializer(Scene sceneName, LoadSceneMode sceneEnum) { //IL_001c: Unknown result type (might be due to invalid IL or missing references) //IL_0022: Expected O, but got Unknown if (((Scene)(ref sceneName)).name == "SampleSceneRelay") { GameObject val = new GameObject("SkinwalkerNetworkManager"); val.AddComponent<NetworkObject>(); val.AddComponent<SkinwalkerNetworkManager>(); Debug.Log((object)"Initialized SkinwalkerNetworkManager"); } } } internal class SkinwalkerNetworkManager : NetworkBehaviour { public NetworkVariable<bool> VoiceEnabled_BaboonHawk = new NetworkVariable<bool>(true, (NetworkVariableReadPermission)0, (NetworkVariableWritePermission)0); public NetworkVariable<bool> VoiceEnabled_Bracken = new NetworkVariable<bool>(true, (NetworkVariableReadPermission)0, (NetworkVariableWritePermission)0); public NetworkVariable<bool> VoiceEnabled_BunkerSpider = new NetworkVariable<bool>(true, (NetworkVariableReadPermission)0, (NetworkVariableWritePermission)0); public NetworkVariable<bool> VoiceEnabled_Centipede = new NetworkVariable<bool>(true, (NetworkVariableReadPermission)0, (NetworkVariableWritePermission)0); public NetworkVariable<bool> VoiceEnabled_CoilHead = new NetworkVariable<bool>(true, (NetworkVariableReadPermission)0, (NetworkVariableWritePermission)0); public NetworkVariable<bool> VoiceEnabled_EyelessDog = new NetworkVariable<bool>(true, (NetworkVariableReadPermission)0, (NetworkVariableWritePermission)0); public NetworkVariable<bool> VoiceEnabled_ForestGiant = new NetworkVariable<bool>(true, (NetworkVariableReadPermission)0, (NetworkVariableWritePermission)0); public NetworkVariable<bool> VoiceEnabled_GhostGirl = new NetworkVariable<bool>(true, (NetworkVariableReadPermission)0, (NetworkVariableWritePermission)0); public NetworkVariable<bool> VoiceEnabled_GiantWorm = new NetworkVariable<bool>(true, (NetworkVariableReadPermission)0, (NetworkVariableWritePermission)0); public NetworkVariable<bool> VoiceEnabled_HoardingBug = new NetworkVariable<bool>(true, (NetworkVariableReadPermission)0, (NetworkVariableWritePermission)0); public NetworkVariable<bool> VoiceEnabled_Hygrodere = new NetworkVariable<bool>(true, (NetworkVariableReadPermission)0, (NetworkVariableWritePermission)0); public NetworkVariable<bool> VoiceEnabled_Jester = new NetworkVariable<bool>(true, (NetworkVariableReadPermission)0, (NetworkVariableWritePermission)0); public NetworkVariable<bool> VoiceEnabled_Masked = new NetworkVariable<bool>(true, (NetworkVariableReadPermission)0, (NetworkVariableWritePermission)0); public NetworkVariable<bool> VoiceEnabled_Nutcracker = new NetworkVariable<bool>(true, (NetworkVariableReadPermission)0, (NetworkVariableWritePermission)0); public NetworkVariable<bool> VoiceEnabled_SporeLizard = new NetworkVariable<bool>(true, (NetworkVariableReadPermission)0, (NetworkVariableWritePermission)0); public NetworkVariable<bool> VoiceEnabled_Thumper = new NetworkVariable<bool>(true, (NetworkVariableReadPermission)0, (NetworkVariableWritePermission)0); public NetworkVariable<float> VoiceLineFrequency = new NetworkVariable<float>(1f, (NetworkVariableReadPermission)0, (NetworkVariableWritePermission)0); public static SkinwalkerNetworkManager Instance { get; private set; } private void Awake() { Instance = this; if (GameNetworkManager.Instance.isHostingGame) { VoiceEnabled_BaboonHawk.Value = SkinwalkerConfig.VoiceEnabled_BaboonHawk.Value; VoiceEnabled_Bracken.Value = SkinwalkerConfig.VoiceEnabled_Bracken.Value; VoiceEnabled_BunkerSpider.Value = SkinwalkerConfig.VoiceEnabled_BunkerSpider.Value; VoiceEnabled_Centipede.Value = SkinwalkerConfig.VoiceEnabled_Centipede.Value; VoiceEnabled_CoilHead.Value = SkinwalkerConfig.VoiceEnabled_CoilHead.Value; VoiceEnabled_EyelessDog.Value = SkinwalkerConfig.VoiceEnabled_EyelessDog.Value; VoiceEnabled_ForestGiant.Value = SkinwalkerConfig.VoiceEnabled_ForestGiant.Value; VoiceEnabled_GhostGirl.Value = SkinwalkerConfig.VoiceEnabled_GhostGirl.Value; VoiceEnabled_GiantWorm.Value = SkinwalkerConfig.VoiceEnabled_GiantWorm.Value; VoiceEnabled_HoardingBug.Value = SkinwalkerConfig.VoiceEnabled_HoardingBug.Value; VoiceEnabled_Hygrodere.Value = SkinwalkerConfig.VoiceEnabled_Hygrodere.Value; VoiceEnabled_Jester.Value = SkinwalkerConfig.VoiceEnabled_Jester.Value; VoiceEnabled_Masked.Value = SkinwalkerConfig.VoiceEnabled_Masked.Value; VoiceEnabled_Nutcracker.Value = SkinwalkerConfig.VoiceEnabled_Nutcracker.Value; VoiceEnabled_SporeLizard.Value = SkinwalkerConfig.VoiceEnabled_SporeLizard.Value; VoiceEnabled_Thumper.Value = SkinwalkerConfig.VoiceEnabled_Thumper.Value; VoiceLineFrequency.Value = SkinwalkerConfig.VoiceLineFrequency.Value; SkinwalkerLogger.Log("HOST SENDING CONFIG TO CLIENTS"); } SkinwalkerLogger.Log("SkinwalkerNetworkManager Awake"); } public override void OnDestroy() { ((NetworkBehaviour)this).OnDestroy(); SkinwalkerLogger.Log("SkinwalkerNetworkManager OnDestroy"); SkinwalkerModPersistent.Instance?.ClearCache(); } protected override void __initializeVariables() { if (VoiceEnabled_BaboonHawk == null) { throw new Exception("SkinwalkerNetworkManager.VoiceEnabled_BaboonHawk cannot be null. All NetworkVariableBase instances must be initialized."); } ((NetworkVariableBase)VoiceEnabled_BaboonHawk).Initialize((NetworkBehaviour)(object)this); ((NetworkBehaviour)this).__nameNetworkVariable((NetworkVariableBase)(object)VoiceEnabled_BaboonHawk, "VoiceEnabled_BaboonHawk"); base.NetworkVariableFields.Add((NetworkVariableBase)(object)VoiceEnabled_BaboonHawk); if (VoiceEnabled_Bracken == null) { throw new Exception("SkinwalkerNetworkManager.VoiceEnabled_Bracken cannot be null. All NetworkVariableBase instances must be initialized."); } ((NetworkVariableBase)VoiceEnabled_Bracken).Initialize((NetworkBehaviour)(object)this); ((NetworkBehaviour)this).__nameNetworkVariable((NetworkVariableBase)(object)VoiceEnabled_Bracken, "VoiceEnabled_Bracken"); base.NetworkVariableFields.Add((NetworkVariableBase)(object)VoiceEnabled_Bracken); if (VoiceEnabled_BunkerSpider == null) { throw new Exception("SkinwalkerNetworkManager.VoiceEnabled_BunkerSpider cannot be null. All NetworkVariableBase instances must be initialized."); } ((NetworkVariableBase)VoiceEnabled_BunkerSpider).Initialize((NetworkBehaviour)(object)this); ((NetworkBehaviour)this).__nameNetworkVariable((NetworkVariableBase)(object)VoiceEnabled_BunkerSpider, "VoiceEnabled_BunkerSpider"); base.NetworkVariableFields.Add((NetworkVariableBase)(object)VoiceEnabled_BunkerSpider); if (VoiceEnabled_Centipede == null) { throw new Exception("SkinwalkerNetworkManager.VoiceEnabled_Centipede cannot be null. All NetworkVariableBase instances must be initialized."); } ((NetworkVariableBase)VoiceEnabled_Centipede).Initialize((NetworkBehaviour)(object)this); ((NetworkBehaviour)this).__nameNetworkVariable((NetworkVariableBase)(object)VoiceEnabled_Centipede, "VoiceEnabled_Centipede"); base.NetworkVariableFields.Add((NetworkVariableBase)(object)VoiceEnabled_Centipede); if (VoiceEnabled_CoilHead == null) { throw new Exception("SkinwalkerNetworkManager.VoiceEnabled_CoilHead cannot be null. All NetworkVariableBase instances must be initialized."); } ((NetworkVariableBase)VoiceEnabled_CoilHead).Initialize((NetworkBehaviour)(object)this); ((NetworkBehaviour)this).__nameNetworkVariable((NetworkVariableBase)(object)VoiceEnabled_CoilHead, "VoiceEnabled_CoilHead"); base.NetworkVariableFields.Add((NetworkVariableBase)(object)VoiceEnabled_CoilHead); if (VoiceEnabled_EyelessDog == null) { throw new Exception("SkinwalkerNetworkManager.VoiceEnabled_EyelessDog cannot be null. All NetworkVariableBase instances must be initialized."); } ((NetworkVariableBase)VoiceEnabled_EyelessDog).Initialize((NetworkBehaviour)(object)this); ((NetworkBehaviour)this).__nameNetworkVariable((NetworkVariableBase)(object)VoiceEnabled_EyelessDog, "VoiceEnabled_EyelessDog"); base.NetworkVariableFields.Add((NetworkVariableBase)(object)VoiceEnabled_EyelessDog); if (VoiceEnabled_ForestGiant == null) { throw new Exception("SkinwalkerNetworkManager.VoiceEnabled_ForestGiant cannot be null. All NetworkVariableBase instances must be initialized."); } ((NetworkVariableBase)VoiceEnabled_ForestGiant).Initialize((NetworkBehaviour)(object)this); ((NetworkBehaviour)this).__nameNetworkVariable((NetworkVariableBase)(object)VoiceEnabled_ForestGiant, "VoiceEnabled_ForestGiant"); base.NetworkVariableFields.Add((NetworkVariableBase)(object)VoiceEnabled_ForestGiant); if (VoiceEnabled_GhostGirl == null) { throw new Exception("SkinwalkerNetworkManager.VoiceEnabled_GhostGirl cannot be null. All NetworkVariableBase instances must be initialized."); } ((NetworkVariableBase)VoiceEnabled_GhostGirl).Initialize((NetworkBehaviour)(object)this); ((NetworkBehaviour)this).__nameNetworkVariable((NetworkVariableBase)(object)VoiceEnabled_GhostGirl, "VoiceEnabled_GhostGirl"); base.NetworkVariableFields.Add((NetworkVariableBase)(object)VoiceEnabled_GhostGirl); if (VoiceEnabled_GiantWorm == null) { throw new Exception("SkinwalkerNetworkManager.VoiceEnabled_GiantWorm cannot be null. All NetworkVariableBase instances must be initialized."); } ((NetworkVariableBase)VoiceEnabled_GiantWorm).Initialize((NetworkBehaviour)(object)this); ((NetworkBehaviour)this).__nameNetworkVariable((NetworkVariableBase)(object)VoiceEnabled_GiantWorm, "VoiceEnabled_GiantWorm"); base.NetworkVariableFields.Add((NetworkVariableBase)(object)VoiceEnabled_GiantWorm); if (VoiceEnabled_HoardingBug == null) { throw new Exception("SkinwalkerNetworkManager.VoiceEnabled_HoardingBug cannot be null. All NetworkVariableBase instances must be initialized."); } ((NetworkVariableBase)VoiceEnabled_HoardingBug).Initialize((NetworkBehaviour)(object)this); ((NetworkBehaviour)this).__nameNetworkVariable((NetworkVariableBase)(object)VoiceEnabled_HoardingBug, "VoiceEnabled_HoardingBug"); base.NetworkVariableFields.Add((NetworkVariableBase)(object)VoiceEnabled_HoardingBug); if (VoiceEnabled_Hygrodere == null) { throw new Exception("SkinwalkerNetworkManager.VoiceEnabled_Hygrodere cannot be null. All NetworkVariableBase instances must be initialized."); } ((NetworkVariableBase)VoiceEnabled_Hygrodere).Initialize((NetworkBehaviour)(object)this); ((NetworkBehaviour)this).__nameNetworkVariable((NetworkVariableBase)(object)VoiceEnabled_Hygrodere, "VoiceEnabled_Hygrodere"); base.NetworkVariableFields.Add((NetworkVariableBase)(object)VoiceEnabled_Hygrodere); if (VoiceEnabled_Jester == null) { throw new Exception("SkinwalkerNetworkManager.VoiceEnabled_Jester cannot be null. All NetworkVariableBase instances must be initialized."); } ((NetworkVariableBase)VoiceEnabled_Jester).Initialize((NetworkBehaviour)(object)this); ((NetworkBehaviour)this).__nameNetworkVariable((NetworkVariableBase)(object)VoiceEnabled_Jester, "VoiceEnabled_Jester"); base.NetworkVariableFields.Add((NetworkVariableBase)(object)VoiceEnabled_Jester); if (VoiceEnabled_Masked == null) { throw new Exception("SkinwalkerNetworkManager.VoiceEnabled_Masked cannot be null. All NetworkVariableBase instances must be initialized."); } ((NetworkVariableBase)VoiceEnabled_Masked).Initialize((NetworkBehaviour)(object)this); ((NetworkBehaviour)this).__nameNetworkVariable((NetworkVariableBase)(object)VoiceEnabled_Masked, "VoiceEnabled_Masked"); base.NetworkVariableFields.Add((NetworkVariableBase)(object)VoiceEnabled_Masked); if (VoiceEnabled_Nutcracker == null) { throw new Exception("SkinwalkerNetworkManager.VoiceEnabled_Nutcracker cannot be null. All NetworkVariableBase instances must be initialized."); } ((NetworkVariableBase)VoiceEnabled_Nutcracker).Initialize((NetworkBehaviour)(object)this); ((NetworkBehaviour)this).__nameNetworkVariable((NetworkVariableBase)(object)VoiceEnabled_Nutcracker, "VoiceEnabled_Nutcracker"); base.NetworkVariableFields.Add((NetworkVariableBase)(object)VoiceEnabled_Nutcracker); if (VoiceEnabled_SporeLizard == null) { throw new Exception("SkinwalkerNetworkManager.VoiceEnabled_SporeLizard cannot be null. All NetworkVariableBase instances must be initialized."); } ((NetworkVariableBase)VoiceEnabled_SporeLizard).Initialize((NetworkBehaviour)(object)this); ((NetworkBehaviour)this).__nameNetworkVariable((NetworkVariableBase)(object)VoiceEnabled_SporeLizard, "VoiceEnabled_SporeLizard"); base.NetworkVariableFields.Add((NetworkVariableBase)(object)VoiceEnabled_SporeLizard); if (VoiceEnabled_Thumper == null) { throw new Exception("SkinwalkerNetworkManager.VoiceEnabled_Thumper cannot be null. All NetworkVariableBase instances must be initialized."); } ((NetworkVariableBase)VoiceEnabled_Thumper).Initialize((NetworkBehaviour)(object)this); ((NetworkBehaviour)this).__nameNetworkVariable((NetworkVariableBase)(object)VoiceEnabled_Thumper, "VoiceEnabled_Thumper"); base.NetworkVariableFields.Add((NetworkVariableBase)(object)VoiceEnabled_Thumper); if (VoiceLineFrequency == null) { throw new Exception("SkinwalkerNetworkManager.VoiceLineFrequency cannot be null. All NetworkVariableBase instances must be initialized."); } ((NetworkVariableBase)VoiceLineFrequency).Initialize((NetworkBehaviour)(object)this); ((NetworkBehaviour)this).__nameNetworkVariable((NetworkVariableBase)(object)VoiceLineFrequency, "VoiceLineFrequency"); base.NetworkVariableFields.Add((NetworkVariableBase)(object)VoiceLineFrequency); ((NetworkBehaviour)this).__initializeVariables(); } protected internal override string __getTypeName() { return "SkinwalkerNetworkManager"; } }
plugins/TVLoader.dll
Decompiled 11 months agousing System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Versioning; using BepInEx; using BepInEx.Logging; using HarmonyLib; using TVLoader.Utils; using UnityEngine; using UnityEngine.Video; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: AssemblyTitle("TVLoader")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("TVLoader")] [assembly: AssemblyCopyright("Copyright © 2023")] [assembly: AssemblyTrademark("")] [assembly: ComVisible(false)] [assembly: Guid("e59845a7-f2f7-4416-9a61-ca1939ce6e2d")] [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 TVLoader { [BepInPlugin("rattenbonkers.TVLoader", "TVLoader", "1.1.1")] public class TVLoaderPlugin : BaseUnityPlugin { private const string MyGUID = "rattenbonkers.TVLoader"; private const string PluginName = "TVLoader"; private const string VersionString = "1.1.1"; private static readonly Harmony Harmony = new Harmony("rattenbonkers.TVLoader"); public static ManualLogSource Log = new ManualLogSource("TVLoader"); private void Awake() { Log = ((BaseUnityPlugin)this).Logger; Harmony.PatchAll(); VideoManager.Load(); ((BaseUnityPlugin)this).Logger.LogInfo((object)string.Format("PluginName: {0}, VersionString: {1} is loaded. Video Count: {2}", "TVLoader", "1.1.1", VideoManager.Videos.Count)); } } } namespace TVLoader.Utils { internal static class VideoManager { public static List<string> Videos = new List<string>(); public static void Load() { string[] directories = Directory.GetDirectories(Paths.PluginPath); foreach (string text in directories) { string path = Path.Combine(Paths.PluginPath, text, "Television Videos"); if (Directory.Exists(path)) { string[] files = Directory.GetFiles(path, "*.mp4"); Videos.AddRange(files); TVLoaderPlugin.Log.LogInfo((object)$"{text} has {files.Length} videos."); } } string path2 = Path.Combine(Paths.PluginPath, "Television Videos"); if (!Directory.Exists(path2)) { Directory.CreateDirectory(path2); } string[] files2 = Directory.GetFiles(path2, "*.mp4"); Videos.AddRange(files2); TVLoaderPlugin.Log.LogInfo((object)$"Global has {files2.Length} videos."); TVLoaderPlugin.Log.LogInfo((object)$"Loaded {Videos.Count} total."); } } } namespace TVLoader.Patches { [HarmonyPatch(typeof(TVScript))] internal class TVScriptPatches { [Serializable] [CompilerGenerated] private sealed class <>c { public static readonly <>c <>9 = new <>c(); public static EventHandler <>9__13_0; internal void <PrepareVideo>b__13_0(VideoPlayer source) { TVLoaderPlugin.Log.LogInfo((object)"Prepared next video!"); } } private static FieldInfo currentClipProperty = typeof(TVScript).GetField("currentClip", BindingFlags.Instance | BindingFlags.NonPublic); private static FieldInfo currentTimeProperty = typeof(TVScript).GetField("currentClipTime", BindingFlags.Instance | BindingFlags.NonPublic); private static FieldInfo wasTvOnLastFrameProp = typeof(TVScript).GetField("wasTvOnLastFrame", BindingFlags.Instance | BindingFlags.NonPublic); private static FieldInfo timeSinceTurningOffTVProp = typeof(TVScript).GetField("timeSinceTurningOffTV", BindingFlags.Instance | BindingFlags.NonPublic); private static MethodInfo setMatMethod = typeof(TVScript).GetMethod("SetTVScreenMaterial", BindingFlags.Instance | BindingFlags.NonPublic); private static MethodInfo onEnableMethod = typeof(TVScript).GetMethod("OnEnable", BindingFlags.Instance | BindingFlags.NonPublic); private static bool tvHasPlayedBefore = false; private static RenderTexture renderTexture; private static VideoPlayer currentVideoPlayer; private static VideoPlayer nextVideoPlayer; [HarmonyPrefix] [HarmonyPatch("Update")] public static bool Update(TVScript __instance) { if ((Object)(object)currentVideoPlayer == (Object)null) { currentVideoPlayer = ((Component)__instance).GetComponent<VideoPlayer>(); renderTexture = currentVideoPlayer.targetTexture; if (VideoManager.Videos.Count > 0) { PrepareVideo(__instance, 0); } } return false; } [HarmonyPrefix] [HarmonyPatch("TurnTVOnOff")] public static bool TurnTVOnOff(TVScript __instance, bool on) { TVLoaderPlugin.Log.LogInfo((object)$"TVOnOff: {on}"); if (VideoManager.Videos.Count == 0) { return false; } int num = (int)currentClipProperty.GetValue(__instance); if (on && tvHasPlayedBefore) { num = (num + 1) % VideoManager.Videos.Count; currentClipProperty.SetValue(__instance, num); } __instance.tvOn = on; if (on) { PlayVideo(__instance); __instance.tvSFX.PlayOneShot(__instance.switchTVOn); WalkieTalkie.TransmitOneShotAudio(__instance.tvSFX, __instance.switchTVOn, 1f); } else { __instance.video.Stop(); __instance.tvSFX.PlayOneShot(__instance.switchTVOff); WalkieTalkie.TransmitOneShotAudio(__instance.tvSFX, __instance.switchTVOff, 1f); } setMatMethod.Invoke(__instance, new object[1] { on }); return false; } [HarmonyPrefix] [HarmonyPatch("TVFinishedClip")] public static bool TVFinishedClip(TVScript __instance, VideoPlayer source) { if (!__instance.tvOn || GameNetworkManager.Instance.localPlayerController.isInsideFactory) { return false; } TVLoaderPlugin.Log.LogInfo((object)"TVFinishedClip"); int num = (int)currentClipProperty.GetValue(__instance); if (VideoManager.Videos.Count > 0) { num = (num + 1) % VideoManager.Videos.Count; } currentTimeProperty.SetValue(__instance, 0f); currentClipProperty.SetValue(__instance, num); PlayVideo(__instance); return false; } private static void PrepareVideo(TVScript instance, int index = -1) { //IL_00e5: Unknown result type (might be due to invalid IL or missing references) //IL_00ea: Unknown result type (might be due to invalid IL or missing references) //IL_00f0: Expected O, but got Unknown if (index == -1) { index = (int)currentClipProperty.GetValue(instance) + 1; } if ((Object)(object)nextVideoPlayer != (Object)null && ((Component)nextVideoPlayer).gameObject.activeInHierarchy) { Object.Destroy((Object)(object)nextVideoPlayer); } nextVideoPlayer = ((Component)instance).gameObject.AddComponent<VideoPlayer>(); nextVideoPlayer.playOnAwake = false; nextVideoPlayer.isLooping = false; nextVideoPlayer.source = (VideoSource)1; nextVideoPlayer.controlledAudioTrackCount = 1; nextVideoPlayer.audioOutputMode = (VideoAudioOutputMode)1; nextVideoPlayer.SetTargetAudioSource((ushort)0, instance.tvSFX); nextVideoPlayer.url = "file://" + VideoManager.Videos[index % VideoManager.Videos.Count]; nextVideoPlayer.Prepare(); VideoPlayer obj = nextVideoPlayer; object obj2 = <>c.<>9__13_0; if (obj2 == null) { EventHandler val = delegate { TVLoaderPlugin.Log.LogInfo((object)"Prepared next video!"); }; <>c.<>9__13_0 = val; obj2 = (object)val; } obj.prepareCompleted += (EventHandler)obj2; } private static void PlayVideo(TVScript instance) { tvHasPlayedBefore = true; if (VideoManager.Videos.Count != 0) { if ((Object)(object)nextVideoPlayer != (Object)null) { VideoPlayer val = currentVideoPlayer; instance.video = (currentVideoPlayer = nextVideoPlayer); nextVideoPlayer = null; TVLoaderPlugin.Log.LogInfo((object)$"Destroy {val}"); Object.Destroy((Object)(object)val); onEnableMethod.Invoke(instance, new object[0]); } currentTimeProperty.SetValue(instance, 0f); instance.video.targetTexture = renderTexture; instance.video.Play(); PrepareVideo(instance); } } } }
plugins/Walkie.dll
Decompiled 11 months agousing System; using System.Diagnostics; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using System.Security; using System.Security.Permissions; using BepInEx; using BepInEx.Logging; using GameNetcodeStuff; using HarmonyLib; using LethalCompanyInputUtils.Api; using Microsoft.CodeAnalysis; 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: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")] [assembly: AssemblyCompany("Walkie")] [assembly: AssemblyConfiguration("Debug")] [assembly: AssemblyDescription("My first plugin")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: AssemblyInformationalVersion("1.0.0+1140cd6824cd255f22105cd5a33a31e275fa9407")] [assembly: AssemblyProduct("Walkie")] [assembly: AssemblyTitle("Walkie")] [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 Walkie { public class WalkieButton : LcInputActions { [InputAction("<Keyboard>/r", Name = "Walkie")] public InputAction WalkieKey { get; set; } } [BepInPlugin("rr.Walkie", "WalkieUse", "1.4.0")] [HarmonyPatch(typeof(PlayerControllerB))] public class WalkieToggle : BaseUnityPlugin { private static string path = Application.persistentDataPath + "/walkiebutton.txt"; internal static ManualLogSource logSource; internal static WalkieButton InputActionInstance = new WalkieButton(); private Harmony _harmony = new Harmony("Walkie"); private void Awake() { _harmony.PatchAll(typeof(WalkieToggle)); ((BaseUnityPlugin)this).Logger.LogInfo((object)"------Walkie done.------"); logSource = ((BaseUnityPlugin)this).Logger; } [HarmonyPatch(typeof(PlayerControllerB), "Update")] [HarmonyPostfix] public static void ReadInput(PlayerControllerB __instance) { GrabbableObject val = null; if (((!((NetworkBehaviour)__instance).IsOwner || !__instance.isPlayerControlled || (((NetworkBehaviour)__instance).IsServer && !__instance.isHostPlayerObject)) && !__instance.isTestingPlayer) || __instance.inTerminalMenu || __instance.isTypingChat || ShipBuildModeManager.Instance.InBuildMode || !Application.isFocused) { return; } for (int i = 0; i < __instance.ItemSlots.Length; i++) { if (__instance.ItemSlots[i] is WalkieTalkie && __instance.ItemSlots[i].isBeingUsed) { val = __instance.ItemSlots[i]; break; } } if ((Object)(object)val == (Object)null) { return; } if (InputActionInstance.WalkieKey.WasPressedThisFrame()) { try { if (__instance.currentlyHeldObjectServer is WalkieTalkie) { __instance.currentlyHeldObjectServer.UseItemOnClient(true); } else if ((Object)(object)val != (Object)null) { val.UseItemOnClient(true); } } catch { } } if (!InputActionInstance.WalkieKey.WasReleasedThisFrame()) { return; } try { if (__instance.currentlyHeldObjectServer is WalkieTalkie) { __instance.currentlyHeldObjectServer.UseItemOnClient(false); } else if ((Object)(object)val != (Object)null) { val.UseItemOnClient(false); } } catch { } } } public static class PluginInfo { public const string PLUGIN_GUID = "Walkie"; public const string PLUGIN_NAME = "Walkie"; public const string PLUGIN_VERSION = "1.0.0"; } }