Decompiled source of REPO REMASTERED v1.0.1
plugins/BobisMods-LargePupils/LargePupils.dll
Decompiled 2 months agousing System.Collections.Generic; using System.Diagnostics; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Versioning; using BepInEx; using HarmonyLib; 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("LargePupils")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("HP")] [assembly: AssemblyProduct("LargePupils")] [assembly: AssemblyCopyright("Copyright © HP 2025")] [assembly: AssemblyTrademark("")] [assembly: ComVisible(false)] [assembly: Guid("9c065692-8a25-40c1-b906-72c5ac397789")] [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 LargePupils; [BepInPlugin("bobismods.largepupils.mod", "LargePupils", "1.0.1")] public class LargePupils : BaseUnityPlugin { public const string plugin_GUID = "bobismods.largepupils.mod"; public const string plugin_name = "LargePupils"; public const string plugin_version = "1.0.1"; private readonly Harmony harmony = new Harmony("bobismods.largepupils.mod"); public static LargePupils Instance; private void Awake() { if ((Object)(object)Instance == (Object)null) { Instance = this; } harmony.PatchAll(typeof(LargePupils)); harmony.PatchAll(typeof(LargePupilsPatch)); } } [HarmonyPatch(typeof(TruckScreenText))] internal class LargePupilsPatch { [HarmonyPatch("ArrowPointAtGoalLogic")] [HarmonyPostfix] private static void PrefixMethod() { List<PlayerAvatar> list = SemiFunc.PlayerGetAll(); foreach (PlayerAvatar item in list) { AccessTools.Field(typeof(PlayerEyes), "pupilSizeMultiplier").SetValue(item.playerAvatarVisuals.playerEyes, 2f); } } }
plugins/Bocon-CartDuplicator/CartDuplicator.dll
Decompiled 2 months agousing System; using 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 CartDuplicator.Patches; using HarmonyLib; using Photon.Pun; 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("CartDuplicator")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("CartDuplicator")] [assembly: AssemblyCopyright("Copyright © 2025")] [assembly: AssemblyTrademark("")] [assembly: ComVisible(false)] [assembly: Guid("c3dd3bd7-b7d1-4490-ad3d-0422f13bcbfd")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: TargetFramework(".NETFramework,Version=v4.8.1", FrameworkDisplayName = ".NET Framework 4.8.1")] [assembly: AssemblyVersion("1.0.0.0")] namespace CartDuplicator { [BepInPlugin("Bocon.CartDuplicator", "Cart Duplicator", "1.3.0")] public class CartDuplicator : BaseUnityPlugin { private const string modGUID = "Bocon.CartDuplicator"; private const string modeName = "Cart Duplicator"; private const string modVersion = "1.3.0"; private readonly Harmony harmony = new Harmony("Bocon.CartDuplicator"); private static CartDuplicator Instance; internal ManualLogSource mls; private ConfigEntry<Vector3> duplicationOffset; private ConfigEntry<int> duplicationAmount; private ConfigEntry<bool> smallCartReplacement; private void Awake() { //IL_0048: 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_008a: Expected O, but got Unknown if ((Object)(object)Instance == (Object)null) { Instance = this; } mls = Logger.CreateLogSource("Bocon.CartDuplicator"); duplicationOffset = ((BaseUnityPlugin)this).Config.Bind<Vector3>("General", "DuplicationOffset", new Vector3(2f, 0f, 0f), "Offset for the duplicated cart position"); duplicationAmount = ((BaseUnityPlugin)this).Config.Bind<int>("General", "DuplicationAmount", 1, new ConfigDescription("Number of additional carts to duplicate", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 10), Array.Empty<object>())); smallCartReplacement = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "SmallCartReplacement", false, "Replace the duplicated carts with the pocket C.A.R.T."); mls.LogInfo((object)"Cart Duplicator Mod Loaded"); harmony.PatchAll(typeof(CartDuplicator)); harmony.PatchAll(typeof(DuplicateCartPatch)); } public static Vector3 GetDuplicationOffset() { //IL_000a: Unknown result type (might be due to invalid IL or missing references) return Instance.duplicationOffset.Value; } public static int GetDuplicationAmount() { return Instance.duplicationAmount.Value; } public static bool GetSmallCartReplacement() { return Instance.smallCartReplacement.Value; } } } namespace CartDuplicator.Patches { [HarmonyPatch(typeof(PunManager))] [HarmonyPatch("SpawnItem")] public class DuplicateCartPatch : MonoBehaviourPunCallbacks { [HarmonyPostfix] public static void After_SpawnItem(Item item, ItemVolume volume) { //IL_003e: 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_008b: 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) //IL_009b: Unknown result type (might be due to invalid IL or missing references) //IL_00a1: Unknown result type (might be due to invalid IL or missing references) //IL_00fb: 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_0106: Unknown result type (might be due to invalid IL or missing references) //IL_010b: 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) if ((Object)(object)item == (Object)null || (Object)(object)volume == (Object)null || item.itemAssetName != "Item Cart Medium") { return; } int duplicationAmount = CartDuplicator.GetDuplicationAmount(); Vector3 duplicationOffset = CartDuplicator.GetDuplicationOffset(); string text = (CartDuplicator.GetSmallCartReplacement() ? "Item Cart Small" : ((Object)item.prefab).name); if (PhotonNetwork.IsConnected && PhotonNetwork.IsMasterClient) { for (int i = 0; i < duplicationAmount; i++) { PhotonNetwork.InstantiateRoomObject("Items/" + text, ((Component)volume).transform.position + duplicationOffset * (float)(i + 1), item.spawnRotationOffset, (byte)0, (object[])null); } } else if (!PhotonNetwork.IsConnected) { GameObject val = (CartDuplicator.GetSmallCartReplacement() ? Resources.Load<GameObject>("Items/Item Cart Small") : item.prefab); for (int j = 0; j < duplicationAmount; j++) { Object.Instantiate<GameObject>(val, ((Component)volume).transform.position + duplicationOffset * (float)(j + 1), item.spawnRotationOffset); } } } } }
plugins/Bocon-StatManager/StatManager.dll
Decompiled 2 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 BepInEx.Logging; using HarmonyLib; 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("StatManager")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("StatManager")] [assembly: AssemblyCopyright("Copyright © 2025")] [assembly: AssemblyTrademark("")] [assembly: ComVisible(false)] [assembly: Guid("179e1f3b-e093-4adf-9132-f04de1bfb69d")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: TargetFramework(".NETFramework,Version=v4.8.1", FrameworkDisplayName = ".NET Framework 4.8.1")] [assembly: AssemblyVersion("1.0.0.0")] namespace StatManager { [BepInPlugin("Bocon.StatManager", "Stat Manager", "1.0.0")] public class StatManager : BaseUnityPlugin { private const string modGUID = "Bocon.StatManager"; private const string modeName = "Stat Manager"; private const string modVersion = "1.0.0"; private const string ASCII_LOGO = "\n _____ _ _ __ __ \n / ____| | | | | \\/ | \n | (___ | |_ __ _| |_ | \\ / | __ _ _ __ __ _ __ _ ___ _ __ \n \\___ \\| __/ _` | __| | |\\/| |/ _` | '_ \\ / _` |/ _` |/ _ \\ '__|\n ____) | || (_| | |_ | | | | (_| | | | | (_| | (_| | __/ | \n |_____/ \\__\\__,_|\\__| |_| |_|\\__,_|_| |_|\\__,_|\\__, |\\___|_| \n __/ | \n |___/ \n"; private readonly Harmony harmony = new Harmony("Bocon.StatManager"); private static StatManager Instance; internal ManualLogSource mls; internal static ConfigEntry<int> HealthBonus; internal static ConfigEntry<int> SpeedBonus; internal static ConfigEntry<int> MapCountBonus; internal static ConfigEntry<int> EnergyBonus; internal static ConfigEntry<int> ExtraJumpBonus; internal static ConfigEntry<int> GrabRangeBonus; internal static ConfigEntry<int> GrabStrengthBonus; internal static ConfigEntry<int> GrabThrowBonus; internal static ConfigEntry<int> TumbleLaunchBonus; private void Awake() { if ((Object)(object)Instance == (Object)null) { Instance = this; } mls = Logger.CreateLogSource("Bocon.StatManager"); mls.LogInfo((object)"\n _____ _ _ __ __ \n / ____| | | | | \\/ | \n | (___ | |_ __ _| |_ | \\ / | __ _ _ __ __ _ __ _ ___ _ __ \n \\___ \\| __/ _` | __| | |\\/| |/ _` | '_ \\ / _` |/ _` |/ _ \\ '__|\n ____) | || (_| | |_ | | | | (_| | | | | (_| | (_| | __/ | \n |_____/ \\__\\__,_|\\__| |_| |_|\\__,_|_| |_|\\__,_|\\__, |\\___|_| \n __/ | \n |___/ \n"); HealthBonus = ((BaseUnityPlugin)this).Config.Bind<int>("Stats", "Health", 10, "Amount of Health upgrades."); SpeedBonus = ((BaseUnityPlugin)this).Config.Bind<int>("Stats", "Sprint Speed", 5, "Amount of Sprint Speed upgrades."); MapCountBonus = ((BaseUnityPlugin)this).Config.Bind<int>("Stats", "Player Map Count", 1, "Amount of Player Map Count upgrades."); EnergyBonus = ((BaseUnityPlugin)this).Config.Bind<int>("Stats", "Energy", 10, "Amount of Energy upgrades."); ExtraJumpBonus = ((BaseUnityPlugin)this).Config.Bind<int>("Stats", "Extra Jump", 1, "Amount of Extra Jump upgrades."); GrabRangeBonus = ((BaseUnityPlugin)this).Config.Bind<int>("Stats", "Grab Range", 5, "Amount of Grab Range upgrades."); GrabStrengthBonus = ((BaseUnityPlugin)this).Config.Bind<int>("Stats", "Grab Strength", 5, "Amount of Grab Strength upgrades."); GrabThrowBonus = ((BaseUnityPlugin)this).Config.Bind<int>("Stats", "Grab Throw", 5, "Amount of Grab Throw upgrades."); TumbleLaunchBonus = ((BaseUnityPlugin)this).Config.Bind<int>("Stats", "Tumble Launch", 5, "Amount of Tumble Launch upgrades."); harmony.PatchAll(); } } } namespace StatManager.Patches { internal class Patch { [HarmonyPatch(typeof(GameDirector), "Start")] private class GameDirectorPatch { private static void Postfix() { Object.FindObjectOfType<MonoBehaviour>().StartCoroutine(WaitForLevel()); } } [HarmonyPatch(typeof(RunManager), "ResetProgress")] private class RunManagerResetPatch { private static void Postfix() { hasAppliedUpgrade = false; } } [CompilerGenerated] private sealed class <WaitForLevel>d__2 : IEnumerator<object>, IDisposable, IEnumerator { private int <>1__state; private object <>2__current; private List<PlayerAvatar>.Enumerator <>s__1; private PlayerAvatar <player>5__2; private int <i>5__3; private int <i>5__4; private int <i>5__5; private int <i>5__6; private int <i>5__7; private int <i>5__8; private int <i>5__9; private int <i>5__10; private int <i>5__11; object IEnumerator<object>.Current { [DebuggerHidden] get { return <>2__current; } } object IEnumerator.Current { [DebuggerHidden] get { return <>2__current; } } [DebuggerHidden] public <WaitForLevel>d__2(int <>1__state) { this.<>1__state = <>1__state; } [DebuggerHidden] void IDisposable.Dispose() { <>s__1 = default(List<PlayerAvatar>.Enumerator); <player>5__2 = null; <>1__state = -2; } private bool MoveNext() { //IL_0029: Unknown result type (might be due to invalid IL or missing references) //IL_0033: Expected O, but got Unknown switch (<>1__state) { default: return false; case 0: <>1__state = -1; break; case 1: <>1__state = -1; break; } if (!SemiFunc.LevelGenDone()) { <>2__current = (object)new WaitForSeconds(0.5f); <>1__state = 1; return true; } if (!hasAppliedUpgrade && SemiFunc.RunIsLevel()) { <>s__1 = SemiFunc.PlayerGetAll().GetEnumerator(); try { while (<>s__1.MoveNext()) { <player>5__2 = <>s__1.Current; <i>5__3 = 0; while (<i>5__3 < StatManager.HealthBonus.Value) { PunManager.instance.UpgradePlayerHealth(SemiFunc.PlayerGetSteamID(<player>5__2)); <i>5__3++; } <i>5__4 = 0; while (<i>5__4 < StatManager.SpeedBonus.Value) { PunManager.instance.UpgradePlayerSprintSpeed(SemiFunc.PlayerGetSteamID(<player>5__2)); <i>5__4++; } <i>5__5 = 0; while (<i>5__5 < StatManager.MapCountBonus.Value) { PunManager.instance.UpgradeMapPlayerCount(SemiFunc.PlayerGetSteamID(<player>5__2)); <i>5__5++; } <i>5__6 = 0; while (<i>5__6 < StatManager.EnergyBonus.Value) { PunManager.instance.UpgradePlayerEnergy(SemiFunc.PlayerGetSteamID(<player>5__2)); <i>5__6++; } <i>5__7 = 0; while (<i>5__7 < StatManager.ExtraJumpBonus.Value) { PunManager.instance.UpgradePlayerExtraJump(SemiFunc.PlayerGetSteamID(<player>5__2)); <i>5__7++; } <i>5__8 = 0; while (<i>5__8 < StatManager.GrabRangeBonus.Value) { PunManager.instance.UpgradePlayerGrabRange(SemiFunc.PlayerGetSteamID(<player>5__2)); <i>5__8++; } <i>5__9 = 0; while (<i>5__9 < StatManager.GrabStrengthBonus.Value) { PunManager.instance.UpgradePlayerGrabStrength(SemiFunc.PlayerGetSteamID(<player>5__2)); <i>5__9++; } <i>5__10 = 0; while (<i>5__10 < StatManager.GrabThrowBonus.Value) { PunManager.instance.UpgradePlayerThrowStrength(SemiFunc.PlayerGetSteamID(<player>5__2)); <i>5__10++; } <i>5__11 = 0; while (<i>5__11 < StatManager.TumbleLaunchBonus.Value) { PunManager.instance.UpgradePlayerTumbleLaunch(SemiFunc.PlayerGetSteamID(<player>5__2)); <i>5__11++; } <player>5__2 = null; } } finally { ((IDisposable)<>s__1).Dispose(); } <>s__1 = default(List<PlayerAvatar>.Enumerator); hasAppliedUpgrade = true; } return false; } bool IEnumerator.MoveNext() { //ILSpy generated this explicit interface implementation from .override directive in MoveNext return this.MoveNext(); } [DebuggerHidden] void IEnumerator.Reset() { throw new NotSupportedException(); } } private static bool hasAppliedUpgrade; [IteratorStateMachine(typeof(<WaitForLevel>d__2))] private static IEnumerator WaitForLevel() { //yield-return decompiler failed: Unexpected instruction in Iterator.Dispose() return new <WaitForLevel>d__2(0); } } }
plugins/BULLETBOT-MoreUpgrades/MoreUpgrades.dll
Decompiled 2 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.Linq; using System.Reflection; using System.Reflection.Emit; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Versioning; using BepInEx; using BepInEx.Bootstrap; using BepInEx.Configuration; using BepInEx.Logging; using CustomColors; using HarmonyLib; using MoreUpgrades.Classes; using MoreUpgrades.Properties; using Photon.Pun; using REPOLib.Modules; using TMPro; using UnityEngine; using UnityEngine.Events; 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("ShrinkItemsInCart")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("ShrinkItemsInCart")] [assembly: AssemblyCopyright("Copyright © 2024")] [assembly: AssemblyTrademark("")] [assembly: ComVisible(false)] [assembly: Guid("5e12a72d-c200-488d-940a-653d1003d96e")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")] [assembly: AssemblyVersion("1.0.0.0")] namespace MoreUpgrades { [BepInDependency(/*Could not decode attribute arguments.*/)] [BepInDependency(/*Could not decode attribute arguments.*/)] [BepInPlugin("bulletbot.moreupgrades", "MoreUpgrades", "1.1.8")] internal class Plugin : BaseUnityPlugin { internal static class CustomColors { internal const string modGUID = "x753.CustomColors"; internal static bool IsLoaded() { return Chainloader.PluginInfos.ContainsKey("x753.CustomColors"); } internal static void OnAwake() { instance.PatchAll("MoreUpgrades.CustomColorsPatches"); } } private const string modGUID = "bulletbot.moreupgrades"; private const string modName = "MoreUpgrades"; private const string modVer = "1.1.8"; internal static Plugin instance; internal ManualLogSource logger; private readonly Harmony harmony = new Harmony("bulletbot.moreupgrades"); internal AssetBundle assetBundle; internal List<UpgradeItem> upgradeItems; private void PatchAll(string _namespace) { foreach (Type item in from t in Assembly.GetExecutingAssembly().GetTypes() where t.Namespace == _namespace select t) { harmony.PatchAll(item); } } internal GameObject GetVisualsFromComponent(Component component) { //IL_0041: Unknown result type (might be due to invalid IL or missing references) //IL_0047: Expected O, but got Unknown GameObject val = null; if (((object)component).GetType() == typeof(EnemyParent)) { EnemyParent val2 = (EnemyParent)(object)((component is EnemyParent) ? component : null); Enemy val3 = (Enemy)AccessTools.Field(typeof(EnemyParent), "Enemy").GetValue(component); try { val = ((Component)val2.EnableObject.gameObject.GetComponentInChildren<Animator>()).gameObject; } catch { } if ((Object)(object)val == (Object)null) { try { val = ((Component)((Component)val3).GetComponent<EnemyVision>().VisionTransform).gameObject; } catch { } } if ((Object)(object)val == (Object)null) { val = ((Component)val3).gameObject; } } else if (((object)component).GetType() == typeof(PlayerAvatar)) { PlayerAvatar val4 = (PlayerAvatar)(object)((component is PlayerAvatar) ? component : null); val = ((Component)val4.playerAvatarVisuals).gameObject; } return val; } internal void AddEnemyToMap(Component component, string enemyName = null) { //IL_0153: Unknown result type (might be due to invalid IL or missing references) UpgradeItem upgradeItem = upgradeItems.FirstOrDefault((UpgradeItem x) => x.name == "Map Enemy Tracker"); if (upgradeItem == null) { return; } EnemyParent val = (EnemyParent)(object)((component is EnemyParent) ? component : null); if (val != null && enemyName == null) { enemyName = val.enemyName; } if ((from x in upgradeItem.GetConfig<string>("Exclude Enemies").Split(new char[1] { ',' }) select x.Trim() into x where !string.IsNullOrEmpty(x) select x).Contains(enemyName)) { return; } GameObject visuals = GetVisualsFromComponent(component); List<(GameObject, Color)> variable = upgradeItem.GetVariable<List<(GameObject, Color)>>("AddToMap"); List<GameObject> variable2 = upgradeItem.GetVariable<List<GameObject>>("RemoveFromMap"); if (!((Object)(object)visuals == (Object)null) && !variable.Any(((GameObject, Color) x) => (Object)(object)x.Item1 == (Object)(object)visuals)) { if (variable2.Contains(visuals)) { variable2.Remove(visuals); } variable.Add((visuals, upgradeItem.GetConfig<Color>("Color"))); } } internal void RemoveEnemyFromMap(Component component, string enemyName = null) { UpgradeItem upgradeItem = upgradeItems.FirstOrDefault((UpgradeItem x) => x.name == "Map Enemy Tracker"); if (upgradeItem == null) { return; } EnemyParent val = (EnemyParent)(object)((component is EnemyParent) ? component : null); if (val != null && enemyName == null) { enemyName = val.enemyName; } if ((from x in upgradeItem.GetConfig<string>("Exclude Enemies").Split(new char[1] { ',' }) select x.Trim() into x where !string.IsNullOrEmpty(x) select x).Contains(enemyName)) { return; } GameObject visuals = GetVisualsFromComponent(component); List<(GameObject, Color)> variable = upgradeItem.GetVariable<List<(GameObject, Color)>>("AddToMap"); List<GameObject> variable2 = upgradeItem.GetVariable<List<GameObject>>("RemoveFromMap"); if ((Object)(object)visuals == (Object)null || variable2.Contains(visuals)) { return; } if (variable.Any(((GameObject, Color) x) => (Object)(object)x.Item1 == (Object)(object)visuals)) { variable.RemoveAll(((GameObject, Color) x) => (Object)(object)x.Item1 == (Object)(object)visuals); } variable2.Add(visuals); } internal void AddPlayerToMap(PlayerAvatar playerAvatar) { //IL_00b6: 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_00fb: 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_00f2: Unknown result type (might be due to invalid IL or missing references) UpgradeItem upgradeItem = upgradeItems.FirstOrDefault((UpgradeItem x) => x.name == "Map Player Tracker"); if (upgradeItem == null) { return; } GameObject visuals = GetVisualsFromComponent((Component)(object)playerAvatar); List<(GameObject, Color)> variable = upgradeItem.GetVariable<List<(GameObject, Color)>>("AddToMap"); List<GameObject> variable2 = upgradeItem.GetVariable<List<GameObject>>("RemoveFromMap"); if (!((Object)(object)visuals == (Object)null) && !variable.Any(((GameObject, Color) x) => (Object)(object)x.Item1 == (Object)(object)visuals)) { if (variable2.Contains(visuals)) { variable2.Remove(visuals); } Color item = upgradeItem.GetConfig<Color>("Color"); if (upgradeItem.GetConfig<bool>("Player Color")) { item = (Color)AccessTools.Field(typeof(PlayerAvatar), "color").GetValue(playerAvatar.playerAvatarVisuals); } variable.Add((visuals, item)); } } internal void RemovePlayerToMap(PlayerAvatar playerAvatar) { UpgradeItem upgradeItem = upgradeItems.FirstOrDefault((UpgradeItem x) => x.name == "Map Player Tracker"); if (upgradeItem == null) { return; } GameObject visuals = GetVisualsFromComponent((Component)(object)playerAvatar); List<(GameObject, Color)> variable = upgradeItem.GetVariable<List<(GameObject, Color)>>("AddToMap"); List<GameObject> variable2 = upgradeItem.GetVariable<List<GameObject>>("RemoveFromMap"); if ((Object)(object)visuals == (Object)null || variable2.Contains(visuals)) { return; } if (variable.Any(((GameObject, Color) x) => (Object)(object)x.Item1 == (Object)(object)visuals)) { variable.RemoveAll(((GameObject, Color) x) => (Object)(object)x.Item1 == (Object)(object)visuals); } variable2.Add(visuals); } private void Awake() { //IL_01b5: Unknown result type (might be due to invalid IL or missing references) //IL_0299: Unknown result type (might be due to invalid IL or missing references) instance = this; logger = Logger.CreateLogSource("MoreUpgrades"); assetBundle = AssetBundle.LoadFromMemory(Resources.moreupgrades); if ((Object)(object)assetBundle == (Object)null) { logger.LogError((object)"Something went wrong when loading the asset bundle."); return; } upgradeItems = new List<UpgradeItem>(); UpgradeItem sprintUsage = new UpgradeItem("Sprint Usage", 5, 2, 3000f, 4500f); sprintUsage.AddConfig("Scaling Factor", 0.15f, "Formula: energySprintDrain / (1 + (upgradeAmount * scalingFactor))"); UpgradeItem upgradeItem2 = sprintUsage; upgradeItem2.onFixedUpdate = (Action)Delegate.Combine(upgradeItem2.onFixedUpdate, (Action)delegate { int amount = sprintUsage.GetAmount(); if ((Object)(object)PlayerController.instance != (Object)null && amount != 0) { if (!sprintUsage.HasVariable("OriginalEnergySprintDrain")) { sprintUsage.AddVariable("OriginalEnergySprintDrain", PlayerController.instance.EnergySprintDrain); } float variable8 = sprintUsage.GetVariable<float>("OriginalEnergySprintDrain"); PlayerController.instance.EnergySprintDrain = variable8 / (1f + (float)amount * sprintUsage.GetConfig<float>("Scaling Factor")); } }); upgradeItems.Add(sprintUsage); UpgradeItem valuableCount = new UpgradeItem("Valuable Count", 1, 1, 5000f, 6000f, 1); valuableCount.AddConfig("Display Total Value", defaultValue: true, "Whether to display the total value next to the valuable counter."); UpgradeItem upgradeItem3 = valuableCount; upgradeItem3.onInit = (Action)Delegate.Combine(upgradeItem3.onInit, (Action)delegate { valuableCount.AddVariable("CurrentValuables", new List<ValuableObject>()); valuableCount.AddVariable("Changed", value: false); valuableCount.AddVariable("PreviousCount", 0); valuableCount.AddVariable("PreviousValue", 0); valuableCount.AddVariable("TextLength", 0); }); UpgradeItem upgradeItem4 = valuableCount; upgradeItem4.onUpdate = (Action)Delegate.Combine(upgradeItem4.onUpdate, (Action)delegate { //IL_005e: Unknown result type (might be due to invalid IL or missing references) //IL_0064: Expected O, but got Unknown if (!SemiFunc.RunIsLobby() && !SemiFunc.RunIsShop() && (Object)(object)MissionUI.instance != (Object)null && valuableCount.GetAmount() != 0) { TextMeshProUGUI val4 = (TextMeshProUGUI)AccessTools.Field(typeof(MissionUI), "Text").GetValue(MissionUI.instance); string text = (string)AccessTools.Field(typeof(MissionUI), "messagePrev").GetValue(MissionUI.instance); List<ValuableObject> variable3 = valuableCount.GetVariable<List<ValuableObject>>("CurrentValuables"); bool variable4 = valuableCount.GetVariable<bool>("Changed"); int variable5 = valuableCount.GetVariable<int>("PreviousCount"); int variable6 = valuableCount.GetVariable<int>("PreviousValue"); int variable7 = valuableCount.GetVariable<int>("TextLength"); int count = variable3.Count; bool config = valuableCount.GetConfig<bool>("Display Total Value"); int num3 = (config ? variable3.Select((ValuableObject x) => (int)x.dollarValueCurrent).Sum() : 0); if (!Utility.IsNullOrWhiteSpace(((TMP_Text)val4).text) && (variable4 || variable5 != count || variable6 != num3)) { string text2 = ((TMP_Text)val4).text; if (!variable4 && (variable5 != count || variable6 != num3)) { text2 = text2.Substring(0, text2.Length - variable7); } string text3 = $"\nValuables: <b>{count}</b>" + (config ? (" (<color=#558B2F>$</color><b>" + SemiFunc.DollarGetString(num3) + "</b>)") : ""); text2 += text3; valuableCount.SetVariable("PreviousCount", count); valuableCount.SetVariable("PreviousValue", num3); valuableCount.SetVariable("TextLength", text3.Length); ((TMP_Text)val4).text = text2; AccessTools.Field(typeof(MissionUI), "messagePrev").SetValue(MissionUI.instance, text2); if (variable4) { valuableCount.SetVariable("Changed", value: false); } } } }); upgradeItems.Add(valuableCount); UpgradeItem mapEnemyTracker = new UpgradeItem("Map Enemy Tracker", 1, 1, 6000f, 7000f, 1); mapEnemyTracker.AddConfig("Arrow Icon", defaultValue: true, "Whether the icon should appear as an arrow showing direction instead of a dot."); mapEnemyTracker.AddConfig<Color>("Color", Color.red, "The color of the icon."); mapEnemyTracker.AddConfig("Exclude Enemies", "", "Exclude specific enemies from displaying their icon by listing their names.\nExample: 'Gnome, Clown', seperated by commas."); UpgradeItem upgradeItem5 = mapEnemyTracker; upgradeItem5.onInit = (Action)Delegate.Combine(upgradeItem5.onInit, (Action)delegate { mapEnemyTracker.AddVariable("AddToMap", new List<(GameObject, Color)>()); mapEnemyTracker.AddVariable("RemoveFromMap", new List<GameObject>()); }); UpgradeItem upgradeItem6 = mapEnemyTracker; upgradeItem6.onUpdate = (Action)Delegate.Combine(upgradeItem6.onUpdate, (Action)delegate { UpdateTracker(mapEnemyTracker); }); upgradeItems.Add(mapEnemyTracker); UpgradeItem mapPlayerTracker = new UpgradeItem("Map Player Tracker", 1, 1, 9500f, 11000f, 1); mapPlayerTracker.AddConfig("Arrow Icon", defaultValue: true, "Whether the icon should appear as an arrow showing direction instead of a dot."); mapPlayerTracker.AddConfig("Player Color", defaultValue: false, "Whether the icon should be colored as the player."); mapPlayerTracker.AddConfig<Color>("Color", Color.blue, "The color of the icon."); UpgradeItem upgradeItem7 = mapPlayerTracker; upgradeItem7.onInit = (Action)Delegate.Combine(upgradeItem7.onInit, (Action)delegate { mapPlayerTracker.AddVariable("AddToMap", new List<(GameObject, Color)>()); mapPlayerTracker.AddVariable("RemoveFromMap", new List<GameObject>()); }); UpgradeItem upgradeItem8 = mapPlayerTracker; upgradeItem8.onUpdate = (Action)Delegate.Combine(upgradeItem8.onUpdate, (Action)delegate { UpdateTracker(mapPlayerTracker); }); upgradeItems.Add(mapPlayerTracker); SceneManager.activeSceneChanged += delegate { //IL_004b: Unknown result type (might be due to invalid IL or missing references) //IL_0051: Expected O, but got Unknown if (!((Object)(object)RunManager.instance == (Object)null) && !((Object)(object)RunManager.instance.levelCurrent == (Object)(object)RunManager.instance.levelMainMenu) && !((Object)(object)RunManager.instance.levelCurrent == (Object)(object)RunManager.instance.levelLobbyMenu)) { GameObject val3 = new GameObject(); PhotonNetwork.AllocateViewID(val3.AddComponent<PhotonView>()); val3.AddComponent<MoreUpgradesManager>(); ((Object)val3).name = "More Upgrades Manager"; } }; logger.LogMessage((object)"MoreUpgrades has started."); PatchAll("MoreUpgrades.Patches"); if (CustomColors.IsLoaded()) { CustomColors.OnAwake(); } void UpdateTracker(UpgradeItem upgradeItem) { //IL_0067: Unknown result type (might be due to invalid IL or missing references) //IL_006c: Unknown result type (might be due to invalid IL or missing references) //IL_009b: 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) if (!SemiFunc.RunIsLobby() && !SemiFunc.RunIsShop() && (Object)(object)SemiFunc.PlayerAvatarLocal() != (Object)null && upgradeItem.GetAmount() != 0) { List<(GameObject, Color)> variable = upgradeItem.GetVariable<List<(GameObject, Color)>>("AddToMap"); for (int num = variable.Count - 1; num >= 0; num--) { var (val, color) = variable[num]; variable.RemoveAt(num); MapCustom component = val.GetComponent<MapCustom>(); if (!((Object)(object)component != (Object)null)) { component = val.AddComponent<MapCustom>(); component.color = color; component.sprite = (upgradeItem.GetConfig<bool>("Arrow Icon") ? assetBundle.LoadAsset<Sprite>("Map Tracker") : SemiFunc.PlayerAvatarLocal().playerDeathHead.mapCustom.sprite); } } List<GameObject> variable2 = upgradeItem.GetVariable<List<GameObject>>("RemoveFromMap"); for (int num2 = variable2.Count - 1; num2 >= 0; num2--) { GameObject val2 = variable2[num2]; variable2.RemoveAt(num2); MapCustom component2 = val2.GetComponent<MapCustom>(); if (!((Object)(object)component2 == (Object)null)) { Object.Destroy((Object)(object)((Component)component2.mapCustomEntity).gameObject); Object.Destroy((Object)(object)component2); } } } } } } } namespace MoreUpgrades.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("MoreUpgrades.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[] moreupgrades { get { object @object = ResourceManager.GetObject("moreupgrades", resourceCulture); return (byte[])@object; } } internal Resources() { } } } namespace MoreUpgrades.Patches { [HarmonyPatch(typeof(PlayerAvatar))] internal class PlayerAvatarPatch { [HarmonyPatch("LateStart")] [HarmonyPostfix] private static void LateStart(PlayerAvatar __instance) { if (!((Object)(object)MoreUpgradesManager.instance == (Object)null) && !((Object)(object)__instance == (Object)(object)SemiFunc.PlayerAvatarLocal())) { Plugin.instance.AddPlayerToMap(__instance); } } [HarmonyPatch("ReviveRPC")] [HarmonyPostfix] private static void ReviveRPC(PlayerAvatar __instance) { if (!((Object)(object)MoreUpgradesManager.instance == (Object)null) && !((Object)(object)__instance == (Object)(object)SemiFunc.PlayerAvatarLocal())) { Plugin.instance.AddPlayerToMap(__instance); } } [HarmonyPatch("PlayerDeathRPC")] [HarmonyPostfix] private static void PlayerDeathRPC(PlayerAvatar __instance) { if (!((Object)(object)MoreUpgradesManager.instance == (Object)null) && !((Object)(object)__instance == (Object)(object)SemiFunc.PlayerAvatarLocal())) { Plugin.instance.RemovePlayerToMap(__instance); Plugin.instance.RemoveEnemyFromMap((Component)(object)__instance); } } [HarmonyPatch("SetColorRPC")] [HarmonyPostfix] private static void SetColorRPC(PlayerAvatar __instance) { if (!((Object)(object)MoreUpgradesManager.instance == (Object)null) && !((Object)(object)__instance == (Object)(object)SemiFunc.PlayerAvatarLocal())) { UpgradeItem upgradeItem = Plugin.instance.upgradeItems.FirstOrDefault((UpgradeItem x) => x.name == "Map Player Tracker"); if (upgradeItem != null && upgradeItem.GetConfig<bool>("Player Color")) { Plugin.instance.RemovePlayerToMap(__instance); Plugin.instance.AddPlayerToMap(__instance); } } } } [HarmonyPatch(typeof(EnemySlowMouth))] internal class EnemySlowMouthPatch { [HarmonyPatch("UpdateStateRPC")] [HarmonyPostfix] private static void UpdateStateRPC(EnemySlowMouth __instance, Enemy ___enemy) { //IL_002f: Unknown result type (might be due to invalid IL or missing references) //IL_0035: Expected O, but got Unknown //IL_004f: Unknown result type (might be due to invalid IL or missing references) //IL_0055: Expected O, but got Unknown //IL_0056: Unknown result type (might be due to invalid IL or missing references) //IL_005b: 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_005f: Invalid comparison between Unknown and I4 //IL_00a9: Unknown result type (might be due to invalid IL or missing references) //IL_00ac: Invalid comparison between Unknown and I4 if ((Object)(object)MoreUpgradesManager.instance == (Object)null) { return; } PlayerAvatar val = (PlayerAvatar)AccessTools.Field(typeof(EnemySlowMouth), "playerTarget").GetValue(__instance); EnemyParent val2 = (EnemyParent)AccessTools.Field(typeof(Enemy), "EnemyParent").GetValue(___enemy); State currentState = __instance.currentState; if ((int)currentState == 9) { Plugin.instance.RemoveEnemyFromMap((Component)(object)val2); if (!((Object)(object)val == (Object)(object)SemiFunc.PlayerAvatarLocal())) { Plugin.instance.RemovePlayerToMap(val); Plugin.instance.AddEnemyToMap((Component)(object)val, val2.enemyName); } } else if ((int)currentState == 11) { Plugin.instance.AddEnemyToMap((Component)(object)val2); if (!((Object)(object)val == (Object)(object)SemiFunc.PlayerAvatarLocal())) { Plugin.instance.AddPlayerToMap(val); Plugin.instance.RemoveEnemyFromMap((Component)(object)val, val2.enemyName); } } } } [HarmonyPatch(typeof(EnemyParent))] internal class EnemyParentPatch { [HarmonyPatch("SpawnRPC")] [HarmonyPostfix] private static void SpawnRPC(EnemyParent __instance) { if (!((Object)(object)MoreUpgradesManager.instance == (Object)null)) { Plugin.instance.AddEnemyToMap((Component)(object)__instance); } } [HarmonyPatch("DespawnRPC")] [HarmonyPostfix] private static void DespawnRPC(EnemyParent __instance) { if (!((Object)(object)MoreUpgradesManager.instance == (Object)null)) { Plugin.instance.RemoveEnemyFromMap((Component)(object)__instance); } } } [HarmonyPatch(typeof(EnemyHealth))] internal class EnemyHealthPatch { [HarmonyPatch("DeathRPC")] [HarmonyPostfix] private static void DeathRPC(EnemyHealth __instance, Enemy ___enemy) { //IL_0031: Unknown result type (might be due to invalid IL or missing references) //IL_003c: Expected O, but got Unknown if (!((Object)(object)MoreUpgradesManager.instance == (Object)null)) { Plugin.instance.RemoveEnemyFromMap((Component)(EnemyParent)AccessTools.Field(typeof(Enemy), "EnemyParent").GetValue(___enemy)); } } } [HarmonyPatch(typeof(MissionUIPatch))] internal class MissionUIPatch { [HarmonyPatch(typeof(MissionUI), "MissionText")] [HarmonyTranspiler] private static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions) { //IL_0003: 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_0036: Expected O, but got Unknown //IL_0064: Unknown result type (might be due to invalid IL or missing references) //IL_006a: Expected O, but got Unknown return new CodeMatcher(instructions, (ILGenerator)null).MatchForward(false, (CodeMatch[])(object)new CodeMatch[1] { new CodeMatch((OpCode?)OpCodes.Stfld, (object)AccessTools.Field(typeof(MissionUI), "messagePrev"), (string)null) }).Advance(1).Insert((CodeInstruction[])(object)new CodeInstruction[1] { new CodeInstruction(OpCodes.Call, (object)AccessTools.Method(typeof(MissionUIPatch), "MissionText", (Type[])null, (Type[])null)) }) .InstructionEnumeration(); } private static void MissionText() { if (!((Object)(object)MoreUpgradesManager.instance == (Object)null)) { Plugin.instance.upgradeItems.FirstOrDefault((UpgradeItem x) => x.name == "Valuable Count")?.SetVariable("Changed", value: true); } } } [HarmonyPatch(typeof(StatsManager))] internal class StatsManagerPatch { [HarmonyPatch("Start")] [HarmonyPostfix] private static void Start(StatsManager __instance) { foreach (UpgradeItem upgradeItem in Plugin.instance.upgradeItems) { string text = new string(upgradeItem.name.Where((char x) => !char.IsWhiteSpace(x)).ToArray()); __instance.dictionaryOfDictionaries.Add("playerUpgrade" + text, upgradeItem.playerUpgrades); __instance.dictionaryOfDictionaries.Add("appliedPlayerUpgrade" + text, upgradeItem.appliedPlayerUpgrades); } } } [HarmonyPatch(typeof(ValuableObject))] internal class ValuableObjectPatch { [HarmonyPatch("Start")] [HarmonyPostfix] private static void Start(ValuableObject __instance) { if ((Object)(object)MoreUpgradesManager.instance == (Object)null) { return; } UpgradeItem upgradeItem = Plugin.instance.upgradeItems.FirstOrDefault((UpgradeItem x) => x.name == "Valuable Count"); if (upgradeItem != null) { List<ValuableObject> variable = upgradeItem.GetVariable<List<ValuableObject>>("CurrentValuables"); if (!variable.Contains(__instance)) { variable.Add(__instance); } } } } [HarmonyPatch(typeof(PhysGrabObject))] internal class PhysGrabObjectPatch { [HarmonyPatch("OnDestroy")] [HarmonyPostfix] private static void OnDestroy(PhysGrabObject __instance) { if ((Object)(object)MoreUpgradesManager.instance == (Object)null) { return; } ValuableObject component = ((Component)__instance).gameObject.GetComponent<ValuableObject>(); if ((Object)(object)component == (Object)null) { return; } UpgradeItem upgradeItem = Plugin.instance.upgradeItems.FirstOrDefault((UpgradeItem x) => x.name == "Valuable Count"); if (upgradeItem != null) { List<ValuableObject> variable = upgradeItem.GetVariable<List<ValuableObject>>("CurrentValuables"); if (variable.Contains(component)) { variable.Remove(component); } } } } [HarmonyPatch(typeof(ItemUpgrade))] internal class ItemUpgradePatch { [HarmonyPatch("Start")] [HarmonyPostfix] private static void Start(ItemUpgrade __instance) { //IL_0087: Unknown result type (might be due to invalid IL or missing references) //IL_0091: Expected O, but got Unknown //IL_009e: Unknown result type (might be due to invalid IL or missing references) //IL_00a8: Expected O, but got Unknown if ((Object)(object)MoreUpgradesManager.instance == (Object)null) { return; } GameObject gameObject = ((Component)__instance).gameObject; foreach (UpgradeItem upgradeItem in Plugin.instance.upgradeItems) { if (!(gameObject.GetComponent<ItemAttributes>().item.itemAssetName == upgradeItem.fullName)) { continue; } __instance.upgradeEvent = new UnityEvent(); __instance.upgradeEvent.AddListener((UnityAction)delegate { if (upgradeItem.GetConfig<bool>("Allow Team Upgrades")) { foreach (PlayerAvatar item in SemiFunc.PlayerGetAll()) { MoreUpgradesManager.instance.Upgrade(upgradeItem.name, SemiFunc.PlayerGetSteamID(item)); } return; } MoreUpgradesManager.instance.Upgrade(upgradeItem.name, SemiFunc.PlayerGetSteamID(SemiFunc.PlayerAvatarGetFromPhotonID((int)AccessTools.Field(typeof(ItemToggle), "playerTogglePhotonID").GetValue(gameObject.GetComponent<ItemToggle>())))); }); } } } [HarmonyPatch(typeof(ShopManager))] internal class ShopManagerPatch { [HarmonyPatch("GetAllItemsFromStatsManager")] [HarmonyTranspiler] private static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions) { //IL_0003: Unknown result type (might be due to invalid IL or missing references) //IL_0009: Expected O, but got Unknown //IL_001f: Unknown result type (might be due to invalid IL or missing references) //IL_0025: Expected O, but got Unknown //IL_0033: Unknown result type (might be due to invalid IL or missing references) //IL_0039: Expected O, but got Unknown //IL_005c: Unknown result type (might be due to invalid IL or missing references) //IL_0062: Expected O, but got Unknown //IL_009b: Unknown result type (might be due to invalid IL or missing references) //IL_00a1: Expected O, but got Unknown //IL_00af: Unknown result type (might be due to invalid IL or missing references) //IL_00b5: Expected O, but got Unknown //IL_00d2: Unknown result type (might be due to invalid IL or missing references) //IL_00d8: Expected O, but got Unknown //IL_00f5: Unknown result type (might be due to invalid IL or missing references) //IL_00fb: Expected O, but got Unknown //IL_0103: Unknown result type (might be due to invalid IL or missing references) //IL_0109: Expected O, but got Unknown CodeMatcher val = new CodeMatcher(instructions, (ILGenerator)null); val.MatchForward(false, (CodeMatch[])(object)new CodeMatch[3] { new CodeMatch((OpCode?)OpCodes.Br, (object)null, (string)null), new CodeMatch((OpCode?)OpCodes.Ldloca_S, (object)null, (string)null), new CodeMatch((OpCode?)OpCodes.Call, (object)AccessTools.Method(typeof(Dictionary<string, Item>.ValueCollection.Enumerator), "get_Current", (Type[])null, (Type[])null), (string)null) }); object operand = val.Operand; val.MatchForward(true, (CodeMatch[])(object)new CodeMatch[2] { new CodeMatch((OpCode?)OpCodes.Call, (object)AccessTools.Method(typeof(Dictionary<string, Item>.ValueCollection.Enumerator), "get_Current", (Type[])null, (Type[])null), (string)null), new CodeMatch((OpCode?)OpCodes.Stloc_1, (object)null, (string)null) }); val.Advance(1); val.Insert((CodeInstruction[])(object)new CodeInstruction[3] { new CodeInstruction(OpCodes.Ldloc_1, (object)null), new CodeInstruction(OpCodes.Call, (object)AccessTools.Method(typeof(ShopManagerPatch), "GetAllItemsFromStatsManager", (Type[])null, (Type[])null)), new CodeInstruction(OpCodes.Brtrue, operand) }); return val.InstructionEnumeration(); } private static bool GetAllItemsFromStatsManager(Item item) { if ((Object)(object)MoreUpgradesManager.instance == (Object)null) { return false; } UpgradeItem upgradeItem = Plugin.instance.upgradeItems.FirstOrDefault((UpgradeItem x) => x.fullName == item.itemAssetName); return upgradeItem != null && !upgradeItem.GetConfig<bool>("Enabled"); } } } namespace MoreUpgrades.CustomColorsPatches { [HarmonyPatch(typeof(ModdedColorPlayerAvatar))] internal class ModdedColorPlayerAvatarPatch { [HarmonyPatch("ModdedSetColorRPC")] [HarmonyPostfix] private static void ModdedSetColorRPC(ModdedColorPlayerAvatar __instance) { PlayerAvatar avatar = __instance.avatar; if (!((Object)(object)MoreUpgradesManager.instance == (Object)null) && !((Object)(object)avatar == (Object)(object)SemiFunc.PlayerAvatarLocal())) { UpgradeItem upgradeItem = Plugin.instance.upgradeItems.FirstOrDefault((UpgradeItem x) => x.name == "Map Player Tracker"); if (upgradeItem != null && upgradeItem.GetConfig<bool>("Player Color")) { Plugin.instance.RemovePlayerToMap(avatar); Plugin.instance.AddPlayerToMap(avatar); } } } } } namespace MoreUpgrades.Classes { public static class MoreUpgradesLib { public static IReadOnlyList<UpgradeItem> GetCoreUpgradeItems() { return Plugin.instance.upgradeItems.Where((UpgradeItem x) => x.modGUID == null).ToList(); } public static IReadOnlyList<UpgradeItem> GetUpgradeItemsByMod(string modGUID) { return Plugin.instance.upgradeItems.Where((UpgradeItem x) => x.modGUID == modGUID).ToList(); } public static UpgradeItem Register(string modGUID, Item item, GameObject prefab, string name, int maxAmount, int maxAmountInShop, float minPrice, float maxPrice, int maxPurchaseAmount = 0) { if ((Object)(object)Plugin.instance.assetBundle == (Object)null) { Plugin.instance.logger.LogWarning((object)"Couldn't register the upgrade item because the core mod failed to start. Contact the mod creator."); return null; } if (Plugin.instance.upgradeItems.Any((UpgradeItem x) => x.name.ToLower().Trim() == name.ToLower().Trim())) { Plugin.instance.logger.LogWarning((object)("An upgrade item with the name '" + name.Trim() + "' already exists. Duplicate upgrade items are not allowed.")); return null; } UpgradeItem upgradeItem = new UpgradeItem(name, maxAmount, maxAmountInShop, minPrice, maxPrice, maxPurchaseAmount, modGUID, item, prefab); Plugin.instance.upgradeItems.Add(upgradeItem); return upgradeItem; } } internal class MoreUpgradesManager : MonoBehaviour { internal static MoreUpgradesManager instance; internal PhotonView photonView; private bool checkAppliedPlayerUpgrades; private void Awake() { instance = this; photonView = ((Component)this).GetComponent<PhotonView>(); foreach (UpgradeItem upgradeItem in Plugin.instance.upgradeItems) { upgradeItem.variables.Clear(); upgradeItem.onInit?.Invoke(); } if (SemiFunc.IsMasterClientOrSingleplayer()) { ((MonoBehaviour)this).StartCoroutine("WaitUntilLevel"); } } private void LateUpdate() { foreach (UpgradeItem upgradeItem in Plugin.instance.upgradeItems) { upgradeItem.onLateUpdate?.Invoke(); } } private void FixedUpdate() { foreach (UpgradeItem upgradeItem in Plugin.instance.upgradeItems) { if (checkAppliedPlayerUpgrades) { int config = upgradeItem.GetConfig<int>("Starting Amount"); if (config >= 0) { foreach (PlayerAvatar item in SemiFunc.PlayerGetAll()) { string text = SemiFunc.PlayerGetSteamID(item); if (!upgradeItem.appliedPlayerUpgrades.ContainsKey(text)) { upgradeItem.appliedPlayerUpgrades[text] = 0; } if (upgradeItem.appliedPlayerUpgrades[text] != config) { Upgrade(upgradeItem.name, text, config - upgradeItem.appliedPlayerUpgrades[text]); upgradeItem.appliedPlayerUpgrades[text] = config; } } } } upgradeItem.onFixedUpdate?.Invoke(); } } private void Update() { foreach (UpgradeItem upgradeItem in Plugin.instance.upgradeItems) { upgradeItem.onUpdate?.Invoke(); } } private IEnumerator WaitUntilLevel() { yield return (object)new WaitUntil((Func<bool>)(() => SemiFunc.LevelGenDone())); checkAppliedPlayerUpgrades = true; } internal void Upgrade(string upgradeItemName, string steamId, int amount = 1) { UpgradeItem upgradeItem = Plugin.instance.upgradeItems.FirstOrDefault((UpgradeItem x) => x.name == upgradeItemName); if (upgradeItem != null) { upgradeItem.playerUpgrades[steamId] += amount; if ((Object)(object)SemiFunc.PlayerAvatarGetFromSteamID(steamId) == (Object)(object)SemiFunc.PlayerAvatarLocal()) { upgradeItem.onChanged?.Invoke(); } if (SemiFunc.IsMasterClient()) { photonView.RPC("UpgradeRPC", (RpcTarget)1, new object[3] { upgradeItemName, steamId, upgradeItem.playerUpgrades[steamId] }); } } } [PunRPC] internal void UpgradeRPC(string upgradeItemName, string steamId, int amount) { UpgradeItem upgradeItem = Plugin.instance.upgradeItems.FirstOrDefault((UpgradeItem x) => x.name == upgradeItemName); if (upgradeItem != null) { upgradeItem.playerUpgrades[steamId] = amount; if ((Object)(object)SemiFunc.PlayerAvatarGetFromSteamID(steamId) == (Object)(object)SemiFunc.PlayerAvatarLocal()) { upgradeItem.onChanged?.Invoke(); } } } } public class UpgradeItem { private static int staticId; private readonly int id; private Dictionary<string, ConfigEntryBase> configEntries; internal Dictionary<string, int> playerUpgrades; internal Dictionary<string, int> appliedPlayerUpgrades; internal Dictionary<string, object> variables; public Action onInit; public Action onLateUpdate; public Action onFixedUpdate; public Action onUpdate; public Action onChanged; public string name { get; private set; } public string fullName { get; private set; } public string modGUID { get; private set; } public void AddConfig<T>(string key, T defaultValue, string description = "") { if (configEntries.ContainsKey(key)) { Plugin.instance.logger.LogWarning((object)("A config entry with the key '" + key + "' already exists. Duplicates are not allowed.")); } else { configEntries.Add(key, (ConfigEntryBase)(object)((BaseUnityPlugin)Plugin.instance).Config.Bind<T>(string.Format("{0}: {1}{2}", id + 1, name, (modGUID != null) ? (" (" + modGUID + ")") : ""), key, defaultValue, description)); } } public T GetConfig<T>(string key) { if (!configEntries.TryGetValue(key, out var value)) { Plugin.instance.logger.LogWarning((object)("Missing config entry '" + key + "'.")); return default(T); } if (typeof(T) != value.SettingType) { Plugin.instance.logger.LogWarning((object)("Type mismatch for config entry '" + key + "'. Expected: " + value.SettingType.FullName + ", but got: " + typeof(T).FullName + ".")); return default(T); } return (T)value.BoxedValue; } public bool HasVariable(string key) { object value; return variables.TryGetValue(key, out value); } public void AddVariable<T>(string key, T value) { if (HasVariable(key)) { Plugin.instance.logger.LogWarning((object)("A variable with the key '" + key + "' already exists. Duplicates are not allowed.")); } else { variables.Add(key, value); } } public void SetVariable<T>(string key, T value) { if (!HasVariable(key)) { Plugin.instance.logger.LogWarning((object)("Variable '" + key + "' does not exist.")); return; } if (value != null) { T val = value; if (true) { variables[key] = val; return; } } Plugin.instance.logger.LogError((object)("Type mismatch for variable '" + key + "'. Expected: " + value.GetType().FullName + ", but got: " + typeof(T).FullName + ".")); } public T GetVariable<T>(string key) { if (!variables.TryGetValue(key, out var value)) { Plugin.instance.logger.LogWarning((object)("Variable '" + key + "' not found. Returning default value.")); return default(T); } if (value is T result) { return result; } Plugin.instance.logger.LogWarning((object)("Type mismatch for variable '" + key + "'. Expected: " + value.GetType().FullName + ", but got: " + typeof(T).FullName + ". Returning default value.")); return default(T); } public int GetAmount(string steamId = null) { if (steamId != null) { return playerUpgrades.ContainsKey(steamId) ? playerUpgrades[steamId] : 0; } PlayerAvatar val = SemiFunc.PlayerAvatarLocal(); if ((Object)(object)val != (Object)null) { steamId = SemiFunc.PlayerGetSteamID(val); } return (steamId != null && playerUpgrades.ContainsKey(steamId)) ? playerUpgrades[steamId] : 0; } internal UpgradeItem(string name, int maxAmount, int maxAmountInShop, float minPrice, float maxPrice, int maxPurchaseAmount = 0, string modGUID = null, Item modItem = null, GameObject modPrefab = null) { id = staticId++; this.name = name; fullName = "Item Upgrade Player " + name; this.modGUID = modGUID; configEntries = new Dictionary<string, ConfigEntryBase>(); AddConfig("Enabled", defaultValue: true, "Whether the upgrade item can be added to the shop."); AddConfig("Max Amount", maxAmount, "The maximum number of times the upgrade item can be bought at once."); AddConfig("Max Amount In Shop", maxAmountInShop, "The maximum number of times the upgrade item can appear in the shop."); AddConfig("Minimum Price", minPrice, "The minimum cost to purchase the upgrade item."); AddConfig("Maximum Price", maxPrice, "The maximum cost to purchase the upgrade item."); AddConfig("Max Purchase Amount", maxPurchaseAmount, "The total number of times the upgrade item can be purchased."); AddConfig("Allow Team Upgrades", defaultValue: false, "Whether the upgrade item applies to the entire team instead of just one player."); AddConfig("Starting Amount", 0, "The number of times the upgrade item is applied at the start of the game."); playerUpgrades = new Dictionary<string, int>(); appliedPlayerUpgrades = new Dictionary<string, int>(); variables = new Dictionary<string, object>(); Item val = modItem ?? Plugin.instance.assetBundle.LoadAsset<Item>(name); ((Object)val).name = fullName; val.itemAssetName = fullName; val.itemName = name + " Upgrade"; val.maxAmount = maxAmount; val.maxAmountInShop = maxAmountInShop; val.maxPurchase = maxPurchaseAmount > 0; val.maxPurchaseAmount = maxPurchaseAmount; val.value = ScriptableObject.CreateInstance<Value>(); val.value.valueMin = minPrice; val.value.valueMax = maxPrice; GameObject val2 = modPrefab ?? Plugin.instance.assetBundle.LoadAsset<GameObject>(name + " Prefab"); ((Object)val2).name = fullName; val2.GetComponent<ItemAttributes>().item = val; val.prefab = val2; Items.RegisterItem(val); } } }
plugins/BULLETBOT-ScaleInCart/ScaleInCart.dll
Decompiled 2 months agousing System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Versioning; using BepInEx; using BepInEx.Bootstrap; using BepInEx.Configuration; using BepInEx.Logging; using HarmonyLib; using REPOLib.Modules; 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("ShrinkItemsInCart")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("ShrinkItemsInCart")] [assembly: AssemblyCopyright("Copyright © 2024")] [assembly: AssemblyTrademark("")] [assembly: ComVisible(false)] [assembly: Guid("5e12a72d-c200-488d-940a-653d1003d96e")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")] [assembly: AssemblyVersion("1.0.0.0")] namespace ScaleInCart { [BepInDependency(/*Could not decode attribute arguments.*/)] [BepInPlugin("bulletbot.scaleincart", "ScaleInCart", "1.1.2")] internal class Plugin : BaseUnityPlugin { internal static class REPOLib { internal const string modGuid = "REPOLib"; internal static bool IsLoaded() { return Chainloader.PluginInfos.ContainsKey("REPOLib"); } internal static void OnAwake() { List<ValuableObject> list = new List<ValuableObject>(); foreach (GameObject registeredValuable in Valuables.RegisteredValuables) { ValuableObject component = registeredValuable.GetComponent<ValuableObject>(); if ((Object)(object)component != (Object)null && !list.Contains(component)) { instance.SetupValuableObject(component, isModded: true); list.Add(component); } } instance.LogMessages(list.Count); } } private const string modGUID = "bulletbot.scaleincart"; private const string modName = "ScaleInCart"; private const string modVer = "1.1.2"; internal static Plugin instance; internal ManualLogSource logger; private readonly Harmony harmony = new Harmony("bulletbot.scaleincart"); internal Dictionary<PhysGrabCart, PhysGrabObject[]> grabObjectsInCarts; internal Dictionary<string, Vector3> grabObjectScales; internal Dictionary<PhysGrabObject, (float, bool)> grabObjectLastUpdates; private Dictionary<float, float> massScaleFactorsDict = new Dictionary<float, float>(); internal ConfigEntry<bool> useMassScaling; internal ConfigEntry<bool> revertBack; internal ConfigEntry<bool> scaleEverything; internal ConfigEntry<float> scaleSpeed; internal ConfigEntry<float> scaleDelay; private ConfigEntry<float> defaultScale; private ConfigEntry<string> massScaleFactors; internal Dictionary<string, ConfigEntry<float>> valuableConfigs; internal bool isLoaded; private void SetupValuableObject(ValuableObject valuableObject, bool isModded) { //IL_001a: Unknown result type (might be due to invalid IL or missing references) string text = ((Object)valuableObject).name.Trim(); grabObjectScales.Add(text, ((Component)valuableObject).transform.localScale); valuableConfigs[text] = ((BaseUnityPlugin)this).Config.Bind<float>((isModded ? "Modded " : "") + "Valuable Scaling (" + text + ")", "Scale", 1f, "Mass: " + valuableObject.physAttributePreset.mass.ToString(CultureInfo.InvariantCulture)); } internal void LogMessages(int moddedCount = -1) { logger.LogMessage((object)$"Found {massScaleFactorsDict.Count} mass scale factors."); logger.LogMessage((object)$"Found {valuableConfigs.Count} valuables."); if (moddedCount != -1) { logger.LogMessage((object)$"Found {moddedCount} modded valuables."); } logger.LogMessage((object)"ScaleInCart has started."); } private void Awake() { instance = this; logger = Logger.CreateLogSource("ScaleInCart"); grabObjectsInCarts = new Dictionary<PhysGrabCart, PhysGrabObject[]>(); grabObjectScales = new Dictionary<string, Vector3>(); grabObjectLastUpdates = new Dictionary<PhysGrabObject, (float, bool)>(); massScaleFactorsDict = new Dictionary<float, float>(); useMassScaling = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "Use Mass Scaling", true, "If enabled, valuables will scale based on their mass.\nIf disabled, valuables will scale based on their valuable setting."); revertBack = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "Revert Back To Original Scale", true, "If enabled, valuables will revert to their original scale when not in the cart.\nIf disabled, the valuables will remain at their modified scale."); scaleEverything = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "Scale Everything", false, "If enabled, every grabbable object will be scaled.\nIf disabled, only valuables will be scaled."); scaleSpeed = ((BaseUnityPlugin)this).Config.Bind<float>("General", "Scale Speed", 0.005f, "The speed at which valuables scale down/up per update.\nHigher values make valuables shrink/expand faster."); scaleDelay = ((BaseUnityPlugin)this).Config.Bind<float>("General", "Scale Delay", 0f, "The initial delay (in seconds) before valuables begin scaling."); defaultScale = ((BaseUnityPlugin)this).Config.Bind<float>("Mass Scaling", "Default Scale", 0.8f, "Default scale factor if no mass threshold is exceeded"); massScaleFactors = ((BaseUnityPlugin)this).Config.Bind<string>("Mass Scaling", "Scale Factors", "1.0=0.75, 1.5=0.7, 2.0=0.65, 2.5=0.6, 3.0=0.55, 3.5=0.5, 4.0=0.45, 4.5=0.4, 5.0=0.35", "Scaling factors for mass >= values.\nFormat: 'mass=scale', separated by commas."); try { string[] array = massScaleFactors.Value.Split(new char[1] { ',' }); foreach (string text in array) { string[] array2 = (from x in text.Split(new char[1] { '=' }) select x.Trim()).ToArray(); if (array2.Length == 2) { float num = float.Parse(array2[0], CultureInfo.InvariantCulture); float value = float.Parse(array2[1], CultureInfo.InvariantCulture); if (massScaleFactorsDict.ContainsKey(num)) { throw new Exception($"Duplicate found for mass {num}."); } massScaleFactorsDict[num] = value; } } } catch (Exception ex) { logger.LogError((object)("Error parsing mass scale factors: " + ex.Message)); logger.LogError((object)"Failed to start ScaleInCart."); return; } valuableConfigs = new Dictionary<string, ConfigEntry<float>>(); ValuableObject[] array3 = Resources.LoadAll<ValuableObject>("Valuables/"); foreach (ValuableObject valuableObject in array3) { SetupValuableObject(valuableObject, isModded: false); } harmony.PatchAll(); logger.LogMessage((object)"ScaleInCart has started."); } public float GetScaleByMass(float mass) { foreach (float item in massScaleFactorsDict.Keys.OrderByDescending((float x) => x)) { if (mass >= item) { return massScaleFactorsDict[item]; } } return defaultScale.Value; } } } namespace ScaleInCart.Patches { [HarmonyPatch(typeof(RunManager))] internal class RunManagerPatch { [HarmonyPatch("Awake")] [HarmonyPostfix] [HarmonyAfter(new string[] { "REPOLib" })] private static void Awake() { if (!Plugin.instance.isLoaded) { if (Plugin.REPOLib.IsLoaded()) { Plugin.REPOLib.OnAwake(); } else { Plugin.instance.LogMessages(); } Plugin.instance.isLoaded = true; } } [HarmonyPatch("ChangeLevel")] [HarmonyPrefix] private static void ChangeLevel() { Plugin.instance.grabObjectsInCarts.Clear(); Plugin.instance.grabObjectScales.Clear(); } } [HarmonyPatch(typeof(PhysGrabObject))] internal class PhysGrabObjectPatch { [HarmonyPatch("Update")] [HarmonyPostfix] private static void Update(PhysGrabObject __instance, bool ___isValuable) { //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_01b7: Unknown result type (might be due to invalid IL or missing references) //IL_027d: Unknown result type (might be due to invalid IL or missing references) //IL_0282: Unknown result type (might be due to invalid IL or missing references) //IL_0287: Unknown result type (might be due to invalid IL or missing references) //IL_0297: Unknown result type (might be due to invalid IL or missing references) //IL_02c8: Unknown result type (might be due to invalid IL or missing references) //IL_02a7: Unknown result type (might be due to invalid IL or missing references) //IL_0382: Unknown result type (might be due to invalid IL or missing references) //IL_0389: Unknown result type (might be due to invalid IL or missing references) //IL_02d7: Unknown result type (might be due to invalid IL or missing references) //IL_02d9: Unknown result type (might be due to invalid IL or missing references) //IL_02d3: Unknown result type (might be due to invalid IL or missing references) //IL_0397: Unknown result type (might be due to invalid IL or missing references) //IL_039e: Unknown result type (might be due to invalid IL or missing references) //IL_02de: Unknown result type (might be due to invalid IL or missing references) //IL_02e3: Unknown result type (might be due to invalid IL or missing references) //IL_03dd: Unknown result type (might be due to invalid IL or missing references) //IL_03ac: Unknown result type (might be due to invalid IL or missing references) //IL_03b3: 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_02f0: Unknown result type (might be due to invalid IL or missing references) //IL_03f1: Unknown result type (might be due to invalid IL or missing references) //IL_03e8: Unknown result type (might be due to invalid IL or missing references) //IL_03ea: Unknown result type (might be due to invalid IL or missing references) //IL_03f3: Unknown result type (might be due to invalid IL or missing references) //IL_03f8: Unknown result type (might be due to invalid IL or missing references) //IL_032e: Unknown result type (might be due to invalid IL or missing references) //IL_031e: Unknown result type (might be due to invalid IL or missing references) //IL_041a: Unknown result type (might be due to invalid IL or missing references) //IL_0421: Unknown result type (might be due to invalid IL or missing references) //IL_0405: Unknown result type (might be due to invalid IL or missing references) //IL_040c: Unknown result type (might be due to invalid IL or missing references) //IL_035c: Unknown result type (might be due to invalid IL or missing references) //IL_034c: Unknown result type (might be due to invalid IL or missing references) //IL_0452: Unknown result type (might be due to invalid IL or missing references) //IL_0459: Unknown result type (might be due to invalid IL or missing references) //IL_043d: Unknown result type (might be due to invalid IL or missing references) //IL_0444: Unknown result type (might be due to invalid IL or missing references) //IL_0371: Unknown result type (might be due to invalid IL or missing references) //IL_048a: Unknown result type (might be due to invalid IL or missing references) //IL_0491: Unknown result type (might be due to invalid IL or missing references) //IL_0475: Unknown result type (might be due to invalid IL or missing references) //IL_047c: 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) if (!(Plugin.instance.scaleEverything.Value || ___isValuable)) { return; } bool flag = false; foreach (KeyValuePair<PhysGrabCart, PhysGrabObject[]> grabObjectsInCart in Plugin.instance.grabObjectsInCarts) { PhysGrabObject[] value = grabObjectsInCart.Value; foreach (PhysGrabObject val in value) { if ((Object)(object)val == (Object)(object)__instance) { flag = true; break; } } } float value2 = Plugin.instance.scaleDelay.Value; if (value2 > 0f) { if (!Plugin.instance.grabObjectLastUpdates.TryGetValue(__instance, out var value3)) { value3 = (Time.time, flag); Plugin.instance.grabObjectLastUpdates[__instance] = value3; } var (num, flag2) = value3; if (flag2 != flag) { num = Time.time + value2; Plugin.instance.grabObjectLastUpdates[__instance] = (num, flag); } if (Time.time < num) { return; } Plugin.instance.grabObjectLastUpdates[__instance] = (Time.time, flag); } string text = ((Object)((Component)__instance).gameObject).name.Replace("(Clone)", "").Trim(); Transform transform = ((Component)__instance).transform; Vector3 localScale = transform.localScale; if (!Plugin.instance.grabObjectScales.ContainsKey(text)) { Plugin.instance.grabObjectScales[text] = localScale; } float num2 = 1f; if (Plugin.instance.useMassScaling.Value || !___isValuable) { num2 = Plugin.instance.GetScaleByMass(__instance.massOriginal); } else { foreach (KeyValuePair<string, ConfigEntry<float>> valuableConfig in Plugin.instance.valuableConfigs) { if (valuableConfig.Key == text) { num2 = valuableConfig.Value.Value; } } } float value4 = Plugin.instance.scaleSpeed.Value; Vector3 val2 = default(Vector3); ((Vector3)(ref val2))..ctor(value4, value4, value4); Vector3 val3 = Plugin.instance.grabObjectScales[text]; if (flag && (!Mathf.Approximately(localScale.x, num2) || !Mathf.Approximately(localScale.y, num2) || !Mathf.Approximately(localScale.z, num2))) { Vector3 val4 = localScale + ((num2 < 1f) ? (-val2) : val2); val4.x = ((num2 < 1f) ? Mathf.Max(val4.x, num2) : Mathf.Min(val4.x, num2)); val4.y = ((num2 < 1f) ? Mathf.Max(val4.y, num2) : Mathf.Min(val4.y, num2)); val4.z = ((num2 < 1f) ? Mathf.Max(val4.z, num2) : Mathf.Min(val4.z, num2)); transform.localScale = val4; } else if (!flag && (!Mathf.Approximately(localScale.x, val3.x) || !Mathf.Approximately(localScale.y, val3.y) || !Mathf.Approximately(localScale.z, val3.z)) && Plugin.instance.revertBack.Value) { Vector3 val5 = localScale + ((num2 < 1f) ? val2 : (-val2)); val5.x = ((num2 < 1f) ? Mathf.Min(val5.x, val3.x) : Mathf.Max(val5.x, val3.x)); val5.y = ((num2 < 1f) ? Mathf.Min(val5.y, val3.y) : Mathf.Max(val5.y, val3.y)); val5.z = ((num2 < 1f) ? Mathf.Min(val5.z, val3.z) : Mathf.Max(val5.z, val3.z)); transform.localScale = val5; } } } [HarmonyPatch(typeof(PhysGrabCart))] internal class PhysGrabCartPatch { [HarmonyPatch("ObjectsInCart")] [HarmonyPostfix] private static void ObjectsInCart(PhysGrabCart __instance, List<PhysGrabObject> ___itemsInCart) { Plugin.instance.grabObjectsInCarts[__instance] = ___itemsInCart.Where((PhysGrabObject x) => Plugin.instance.scaleEverything.Value || (bool)AccessTools.Field(typeof(PhysGrabObject), "isValuable").GetValue(x)).ToArray(); } } }
plugins/CCarrMcMahon-Essentials/Essentials/Essentials.dll
Decompiled 2 months agousing System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; 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.Configuration; using BepInEx.Logging; using HarmonyLib; using Microsoft.CodeAnalysis; using RepoEssentials.src.patches; using TMPro; 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("Essentials")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyFileVersion("0.3.1.0")] [assembly: AssemblyInformationalVersion("0.3.1+2b1585065a91d580d713e4f80cac9797d7629b83")] [assembly: AssemblyProduct("R.E.P.O Essentials Plugin")] [assembly: AssemblyTitle("Essentials")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("0.3.1.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 RepoEssentials.src { [BepInPlugin("org.ccarrmcmahon.plugins.repo.essentials", "Essentials", "0.3.1")] [BepInProcess("REPO.exe")] [BepInIncompatibility("nickklmao.nolimitchatbox")] public class Plugin : BaseUnityPlugin { internal static ManualLogSource Logger; private void Awake() { //IL_001f: Unknown result type (might be due to invalid IL or missing references) //IL_0025: Expected O, but got Unknown Logger = ((BaseUnityPlugin)this).Logger; Logger.LogInfo((object)"Loading plugin..."); Harmony harmony = new Harmony("org.ccarrmcmahon.plugins.repo.essentials"); Logger.LogDebug((object)"Loading Harmony patches..."); CurrentCulture.Initialize(harmony); SinglePlayerChat.Initialize(harmony); ChatCharacterLimit.Initialize(((BaseUnityPlugin)this).Config, harmony); Logger.LogDebug((object)"Harmony patches loaded!"); Logger.LogInfo((object)"Plugin loaded successfully!"); } } } namespace RepoEssentials.src.patches { public static class ChatCharacterLimit { public static ConfigEntry<int> CharacterLimit { get; private set; } public static ConfigEntry<float> ChatTextWidth { get; private set; } public static ConfigEntry<float> CharacterSpacing { get; private set; } public static ConfigEntry<float> LineSpacing { get; private set; } private static void LoadConfig(ConfigFile config) { CharacterLimit = config.Bind<int>("Chat", "CharacterLimit", 250, "The maximum number of characters allowed in a chat messages."); ChatTextWidth = config.Bind<float>("Chat", "ChatTextWidth", 525f, "The width of the chat area."); CharacterSpacing = config.Bind<float>("Chat", "CharacterSpacing", -0.5f, "The spacing between characters in chat."); LineSpacing = config.Bind<float>("Chat", "LineSpacing", -60f, "The spacing between lines in chat."); } private static void ChatManagerAwakePatch(Harmony harmony) { harmony.CreateClassProcessor(typeof(ChatManager_Awake_Patch)).Patch(); Plugin.Logger.LogDebug((object)" - ChatManager_Awake_Patch: True"); } private static bool ChatManagerStateActivePatch(Harmony harmony) { harmony.CreateClassProcessor(typeof(ChatManager_StateActive_Patch)).Patch(); bool patchSuccessful = ChatManager_StateActive_Patch.PatchSuccessful; Plugin.Logger.LogDebug((object)$" - ChatManager_StateActive_Patch: {patchSuccessful}"); return patchSuccessful; } private static bool ApplyPatches(Harmony harmony) { ChatManagerAwakePatch(harmony); return true & ChatManagerStateActivePatch(harmony); } public static void Initialize(ConfigFile config, Harmony harmony) { Plugin.Logger.LogDebug((object)"Loading ChatCharacterLimit config..."); LoadConfig(config); Plugin.Logger.LogDebug((object)" > Success: True"); Plugin.Logger.LogDebug((object)"Applying ChatCharacterLimit patches..."); bool flag = ApplyPatches(harmony); Plugin.Logger.LogDebug((object)$" > Success: {flag}"); } } [HarmonyPatch(typeof(ChatManager), "Awake")] public class ChatManager_Awake_Patch { public static bool PatchSuccessful { get; private set; } private static void Prefix(ChatManager __instance) { //IL_0089: 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) int value = ChatCharacterLimit.CharacterLimit.Value; Traverse.Create((object)__instance).Field("characterLimit").SetValue((object)value); TextMeshProUGUI value2 = Traverse.Create((object)__instance).Field("chatText").GetValue<TextMeshProUGUI>(); if ((Object)(object)value2 == (Object)null) { Plugin.Logger.LogError((object)"Failed to find chatText component"); return; } RectTransform component = ((Component)value2).GetComponent<RectTransform>(); if ((Object)(object)component == (Object)null) { Plugin.Logger.LogError((object)"Failed to get RectTransform from chatText"); return; } ((TMP_Text)value2).enableWordWrapping = true; component.sizeDelta = new Vector2(ChatCharacterLimit.ChatTextWidth.Value, component.sizeDelta.y); ((TMP_Text)value2).characterSpacing = ChatCharacterLimit.CharacterSpacing.Value; ((TMP_Text)value2).lineSpacing = ChatCharacterLimit.LineSpacing.Value; PatchSuccessful = true; } } [HarmonyPatch(typeof(ChatManager), "StateActive")] public class ChatManager_StateActive_Patch { public static bool PatchSuccessful { get; private set; } private static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions) { //IL_00cb: 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_00e7: Expected O, but got Unknown bool flag = false; int num = -1; List<CodeInstruction> list = instructions.ToList(); for (int i = 0; i < list.Count; i++) { if (!flag) { if (list[i].opcode == OpCodes.Ldstr && list[i].operand.ToString().Equals("\n")) { flag = true; } } else if (flag && num == -1) { if (list[i].opcode == OpCodes.Callvirt && list[i].operand.ToString().Equals("Int32 get_Length()")) { num = i; } } else if (i == num + 1 && list[i].opcode == OpCodes.Ldc_I4_S) { list[i] = new CodeInstruction(OpCodes.Ldc_I4, (object)ChatCharacterLimit.CharacterLimit.Value) { labels = list[i].labels }; PatchSuccessful = true; break; } } if (!PatchSuccessful) { Plugin.Logger.LogError((object)"Failed to find the expected instructions to patch."); return instructions; } return list.AsEnumerable(); } } public static class CurrentCulture { private static void SemiFuncDollarGetStringPatch(Harmony harmony) { harmony.CreateClassProcessor(typeof(SemiFunc_DollarGetString_Patch)).Patch(); Plugin.Logger.LogDebug((object)" - SemiFunc_DollarGetString_Patch: True"); } private static void ApplyPatches(Harmony harmony) { SemiFuncDollarGetStringPatch(harmony); } public static void Initialize(Harmony harmony) { Plugin.Logger.LogDebug((object)"Applying CurrentCulture patches..."); ApplyPatches(harmony); Plugin.Logger.LogDebug((object)" > Success: True"); } } [HarmonyPatch(typeof(SemiFunc), "DollarGetString")] public class SemiFunc_DollarGetString_Patch { private static bool Prefix(int value, ref string __result) { __result = string.Format(CultureInfo.CurrentCulture, "{0:#,0}", value); return false; } } public static class SinglePlayerChat { private static bool ChatManagerUpdatePatch(Harmony harmony) { harmony.CreateClassProcessor(typeof(ChatManager_Update_Patch)).Patch(); bool patchSuccessful = ChatManager_Update_Patch.PatchSuccessful; Plugin.Logger.LogDebug((object)$" - ChatManager_Update_Patch: {patchSuccessful}"); return patchSuccessful; } private static bool ApplyPatches(Harmony harmony) { return true & ChatManagerUpdatePatch(harmony); } public static void Initialize(Harmony harmony) { Plugin.Logger.LogDebug((object)"Applying SinglePlayerChat patches..."); bool flag = ApplyPatches(harmony); Plugin.Logger.LogDebug((object)$" > Success: {flag}"); } } [HarmonyPatch(typeof(ChatManager), "Update")] public class ChatManager_Update_Patch { public static bool PatchSuccessful { get; private set; } private static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions) { //IL_0048: Unknown result type (might be due to invalid IL or missing references) //IL_004d: Unknown result type (might be due to invalid IL or missing references) //IL_0060: Expected O, but got Unknown int num = 0; List<CodeInstruction> list = instructions.ToList(); for (int i = 0; i < list.Count; i++) { if (list[i].opcode == OpCodes.Call && list[i].operand.ToString().Equals("Boolean IsMultiplayer()")) { CodeInstruction value = new CodeInstruction(OpCodes.Ldc_I4_1, (object)null) { labels = list[i].labels }; list[i] = value; num++; } } PatchSuccessful = num == 2; if (!PatchSuccessful) { Plugin.Logger.LogError((object)$"Found {num} occurances of SemiFunc::IsMultiplayer() instead of {2}."); return instructions; } return list.AsEnumerable(); } } } namespace RepoEssentials.src.configs { public static class GameInfo { public const string NAME = "R.E.P.O."; public const string VERSION = "0.1.2"; public const string APP_ID = "3241660"; public const string BUILD_ID = "17560228"; public const string EXECUTABLE_NAME = "REPO.exe"; } public static class PluginInfo { public const string GUID = "org.ccarrmcmahon.plugins.repo.essentials"; public const string NAME = "Essentials"; public const string VERSION = "0.3.1"; public const string AUTHOR = "CCarrMcMahon"; public const string ENTRY = "RepoEssentials.Plugin.Awake"; public const string MANIFEST = "manifest.json"; public const string ASSEMBLY = "Essentials.dll"; } }
plugins/ColtG5-LegoGnomes/GnomeLegoBreakMod.dll
Decompiled 2 months agousing System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Versioning; using BepInEx; using BepInEx.Logging; using HarmonyLib; 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("GnomeLegoBreakMod")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("GnomeLegoBreakMod")] [assembly: AssemblyCopyright("Copyright © 2025")] [assembly: AssemblyTrademark("")] [assembly: ComVisible(false)] [assembly: Guid("181d68d9-b8f0-46ac-acb9-aa87936fbf55")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")] [assembly: AssemblyVersion("1.0.0.0")] namespace GnomeLegoBreakMod { [BepInPlugin("ColtG5.LegoGnomes", "LegoGnomes", "1.0.2")] public class GnomeLegoBreakMod : BaseUnityPlugin { private const string modGUID = "ColtG5.LegoGnomes"; private const string modName = "LegoGnomes"; private const string modVersion = "1.0.2"; private readonly Harmony harmony = new Harmony("ColtG5.LegoGnomes"); internal static GnomeLegoBreakMod instance; internal ManualLogSource logger; internal static List<AudioClip> newBreakSound; internal static AssetBundle Bundle; private void Awake() { if ((Object)(object)instance == (Object)null) { instance = this; } logger = ((BaseUnityPlugin)this).Logger; harmony.PatchAll(); logger = Logger.CreateLogSource("ColtG5.LegoGnomes"); string location = ((BaseUnityPlugin)instance).Info.Location; location = location.TrimEnd("GnomeLegoBreakMod.dll".ToCharArray()); Bundle = AssetBundle.LoadFromFile(location + "coltg5-gnome-sounds"); if ((Object)(object)Bundle != (Object)null) { newBreakSound = Bundle.LoadAllAssets<AudioClip>().ToList(); ((BaseUnityPlugin)this).Logger.LogInfo((object)"Asset bundle loaded!"); } else { ((BaseUnityPlugin)this).Logger.LogError((object)"Failed to load asset bundle!"); } logger.LogInfo((object)"GnomeLegoBreakMod loaded!"); } } } namespace GnomeLegoBreakMod.Patches { [HarmonyPatch(typeof(EnemyGnome))] internal class EnemyGnomePatch { private static GnomeLegoBreakMod Instance = GnomeLegoBreakMod.instance; private static ManualLogSource Logger => Instance.logger; [HarmonyPatch("Awake")] [HarmonyPostfix] private static void PatchEnemyGnomeAnimAwake(EnemyGnome __instance) { __instance.soundDeath.Sounds = GnomeLegoBreakMod.newBreakSound.ToArray(); __instance.soundDeath.Volume = 2f; } } }
plugins/Danos-REPOStats/com.danos.repostats.dll
Decompiled 2 months agousing System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.Linq; using System.Net.Http; using System.Net.Http.Headers; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.Serialization; using System.Runtime.Serialization.Json; using System.Runtime.Versioning; using System.Security; using System.Security.Cryptography; using System.Security.Permissions; using System.Text; using System.Threading.Tasks; using BepInEx; using BepInEx.Logging; using HarmonyLib; using MenuLib; using Microsoft.CodeAnalysis; using REPOStats_Mod.Data; using REPOStats_Mod.Patches; using UnityEngine; using UnityEngine.Networking; 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("com.danos.repostats")] [assembly: AssemblyConfiguration("Debug")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: AssemblyInformationalVersion("1.0.0+1d0b965d5d7a8b168d2e3e7971e934791ee31c58")] [assembly: AssemblyProduct("REPOStats-Mod")] [assembly: AssemblyTitle("com.danos.repostats")] [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 REPOStats_Mod { public static class DanosRepoStatsPluginInfo { public const string PLUGIN_GUID = "com.danos.repostats"; public const string PLUGIN_NAME = "repostats"; public const string PLUGIN_VERSION = "0.5.3"; } [BepInPlugin("com.danos.repostats", "repostats", "0.5.3")] [BepInDependency(/*Could not decode attribute arguments.*/)] public class REPOStats_Mod : BaseUnityPlugin { private static readonly HashSet<Type> AppliedPatches = new HashSet<Type>(); private static readonly HashSet<string> AppliedDynamicPatches = new HashSet<string>(); private static bool _additionalPatchesApplied = false; public static REPOStats_Mod Instance { get; private set; } = null; internal static ManualLogSource Logger { get; private set; } = null; internal static Harmony? Harmony { get; set; } private void Awake() { Logger = ((BaseUnityPlugin)this).Logger; Instance = this; Patch(); Logger.LogInfo((object)"com.danos.repostats v0.5.3 has loaded!"); } internal static void Patch() { //IL_000d: Unknown result type (might be due to invalid IL or missing references) //IL_0012: Unknown result type (might be due to invalid IL or missing references) //IL_0018: Expected O, but got Unknown if (Harmony == null) { Harmony = new Harmony("com.danos.repostats"); } Logger.LogDebug((object)"Patching..."); Harmony.PatchAll(typeof(PrivacyPolicyPatch)); Logger.LogDebug((object)"Finished patching!"); } internal static void Unpatch() { Logger.LogDebug((object)"Unpatching..."); Harmony? harmony = Harmony; if (harmony != null) { harmony.UnpatchSelf(); } Logger.LogDebug((object)"Finished unpatching!"); } public static void ApplyAdditionalPatches() { if (_additionalPatchesApplied) { Logger.LogDebug((object)"Additional patches already applied."); return; } ApplyPatch(typeof(RunPatches)); ApplyPatch(typeof(RoundDirectorPatches)); ApplyPatch(typeof(DeathPatches)); DanosCustomMenuManager.Initialize(); List<DanosPatchConfiguration> patchConfigurations = DanosPatchManager.GetPatchConfigurations(); foreach (DanosPatchConfiguration item in patchConfigurations) { ApplyDynamicPatch(item); } _additionalPatchesApplied = true; Logger.LogDebug((object)"RepoStats is loaded!"); } private static void ApplyDynamicPatch(DanosPatchConfiguration patchConfig) { //IL_01b5: Unknown result type (might be due to invalid IL or missing references) //IL_01c2: Expected O, but got Unknown try { string text = patchConfig.TargetClass + "." + patchConfig.TargetMethod + "." + patchConfig.PostfixMethod; if (AppliedDynamicPatches.Contains(text)) { Logger.LogDebug((object)("Patch already applied: " + text)); return; } Type type = AccessTools.TypeByName(patchConfig.TargetClass); if (type == null) { Logger.LogDebug((object)("Target class '" + patchConfig.TargetClass + "' not found. Skipping patch.")); return; } MethodInfo methodInfo = AccessTools.Method(type, patchConfig.TargetMethod, (Type[])null, (Type[])null); if (methodInfo == null) { Logger.LogDebug((object)("Target method '" + patchConfig.TargetMethod + "' not found in class '" + patchConfig.TargetClass + "'. Skipping patch.")); return; } string[] array = patchConfig.PostfixMethod.Split('.'); string name = array.Last(); string text2 = string.Join('.', array.Take(array.Length - 1)); Type type2 = Type.GetType(text2); if (type2 == null) { Logger.LogDebug((object)("Postfix class '" + text2 + "' not found. Skipping patch.")); return; } MethodInfo method = type2.GetMethod(name, BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); if (method == null) { Logger.LogDebug((object)("Postfix method '" + patchConfig.PostfixMethod + "' not found. Skipping patch.")); return; } Harmony.Patch((MethodBase)methodInfo, (HarmonyMethod)null, new HarmonyMethod(method), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); AppliedDynamicPatches.Add(text); Logger.LogDebug((object)("Successfully patched " + patchConfig.TargetClass + "." + patchConfig.TargetMethod)); } catch (Exception ex) { Logger.LogDebug((object)("Failed to apply patch for " + patchConfig.TargetClass + "." + patchConfig.TargetMethod + ": " + ex.Message)); } } private static void ApplyPatch(Type patchType) { if (!AppliedPatches.Contains(patchType)) { Harmony.PatchAll(patchType); AppliedPatches.Add(patchType); Logger.LogDebug((object)("Patch applied: " + patchType.Name)); } else { Logger.LogDebug((object)("Patch already applied: " + patchType.Name)); } } } public static class MyPluginInfo { public const string PLUGIN_GUID = "com.danos.repostats"; public const string PLUGIN_NAME = "REPOStats-Mod"; public const string PLUGIN_VERSION = "1.0.0"; } } namespace REPOStats_Mod.Patches { [HarmonyPatch] public class DeathPatches { private static readonly FieldRef<Enemy, EnemyParent> enemyRef = AccessTools.FieldRefAccess<Enemy, EnemyParent>("EnemyParent"); [HarmonyPatch(typeof(PlayerAvatar), "PlayerDeathRPC")] [HarmonyPostfix] public static void PlayerDeathRPCPostfix(PlayerAvatar __instance, int enemyIndex) { string text = SemiFunc.PlayerGetSteamID(__instance); if (text == null || !DanosUtils.GetMySteamID().Equals(text)) { return; } string causeOfDeath = "Unknown"; Enemy val = SemiFunc.EnemyGetFromIndex(enemyIndex); if ((Object)(object)val != (Object)null) { causeOfDeath = ((Object)val).name; EnemyParent val2 = enemyRef.Invoke(val); if ((Object)(object)val2 != (Object)null) { causeOfDeath = val2.enemyName; } } DanosDeathContainer danosDeathContainer = new DanosDeathContainer(); danosDeathContainer.DeathTime = DateTimeOffset.UtcNow.ToUnixTimeSeconds(); danosDeathContainer.CauseOfDeath = causeOfDeath; DanosStaticStore.statsStore.Deaths.Add(danosDeathContainer); } } [HarmonyPatch] public class PrivacyPolicyPatch { public class PolicyLoader : MonoBehaviour { private async void Start() { await LoadPolicyAndShowPopup(); Object.Destroy((Object)(object)((Component)this).gameObject); } private async Task LoadPolicyAndShowPopup() { policy = await GetPolicy(); Debug.Log((object)("Policy version: " + policy.Version)); if (HasUserAcceptedPolicy(policy.Version)) { Debug.Log((object)"User has already accepted the current policy version."); REPOStats_Mod.ApplyAdditionalPatches(); return; } Debug.Log((object)"User has not accepted the current policy version. Showing the popup."); ShowPopup(delegate { Debug.Log((object)"User accepted REPOStats terms."); SaveUserResponse(accepted: true, policy.Version); REPOStats_Mod.ApplyAdditionalPatches(); }, delegate { Debug.Log((object)"User declined REPOStats terms. Closing the game."); Application.Quit(); }); } } public static PolicyVersion policy = new PolicyVersion(); public static bool running = false; [HarmonyPatch(typeof(MenuManager), "Start")] [HarmonyPrefix] public static bool StartPrefix() { //IL_0025: Unknown result type (might be due to invalid IL or missing references) Debug.Log((object)"Checking if user has accepted the current policy version."); if ((Object)(object)Object.FindObjectOfType<PolicyLoader>() != (Object)null) { return true; } new GameObject("PolicyLoader").AddComponent<PolicyLoader>(); return true; } private static bool HasUserAcceptedPolicy(string policyVersion) { try { string location = Assembly.GetExecutingAssembly().Location; string directoryName = Path.GetDirectoryName(location); string path = Path.Combine(directoryName, "REPOStatsPrivacyResponse.txt"); if (!File.Exists(path)) { return false; } string[] array = File.ReadAllLines(path); string[] array2 = array; foreach (string text in array2) { if (text.Contains("Policy Version: " + policyVersion)) { return true; } } } catch (Exception ex) { Debug.Log((object)("Error checking user response: " + ex.Message)); } return false; } private static void SaveUserResponse(bool accepted, string policyVersion) { try { string location = Assembly.GetExecutingAssembly().Location; string directoryName = Path.GetDirectoryName(location); string text = Path.Combine(directoryName, "REPOStatsPrivacyResponse.txt"); string arg = (accepted ? "Accepted" : "Declined"); string contents = $"User Response: {arg}\nPolicy Version: {policyVersion}\nDate: {DateTime.Now}\n\nDelete this file to revoke RepoStats Privacy policy consent for this mod profile. \nYou will need to do this for each mod profile that has RepoStats installed if you are using a mod manager like r2modman. "; File.WriteAllText(text, contents); Debug.Log((object)("User response saved to: " + text)); } catch (Exception ex) { Debug.Log((object)("Error saving user response: " + ex.Message)); } } [HarmonyPatch(typeof(MenuManager), "Update")] [HarmonyPrefix] public static void UpdatePostfix() { GlobalInputManager.Update(); } public static void ShowPopup(Action onAccept, Action onDecline) { //IL_0026: Unknown result type (might be due to invalid IL or missing references) //IL_0030: Expected O, but got Unknown //IL_0075: Unknown result type (might be due to invalid IL or missing references) //IL_007b: Expected O, but got Unknown //IL_00b1: 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_00d3: Unknown result type (might be due to invalid IL or missing references) //IL_00e0: Unknown result type (might be due to invalid IL or missing references) //IL_00fb: 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_01c8: Unknown result type (might be due to invalid IL or missing references) //IL_01f4: Unknown result type (might be due to invalid IL or missing references) //IL_0221: Unknown result type (might be due to invalid IL or missing references) //IL_024e: Unknown result type (might be due to invalid IL or missing references) Action onAccept2 = onAccept; Action onDecline2 = onDecline; Debug.Log((object)"Creating fullscreen popup..."); GameObject popupCanvas = new GameObject("RepoStatsPopupCanvas"); Canvas val = popupCanvas.AddComponent<Canvas>(); val.renderMode = (RenderMode)0; val.sortingOrder = 9999; CanvasScaler val2 = popupCanvas.AddComponent<CanvasScaler>(); val2.uiScaleMode = (ScaleMode)1; popupCanvas.AddComponent<GraphicRaycaster>(); GameObject val3 = new GameObject("Panel"); val3.transform.SetParent(popupCanvas.transform, false); Image val4 = val3.AddComponent<Image>(); ((Graphic)val4).color = new Color(0f, 0f, 0f, 0.95f); RectTransform component = val3.GetComponent<RectTransform>(); component.anchorMin = Vector2.zero; component.anchorMax = Vector2.one; component.sizeDelta = Vector2.zero; CreateText(val3, "REPOStats", new Vector2(0f, 150f), 36, (TextAnchor)1, "#6ac4a7"); string message = "Welcome to REPOStats! By using this mod, you agree to the privacy policy at https://repo.splitstats.io/privacypolicy.\n\nGame stats will be collected and uploaded during gameplay. Your response to the policy will be saved in the mod folder until you uninstall the mod or the policy changes.\n\nManage or delete your data using tools on our website. Decline to close the game and uninstall the mod."; string message2 = "We do not store contact information, so we cannot directly inform you of any changes, however this prompt will popup any time we make any.\n\nVersion: " + policy.Version + "\nLast Updated: " + policy.LastUpdated.ToShortDateString() + "\nChanges: " + policy.DescriptionOfChanges + "\nLast Updated: " + policy.LastUpdatedDaysAgo + "."; CreateText(val3, message, new Vector2(0f, 75f), 8, (TextAnchor)4); CreateText(val3, message2, new Vector2(0f, -25f), 5, (TextAnchor)4); CreateText(val3, "[F5] Open Privacy Policy", new Vector2(0f, -60f), 24, (TextAnchor)4, "#6ac4a7"); CreateText(val3, "[F6] Accept", new Vector2(-100f, -120f), 24, (TextAnchor)4, "#6ac4a7"); CreateText(val3, "[F7] Decline", new Vector2(100f, -120f), 24, (TextAnchor)4, "#FF6A6A"); GlobalInputManager.ListenForKeys((KeyCode)286, delegate { Application.OpenURL("https://repo.splitstats.io/privacypolicy"); }); GlobalInputManager.ListenForKeys((KeyCode)287, delegate { Object.Destroy((Object)(object)popupCanvas); GlobalInputManager.StopListeningForKeys((KeyCode)286); GlobalInputManager.StopListeningForKeys((KeyCode)287); GlobalInputManager.StopListeningForKeys((KeyCode)288); onAccept2?.Invoke(); }); GlobalInputManager.ListenForKeys((KeyCode)288, delegate { Object.Destroy((Object)(object)popupCanvas); GlobalInputManager.StopListeningForKeys((KeyCode)286); GlobalInputManager.StopListeningForKeys((KeyCode)287); GlobalInputManager.StopListeningForKeys((KeyCode)288); onDecline2?.Invoke(); }); } private static async Task<PolicyVersion> GetPolicy() { PolicyVersion policy = new PolicyVersion(); using (HttpClient client = new HttpClient()) { Debug.Log((object)"Getting policy from: https://repo.splitstats.io/api/Privacy/current"); HttpResponseMessage response = await client.GetAsync("https://repo.splitstats.io/api/Privacy/current"); Debug.Log((object)("Response: " + response.StatusCode)); if (response.IsSuccessStatusCode) { policy = DeserializeJson<PolicyVersion>(await response.Content.ReadAsStringAsync().ConfigureAwait(continueOnCapturedContext: false)); } } return policy; } private static T DeserializeJson<T>(string json) { using MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(json)); DataContractJsonSerializer dataContractJsonSerializer = new DataContractJsonSerializer(typeof(T)); return (T)dataContractJsonSerializer.ReadObject(stream); } private static void CreateText(GameObject parent, string message, Vector2 position, int fontSize = 20, TextAnchor alignment = 4, string hexColor = "#FFFFFF", Color? backgroundColor = null) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_000c: Expected O, but got Unknown //IL_0035: Unknown result type (might be due to invalid IL or missing references) //IL_0040: Unknown result type (might be due to invalid IL or missing references) //IL_005d: Unknown result type (might be due to invalid IL or missing references) //IL_0069: 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_0096: Expected O, but got Unknown //IL_00a3: Unknown result type (might be due to invalid IL or missing references) //IL_00c3: 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) GameObject val = new GameObject("TextElement"); Text val2 = val.AddComponent<Text>(); val2.text = message; val2.font = Resources.GetBuiltinResource<Font>("Arial.ttf"); val2.fontSize = fontSize; val2.alignment = alignment; ((Graphic)val2).color = HexToColor(hexColor); RectTransform component = ((Component)val2).GetComponent<RectTransform>(); component.sizeDelta = new Vector2(460f, 100f); component.anchoredPosition = position; ((Transform)component).SetParent(parent.transform, false); if (backgroundColor.HasValue) { GameObject val3 = new GameObject("Background"); Image val4 = val3.AddComponent<Image>(); ((Graphic)val4).color = backgroundColor.Value; RectTransform component2 = val3.GetComponent<RectTransform>(); component2.sizeDelta = new Vector2(220f, 60f); component2.anchoredPosition = position; ((Transform)component2).SetParent(parent.transform, false); ((Component)val2).transform.SetParent(val3.transform, false); } } private static Color HexToColor(string hex) { //IL_0012: Unknown result type (might be due to invalid IL or missing references) //IL_0017: Unknown result type (might be due to invalid IL or missing references) //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) //IL_001a: Unknown result type (might be due to invalid IL or missing references) Color result = default(Color); if (ColorUtility.TryParseHtmlString(hex, ref result)) { return result; } return Color.white; } } public static class GlobalInputManager { private static readonly Dictionary<KeyCode, Action> keyActions = new Dictionary<KeyCode, Action>(); public static void ListenForKeys(KeyCode key, Action action) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_0019: Unknown result type (might be due to invalid IL or missing references) if (!keyActions.ContainsKey(key)) { keyActions[key] = action; } } public static void StopListeningForKeys(KeyCode key) { //IL_0006: 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) if (keyActions.ContainsKey(key)) { keyActions.Remove(key); } } public static void StopAllListening() { keyActions.Clear(); } public static void Update() { //IL_002e: Unknown result type (might be due to invalid IL or missing references) if (keyActions.Count == 0) { return; } foreach (KeyValuePair<KeyCode, Action> keyAction in keyActions) { if (Input.GetKeyDown(keyAction.Key)) { keyAction.Value?.Invoke(); } } } } [HarmonyPatch] public class RoundDirectorPatches { private static readonly FieldRef<RoundDirector, int> extractionPointsCompletedRef = AccessTools.FieldRefAccess<RoundDirector, int>("extractionPointsCompleted"); private static readonly FieldRef<RoundDirector, int> extractionPointsRef = AccessTools.FieldRefAccess<RoundDirector, int>("extractionPoints"); [HarmonyPatch(typeof(RoundDirector), "ExtractionCompleted")] [HarmonyPostfix] public static void ExtractionCompletedPostfix(RoundDirector __instance) { DanosStaticStore.statsStore.RunStats.extractions_completed = extractionPointsCompletedRef.Invoke(__instance); } [HarmonyPatch(typeof(RoundDirector), "StartRoundLogic")] [HarmonyPostfix] public static void StartRoundLogicPostfix(RoundDirector __instance, int value) { DanosStaticStore.statsStore.RunStats.extractions_on_map = extractionPointsRef.Invoke(__instance); } [HarmonyPatch(typeof(ExtractionPoint), "HaulGoalSetRPC")] [HarmonyPostfix] public static void StartRoundLogicPostfix(ExtractionPoint __instance, int value) { DanosRunStats runStats = DanosStaticStore.statsStore.RunStats; runStats.extraction_goals_csv = runStats.extraction_goals_csv + value + ","; } } [HarmonyPatch] public class RunPatches { [HarmonyPatch(typeof(RunManager), "UpdateLevel")] [HarmonyPostfix] public static void UpdateLevelPostFix(string _levelName, int _levelsCompleted, bool _gameOver) { if (!DanosUtils.GetHostSteamID().Equals(DanosUtils.GetMySteamID())) { CombinedLevelLogic(_levelName, _levelsCompleted, _gameOver); } } [HarmonyPatch(typeof(RunManager), "ChangeLevel")] [HarmonyPostfix] public static void ChangeLevelPostFix(bool _completedLevel, bool _levelFailed, ChangeLevelType _changeLevelType = 0) { if (DanosUtils.GetHostSteamID().Equals(DanosUtils.GetMySteamID())) { RunManager instance = RunManager.instance; if ((Object)(object)instance != (Object)null) { CombinedLevelLogic(((Object)instance.levelCurrent).name, instance.levelsCompleted, (Object)(object)RunManager.instance.levelCurrent == (Object)(object)RunManager.instance.levelArena && _levelFailed && (Object)(object)RunManager.instance.levelCurrent != (Object)(object)RunManager.instance.levelShop && (Object)(object)RunManager.instance.levelCurrent != (Object)(object)RunManager.instance.levelLobby); } } } [HarmonyPatch(typeof(TruckScreenText), "Start")] [HarmonyPostfix] public static void Postfix(TruckScreenText __instance) { string mySteamID = DanosUtils.GetMySteamID(); if (string.IsNullOrEmpty(mySteamID)) { Debug.LogError((object)"Could not get my steam id"); return; } if (!long.TryParse(mySteamID, out var _)) { Debug.LogError((object)"Could not parse steam id as long"); return; } string hostSteamID = DanosUtils.GetHostSteamID(); long result2; if (string.IsNullOrEmpty(hostSteamID)) { Debug.LogError((object)"Could not get host steam id"); } else if (!long.TryParse(hostSteamID, out result2)) { Debug.LogError((object)"Could not parse host steam id as long"); } else { DanosStaticStore.InitializeStatsStore(); } } public static void CombinedLevelLogic(string _levelName, int _levelsCompleted, bool _gameOver) { if (DanosStaticStore.statsStore != null) { DanosStaticStore.statsStore.RunStats.completed_levels = _levelsCompleted; } if ((Object)(object)RunManager.instance == (Object)null) { Debug.LogError((object)"RunManager instance is null"); } else if (RunManager.instance.levels == null) { Debug.LogError((object)"RunManager levels is null"); } else if (_levelName == ((Object)RunManager.instance.levelLobbyMenu).name) { DanosStaticStore.ResetStatsStore(); } else if (_levelName == ((Object)RunManager.instance.levelShop).name) { RoundEnded("Success"); } else if (_levelName == ((Object)RunManager.instance.levelArena).name) { RoundEnded("GameOver"); } else { if (_levelName == ((Object)RunManager.instance.levelRecording).name) { return; } Debug.Log((object)("Level: " + _levelName)); foreach (Level level in RunManager.instance.levels) { if (((Object)level).name == _levelName) { DanosStaticStore.ResetStatsStore(); break; } } } } public static void RoundEnded(string a_reason) { DanosStaticStore.statsStore.RoundEnded = DateTimeOffset.UtcNow.ToUnixTimeSeconds(); DanosStaticStore.statsStore.RunEndReason = a_reason; DanosStaticStore.SendStatsToAPI(); DanosStaticStore.ResetStatsStore(); } } } namespace REPOStats_Mod.Data { internal class DanosCustomMenuManager : MonoBehaviour { private static REPOPopupPage challengesPage; private static List<REPOButton> challengeButtons = new List<REPOButton>(); private const string ApiUrl = "https://repo-api.splitstats.io/api/challenges"; private const string DiscordInviteUrl = "https://discord.gg/vPJtKhYAFe"; public static void Initialize() { //IL_0025: 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_003e: Expected O, but got Unknown MenuAPI.AddElementToEscapeMenu((REPOElement)new REPOButton("REPOStats Challenges", (Action)delegate { CreateChallengesPage().OpenPage(false); }), new Vector2(356f, 86f)); } private static REPOSimplePage CreateChallengesPage() { //IL_0018: 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_0074: 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_008d: Expected O, but got Unknown //IL_0099: Unknown result type (might be due to invalid IL or missing references) //IL_009f: Expected O, but got Unknown //IL_00b8: Unknown result type (might be due to invalid IL or missing references) //IL_00e1: Unknown result type (might be due to invalid IL or missing references) challengesPage = null; challengeButtons.Clear(); challengesPage = new REPOPopupPage("REPOStats Challenges", (Action<REPOPopupPage>)null).SetBackgroundDimming(true).SetMaskPadding((Padding?)new Padding(0f, 0f, 0f, 0f)); ((REPOSimplePage)challengesPage).AddElementToPage((REPOElement)new REPOButton("Back", (Action)delegate { ((REPOSimplePage)challengesPage).ClosePage(true); }), new Vector2(77f, 34f)); for (int i = 0; i < 5; i++) { REPOButton val = new REPOButton("Loading...", (Action)null); ((REPOSimplePage)challengesPage).AddElementToPage((REPOElement)(object)val, new Vector2(100f, 250f - (float)i * 50f)); challengeButtons.Add(val); } ChallengeFetcher challengeFetcher = new GameObject("ChallengeFetcher").AddComponent<ChallengeFetcher>(); challengeFetcher.StartFetching(); return (REPOSimplePage)(object)challengesPage; } public static void UpdateChallengeButtons(List<string> challenges) { //IL_0016: Unknown result type (might be due to invalid IL or missing references) //IL_001c: Expected O, but got Unknown //IL_0036: Unknown result type (might be due to invalid IL or missing references) float num = 250f; float num2 = 50f; while (challengeButtons.Count < challenges.Count) { REPOButton val = new REPOButton("Loading...", (Action)null); ((REPOSimplePage)challengesPage).AddElementToPage((REPOElement)(object)val, new Vector2(250f, num - (float)challengeButtons.Count * num2)); challengeButtons.Add(val); } for (int i = 0; i < challengeButtons.Count; i++) { if (i < challenges.Count) { string text = challenges[i]; if (text == "Click here to join!") { challengeButtons[i].SetText(text).SetOnClick((Action)delegate { Application.OpenURL("https://discord.gg/vPJtKhYAFe"); }); } else { challengeButtons[i].SetText(text); } } else { challengeButtons[i].SetText(""); } } } } public class ChallengeFetcher : MonoBehaviour { [Serializable] private class ChallengeList { public List<string> challenges; } [CompilerGenerated] private sealed class <FetchChallenges>d__3 : IEnumerator<object>, IEnumerator, IDisposable { private int <>1__state; private object <>2__current; public ChallengeFetcher <>4__this; private string <apiUrl>5__1; private string <ApiUrlWSteam>5__2; private UnityWebRequest <request>5__3; private string <jsonResponse>5__4; private List<string> <challenges>5__5; object IEnumerator<object>.Current { [DebuggerHidden] get { return <>2__current; } } object IEnumerator.Current { [DebuggerHidden] get { return <>2__current; } } [DebuggerHidden] public <FetchChallenges>d__3(int <>1__state) { this.<>1__state = <>1__state; } [DebuggerHidden] void IDisposable.Dispose() { int num = <>1__state; if (num == -3 || num == 1) { try { } finally { <>m__Finally1(); } } <apiUrl>5__1 = null; <ApiUrlWSteam>5__2 = null; <request>5__3 = null; <jsonResponse>5__4 = null; <challenges>5__5 = null; <>1__state = -2; } private bool MoveNext() { //IL_00af: Unknown result type (might be due to invalid IL or missing references) //IL_00b5: Invalid comparison between Unknown and I4 try { switch (<>1__state) { default: return false; case 0: <>1__state = -1; <apiUrl>5__1 = Encoding.UTF8.GetString(Convert.FromBase64String("aHR0cHM6Ly9yZXBvLWFwaS5zcGxpdHN0YXRzLmlvL2FwaS9jaGFsbGVuZ2Vz")); <ApiUrlWSteam>5__2 = $"{<apiUrl>5__1}?steamid={<>4__this.mySteamId}"; <request>5__3 = UnityWebRequest.Get(<ApiUrlWSteam>5__2); <>1__state = -3; <>2__current = <request>5__3.SendWebRequest(); <>1__state = 1; return true; case 1: <>1__state = -3; if ((int)<request>5__3.result != 1) { Debug.LogError((object)("Failed to fetch challenges: " + <request>5__3.error)); DanosCustomMenuManager.UpdateChallengeButtons(new List<string> { "Error loading challenges." }); } else { <jsonResponse>5__4 = <request>5__3.downloadHandler.text; <challenges>5__5 = <>4__this.ParseChallenges(<jsonResponse>5__4); DanosCustomMenuManager.UpdateChallengeButtons(<challenges>5__5); <jsonResponse>5__4 = null; <challenges>5__5 = null; } <>m__Finally1(); <request>5__3 = null; Object.Destroy((Object)(object)((Component)<>4__this).gameObject); return false; } } catch { //try-fault ((IDisposable)this).Dispose(); throw; } } bool IEnumerator.MoveNext() { //ILSpy generated this explicit interface implementation from .override directive in MoveNext return this.MoveNext(); } private void <>m__Finally1() { <>1__state = -1; if (<request>5__3 != null) { ((IDisposable)<request>5__3).Dispose(); } } [DebuggerHidden] void IEnumerator.Reset() { throw new NotSupportedException(); } } private const string ApiUrl = "aHR0cHM6Ly9yZXBvLWFwaS5zcGxpdHN0YXRzLmlvL2FwaS9jaGFsbGVuZ2Vz"; private long mySteamId; public void StartFetching() { mySteamId = 0L; string mySteamID = DanosUtils.GetMySteamID(); if (string.IsNullOrEmpty(mySteamID)) { Debug.LogError((object)"Could not get my steam id"); } if (!long.TryParse(mySteamID, out mySteamId)) { Debug.LogError((object)"Could not parse steam id as long"); } ((MonoBehaviour)this).StartCoroutine(FetchChallenges()); } [IteratorStateMachine(typeof(<FetchChallenges>d__3))] private IEnumerator FetchChallenges() { //yield-return decompiler failed: Unexpected instruction in Iterator.Dispose() return new <FetchChallenges>d__3(0) { <>4__this = this }; } private List<string> ParseChallenges(string jsonResponse) { try { return JsonUtility.FromJson<ChallengeList>("{\"challenges\": " + jsonResponse + "}").challenges; } catch (Exception ex) { Debug.LogError((object)("Error parsing challenge data: " + ex.Message)); return new List<string> { "Failed to load challenges." }; } } } [DataContract] public class DanosDeathContainer { [DataMember] public string CauseOfDeath { get; set; } = ""; [DataMember] public long DeathTime { get; set; } } public class DanosPatchConfiguration { public string TargetClass { get; set; } public string TargetMethod { get; set; } public string PostfixMethod { get; set; } } public static class DanosPatchManager { public static List<DanosPatchConfiguration> GetPatchConfigurations() { return new List<DanosPatchConfiguration>(); } } [DataContract] public class DanosRunStats { [DataMember] public int extractions_completed { get; set; } = 0; [DataMember] public int extractions_on_map { get; set; } = 0; [DataMember] public bool failed { get; set; } = false; [DataMember] public int top_extraction_target { get; set; } = 0; [DataMember] public int take_home_money { get; set; } = 0; [DataMember] public int total_money { get; set; } = 0; [DataMember] public int completed_levels { get; set; } = 0; [DataMember] public string extraction_goals_csv { get; set; } = ""; } public static class DanosStaticStore { public static long lastSentStats = 0L; public static DanosStatsStore statsStore = new DanosStatsStore(); public static void SendStatsToAPI() { if (CheckStatsStore()) { Debug.Log((object)"Sending stats to API"); DanosStatSender.Instance.SendStats(statsStore); } Debug.Log((object)"Resetting stats store"); ResetStatsStore(); lastSentStats = DateTimeOffset.UtcNow.ToUnixTimeSeconds(); } public static bool CheckStatsStore() { if (statsStore == null) { return false; } if (statsStore.MySteamId <= 1000) { return false; } if (statsStore.RoundStarted <= 0) { return false; } if (statsStore.RoundEnded <= 0) { return false; } if (statsStore.RoundEnded < statsStore.RoundStarted) { return false; } return true; } public static void ResetStatsStore() { statsStore = new DanosStatsStore(); } public static void InitializeStatsStore() { ResetStatsStore(); string mySteamID = DanosUtils.GetMySteamID(); if (string.IsNullOrEmpty(mySteamID)) { Debug.LogError((object)"Could not get my steam id"); return; } if (!long.TryParse(mySteamID, out var result)) { Debug.LogError((object)"Could not parse steam id as long"); return; } string hostSteamID = DanosUtils.GetHostSteamID(); Debug.Log((object)("Host: " + hostSteamID)); if (string.IsNullOrEmpty(hostSteamID)) { Debug.LogError((object)"Could not get host steam id"); return; } if (!long.TryParse(hostSteamID, out var result2)) { Debug.LogError((object)"Could not parse host steam id as long"); return; } statsStore.MySteamId = result; statsStore.LobbyHash = DanosUtils.GetLobbyHash(); statsStore.isHost = result == result2; statsStore.RoundStarted = DateTimeOffset.UtcNow.ToUnixTimeSeconds(); statsStore.Deaths = new List<DanosDeathContainer>(); statsStore.RunStats = new DanosRunStats(); RunManager instance = RunManager.instance; if ((Object)(object)instance != (Object)null) { statsStore.LevelName = ((Object)instance.levelCurrent).name; } } } public class DanosStatSender : MonoBehaviour { [CompilerGenerated] private sealed class <>c__DisplayClass4_0 { public Task<HttpResponseMessage> requestTask; internal bool <PostStatsCoroutine>b__0() { return requestTask.IsCompleted; } } [CompilerGenerated] private sealed class <PostStatsCoroutine>d__4 : IEnumerator<object>, IEnumerator, IDisposable { private int <>1__state; private object <>2__current; public DanosStatsStore stats; public DanosStatSender <>4__this; private string <encodedUrl>5__1; private string <apiUrl>5__2; private string <json>5__3; private HttpClient <client>5__4; private <>c__DisplayClass4_0 <>8__5; private HttpContent <content>5__6; object IEnumerator<object>.Current { [DebuggerHidden] get { return <>2__current; } } object IEnumerator.Current { [DebuggerHidden] get { return <>2__current; } } [DebuggerHidden] public <PostStatsCoroutine>d__4(int <>1__state) { this.<>1__state = <>1__state; } [DebuggerHidden] void IDisposable.Dispose() { int num = <>1__state; if (num == -3 || num == 1) { try { } finally { <>m__Finally1(); } } <encodedUrl>5__1 = null; <apiUrl>5__2 = null; <json>5__3 = null; <client>5__4 = null; <>8__5 = null; <content>5__6 = null; <>1__state = -2; } private bool MoveNext() { //IL_012f: Unknown result type (might be due to invalid IL or missing references) //IL_0139: Expected O, but got Unknown try { switch (<>1__state) { default: return false; case 0: <>1__state = -1; Debug.Log((object)"Posting stats to API"); <encodedUrl>5__1 = "aHR0cHM6Ly9yZXBvLWFwaS5zcGxpdHN0YXRzLmlvL2FwaS9wb3N0Z2FtZS9zZW5kc3RhdHM="; <apiUrl>5__2 = Encoding.UTF8.GetString(Convert.FromBase64String(<encodedUrl>5__1)); <json>5__3 = <>4__this.SerializeToJson(stats); <client>5__4 = new HttpClient(); <>1__state = -3; <>8__5 = new <>c__DisplayClass4_0(); <client>5__4.DefaultRequestHeaders.Accept.Clear(); <client>5__4.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); <client>5__4.DefaultRequestHeaders.Add("XAuthCode", "cmVwb3N0YXRzbGt0b3A0MzI="); <content>5__6 = new StringContent(<json>5__3, Encoding.UTF8, "application/json"); <>8__5.requestTask = <client>5__4.PostAsync(<apiUrl>5__2, <content>5__6); <>2__current = (object)new WaitUntil((Func<bool>)(() => <>8__5.requestTask.IsCompleted)); <>1__state = 1; return true; case 1: <>1__state = -3; <>8__5 = null; <content>5__6 = null; <>m__Finally1(); <client>5__4 = null; return false; } } catch { //try-fault ((IDisposable)this).Dispose(); throw; } } bool IEnumerator.MoveNext() { //ILSpy generated this explicit interface implementation from .override directive in MoveNext return this.MoveNext(); } private void <>m__Finally1() { <>1__state = -1; if (<client>5__4 != null) { ((IDisposable)<client>5__4).Dispose(); } } [DebuggerHidden] void IEnumerator.Reset() { throw new NotSupportedException(); } } private static DanosStatSender _instance; public static DanosStatSender Instance { get { //IL_0038: Unknown result type (might be due to invalid IL or missing references) //IL_003e: Expected O, but got Unknown if ((Object)(object)_instance == (Object)null) { _instance = Object.FindObjectOfType<DanosStatSender>(); if ((Object)(object)_instance != (Object)null) { return _instance; } GameObject val = new GameObject("DanosStatSender"); _instance = val.AddComponent<DanosStatSender>(); Object.DontDestroyOnLoad((Object)(object)val); } return _instance; } } public void SendStats(DanosStatsStore stats) { ((MonoBehaviour)this).StartCoroutine(PostStatsCoroutine(stats)); } [IteratorStateMachine(typeof(<PostStatsCoroutine>d__4))] private IEnumerator PostStatsCoroutine(DanosStatsStore stats) { //yield-return decompiler failed: Unexpected instruction in Iterator.Dispose() return new <PostStatsCoroutine>d__4(0) { <>4__this = this, stats = stats }; } private string SerializeToJson(DanosStatsStore stats) { using MemoryStream memoryStream = new MemoryStream(); DataContractJsonSerializer dataContractJsonSerializer = new DataContractJsonSerializer(typeof(DanosStatsStore)); dataContractJsonSerializer.WriteObject(memoryStream, stats); return Encoding.UTF8.GetString(memoryStream.ToArray()); } } [DataContract] public class DanosStatsStore { [DataMember] public long RoundStarted { get; set; } = 0L; [DataMember] public long RoundEnded { get; set; } = 0L; [DataMember] public string LevelName { get; set; } = ""; [DataMember] public string LobbyHash { get; set; } = ""; [DataMember] public string ModVersion { get; set; } = "0.5.3"; [DataMember] public string GameVersion { get; set; } = "Unknown"; [DataMember] public string RunEndReason { get; set; } = ""; [DataMember] public long MySteamId { get; set; } = 0L; [DataMember] public bool isHost { get; set; } = false; [DataMember] public List<DanosDeathContainer> Deaths { get; set; } = new List<DanosDeathContainer>(); [DataMember] public DanosRunStats RunStats { get; set; } = new DanosRunStats(); } public static class DanosUtils { public static string GetHostSteamID() { try { List<PlayerAvatar> list = SemiFunc.PlayerGetAll(); if (list == null || list.Count == 0) { return string.Empty; } foreach (PlayerAvatar item in SemiFunc.PlayerGetAll()) { if ((Object)(object)item != (Object)null && (Object)(object)item.photonView != (Object)null && item.photonView.Owner.IsMasterClient) { return SemiFunc.PlayerGetSteamID(item); } } return string.Empty; } catch (Exception) { return string.Empty; } } public static string GetMySteamID() { foreach (PlayerAvatar item in SemiFunc.PlayerGetAll()) { if ((Object)(object)item != (Object)null && item.photonView.IsMine) { return SemiFunc.PlayerGetSteamID(item); } } return string.Empty; } public static string GetLobbyHash() { List<string> list = new List<string>(); string hostSteamID = GetHostSteamID(); foreach (PlayerAvatar item in SemiFunc.PlayerGetAll()) { if ((Object)(object)item != (Object)null) { string text = SemiFunc.PlayerGetSteamID(item); if (!string.IsNullOrEmpty(text) && text != hostSteamID) { list.Add(text); } } } if (!string.IsNullOrEmpty(hostSteamID)) { list.Insert(0, hostSteamID); } list.Sort(); string input = string.Join(",", list); return ComputeSHA256(input); } private static string ComputeSHA256(string input) { using SHA256 sHA = SHA256.Create(); byte[] array = sHA.ComputeHash(Encoding.UTF8.GetBytes(input)); return BitConverter.ToString(array).Replace("-", "").ToLower(); } } [DataContract] public class PolicyVersion { [DataMember(Name = "version")] public string Version { get; set; } = "0.0.0"; [DataMember(Name = "lastUpdated")] public string LastUpdatedRaw { get; set; } = "2025-03-06"; [DataMember(Name = "descriptionOfChanges")] public string DescriptionOfChanges { get; set; } = "Newly drafted policy to clear some things up."; public DateTime LastUpdated { get { if (DateTime.TryParseExact(LastUpdatedRaw, "yyyy-MM-dd", CultureInfo.InvariantCulture, DateTimeStyles.None, out var result)) { return result; } return DateTime.MinValue; } } public string LastUpdatedDaysAgo => $"{(DateTime.UtcNow - LastUpdated).Days} day(s) ago"; } }
plugins/darmuh-FovUpdate/FovUpdate.dll
Decompiled 2 months agousing System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Reflection; using System.Reflection.Emit; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using System.Security; using System.Security.Permissions; using BepInEx; using BepInEx.Configuration; using BepInEx.Logging; using HarmonyLib; using Microsoft.CodeAnalysis; using UnityEngine; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: AssemblyTitle("FovUpdate")] [assembly: AssemblyFileVersion("0.2.3")] [assembly: AssemblyInformationalVersion("0.2.3")] [assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("0.2.3.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 FovUpdate { public static class FovConfig { internal static ConfigEntry<bool> DeveloperLogging; internal static ConfigEntry<float> UserDefinedFov; internal static ConfigEntry<float> UserCrouchFov; internal static ConfigEntry<float> UserSprintFov; public static ConfigEntry<bool> AspectRatioFix; internal static void Init() { //IL_0020: Unknown result type (might be due to invalid IL or missing references) //IL_002a: 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 //IL_00a2: Unknown result type (might be due to invalid IL or missing references) //IL_00ac: Expected O, but got Unknown //IL_00e3: Unknown result type (might be due to invalid IL or missing references) //IL_00ed: Expected O, but got Unknown DeveloperLogging = ((BaseUnityPlugin)Plugin.instance).Config.Bind<bool>("Debug", "Developer Logging", false, new ConfigDescription("Enable this to see developer logging output", (AcceptableValueBase)null, Array.Empty<object>())); UserDefinedFov = ((BaseUnityPlugin)Plugin.instance).Config.Bind<float>("Settings", "Fov", 70f, new ConfigDescription("Set this to desired Fov value (standard gameplay)", (AcceptableValueBase)(object)new AcceptableValueRange<float>(45f, 140f), Array.Empty<object>())); UserCrouchFov = ((BaseUnityPlugin)Plugin.instance).Config.Bind<float>("Settings", "CrouchFov", 55f, new ConfigDescription("Set this to desired Fov value for when the player is crouched (tumble mode)", (AcceptableValueBase)(object)new AcceptableValueRange<float>(45f, 140f), Array.Empty<object>())); UserSprintFov = ((BaseUnityPlugin)Plugin.instance).Config.Bind<float>("Settings", "SprintFov", 20f, new ConfigDescription("Set this to desired modifier for your fov when sprinting.\nThis number will be added on to your regular fov when you start sprinting.\nDefault is vanilla (20)", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 100f), Array.Empty<object>())); AspectRatioFix = ((BaseUnityPlugin)Plugin.instance).Config.Bind<bool>("Settings", "Aspect-ratio fix on/off", false, "Set this to true to enable Oksamies' UltrawideOrLongFix for widescreen compatibility"); } } [HarmonyPatch(typeof(CameraZoom), "Awake")] public class CameraPatchThings { public static List<Camera> playerCams = new List<Camera>(); public static void Prefix(CameraZoom __instance) { if (ShouldChangeFov()) { playerCams.RemoveAll((Camera c) => (Object)(object)c == (Object)null); CollectionExtensions.Do<Camera>((IEnumerable<Camera>)__instance.cams, (Action<Camera>)delegate(Camera x) { playerCams.Add(x); Plugin.Spam($"Original Fov of {((Object)x).name} is {x.fieldOfView}"); x.fieldOfView = FovConfig.UserDefinedFov.Value; Plugin.Spam($"Field of view for {((Object)x).name} set to {FovConfig.UserDefinedFov.Value}"); }); __instance.zoomPrev = FovConfig.UserDefinedFov.Value; __instance.zoomNew = FovConfig.UserDefinedFov.Value; __instance.zoomCurrent = FovConfig.UserDefinedFov.Value; __instance.playerZoomDefault = FovConfig.UserDefinedFov.Value; __instance.SprintZoom = FovConfig.UserSprintFov.Value; } } internal static bool ShouldChangeFov() { if (SemiFunc.IsMainMenu()) { return false; } if (GameDirector.instance.PlayerList.Count <= 0) { return false; } if ((Object)(object)CameraNoPlayerTarget.instance == (Object)null) { return true; } if (((Behaviour)CameraNoPlayerTarget.instance).enabled) { return false; } return true; } } [HarmonyPatch(typeof(GraphicsManager), "Update")] public class UltraWideSupport { public static float previousAspectRatio; public static float currentAspectRatio; public static readonly float defaultAspectRatio = 1.7777778f; public static List<RectTransform> Rects = new List<RectTransform>(); public static void Postfix(GraphicsManager __instance) { if (!FovConfig.AspectRatioFix.Value || __instance.fullscreenCheckTimer > 0f) { return; } Rects.RemoveAll((RectTransform r) => (Object)(object)r == (Object)null); bool flag = false; if (Rects.Count == 0) { Rects = ((Component)RenderTextureMain.instance).gameObject.GetComponentsInChildren<RectTransform>().ToList(); flag = true; } currentAspectRatio = (float)Screen.width / (float)Screen.height; if (previousAspectRatio == currentAspectRatio && !flag) { return; } if (currentAspectRatio > defaultAspectRatio) { CollectionExtensions.Do<RectTransform>((IEnumerable<RectTransform>)Rects, (Action<RectTransform>)delegate(RectTransform r) { //IL_0011: Unknown result type (might be due to invalid IL or missing references) r.sizeDelta = new Vector2(428f * currentAspectRatio, 428f); }); } else { CollectionExtensions.Do<RectTransform>((IEnumerable<RectTransform>)Rects, (Action<RectTransform>)delegate(RectTransform r) { //IL_0011: Unknown result type (might be due to invalid IL or missing references) r.sizeDelta = new Vector2(750f, 750f / currentAspectRatio); }); } previousAspectRatio = currentAspectRatio; Plugin.Spam("Updating Aspect Ratio for ultrawide support!"); } } [HarmonyPatch(typeof(PlayerAvatar), "Spawn")] public class SpawnPlayerFov { public static void Postfix(PlayerAvatar __instance) { if (!CameraPatchThings.ShouldChangeFov()) { return; } if (__instance.localCamera.fieldOfView == FovConfig.UserDefinedFov.Value) { Plugin.Spam("Fov already set to correct value"); return; } ((MonoBehaviour)__instance).StartCoroutine(ChatCommandHandler.ForceFovZoomCurve(FovConfig.UserDefinedFov.Value, FovConfig.UserDefinedFov, ((Component)__instance).gameObject)); Plugin.Log.LogMessage((object)$"@SpawnPatch: Fov set to number [ {FovConfig.UserDefinedFov.Value} ]"); if (!((Object)(object)CameraZoom.Instance == (Object)null)) { CameraZoom.Instance.SprintZoom = FovConfig.UserSprintFov.Value; Plugin.Log.LogMessage((object)$"@SpawnPatch: SprintFov set to number [ {FovConfig.UserSprintFov.Value} ]"); } } } [HarmonyPatch(typeof(PlayerTumble), "Update")] [HarmonyPriority(0)] public class TumbleAdjustment { private static int replacements; [HarmonyTranspiler] private static IEnumerable<CodeInstruction> TumbleAdjustment_Transpiler(IEnumerable<CodeInstruction> instructions) { Plugin.Log.LogMessage((object)"TumbleAdjustment Transpiler Initialized"); MethodInfo methodInfo = AccessTools.Method("CameraZoom:OverrideZoomSet", (Type[])null, (Type[])null); replacements = 0; instructions = Transpilers.Manipulator(instructions, (Func<CodeInstruction, bool>)((CodeInstruction x) => ChangeThisFloat(x)), (Action<CodeInstruction>)NewInstruction); return instructions; } internal static void NewInstruction(CodeInstruction instruction) { CodeInstruction val = Transpilers.EmitDelegate<Func<float>>((Func<float>)OverrideZoomSpecial); instruction.opcode = val.opcode; instruction.operand = val.operand; checked { replacements++; Plugin.Log.LogMessage((object)$"TumbleAdjustment patched crouchfov config!\n[ {replacements} ] lines changed"); } } internal static bool ChangeThisFloat(CodeInstruction instruction) { if (instruction.opcode != OpCodes.Ldc_R4) { return false; } if (!float.TryParse(instruction.operand.ToString(), out var result)) { return false; } if (result != 55f) { return false; } return true; } internal static float OverrideZoomSpecial() { return FovConfig.UserCrouchFov.Value; } } [HarmonyPatch(typeof(ChatManager), "MessageSend")] public class ChatCommandHandler { [CompilerGenerated] private sealed class <ForceFovZoomCurve>d__6 : IEnumerator<object>, IEnumerator, IDisposable { private int <>1__state; private object <>2__current; public GameObject obj; public float newFov; public bool updateDef; public ConfigEntry<float> configEntry; object IEnumerator<object>.Current { [DebuggerHidden] get { return <>2__current; } } object IEnumerator.Current { [DebuggerHidden] get { return <>2__current; } } [DebuggerHidden] public <ForceFovZoomCurve>d__6(int <>1__state) { this.<>1__state = <>1__state; } [DebuggerHidden] void IDisposable.Dispose() { <>1__state = -2; } private bool MoveNext() { switch (<>1__state) { default: return false; case 0: <>1__state = -1; if ((Object)(object)PlayerAvatar.instance == (Object)null) { return false; } if (changingFov) { return false; } if ((Object)(object)obj == (Object)null) { obj = PlayerController.instance.playerAvatar.gameObject; } CameraZoom.Instance.OverrideZoomSet(newFov, 2f, 1f, 1f, obj, 150); changingFov = true; break; case 1: <>1__state = -1; break; } if ((double)Mathf.Abs(CameraZoom.Instance.zoomCurrent - newFov) > 0.25 && (Object)(object)CameraZoom.Instance.OverrideZoomObject == (Object)(object)obj) { <>2__current = null; <>1__state = 1; return true; } if (updateDef) { CameraZoom.Instance.playerZoomDefault = newFov; } if (configEntry != null) { configEntry.Value = newFov; ((BaseUnityPlugin)Plugin.instance).Config.Save(); } changingFov = false; if ((Object)(object)CameraZoom.Instance.OverrideZoomObject != (Object)(object)obj) { return false; } CameraZoom.Instance.OverrideActive = false; CameraZoom.Instance.OverrideZoomObject = null; CameraZoom.Instance.OverrideZoomPriority = 999; CameraZoom.Instance.OverrideZoomSpeedIn = 1f; CameraZoom.Instance.OverrideZoomSpeedOut = 1f; return false; } bool IEnumerator.MoveNext() { //ILSpy generated this explicit interface implementation from .override directive in MoveNext return this.MoveNext(); } [DebuggerHidden] void IEnumerator.Reset() { throw new NotSupportedException(); } } private static string lastMsg = ":o"; private static bool changingFov = false; public static bool Prefix(ChatManager __instance) { if (__instance.chatMessage == lastMsg) { return true; } Plugin.Spam("Reading chat message - " + __instance.chatMessage); lastMsg = __instance.chatMessage; if (__instance.chatMessage.StartsWith("/fov")) { __instance.AddLetterToChat(" " + HandleFovChange(__instance.chatMessage)); } else if (__instance.chatMessage.StartsWith("/cfov")) { __instance.AddLetterToChat(" " + HandleCrouchFovChange(__instance.chatMessage)); } else if (__instance.chatMessage.StartsWith("/sfov")) { __instance.AddLetterToChat(" " + HandleSprintFovChange(__instance.chatMessage)); } return true; } internal static string HandleSprintFovChange(string message) { string[] array = message.Split(' '); if (array.Length == 1) { Plugin.Log.LogMessage((object)("Invalid sprint fov message format given - [ " + message + " ]")); return "No number specified for /sfov!"; } string text = array[1]; if (float.TryParse(text, out var result)) { if (result < 0f || result > 100f) { return $"Unable to set sprint fov to {result} (out of range)"; } CameraZoom.Instance.SprintZoom = result; FovConfig.UserSprintFov.Value = result; Plugin.Log.LogMessage((object)$"SprintFov set to number [ {result} ]"); return $"Sprint fov set to {result}"; } Plugin.Log.LogMessage((object)("Unable to parse value from " + text + "!")); return "Unable to parse value from " + text + "!"; } internal static string HandleCrouchFovChange(string message) { if (CameraZoom.Instance.OverrideActive && !PlayerAvatar.instance.tumble.isTumbling) { Plugin.Log.LogMessage((object)"Unable to update crouch fov, camera OverrideActive is true! (not tumbling)"); lastMsg = ""; return "Unable to change crouch fov, overriden by outside entity!"; } string[] array = message.Split(' '); if (array.Length == 1) { Plugin.Log.LogMessage((object)("Invalid crouch fov message format given - [ " + message + " ]")); return "No number specified for /cfov!"; } string text = array[1]; if (float.TryParse(text, out var result)) { if (result < 45f || result > 140f) { return $"Unable to set crouch fov to {result} (out of range)"; } if (PlayerAvatar.instance.isTumbling) { ((MonoBehaviour)ChatManager.instance).StartCoroutine(ForceFovZoomCurve(result, FovConfig.UserCrouchFov, ((Component)PlayerAvatar.instance.tumble).gameObject, updateDef: false)); } else { FovConfig.UserCrouchFov.Value = result; } Plugin.Log.LogMessage((object)$"CrouchFov set to number [ {result} ]"); return $"crouch fov set to {result}"; } Plugin.Log.LogMessage((object)("Unable to parse value from " + text + "!")); return "Unable to parse value from " + text + "!"; } internal static string HandleFovChange(string message) { if (CameraZoom.Instance.OverrideActive && !PlayerAvatar.instance.isTumbling) { Plugin.Log.LogMessage((object)"Unable to update fov, camera OverrideActive is true!"); lastMsg = ""; return "Unable to change fov, camera is overriden!"; } string[] array = message.Split(' '); if (array.Length == 1) { Plugin.Log.LogMessage((object)("Invalid fov message format given - [ " + message + " ]")); return "No number specified for /fov!"; } string text = array[1]; if (float.TryParse(text, out var result)) { if (result < 45f || result > 140f) { return $"Unable to set fov to {result} (out of range)"; } if (PlayerAvatar.instance.isTumbling) { CameraZoom.Instance.playerZoomDefault = result; return $"fov will be {result} when you get up"; } ((MonoBehaviour)ChatManager.instance).StartCoroutine(ForceFovZoomCurve(result, FovConfig.UserDefinedFov, ((Component)PlayerAvatar.instance).gameObject)); Plugin.Log.LogMessage((object)$"Fov set to number [ {result} ]"); return $"fov set to {result}"; } Plugin.Log.LogMessage((object)("Unable to parse value from " + text + "!")); return "Unable to parse value from " + text + "!"; } [IteratorStateMachine(typeof(<ForceFovZoomCurve>d__6))] internal static IEnumerator ForceFovZoomCurve(float newFov, ConfigEntry<float> configEntry, GameObject obj = null, bool updateDef = true) { //yield-return decompiler failed: Unexpected instruction in Iterator.Dispose() return new <ForceFovZoomCurve>d__6(0) { newFov = newFov, configEntry = configEntry, obj = obj, updateDef = updateDef }; } } [BepInPlugin("com.github.darmuh.FovUpdate", "FovUpdate", "0.2.3")] public class Plugin : BaseUnityPlugin { public static class PluginInfo { public const string PLUGIN_GUID = "com.github.darmuh.FovUpdate"; public const string PLUGIN_NAME = "FovUpdate"; public const string PLUGIN_VERSION = "0.2.3"; } public static Plugin instance; internal static ManualLogSource Log; private void Awake() { instance = this; Log = ((BaseUnityPlugin)this).Logger; Log.LogInfo((object)"FovUpdate is loading with version 0.2.3!"); FovConfig.Init(); ((BaseUnityPlugin)instance).Config.SettingChanged += OnSettingChanged; Harmony.CreateAndPatchAll(Assembly.GetExecutingAssembly(), (string)null); Log.LogInfo((object)"FovUpdate load complete!"); } private void OnSettingChanged(object sender, SettingChangedEventArgs settingChangedArg) { Spam("CONFIG SETTING CHANGE EVENT"); if (settingChangedArg.ChangedSetting == null || (Object)(object)CameraZoom.Instance == (Object)null) { return; } if (settingChangedArg.ChangedSetting == FovConfig.DeveloperLogging || settingChangedArg.ChangedSetting == FovConfig.AspectRatioFix) { Log.LogDebug((object)$"{settingChangedArg.ChangedSetting.Definition.Key} is enabled [ {(bool)settingChangedArg.ChangedSetting.BoxedValue} ]"); } if (settingChangedArg.ChangedSetting == FovConfig.UserSprintFov) { CameraZoom.Instance.SprintZoom = (float)settingChangedArg.ChangedSetting.BoxedValue; Spam($"SprintFov updated to {(float)settingChangedArg.ChangedSetting.BoxedValue}"); } if (settingChangedArg.ChangedSetting == FovConfig.UserDefinedFov) { if (!CameraZoom.Instance.OverrideActive && (Object)(object)CameraNoPlayerTarget.instance == (Object)null) { ((MonoBehaviour)PlayerAvatar.instance).StartCoroutine(ChatCommandHandler.ForceFovZoomCurve((float)settingChangedArg.ChangedSetting.BoxedValue, null, ((Component)PlayerAvatar.instance).gameObject)); } else { CameraZoom.Instance.playerZoomDefault = FovConfig.UserDefinedFov.Value; } Spam($"Fov updated to {(float)settingChangedArg.ChangedSetting.BoxedValue}"); } if (settingChangedArg.ChangedSetting == FovConfig.UserCrouchFov && !((Object)(object)PlayerAvatar.instance == (Object)null) && !((Object)(object)PlayerAvatar.instance.tumble == (Object)null)) { if (CameraZoom.Instance.OverrideActive && PlayerAvatar.instance.tumble.isTumbling) { ((MonoBehaviour)PlayerAvatar.instance).StartCoroutine(ChatCommandHandler.ForceFovZoomCurve((float)settingChangedArg.ChangedSetting.BoxedValue, null, ((Component)PlayerAvatar.instance.tumble).gameObject, updateDef: false)); } Spam($"CrouchFov updated to {(float)settingChangedArg.ChangedSetting.BoxedValue}"); } } internal static void Spam(string message) { if (FovConfig.DeveloperLogging.Value) { Log.LogDebug((object)message); } } internal static void ERROR(string message) { Log.LogError((object)message); } internal static void WARNING(string message) { Log.LogWarning((object)message); } } } namespace System.Runtime.CompilerServices { [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)] internal sealed class IgnoresAccessChecksToAttribute : Attribute { public IgnoresAccessChecksToAttribute(string assemblyName) { } } }
plugins/DirtyGames-DynamicLighting/DynamicLighting.dll.old
Decompiled 2 months agousing System; using System.Collections.Generic; 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 HarmonyLib; 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: IgnoresAccessChecksTo("Assembly-CSharp-firstpass")] [assembly: IgnoresAccessChecksTo("Assembly-CSharp")] [assembly: IgnoresAccessChecksTo("Autodesk.Fbx")] [assembly: IgnoresAccessChecksTo("Facepunch.Steamworks.Win64")] [assembly: IgnoresAccessChecksTo("FbxBuildTestAssets")] [assembly: IgnoresAccessChecksTo("Klattersynth")] [assembly: IgnoresAccessChecksTo("Photon3Unity3D")] [assembly: IgnoresAccessChecksTo("PhotonChat")] [assembly: IgnoresAccessChecksTo("PhotonRealtime")] [assembly: IgnoresAccessChecksTo("PhotonUnityNetworking")] [assembly: IgnoresAccessChecksTo("PhotonUnityNetworking.Utilities")] [assembly: IgnoresAccessChecksTo("PhotonVoice.API")] [assembly: IgnoresAccessChecksTo("PhotonVoice")] [assembly: IgnoresAccessChecksTo("PhotonVoice.PUN")] [assembly: IgnoresAccessChecksTo("SingularityGroup.HotReload.Runtime")] [assembly: IgnoresAccessChecksTo("SingularityGroup.HotReload.Runtime.Public")] [assembly: IgnoresAccessChecksTo("Sirenix.OdinInspector.Attributes")] [assembly: IgnoresAccessChecksTo("Sirenix.Serialization.Config")] [assembly: IgnoresAccessChecksTo("Sirenix.Serialization")] [assembly: IgnoresAccessChecksTo("Sirenix.Utilities")] [assembly: IgnoresAccessChecksTo("Unity.AI.Navigation")] [assembly: IgnoresAccessChecksTo("Unity.Formats.Fbx.Runtime")] [assembly: IgnoresAccessChecksTo("Unity.InputSystem")] [assembly: IgnoresAccessChecksTo("Unity.InputSystem.ForUI")] [assembly: IgnoresAccessChecksTo("Unity.Postprocessing.Runtime")] [assembly: IgnoresAccessChecksTo("Unity.RenderPipelines.Core.Runtime")] [assembly: IgnoresAccessChecksTo("Unity.RenderPipelines.Core.ShaderLibrary")] [assembly: IgnoresAccessChecksTo("Unity.RenderPipelines.ShaderGraph.ShaderGraphLibrary")] [assembly: IgnoresAccessChecksTo("Unity.TextMeshPro")] [assembly: IgnoresAccessChecksTo("Unity.Timeline")] [assembly: IgnoresAccessChecksTo("Unity.VisualScripting.Antlr3.Runtime")] [assembly: IgnoresAccessChecksTo("Unity.VisualScripting.Core")] [assembly: IgnoresAccessChecksTo("Unity.VisualScripting.Flow")] [assembly: IgnoresAccessChecksTo("Unity.VisualScripting.State")] [assembly: IgnoresAccessChecksTo("UnityEngine.ARModule")] [assembly: IgnoresAccessChecksTo("UnityEngine.NVIDIAModule")] [assembly: IgnoresAccessChecksTo("UnityEngine.UI")] [assembly: IgnoresAccessChecksTo("websocket-sharp")] [assembly: AssemblyCompany("DirtyGames")] [assembly: AssemblyConfiguration("Debug")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: AssemblyInformationalVersion("1.0.0")] [assembly: AssemblyProduct("DynamicLighting")] [assembly: AssemblyTitle("DynamicLighting")] [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 DynamicLighting { [BepInPlugin("DirtyGames.DynamicLighting", "DynamicLighting", "1.0.0")] public class DynamicLighting : BaseUnityPlugin { [HarmonyPatch(typeof(EnvironmentDirector), "Setup")] public class EnvironmentPatches { [HarmonyPostfix] private static void ApplyCustomLighting() { //IL_0093: 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) //IL_00d2: Unknown result type (might be due to invalid IL or missing references) //IL_00e1: Unknown result type (might be due to invalid IL or missing references) //IL_0111: Unknown result type (might be due to invalid IL or missing references) //IL_0120: Unknown result type (might be due to invalid IL or missing references) //IL_0150: Unknown result type (might be due to invalid IL or missing references) //IL_015f: Unknown result type (might be due to invalid IL or missing references) //IL_01ce: Unknown result type (might be due to invalid IL or missing references) //IL_01dd: Unknown result type (might be due to invalid IL or missing references) //IL_024c: Unknown result type (might be due to invalid IL or missing references) //IL_025b: Unknown result type (might be due to invalid IL or missing references) //IL_02fb: Unknown result type (might be due to invalid IL or missing references) if (!((Object)(object)LevelGenerator.Instance.Level == (Object)null)) { Level level = LevelGenerator.Instance.Level; string narrativeName = level.NarrativeName; Debug.Log((object)("[DynamicLighting] Processing lighting settings for: " + narrativeName)); if (!Instance.originalFogColors.ContainsKey(narrativeName)) { Instance.InitializeLevelConfig(narrativeName); } Debug.Log((object)"[DynamicLighting] Applying configured settings..."); RenderSettings.ambientSkyColor = ((BaseUnityPlugin)Instance).Config.Bind<Color>("Lighting - " + narrativeName, "AmbientSkyColor", Instance.originalSkyColors[narrativeName], "Sky ambient lighting color").Value; RenderSettings.ambientEquatorColor = ((BaseUnityPlugin)Instance).Config.Bind<Color>("Lighting - " + narrativeName, "AmbientEquatorColor", Instance.originalEquatorColors[narrativeName], "Equator ambient lighting color").Value; RenderSettings.ambientGroundColor = ((BaseUnityPlugin)Instance).Config.Bind<Color>("Lighting - " + narrativeName, "AmbientGroundColor", Instance.originalGroundColors[narrativeName], "Ground ambient lighting color").Value; RenderSettings.ambientLight = ((BaseUnityPlugin)Instance).Config.Bind<Color>("Lighting - " + narrativeName, "AmbientLight", Instance.originalAmbientLights[narrativeName], "General ambient lighting color").Value; RenderSettings.ambientIntensity = ((BaseUnityPlugin)Instance).Config.Bind<float>("Lighting - " + narrativeName, "AmbientIntensity", Instance.originalAmbientIntensity[narrativeName], "Intensity of ambient light").Value; RenderSettings.fogColor = ((BaseUnityPlugin)Instance).Config.Bind<Color>("Fog - " + narrativeName, "FogColor", Instance.originalFogColors[narrativeName], "Fog color").Value; RenderSettings.fogDensity = ((BaseUnityPlugin)Instance).Config.Bind<float>("Fog - " + narrativeName, "FogDensity", Instance.originalFogDensity[narrativeName], "Fog density").Value; RenderSettings.fogMode = ((BaseUnityPlugin)Instance).Config.Bind<FogMode>("Fog - " + narrativeName, "FogMode", Instance.originalFogMode[narrativeName], "Fog mode (Linear, Exponential, ExponentialSquared)").Value; RenderSettings.fogStartDistance = ((BaseUnityPlugin)Instance).Config.Bind<float>("Fog - " + narrativeName, "FogStartDistance", Instance.originalFogStartDistance[narrativeName], "Fog start distance").Value; RenderSettings.fogEndDistance = ((BaseUnityPlugin)Instance).Config.Bind<float>("Fog - " + narrativeName, "FogEndDistance", Instance.originalFogEndDistance[narrativeName], "Fog end distance").Value; if ((Object)(object)Camera.main != (Object)null) { Camera.main.backgroundColor = RenderSettings.fogColor; Debug.Log((object)"[DynamicLighting] Updated camera background to match fog color."); } Debug.Log((object)"[DynamicLighting] Custom lighting and fog settings applied!"); } } } private readonly Dictionary<string, Color> originalFogColors = new Dictionary<string, Color>(); private readonly Dictionary<string, float> originalFogDensity = new Dictionary<string, float>(); private readonly Dictionary<string, FogMode> originalFogMode = new Dictionary<string, FogMode>(); private readonly Dictionary<string, float> originalFogStartDistance = new Dictionary<string, float>(); private readonly Dictionary<string, float> originalFogEndDistance = new Dictionary<string, float>(); private readonly Dictionary<string, Color> originalSkyColors = new Dictionary<string, Color>(); private readonly Dictionary<string, Color> originalEquatorColors = new Dictionary<string, Color>(); private readonly Dictionary<string, Color> originalGroundColors = new Dictionary<string, Color>(); private readonly Dictionary<string, Color> originalAmbientLights = new Dictionary<string, Color>(); private readonly Dictionary<string, float> originalAmbientIntensity = new Dictionary<string, float>(); private readonly Dictionary<string, (Color skyColor, Color equatorColor, Color groundColor, Color ambientLight, float ambientIntensity)> defaultLighting = new Dictionary<string, (Color, Color, Color, Color, float)> { { "Headman Manor", (new Color(0f, 0f, 0.2f, 1f), new Color(0f, 0f, 0.2f, 1f), new Color(0f, 0f, 0f, 1f), new Color(0f, 0f, 0.2f, 1f), 0.6f) }, { "Lobby Menu", (new Color(0f, 0f, 0.2f, 1f), new Color(0f, 0f, 0.2f, 1f), new Color(0f, 0f, 0f, 1f), new Color(0f, 0f, 0.2f, 1f), 1f) }, { "Main Menu", (new Color(0.96f, 0.88f, 0.76f, 1f), new Color(0.79f, 0.64f, 0.45f, 1f), new Color(0.65f, 0.54f, 0.41f, 1f), new Color(0.89f, 0.77f, 0.56f, 1f), 1f) }, { "McJannek Station", (new Color(0f, 0.45f, 0.61f, 1f), new Color(0f, 0.45f, 0.61f, 1f), new Color(0.15f, 0.36f, 0.4f, 1f), new Color(0f, 0.45f, 0.61f, 1f), 0.7f) }, { "Swiftbroom Academy", (new Color(0.29f, 0f, 0.48f, 1f), new Color(0.29f, 0f, 0.48f, 1f), new Color(0f, 0f, 0f, 1f), new Color(0.29f, 0f, 0.48f, 1f), 1f) } }; private readonly Dictionary<string, (Color fogColor, float fogDensity, FogMode fogMode, float fogStart, float fogEnd)> defaultFog = new Dictionary<string, (Color, float, FogMode, float, float)> { { "Headman Manor", (new Color(0.07f, 0.02f, 0f, 1f), 0.15f, (FogMode)2, 0f, 15f) }, { "Lobby Menu", (new Color(0f, 0.03f, 0.13f, 1f), 0.25f, (FogMode)1, 0f, 200f) }, { "Main Menu", (new Color(0.82f, 0.7f, 0.55f, 1f), 0.18f, (FogMode)1, 5f, 200f) }, { "McJannek Station", (new Color(0f, 0f, 0f, 1f), 0.25f, (FogMode)2, 0f, 20f) }, { "Swiftbroom Academy", (new Color(0f, 0f, 0f, 1f), 0.15f, (FogMode)2, 0f, 17f) } }; internal static DynamicLighting Instance { get; private set; } internal static ManualLogSource Logger => Instance._logger; private ManualLogSource _logger => ((BaseUnityPlugin)this).Logger; internal Harmony? Harmony { get; set; } private void Awake() { Instance = this; ((Component)this).gameObject.transform.parent = null; ((Object)((Component)this).gameObject).hideFlags = (HideFlags)61; Patch(); Logger.LogInfo((object)$"{((BaseUnityPlugin)this).Info.Metadata.GUID} v{((BaseUnityPlugin)this).Info.Metadata.Version} has loaded!"); } internal void Patch() { //IL_001a: Unknown result type (might be due to invalid IL or missing references) //IL_001f: Unknown result type (might be due to invalid IL or missing references) //IL_0021: Expected O, but got Unknown //IL_0026: Expected O, but got Unknown if (Harmony == null) { Harmony val = new Harmony(((BaseUnityPlugin)this).Info.Metadata.GUID); Harmony val2 = val; Harmony = val; } Harmony.PatchAll(); } internal void Unpatch() { Harmony? harmony = Harmony; if (harmony != null) { harmony.UnpatchSelf(); } } private void InitializeLevelConfig(string levelName) { //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_003c: Unknown result type (might be due to invalid IL or missing references) //IL_0041: 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_00cf: Unknown result type (might be due to invalid IL or missing references) //IL_0103: Unknown result type (might be due to invalid IL or missing references) //IL_0112: Unknown result type (might be due to invalid IL or missing references) //IL_0146: Unknown result type (might be due to invalid IL or missing references) //IL_0155: Unknown result type (might be due to invalid IL or missing references) //IL_0189: Unknown result type (might be due to invalid IL or missing references) //IL_0198: Unknown result type (might be due to invalid IL or missing references) //IL_020f: Unknown result type (might be due to invalid IL or missing references) //IL_021e: Unknown result type (might be due to invalid IL or missing references) //IL_0295: Unknown result type (might be due to invalid IL or missing references) //IL_02a4: 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) //IL_007c: Unknown result type (might be due to invalid IL or missing references) if (!defaultLighting.ContainsKey(levelName)) { Debug.LogWarning((object)("[DynamicLighting] No predefined values for " + levelName + ". Capturing current in-game settings.")); defaultLighting[levelName] = (RenderSettings.ambientSkyColor, RenderSettings.ambientEquatorColor, RenderSettings.ambientGroundColor, RenderSettings.ambientLight, RenderSettings.ambientIntensity); } if (!defaultFog.ContainsKey(levelName)) { defaultFog[levelName] = (RenderSettings.fogColor, RenderSettings.fogDensity, RenderSettings.fogMode, RenderSettings.fogStartDistance, RenderSettings.fogEndDistance); } originalSkyColors[levelName] = ((BaseUnityPlugin)this).Config.Bind<Color>("Lighting - " + levelName, "AmbientSkyColor", defaultLighting[levelName].skyColor, "Sky ambient lighting color").Value; originalEquatorColors[levelName] = ((BaseUnityPlugin)this).Config.Bind<Color>("Lighting - " + levelName, "AmbientEquatorColor", defaultLighting[levelName].equatorColor, "Equator ambient lighting color").Value; originalGroundColors[levelName] = ((BaseUnityPlugin)this).Config.Bind<Color>("Lighting - " + levelName, "AmbientGroundColor", defaultLighting[levelName].groundColor, "Ground ambient lighting color").Value; originalAmbientLights[levelName] = ((BaseUnityPlugin)this).Config.Bind<Color>("Lighting - " + levelName, "AmbientLight", defaultLighting[levelName].ambientLight, "General ambient lighting color").Value; originalAmbientIntensity[levelName] = ((BaseUnityPlugin)this).Config.Bind<float>("Lighting - " + levelName, "AmbientIntensity", defaultLighting[levelName].ambientIntensity, "Intensity of ambient light").Value; originalFogColors[levelName] = ((BaseUnityPlugin)this).Config.Bind<Color>("Fog - " + levelName, "FogColor", defaultFog[levelName].fogColor, "Fog color").Value; originalFogDensity[levelName] = ((BaseUnityPlugin)this).Config.Bind<float>("Fog - " + levelName, "FogDensity", defaultFog[levelName].fogDensity, "Fog density").Value; originalFogMode[levelName] = ((BaseUnityPlugin)this).Config.Bind<FogMode>("Fog - " + levelName, "FogMode", defaultFog[levelName].fogMode, "Fog mode (Linear, Exponential, ExponentialSquared)").Value; originalFogStartDistance[levelName] = ((BaseUnityPlugin)this).Config.Bind<float>("Fog - " + levelName, "FogStartDistance", defaultFog[levelName].fogStart, "Fog start distance").Value; originalFogEndDistance[levelName] = ((BaseUnityPlugin)this).Config.Bind<float>("Fog - " + levelName, "FogEndDistance", defaultFog[levelName].fogEnd, "Fog end distance").Value; Debug.Log((object)("[DynamicLighting] Config initialized for level: " + levelName)); } } }
plugins/eth9n-Mimic/Mimics.dll
Decompiled 2 months agousing System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; 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 System.Threading.Tasks; using BepInEx; using BepInEx.Logging; using HarmonyLib; using Microsoft.CodeAnalysis; using NAudio.Wave; using Photon.Pun; 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("Mimics")] [assembly: AssemblyConfiguration("Debug")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: AssemblyInformationalVersion("1.0.0")] [assembly: AssemblyProduct("My first plugin")] [assembly: AssemblyTitle("Mimics")] [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 Mimics { public class Mimics : MonoBehaviour { [CompilerGenerated] private sealed class <DestroyAfterDelay>d__28 : IEnumerator<object>, IEnumerator, IDisposable { private int <>1__state; private object <>2__current; public AudioSource audioSource; public float delay; public Mimics <>4__this; object IEnumerator<object>.Current { [DebuggerHidden] get { return <>2__current; } } object IEnumerator.Current { [DebuggerHidden] get { return <>2__current; } } [DebuggerHidden] public <DestroyAfterDelay>d__28(int <>1__state) { this.<>1__state = <>1__state; } [DebuggerHidden] void IDisposable.Dispose() { <>1__state = -2; } private bool MoveNext() { //IL_0026: Unknown result type (might be due to invalid IL or missing references) //IL_0030: Expected O, but got Unknown switch (<>1__state) { default: return false; case 0: <>1__state = -1; <>2__current = (object)new WaitForSeconds(4f); <>1__state = 1; return true; case 1: <>1__state = -1; Object.Destroy((Object)(object)audioSource); log.LogInfo((object)("Destroyed AudioSource after " + delay + " seconds.")); return false; } } bool IEnumerator.MoveNext() { //ILSpy generated this explicit interface implementation from .override directive in MoveNext return this.MoveNext(); } [DebuggerHidden] void IEnumerator.Reset() { throw new NotSupportedException(); } } [CompilerGenerated] private sealed class <RecordAtRandomIntervals>d__10 : IEnumerator<object>, IEnumerator, IDisposable { private int <>1__state; private object <>2__current; public Mimics <>4__this; private int <clipCount>5__1; private float <randomDelay>5__2; object IEnumerator<object>.Current { [DebuggerHidden] get { return <>2__current; } } object IEnumerator.Current { [DebuggerHidden] get { return <>2__current; } } [DebuggerHidden] public <RecordAtRandomIntervals>d__10(int <>1__state) { this.<>1__state = <>1__state; } [DebuggerHidden] void IDisposable.Dispose() { <>1__state = -2; } private bool MoveNext() { //IL_00bd: Unknown result type (might be due to invalid IL or missing references) //IL_00c7: Expected O, but got Unknown switch (<>1__state) { default: return false; case 0: <>1__state = -1; break; case 1: <>1__state = -1; <>4__this.StartRecording(); break; } while (true) { <clipCount>5__1 = Directory.GetFiles(<>4__this.audioFolderPath, "*.wav").Length; if (<clipCount>5__1 < <>4__this.maxClipCount) { break; } log.LogInfo((object)"Maximum clip count reached. Clearing the folder."); <>4__this.ClearAudioFolder(); } <randomDelay>5__2 = Random.Range(30f, 120f); log.LogInfo((object)$"Next recording will start in {<randomDelay>5__2} seconds."); <>2__current = (object)new WaitForSeconds(<randomDelay>5__2); <>1__state = 1; return true; } bool IEnumerator.MoveNext() { //ILSpy generated this explicit interface implementation from .override directive in MoveNext return this.MoveNext(); } [DebuggerHidden] void IEnumerator.Reset() { throw new NotSupportedException(); } } private static readonly ManualLogSource log = Logger.CreateLogSource("Mimics"); public PhotonView photonView; private WaveInEvent waveIn; private int sampleRate = 44100; private float[] audioBuffer; private int bufferPosition = 0; private bool isRecording = false; private string audioFolderPath; private int maxClipCount = 10; private bool fileSaved = false; private HashSet<int> sentChunks = new HashSet<int>(); private List<byte[]> receivedChunks = new List<byte[]>(); private int expectedChunkCount = 0; private void Awake() { photonView = ((Component)this).GetComponent<PhotonView>(); if ((Object)(object)photonView == (Object)null) { log.LogInfo((object)"PhotonView not found on Mimics."); } else if (photonView.IsMine && SemiFunc.RunIsLevel()) { audioFolderPath = Path.Combine(Application.dataPath, "AudioFiles"); Directory.CreateDirectory(audioFolderPath); ((MonoBehaviour)this).StartCoroutine(RecordAtRandomIntervals()); } } [IteratorStateMachine(typeof(<RecordAtRandomIntervals>d__10))] private IEnumerator RecordAtRandomIntervals() { //yield-return decompiler failed: Unexpected instruction in Iterator.Dispose() return new <RecordAtRandomIntervals>d__10(0) { <>4__this = this }; } private void StartRecording() { //IL_003c: Unknown result type (might be due to invalid IL or missing references) //IL_0041: Unknown result type (might be due to invalid IL or missing references) //IL_0049: Unknown result type (might be due to invalid IL or missing references) //IL_0051: Unknown result type (might be due to invalid IL or missing references) //IL_005b: Expected O, but got Unknown //IL_0061: Expected O, but got Unknown if (isRecording) { log.LogInfo((object)"Already recording."); return; } audioBuffer = new float[sampleRate * 2]; bufferPosition = 0; waveIn = new WaveInEvent { DeviceNumber = 0, WaveFormat = new WaveFormat(sampleRate, 1) }; waveIn.DataAvailable += OnAudioDataAvailable; waveIn.RecordingStopped += OnRecordingStopped; waveIn.StartRecording(); isRecording = true; log.LogInfo((object)"Recording started using NAudio."); } private void OnAudioDataAvailable(object sender, WaveInEventArgs e) { int num = e.BytesRecorded / 4; float[] array = new float[num]; Buffer.BlockCopy(e.Buffer, 0, array, 0, e.BytesRecorded); if (audioBuffer.Length >= bufferPosition + num) { Array.Copy(array, 0, audioBuffer, bufferPosition, num); bufferPosition += num; } if (bufferPosition >= sampleRate * 2 && !fileSaved) { log.LogInfo((object)"Stopping Recording!"); waveIn.StopRecording(); SaveAudioToFile(audioBuffer); fileSaved = true; } } private void OnRecordingStopped(object sender, StoppedEventArgs e) { isRecording = false; fileSaved = false; } private void SaveAudioToFile(float[] audioData) { //IL_0058: Unknown result type (might be due to invalid IL or missing references) //IL_0062: Expected O, but got Unknown //IL_005d: Unknown result type (might be due to invalid IL or missing references) //IL_0064: Expected O, but got Unknown string text = Path.Combine(audioFolderPath, $"audio_{Guid.NewGuid()}.wav"); byte[] array = ConvertFloatArrayToByteArray(audioData); if (File.Exists(text)) { log.LogInfo((object)"File already exists. Skipping save."); return; } using (FileStream fileStream = new FileStream(text, FileMode.Create, FileAccess.Write)) { WaveFileWriter val = new WaveFileWriter((Stream)fileStream, new WaveFormat(sampleRate, 1)); try { ((Stream)(object)val).Write(array, 0, array.Length); } finally { ((IDisposable)val)?.Dispose(); } } log.LogInfo((object)("Audio saved to file: " + text)); PlayRandomAudioFile(); } private async void PlayRandomAudioFile() { string[] files = Directory.GetFiles(audioFolderPath, "*.wav"); if (files.Length != 0) { string selectedFile = files[Random.Range(0, files.Length)]; try { byte[] audioBytes = await File.ReadAllBytesAsync(selectedFile); log.LogInfo((object)$"{audioBytes.Length} bytes have been read, sending in chunks."); SendAudioInChunksAsync(audioBytes); } catch (Exception ex2) { Exception ex = ex2; log.LogInfo((object)("Error reading audio file: " + ex.Message)); } } else { log.LogInfo((object)"No audio files found."); } } private byte[] ConvertFloatArrayToByteArray(float[] audioData) { byte[] array = new byte[audioData.Length * 4]; Buffer.BlockCopy(audioData, 0, array, 0, array.Length); return array; } private async void SendAudioInChunksAsync(byte[] audioData) { List<byte[]> chunks = ChunkAudioData(audioData, 16384); HashSet<int> chunksToSend = new HashSet<int>(); for (int i = 0; i < chunks.Count; i++) { if (!sentChunks.Contains(i)) { chunksToSend.Add(i); log.LogInfo((object)"Chunk added."); } } foreach (int j in chunksToSend) { byte[] chunk = chunks[j]; sentChunks.Add(j); await Task.Delay(100); log.LogInfo((object)"Chunk sent!"); photonView.RPC("ReceiveAudioChunk", (RpcTarget)0, new object[3] { chunk, j, chunks.Count }); } } [PunRPC] public void ReceiveAudioChunk(byte[] chunk, int chunkIndex, int totalChunks) { log.LogInfo((object)$"Received chunk {chunkIndex + 1}/{totalChunks}, size: {chunk.Length} bytes."); if (expectedChunkCount == 0) { expectedChunkCount = totalChunks; log.LogInfo((object)$"Expecting {expectedChunkCount} chunks."); } if (chunkIndex != receivedChunks.Count) { log.LogInfo((object)$"Out-of-order chunk received. Expected chunk index {receivedChunks.Count}, but received {chunkIndex}."); return; } receivedChunks.Add(chunk); if (receivedChunks.Count == expectedChunkCount) { byte[] audioData = CombineChunks(receivedChunks); PlayReceivedAudio(audioData); receivedChunks.Clear(); expectedChunkCount = 0; sentChunks.Clear(); } } private byte[] CombineChunks(List<byte[]> chunks) { int num = chunks.Sum((byte[] chunk) => chunk.Length); byte[] array = new byte[num]; int num2 = 0; foreach (byte[] chunk in chunks) { Array.Copy(chunk, 0, array, num2, chunk.Length); num2 += chunk.Length; } return array; } private void PlayReceivedAudio(byte[] audioData) { //IL_0009: Unknown result type (might be due to invalid IL or missing references) //IL_000f: Expected O, but got Unknown using MemoryStream memoryStream = new MemoryStream(audioData); WaveFileReader val = new WaveFileReader((Stream)memoryStream); try { byte[] array = new byte[((Stream)(object)val).Length]; ((Stream)(object)val).Read(array, 0, array.Length); float[] array2 = ConvertByteArrayToFloatArray(array); List<GameObject> enemiesList = GetEnemiesList(); foreach (GameObject item in enemiesList) { if ((Object)(object)item == (Object)null) { log.LogInfo((object)"Enemy is null, skipping..."); continue; } AudioClip val2 = AudioClip.Create("ReceivedClip", array2.Length, 1, sampleRate, false); val2.SetData(array2, 0); GameObject gameObject = ((Component)((Component)item.transform.Find("Enable")).transform.Find("Controller")).gameObject; if ((Object)(object)gameObject.GetComponent<AudioSource>() == (Object)null) { AudioSource val3 = gameObject.AddComponent<AudioSource>(); val3.clip = val2; val3.volume = 1f; val3.spatialBlend = 1f; val3.minDistance = 1f; val3.maxDistance = 20f; val3.rolloffMode = (AudioRolloffMode)1; val3.Play(); ((MonoBehaviour)this).StartCoroutine(DestroyAfterDelay(val3, 4f)); } else { log.LogInfo((object)"Audio source already found!"); } } } finally { ((IDisposable)val)?.Dispose(); } } private List<GameObject> GetEnemiesList() { //IL_0051: Unknown result type (might be due to invalid IL or missing references) //IL_0058: Expected O, but got Unknown Transform val = GameObject.Find("Level Generator").transform.Find("Enemies"); GameObject val2 = ((val != null) ? ((Component)val).gameObject : null); List<GameObject> list = new List<GameObject>(); if ((Object)(object)val2 != (Object)null) { foreach (Transform item in val2.transform) { Transform val3 = item; list.Add(((Component)val3).gameObject); } } return list; } private float[] ConvertByteArrayToFloatArray(byte[] byteArray) { int num = byteArray.Length / 2; float[] array = new float[num]; for (int i = 0; i < num; i++) { short num2 = BitConverter.ToInt16(byteArray, i * 2); array[i] = (float)num2 / 32768f; } return array; } private void ClearAudioFolder() { string[] files = Directory.GetFiles(audioFolderPath, "*.wav"); string[] array = files; foreach (string text in array) { try { File.Delete(text); log.LogInfo((object)("Deleted file: " + text)); } catch (Exception ex) { log.LogInfo((object)("Failed to delete file " + text + ": " + ex.Message)); } } log.LogInfo((object)"Audio folder cleared."); } [IteratorStateMachine(typeof(<DestroyAfterDelay>d__28))] private IEnumerator DestroyAfterDelay(AudioSource audioSource, float delay) { //yield-return decompiler failed: Unexpected instruction in Iterator.Dispose() return new <DestroyAfterDelay>d__28(0) { <>4__this = this, audioSource = audioSource, delay = delay }; } private List<byte[]> ChunkAudioData(byte[] audioData, int chunkSize = 32768) { List<byte[]> list = new List<byte[]>(); for (int i = 0; i < audioData.Length; i += chunkSize) { int num = Mathf.Min(chunkSize, audioData.Length - i); byte[] array = new byte[num]; Array.Copy(audioData, i, array, 0, num); list.Add(array); } return list; } } [BepInPlugin("Mimics", "Mimics", "1.0.0")] public class Plugin : BaseUnityPlugin { internal static ManualLogSource Logger; private static Harmony _harmony; private void Awake() { //IL_0021: Unknown result type (might be due to invalid IL or missing references) //IL_002b: Expected O, but got Unknown Logger = ((BaseUnityPlugin)this).Logger; Logger.LogInfo((object)"Plugin Mimics is loaded!"); _harmony = new Harmony("Mimics"); _harmony.PatchAll(); } } public static class MyPluginInfo { public const string PLUGIN_GUID = "Mimics"; public const string PLUGIN_NAME = "My first plugin"; public const string PLUGIN_VERSION = "1.0.0"; } } namespace Mimics.patches { [HarmonyPatch(typeof(PlayerAvatar), "Awake")] internal class PlayerAvatarPatch { private static void Postfix(PlayerAvatar __instance) { if ((Object)(object)((Component)__instance).GetComponent<Mimics>() == (Object)null) { ((Component)__instance).gameObject.AddComponent<Mimics>(); } } } }
plugins/EvilCheetah-ScalingPrices/ScalingPrices.dll
Decompiled 2 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 HarmonyLib; using Photon.Pun; using ScalingPrices.Config; using ScalingPrices.Helpers; using ScalingPrices.Patches; using UnityEngine; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: AssemblyTitle("ScalingPrices")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("ScalingPrices")] [assembly: AssemblyCopyright("Copyright © 2025")] [assembly: AssemblyTrademark("")] [assembly: ComVisible(false)] [assembly: Guid("b44f6998-ed7b-478f-a3b6-3791193d4005")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")] [assembly: AssemblyVersion("1.0.0.0")] namespace ScalingPrices { [BepInPlugin("EvilCheetah.REPO.PlayerCountPricing", "Scaling Prices", "1.1.2")] public class ScalingPricingBase : BaseUnityPlugin { private const string mod_guid = "EvilCheetah.REPO.PlayerCountPricing"; private const string mod_name = "Scaling Prices"; private const string mod_version = "1.1.2"; private readonly Harmony harmony = new Harmony("EvilCheetah.REPO.PlayerCountPricing"); private static ScalingPricingBase instance; internal ManualLogSource mls; private void Awake() { if ((Object)(object)instance == (Object)null) { instance = this; } mls = Logger.CreateLogSource("EvilCheetah.REPO.PlayerCountPricing"); Configuration.Init(((BaseUnityPlugin)this).Config); mls.LogInfo((object)"Player Count Pricing mod has been activated"); harmony.PatchAll(typeof(ScalingPricingBase)); harmony.PatchAll(typeof(ShopManagerPatch)); harmony.PatchAll(typeof(ItemAttributesPatch)); } } } namespace ScalingPrices.Patches { [HarmonyPatch(typeof(ItemAttributes), "GetValue")] internal class ItemAttributesPatch { public static bool Prefix(ItemAttributes __instance) { //IL_0050: Unknown result type (might be due to invalid IL or missing references) //IL_0055: 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) //IL_0058: Invalid comparison between Unknown and I4 //IL_005a: Unknown result type (might be due to invalid IL or missing references) //IL_005c: Invalid comparison between Unknown and I4 //IL_005e: Unknown result type (might be due to invalid IL or missing references) //IL_0060: Invalid comparison between Unknown and I4 ItemAttributesHelper.Instance = __instance; if (!GameManager.Multiplayer() || PhotonNetwork.IsMasterClient) { float num = Random.Range(ItemAttributesHelper.ItemValueMin, ItemAttributesHelper.ItemValueMax) * ShopManagerHelper.ItemValueMultiplier; if (num < 1000f) { num = 1000f; } if (num >= 1000f) { num = Mathf.Ceil(num / 1000f); } itemType itemType = ItemAttributesHelper.ItemType; if ((int)itemType != 3) { if ((int)itemType != 5) { if ((int)itemType == 8) { num += num * ShopManagerHelper.HealthPackIncrease * (float)RunManager.instance.levelsCompleted + (float)SemiFunc.PlayerGetAll().Count * Configuration.HealthPackIncreasePerPlayer.Value; } } else { num += num * ShopManagerHelper.CrystalIncrease * (float)RunManager.instance.levelsCompleted + (float)SemiFunc.PlayerGetAll().Count * Configuration.CrystalIncreasePerPlayer.Value; } } else { num += num * ShopManagerHelper.UpgradeIncrease * (float)StatsManager.instance.GetItemsUpgradesPurchased(ItemAttributesHelper.ItemAssetName) + (float)SemiFunc.PlayerGetAll().Count * Configuration.UpgradeIncreasePerPlayer.Value; } ItemAttributesHelper.ItemValue = (int)num; if (GameManager.Multiplayer()) { ItemAttributesHelper.PhotonView.RPC("GetValueRPC", (RpcTarget)1, new object[1] { ItemAttributesHelper.ItemValue }); } } return false; } } [HarmonyPatch(typeof(ShopManager), "Update")] internal class ShopManagerPatch { private static void Postfix(ShopManager __instance) { ShopManagerHelper.Instance = __instance; ShopManagerHelper.ItemValueMultiplier = Configuration.ItemValueMultiplier.Value; ShopManagerHelper.UpgradeIncrease = Configuration.UpgradeIncrease.Value; ShopManagerHelper.HealthPackIncrease = Configuration.HealthPackIncrease.Value; ShopManagerHelper.CrystalIncrease = Configuration.CrystalIncrease.Value; } } } namespace ScalingPrices.Helpers { internal class ItemAttributesHelper { private static readonly FieldRef<ItemAttributes, PhotonView> photon_view_ref = AccessTools.FieldRefAccess<ItemAttributes, PhotonView>("photonView"); private static readonly FieldRef<ItemAttributes, string> item_asset_name_ref = AccessTools.FieldRefAccess<ItemAttributes, string>("itemAssetName"); private static readonly FieldRef<ItemAttributes, itemType> item_type_ref = AccessTools.FieldRefAccess<ItemAttributes, itemType>("itemType"); private static readonly FieldRef<ItemAttributes, int> item_value_ref = AccessTools.FieldRefAccess<ItemAttributes, int>("value"); private static readonly FieldRef<ItemAttributes, float> item_value_min_ref = AccessTools.FieldRefAccess<ItemAttributes, float>("itemValueMin"); private static readonly FieldRef<ItemAttributes, float> item_value_max_ref = AccessTools.FieldRefAccess<ItemAttributes, float>("itemValueMax"); public static ItemAttributes Instance { get; set; } public static PhotonView PhotonView => photon_view_ref.Invoke(Instance); public static string ItemAssetName { get { return item_asset_name_ref.Invoke(Instance); } set { item_asset_name_ref.Invoke(Instance) = value; } } public static itemType ItemType { get { return item_type_ref.Invoke(Instance); } set { //IL_000f: Unknown result type (might be due to invalid IL or missing references) //IL_0011: Expected I4, but got Unknown item_type_ref.Invoke(Instance) = (itemType)(int)value; } } public static int ItemValue { get { return item_value_ref.Invoke(Instance); } set { item_value_ref.Invoke(Instance) = value; } } public static float ItemValueMin { get { return item_value_min_ref.Invoke(Instance); } set { item_value_min_ref.Invoke(Instance) = value; } } public static float ItemValueMax { get { return item_value_max_ref.Invoke(Instance); } set { _ = ref item_value_max_ref.Invoke(Instance); } } } internal class ShopManagerHelper { private static readonly FieldRef<ShopManager, float> item_value_multiplier_ref = AccessTools.FieldRefAccess<ShopManager, float>("itemValueMultiplier"); private static readonly FieldRef<ShopManager, float> upgrade_increase_ref = AccessTools.FieldRefAccess<ShopManager, float>("upgradeValueIncrease"); private static readonly FieldRef<ShopManager, float> health_pack_increase_ref = AccessTools.FieldRefAccess<ShopManager, float>("healthPackValueIncrease"); private static readonly FieldRef<ShopManager, float> crystal_increase_ref = AccessTools.FieldRefAccess<ShopManager, float>("crystalValueIncrease"); public static ShopManager Instance { get; set; } public static float ItemValueMultiplier { get { return item_value_multiplier_ref.Invoke(Instance); } set { item_value_multiplier_ref.Invoke(Instance) = value; } } public static float UpgradeIncrease { get { return upgrade_increase_ref.Invoke(Instance); } set { upgrade_increase_ref.Invoke(Instance) = value; } } public static float HealthPackIncrease { get { return health_pack_increase_ref.Invoke(Instance); } set { health_pack_increase_ref.Invoke(Instance) = value; } } public static float CrystalIncrease { get { return crystal_increase_ref.Invoke(Instance); } set { crystal_increase_ref.Invoke(Instance) = value; } } } } namespace ScalingPrices.Config { internal class Configuration { public static ConfigEntry<float> ItemValueMultiplier; public static ConfigEntry<float> UpgradeIncrease; public static ConfigEntry<float> HealthPackIncrease; public static ConfigEntry<float> CrystalIncrease; public static ConfigEntry<float> UpgradeIncreasePerPlayer; public static ConfigEntry<float> HealthPackIncreasePerPlayer; public static ConfigEntry<float> CrystalIncreasePerPlayer; public static void Init(ConfigFile config) { ItemValueMultiplier = config.Bind<float>("Default", "ValueMultiplier", 4f, "Multiplier applied to the base price of items"); UpgradeIncrease = config.Bind<float>("Default", "UpgradeIncrease", 0.5f, "Multiplier applied to the base price of items"); HealthPackIncrease = config.Bind<float>("Default", "HealthPackIncrease", 0.05f, "Multiplier applied to the base price of items"); CrystalIncrease = config.Bind<float>("Default", "CrystalIncrease", 0.2f, "Multiplier applied to the base price of items"); UpgradeIncreasePerPlayer = config.Bind<float>("PerPlayerIncrease", "UpgradeIncrease", 0f, "Multiplier applied to the base price of items"); HealthPackIncreasePerPlayer = config.Bind<float>("PerPlayerIncrease", "HealthPackIncrease", 0f, "Multiplier applied to the base price of items"); CrystalIncreasePerPlayer = config.Bind<float>("PerPlayerIncrease", "CrystalIncrease", 0f, "Multiplier applied to the base price of items"); } } }
plugins/EvilCheetah-TeamUpgrades/TeamUpgrades.dll
Decompiled 2 months agousing System; using 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 HarmonyLib; using REPOTeamBoosters.Patches; using TeamUpgrades.Configuration; using TeamUpgrades.Patches; using UnityEngine; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: AssemblyTitle("TeamUpgrades")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("TeamUpgrades")] [assembly: AssemblyCopyright("Copyright © 2025")] [assembly: AssemblyTrademark("")] [assembly: ComVisible(false)] [assembly: Guid("ef74d5e5-8fe6-4b6a-86ed-0e29e12695bb")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")] [assembly: AssemblyVersion("1.0.0.0")] namespace REPOTeamBoosters { [BepInPlugin("EvilCheetah.REPO.TeamBoosters", "Team Boosters", "1.1.4")] public class TeamBoostersBase : BaseUnityPlugin { private const string mod_guid = "EvilCheetah.REPO.TeamBoosters"; private const string mod_name = "Team Boosters"; private const string mod_version = "1.1.4"; private readonly Harmony harmony = new Harmony("EvilCheetah.REPO.TeamBoosters"); private static TeamBoostersBase instance; internal ManualLogSource mls; private void Awake() { if ((Object)(object)instance == (Object)null) { instance = this; } mls = Logger.CreateLogSource("EvilCheetah.REPO.TeamBoosters"); harmony.PatchAll(typeof(TeamBoostersBase)); Configuration.Init(((BaseUnityPlugin)this).Config); (ConfigEntry<bool>, Action, string)[] array = new(ConfigEntry<bool>, Action, string)[9] { (Configuration.EnableItemUpgradeMapPlayerCountPatch, delegate { harmony.PatchAll(typeof(ItemUpgradeMapPlayerCountPatch)); }, "Map Player Count Upgrade"), (Configuration.EnableItemUpgradePlayerEnergyPatch, delegate { harmony.PatchAll(typeof(ItemUpgradePlayerEnergyPatch)); }, "Player Energy Upgrade"), (Configuration.EnableItemUpgradePlayerExtraJumpPatch, delegate { harmony.PatchAll(typeof(ItemUpgradePlayerExtraJumpPatch)); }, "Player Extra Jump Upgrade"), (Configuration.EnableItemUpgradePlayerGrabRangePatch, delegate { harmony.PatchAll(typeof(ItemUpgradePlayerGrabRangePatch)); }, "Player Grab Range Upgrade"), (Configuration.EnableItemUpgradePlayerGrabStrengthPatch, delegate { harmony.PatchAll(typeof(ItemUpgradePlayerGrabStrengthPatch)); }, "Player Grab Strength Upgrade"), (Configuration.EnableItemUpgradePlayerGrabThrowPatch, delegate { harmony.PatchAll(typeof(ItemUpgradePlayerGrabThrowPatch)); }, "Player Grab Throw Upgrade"), (Configuration.EnableItemUpgradePlayerHealthPatch, delegate { harmony.PatchAll(typeof(ItemUpgradePlayerHealthPatch)); }, "Player Health Upgrade"), (Configuration.EnableItemUpgradePlayerSprintSpeedPatch, delegate { harmony.PatchAll(typeof(ItemUpgradePlayerSprintSpeedPatch)); }, "Player Sprint Speed Upgrade"), (Configuration.EnableItemUpgradePlayerTumbleLaunchPatch, delegate { harmony.PatchAll(typeof(ItemUpgradePlayerTumbleLaunchPatch)); }, "Player Thumle Lauch Upgrade") }; for (int i = 0; i < array.Length; i++) { var (val, action, text) = array[i]; if (val.Value) { action(); mls.LogInfo((object)(text + " patch is applied")); } } mls.LogInfo((object)"Team Boosters mod has been activated"); } } } namespace REPOTeamBoosters.Patches { [HarmonyPatch(typeof(ItemUpgradeMapPlayerCount), "Upgrade")] internal class ItemUpgradeMapPlayerCountPatch { private static bool Prefix(ItemUpgradeMapPlayerCount __instance) { foreach (PlayerAvatar item in SemiFunc.PlayerGetAll()) { PunManager.instance.UpgradeMapPlayerCount(SemiFunc.PlayerGetSteamID(item)); } return false; } } [HarmonyPatch(typeof(ItemUpgradePlayerEnergy), "Upgrade")] internal class ItemUpgradePlayerEnergyPatch { private static bool Prefix(ItemUpgradePlayerEnergy __instance) { foreach (PlayerAvatar item in SemiFunc.PlayerGetAll()) { PunManager.instance.UpgradePlayerEnergy(SemiFunc.PlayerGetSteamID(item)); } return false; } } [HarmonyPatch(typeof(ItemUpgradePlayerHealth), "Upgrade")] internal class ItemUpgradePlayerHealthPatch { private static bool Prefix(ItemUpgradePlayerHealth __instance) { foreach (PlayerAvatar item in SemiFunc.PlayerGetAll()) { PunManager.instance.UpgradePlayerHealth(SemiFunc.PlayerGetSteamID(item)); } return false; } } [HarmonyPatch(typeof(ItemUpgradePlayerSprintSpeed), "Upgrade")] internal class ItemUpgradePlayerSprintSpeedPatch { private static bool Prefix(ItemUpgradePlayerSprintSpeed __instance) { foreach (PlayerAvatar item in SemiFunc.PlayerGetAll()) { PunManager.instance.UpgradePlayerSprintSpeed(SemiFunc.PlayerGetSteamID(item)); } return false; } } } namespace TeamUpgrades.Patches { [HarmonyPatch(typeof(ItemUpgradePlayerExtraJump), "Upgrade")] internal class ItemUpgradePlayerExtraJumpPatch { private static bool Prefix(ItemUpgradePlayerExtraJump __instance) { foreach (PlayerAvatar item in SemiFunc.PlayerGetAll()) { PunManager.instance.UpgradePlayerExtraJump(SemiFunc.PlayerGetSteamID(item)); } return false; } } [HarmonyPatch(typeof(ItemUpgradePlayerGrabRange), "Upgrade")] internal class ItemUpgradePlayerGrabRangePatch { private static bool Prefix(ItemUpgradePlayerGrabRange __instance) { foreach (PlayerAvatar item in SemiFunc.PlayerGetAll()) { PunManager.instance.UpgradePlayerGrabRange(SemiFunc.PlayerGetSteamID(item)); } return false; } } [HarmonyPatch(typeof(ItemUpgradePlayerGrabStrength), "Upgrade")] internal class ItemUpgradePlayerGrabStrengthPatch { private static bool Prefix(ItemUpgradePlayerGrabStrength __instance) { foreach (PlayerAvatar item in SemiFunc.PlayerGetAll()) { PunManager.instance.UpgradePlayerGrabStrength(SemiFunc.PlayerGetSteamID(item)); } return false; } } [HarmonyPatch(typeof(ItemUpgradePlayerGrabThrow), "Upgrade")] internal class ItemUpgradePlayerGrabThrowPatch { private static bool Prefix(ItemUpgradePlayerGrabThrow __instance) { foreach (PlayerAvatar item in SemiFunc.PlayerGetAll()) { PunManager.instance.UpgradePlayerThrowStrength(SemiFunc.PlayerGetSteamID(item)); } return false; } } [HarmonyPatch(typeof(ItemUpgradePlayerTumbleLaunch), "Upgrade")] internal class ItemUpgradePlayerTumbleLaunchPatch { private static bool Prefix(ItemUpgradePlayerTumbleLaunch __instance) { foreach (PlayerAvatar item in SemiFunc.PlayerGetAll()) { PunManager.instance.UpgradePlayerTumbleLaunch(SemiFunc.PlayerGetSteamID(item)); } return false; } } } namespace TeamUpgrades.Configuration { internal class Configuration { public static ConfigEntry<bool> EnableItemUpgradeMapPlayerCountPatch; public static ConfigEntry<bool> EnableItemUpgradePlayerEnergyPatch; public static ConfigEntry<bool> EnableItemUpgradePlayerExtraJumpPatch; public static ConfigEntry<bool> EnableItemUpgradePlayerGrabRangePatch; public static ConfigEntry<bool> EnableItemUpgradePlayerGrabStrengthPatch; public static ConfigEntry<bool> EnableItemUpgradePlayerGrabThrowPatch; public static ConfigEntry<bool> EnableItemUpgradePlayerHealthPatch; public static ConfigEntry<bool> EnableItemUpgradePlayerSprintSpeedPatch; public static ConfigEntry<bool> EnableItemUpgradePlayerTumbleLaunchPatch; public static void Init(ConfigFile config) { EnableItemUpgradeMapPlayerCountPatch = config.Bind<bool>("General", "EnableUpgradeMapPlayer", true, "Enables Team Upgrades for Map Player Count Upgrade"); EnableItemUpgradePlayerEnergyPatch = config.Bind<bool>("General", "EnableUpgradePlayerEnergy", true, "Enables Team Upgrades for Player Energy Upgrade"); EnableItemUpgradePlayerExtraJumpPatch = config.Bind<bool>("General", "EnableUpgradePlayerExtraJump", true, "Enables Team Upgrades for Player Extra Jump Upgrade"); EnableItemUpgradePlayerGrabRangePatch = config.Bind<bool>("General", "EnableUpgradePlayerGrabRange", true, "Enables Team Upgrades for Player Grab Range Upgrade"); EnableItemUpgradePlayerGrabStrengthPatch = config.Bind<bool>("General", "EnableUpgradePlayerGrabStrength", true, "Enables Team Upgrades for Player Grab Strength Upgrade"); EnableItemUpgradePlayerGrabThrowPatch = config.Bind<bool>("General", "EnableUpgradePlayerGrabThrow", true, "Enables Team Upgrades for Player Grab Throw Upgrade"); EnableItemUpgradePlayerHealthPatch = config.Bind<bool>("General", "EnableUpgradePlayerHealth", true, "Enables Team Upgrades for Player Health Upgrade"); EnableItemUpgradePlayerSprintSpeedPatch = config.Bind<bool>("General", "EnableUpgradePlayerSprintSpeed", true, "Enables Team Upgrades for Player Sprint Speed Upgrade"); EnableItemUpgradePlayerTumbleLaunchPatch = config.Bind<bool>("General", "EnableUpgradePlayerTumbleLaunch", true, "Enables Team Upgrades for Player Tumble Launch Upgrade"); } } }
plugins/flipf17-DeadTTS/REPO-DeadTTS.dll
Decompiled 2 months agousing System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Versioning; using BepInEx; using BepInEx.Configuration; using BepInEx.Logging; using HarmonyLib; using REPO_DeadTTS.Config; using TMPro; 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("REPO-DeadTTS")] [assembly: AssemblyDescription("Mod created by flipf17")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("REPO-DeadTTS")] [assembly: AssemblyCopyright("Copyright © 2025")] [assembly: AssemblyTrademark("")] [assembly: ComVisible(false)] [assembly: Guid("8e05cd18-c8aa-419a-b430-33faaf371490")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")] [assembly: AssemblyVersion("1.0.0.0")] namespace REPO_DeadTTS { [BepInPlugin("flipf17.DeadTTS", "DeadTTS", "0.1.2")] public class Plugin : BaseUnityPlugin { private Harmony _harmony; public static Plugin instance; private static ManualLogSource logger; private void Awake() { //IL_001a: Unknown result type (might be due to invalid IL or missing references) //IL_0024: Expected O, but got Unknown instance = this; CreateCustomLogger(); ConfigSettings.BindConfigSettings(); _harmony = new Harmony("DeadTTS"); PatchAll(); Log("DeadTTS loaded"); } private void PatchAll() { IEnumerable<Type> enumerable; try { enumerable = Assembly.GetExecutingAssembly().GetTypes(); } catch (ReflectionTypeLoadException ex) { enumerable = ex.Types.Where((Type t) => t != null); } foreach (Type item in enumerable) { _harmony.PatchAll(item); } } private void CreateCustomLogger() { try { logger = Logger.CreateLogSource(string.Format("{0}-{1}", "DeadTTS", "0.1.2")); } catch { logger = ((BaseUnityPlugin)this).Logger; } } public static void Log(string message) { logger.LogInfo((object)message); } public static void LogError(string message) { logger.LogError((object)message); } public static void LogWarning(string message) { logger.LogWarning((object)message); } } public static class PluginInfo { public const string PLUGIN_GUID = "flipf17.DeadTTS"; public const string PLUGIN_NAME = "DeadTTS"; public const string PLUGIN_VERSION = "0.1.2"; } } namespace REPO_DeadTTS.Patches { [HarmonyPatch] public static class UIPatcher { private static HashSet<WorldSpaceUITTS> deadTTSElements = new HashSet<WorldSpaceUITTS>(); private static Dictionary<PlayerAvatar, bool> isDisabledStates = new Dictionary<PlayerAvatar, bool>(); private static FieldInfo textField = typeof(WorldSpaceUITTS).GetField("text", BindingFlags.Instance | BindingFlags.NonPublic); private static FieldInfo playerAvatarField = typeof(WorldSpaceUITTS).GetField("playerAvatar", BindingFlags.Instance | BindingFlags.NonPublic); private static FieldInfo followTransformField = typeof(WorldSpaceUITTS).GetField("followTransform", BindingFlags.Instance | BindingFlags.NonPublic); private static FieldInfo worldPositionField = typeof(WorldSpaceUITTS).GetField("worldPosition", BindingFlags.Instance | BindingFlags.NonPublic); private static FieldInfo followPositionField = typeof(WorldSpaceUITTS).GetField("followPosition", BindingFlags.Instance | BindingFlags.NonPublic); private static FieldInfo wordTimeField = typeof(WorldSpaceUITTS).GetField("wordTime", BindingFlags.Instance | BindingFlags.NonPublic); private static FieldInfo voiceChatField = typeof(PlayerAvatar).GetField("voiceChat", BindingFlags.Instance | BindingFlags.NonPublic); private static FieldInfo ttsVoiceField = typeof(WorldSpaceUITTS).GetField("ttsVoice", BindingFlags.Instance | BindingFlags.NonPublic); [HarmonyPatch(typeof(WorldSpaceUIParent), "TTS")] [HarmonyPrefix] private static void OnTTSUI(PlayerAvatar _player, string _text, float _time, WorldSpaceUIParent __instance) { //IL_0012: Unknown result type (might be due to invalid IL or missing references) //IL_0018: Invalid comparison between Unknown and I4 //IL_0058: Unknown result type (might be due to invalid IL or missing references) //IL_0063: 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_009e: Expected O, but got Unknown //IL_00d3: 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_0117: Unknown result type (might be due to invalid IL or missing references) //IL_011e: Expected O, but got Unknown if (!ConfigSettings.deadTTSSpatialAudio.Value || (int)GameDirector.instance.currentState != 2 || !Object.op_Implicit((Object)(object)_player) || ((Behaviour)_player).isActiveAndEnabled || !Object.op_Implicit((Object)(object)_player.playerDeathHead) || string.IsNullOrEmpty(_text)) { return; } try { WorldSpaceUITTS component = Object.Instantiate<GameObject>(__instance.TTSPrefab, ((Component)__instance).transform.position, ((Component)__instance).transform.rotation, ((Component)__instance).transform).GetComponent<WorldSpaceUITTS>(); if (!Object.op_Implicit((Object)(object)component)) { return; } TMP_Text val = (TMP_Text)textField.GetValue(component); val.text = _text; playerAvatarField.SetValue(component, _player); Transform transform = ((Component)_player.playerDeathHead).transform; followTransformField.SetValue(component, transform); worldPositionField.SetValue(component, transform.position); followPositionField.SetValue(component, transform.position); wordTimeField.SetValue(component, _time); PlayerVoiceChat val2 = (PlayerVoiceChat)voiceChatField.GetValue(_player); ttsVoiceField.SetValue(component, val2.ttsVoice); deadTTSElements.Add(component); try { deadTTSElements.RemoveWhere((WorldSpaceUITTS obj) => (Object)(object)obj == (Object)null); } catch { } } catch (Exception ex) { Plugin.LogError("Error initializing dead TTS UI:\n" + ex); } } [HarmonyPatch(typeof(WorldSpaceUITTS), "Update")] [HarmonyPrefix] private static void OnUpdatePrefix(WorldSpaceUITTS __instance) { //IL_002c: Unknown result type (might be due to invalid IL or missing references) //IL_0032: Expected O, but got Unknown if (ConfigSettings.displayDeadTTSText.Value && deadTTSElements.Contains(__instance)) { try { PlayerAvatar val = (PlayerAvatar)playerAvatarField.GetValue(__instance); bool value = (bool)PlayerPatcher.isDisabledField.GetValue(val); isDisabledStates[val] = value; PlayerPatcher.isDisabledField.SetValue(val, false); } catch (Exception ex) { Plugin.LogError("Error (A) updating dead TTS UI location:\n" + ex); deadTTSElements.Remove(__instance); } } } [HarmonyPatch(typeof(WorldSpaceUITTS), "Update")] [HarmonyPostfix] private static void OnUpdatePostfix(WorldSpaceUITTS __instance) { //IL_001d: Unknown result type (might be due to invalid IL or missing references) //IL_0023: Expected O, but got Unknown if (!deadTTSElements.Contains(__instance)) { return; } try { PlayerAvatar val = (PlayerAvatar)playerAvatarField.GetValue(__instance); if (isDisabledStates.TryGetValue(val, out var value)) { PlayerPatcher.isDisabledField.SetValue(val, value); } } catch (Exception ex) { Plugin.LogError("Error (B) updating dead TTS UI location:\n" + ex); deadTTSElements.Remove(__instance); } } } [HarmonyPatch] public static class PlayerPatcher { internal static PlayerAvatar localPlayer; internal static FieldInfo isDisabledField = typeof(PlayerAvatar).GetField("isDisabled", BindingFlags.Instance | BindingFlags.NonPublic); [HarmonyPatch(typeof(PlayerAvatar), "Awake")] [HarmonyPostfix] private static void InitLocalPlayer(ref bool ___isLocal, PlayerAvatar __instance) { if (___isLocal) { localPlayer = __instance; } } [HarmonyPatch(typeof(PlayerVoiceChat), "TtsFollowVoiceSettings")] [HarmonyPostfix] private static void OnTtsFollowVoiceSettings(ref PlayerAvatar ___playerAvatar, ref AudioLowPassLogic ___lowPassLogicTTS, ref bool ___inLobbyMixerTTS, PlayerVoiceChat __instance) { //IL_0058: Unknown result type (might be due to invalid IL or missing references) //IL_005e: Invalid comparison between Unknown and I4 if (Object.op_Implicit((Object)(object)___playerAvatar) && Object.op_Implicit((Object)(object)___playerAvatar.playerDeathHead) && Object.op_Implicit((Object)(object)__instance.ttsAudioSource) && Object.op_Implicit((Object)(object)__instance.ttsVoice) && Object.op_Implicit((Object)(object)__instance.mixerTTSSound) && GameManager.Multiplayer() && (int)GameDirector.instance.currentState >= 2 && (((bool)isDisabledField.GetValue(___playerAvatar) && ((Behaviour)___playerAvatar.playerDeathHead).isActiveAndEnabled) & ___inLobbyMixerTTS)) { if ((Object)(object)__instance.ttsAudioSource.outputAudioMixerGroup != (Object)(object)__instance.mixerTTSSound) { Plugin.Log("The game has toggled ON lobby chat for player: " + ((Object)___playerAvatar).name + ". Disabling TTS lobby mixer."); __instance.ttsVoice.setVoice(1); __instance.ttsAudioSource.outputAudioMixerGroup = __instance.mixerTTSSound; __instance.ttsVoice.StopAndClearVoice(); } __instance.ttsAudioSource.pitch = ConfigSettings.deadTTSPitch.Value; __instance.ttsAudioSource.volume = ConfigSettings.deadTTSVolume.Value; if (ConfigSettings.deadTTSSpatialAudio.Value) { __instance.ttsAudioSource.spatialBlend = 1f; } } } [HarmonyPatch(typeof(PlayerVoiceChat), "ToggleLobby")] [HarmonyPostfix] private static void OnToggleOffLobbyChat(bool _toggle, ref PlayerAvatar ___playerAvatar, PlayerVoiceChat __instance) { //IL_0031: Unknown result type (might be due to invalid IL or missing references) //IL_0037: Invalid comparison between Unknown and I4 if (Object.op_Implicit((Object)(object)__instance.ttsAudioSource) && Object.op_Implicit((Object)(object)__instance.mixerTTSSound) && GameManager.Multiplayer() && (int)GameDirector.instance.currentState >= 2 && !_toggle) { Plugin.Log("The game has toggled OFF lobby chat for player: " + ((Object)___playerAvatar).name); __instance.ttsAudioSource.volume = 1f; } } [HarmonyPatch(typeof(PlayerVoiceChat), "LateUpdate")] [HarmonyPrefix] private static void MoveTTSAudioTransform(ref PlayerAvatar ___playerAvatar, ref bool ___inLobbyMixerTTS, PlayerVoiceChat __instance) { //IL_0019: Unknown result type (might be due to invalid IL or missing references) //IL_001f: Invalid comparison between Unknown and I4 //IL_0078: Unknown result type (might be due to invalid IL or missing references) //IL_0089: Unknown result type (might be due to invalid IL or missing references) //IL_0099: Unknown result type (might be due to invalid IL or missing references) if (LevelGenerator.Instance.Generated && GameManager.Multiplayer() && (int)GameDirector.instance.currentState >= 2 && Object.op_Implicit((Object)(object)___playerAvatar) && ___inLobbyMixerTTS && (bool)isDisabledField.GetValue(___playerAvatar) && Object.op_Implicit((Object)(object)___playerAvatar.playerDeathHead) && Object.op_Implicit((Object)(object)__instance.ttsVoice)) { ((Component)__instance).transform.position = Vector3.Lerp(((Component)__instance).transform.position, ((Component)___playerAvatar.playerDeathHead).transform.position, 30f * Time.deltaTime); } } } } namespace REPO_DeadTTS.Config { [Serializable] public static class ConfigSettings { public static ConfigEntry<float> deadTTSPitch; public static ConfigEntry<float> deadTTSVolume; public static ConfigEntry<bool> displayDeadTTSText; public static ConfigEntry<bool> deadTTSSpatialAudio; public static Dictionary<string, ConfigEntryBase> currentConfigEntries = new Dictionary<string, ConfigEntryBase>(); public static void BindConfigSettings() { //IL_003e: Unknown result type (might be due to invalid IL or missing references) //IL_0048: Expected O, but got Unknown //IL_0084: Unknown result type (might be due to invalid IL or missing references) //IL_008e: Expected O, but got Unknown Plugin.Log("Binding Configs"); deadTTSPitch = AddConfigEntry<float>(((BaseUnityPlugin)Plugin.instance).Config.Bind<float>("General", "Dead TTS Pitch", 1.1f, new ConfigDescription("Affects the TTS pitch of all dead players.\nValues will be clamped between 0.1 and 2.0", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.1f, 2f), Array.Empty<object>()))); deadTTSVolume = AddConfigEntry<float>(((BaseUnityPlugin)Plugin.instance).Config.Bind<float>("General", "Dead TTS Volume", 0.8f, new ConfigDescription("Affects the TTS volume of all dead players.\nValues will be clamped between 0.1 and 1.0", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.1f, 1f), Array.Empty<object>()))); displayDeadTTSText = AddConfigEntry<bool>(((BaseUnityPlugin)Plugin.instance).Config.Bind<bool>("General", "Display Dead TTS Text", true, "If true, TTS Text will appear from dead players' heads.")); deadTTSSpatialAudio = AddConfigEntry<bool>(((BaseUnityPlugin)Plugin.instance).Config.Bind<bool>("General", "Use Spatial Audio", true, "If true, TTS audio from dead players should be 3D directional.\nIf false, the audio should appear as if it's in your head all the time.")); deadTTSPitch.Value = Mathf.Clamp(deadTTSPitch.Value, 0.1f, 2f); deadTTSVolume.Value = Mathf.Clamp(deadTTSVolume.Value, 0.1f, 2f); } public static ConfigEntry<T> AddConfigEntry<T>(ConfigEntry<T> configEntry) { currentConfigEntries.Add(((ConfigEntryBase)configEntry).Definition.Key, (ConfigEntryBase)(object)configEntry); return configEntry; } } }
plugins/Flopper-ImprovedStamina/ImprovedStamina.dll
Decompiled 2 months agousing System; using System.Collections; 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 BepInEx.Logging; using HarmonyLib; using Microsoft.CodeAnalysis; using UnityEngine; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")] [assembly: AssemblyCompany("ImprovedStamina")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyFileVersion("1.2.0.0")] [assembly: AssemblyInformationalVersion("1.2.0+c8f2cea1b32c76bda37659e15fffea03a128d49e")] [assembly: AssemblyProduct("Improved Stamina")] [assembly: AssemblyTitle("ImprovedStamina")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("1.2.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 ImprovedStamina { [BepInPlugin("ImprovedStamina", "Improved Stamina", "1.2.0")] public class Plugin : BaseUnityPlugin { internal static ManualLogSource Logger; private static Harmony _harmony; private void Awake() { //IL_002a: Unknown result type (might be due to invalid IL or missing references) //IL_0034: Expected O, but got Unknown Logger = ((BaseUnityPlugin)this).Logger; Logger.LogInfo((object)"Plugin ImprovedStamina is loaded!"); ConfigManager.Initialize(((BaseUnityPlugin)this).Config); _harmony = new Harmony("ImprovedStamina"); _harmony.PatchAll(); } } public static class ConfigManager { public static ConfigEntry<float> MaxRegenRate { get; private set; } public static ConfigEntry<float> RegenRampUpTime { get; private set; } public static ConfigEntry<float> DelayBeforeRegen { get; private set; } public static ConfigEntry<float> SprintDrainMultiplier { get; private set; } public static void Initialize(ConfigFile config) { //IL_0029: Unknown result type (might be due to invalid IL or missing references) //IL_0033: 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 //IL_0099: Unknown result type (might be due to invalid IL or missing references) //IL_00a3: Expected O, but got Unknown //IL_00d1: Unknown result type (might be due to invalid IL or missing references) //IL_00db: Expected O, but got Unknown MaxRegenRate = config.Bind<float>("Stamina Settings", "MaxRegenRate", 8f, new ConfigDescription("Maximum stamina regeneration multiplier after not sprinting for some time.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(1f, 25f), Array.Empty<object>())); RegenRampUpTime = config.Bind<float>("Stamina Settings", "RegenRampUpTime", 3f, new ConfigDescription("Time in seconds before stamina regeneration reaches max multiplier.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 25f), Array.Empty<object>())); DelayBeforeRegen = config.Bind<float>("Stamina Settings", "DelayBeforeRegen", 0.5f, new ConfigDescription("Time in seconds before stamina starts regenerating after stopping sprinting.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 25f), Array.Empty<object>())); SprintDrainMultiplier = config.Bind<float>("Stamina Settings", "SprintDrainMultiplier", 1f, new ConfigDescription("Multiplier for stamina cost when sprinting. 1.0x is default.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 10f), Array.Empty<object>())); } } public static class MyPluginInfo { public const string PLUGIN_GUID = "ImprovedStamina"; public const string PLUGIN_NAME = "Improved Stamina"; public const string PLUGIN_VERSION = "1.2.0"; } } namespace ImprovedStamina.Patches { [HarmonyPatch(typeof(PlayerController), "LateStart")] public static class PlayerControllerLateStartPatch { public static void Postfix(PlayerController __instance) { if (!((Object)(object)__instance == (Object)null)) { ((MonoBehaviour)__instance).StartCoroutine(AdjustSprintDrain(__instance)); } } private static IEnumerator AdjustSprintDrain(PlayerController player) { yield return (object)new WaitForSeconds(0.1f); float energySprintDrain = player.EnergySprintDrain; float value = ConfigManager.SprintDrainMultiplier.Value; player.EnergySprintDrain = energySprintDrain * value; } } [HarmonyPatch(typeof(PlayerController), "Update")] public static class PlayerControllerPatch { private static float timeSinceStoppedSprinting; private static float staminaRegenRate; public static void Postfix(PlayerController __instance) { if ((Object)(object)__instance == (Object)null) { return; } if (__instance.sprinting) { timeSinceStoppedSprinting = 0f; staminaRegenRate = 0f; } else { timeSinceStoppedSprinting += Time.deltaTime; if (timeSinceStoppedSprinting >= ConfigManager.DelayBeforeRegen.Value) { float num = timeSinceStoppedSprinting - ConfigManager.DelayBeforeRegen.Value; staminaRegenRate = Mathf.Min(ConfigManager.MaxRegenRate.Value, num / ConfigManager.RegenRampUpTime.Value * ConfigManager.MaxRegenRate.Value); } } if (staminaRegenRate > 0f && __instance.EnergyCurrent < __instance.EnergyStart) { __instance.EnergyCurrent += staminaRegenRate * Time.deltaTime; if (__instance.EnergyCurrent > __instance.EnergyStart) { __instance.EnergyCurrent = __instance.EnergyStart; } } } } }
plugins/FNKT_Labs-REPONoItemsLeft/REPONoItemsLeft.dll
Decompiled 2 months agousing System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Versioning; using BepInEx; using BepInEx.Configuration; using BepInEx.Logging; using HarmonyLib; using Photon.Pun; using TMPro; using UnityEngine; using UnityEngine.UI; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)] [assembly: AssemblyTitle("REPONoItemsLeft")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("REPONoItemsLeft")] [assembly: AssemblyCopyright("Copyright © 2025")] [assembly: AssemblyTrademark("")] [assembly: ComVisible(false)] [assembly: Guid("2ad62837-eb44-4bdd-9102-c6d3ae425ed5")] [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 ModPatch { public static float counterTime; private static float currentValuablesValue; private static int currentExtractionHaulGoal; private static bool hasCompletedAllTasks; private static bool onCountdown; private static State _currentExtractionPointState; [HarmonyPatch(typeof(LevelGenerator), "GenerateDone")] [HarmonyPostfix] public static void GenerateDonePostfix(LevelGenerator __instance) { if (SemiFunc.RunIsLevel()) { GameObject val = GameObject.Find("Run Manager PUN"); if ((Object)(object)val != (Object)null) { val.AddComponent<HUDManager>(); val.AddComponent<KillManager>(); } PrepareVariables(); CreateHUDElements(); } } private static void PrepareVariables() { hasCompletedAllTasks = false; onCountdown = false; KillManager.hasCompletedTask = false; currentValuablesValue = 0f; } private static void KillCheck() { //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_000e: Invalid comparison between Unknown and I4 if (hasCompletedAllTasks || (int)_currentExtractionPointState == 6 || !(currentValuablesValue < (float)currentExtractionHaulGoal) || onCountdown) { return; } onCountdown = true; FieldInfo fieldInfo = AccessTools.Field(typeof(PlayerAvatar), "playerName"); string text = (string)fieldInfo.GetValue(PlayerAvatar.instance); int num = Random.Range(0, 15); if (GameManager.instance.gameMode == 0) { KillManager.instance.CallKillThemAll(text, num); } else if ((Object)(object)KillManager.instance != (Object)null) { PhotonView component = ((Component)KillManager.instance).GetComponent<PhotonView>(); if ((Object)(object)component != (Object)null) { component.RPC("CallKillThemAll", (RpcTarget)0, new object[2] { text, num }); } else { DebugRepo("PhotonView not found on KillManager."); } } else { DebugRepo("KillManager instance is null!"); } } private static void CheckForItems(ValuableObject ignoreThis = null) { if (!hasCompletedAllTasks) { currentValuablesValue = 0f; List<ValuableObject> list = Object.FindObjectsOfType<ValuableObject>().ToList(); if ((Object)(object)ignoreThis != (Object)null) { list.Remove(ignoreThis); } for (int i = 0; i < list.Count; i++) { currentValuablesValue += list[i].dollarValueCurrent; } UpdateHaulGoal(); } } private static void UpdateHaulGoal() { //IL_0021: Unknown result type (might be due to invalid IL or missing references) //IL_0027: Expected O, but got Unknown //IL_0058: Unknown result type (might be due to invalid IL or missing references) //IL_005d: Unknown result type (might be due to invalid IL or missing references) //IL_006a: Unknown result type (might be due to invalid IL or missing references) //IL_006c: Unknown result type (might be due to invalid IL or missing references) FieldInfo fieldInfo = AccessTools.Field(typeof(RoundDirector), "extractionPointCurrent"); ExtractionPoint val = (ExtractionPoint)fieldInfo.GetValue(RoundDirector.instance); if ((Object)(object)val != (Object)null) { ExtractionPoint component = ((Component)val).GetComponent<ExtractionPoint>(); FieldInfo fieldInfo2 = AccessTools.Field(typeof(ExtractionPoint), "currentState"); State currentExtractionPointState = (State)fieldInfo2.GetValue(component); currentExtractionHaulGoal = component.haulGoal; _currentExtractionPointState = currentExtractionPointState; } } [HarmonyPatch(typeof(PhysGrabObject), "DestroyPhysGrabObject")] [HarmonyPostfix] public static void DestroyPhysGrabObjectPostfix(PhysGrabObject __instance) { if (SemiFunc.RunIsLevel()) { FieldInfo fieldInfo = AccessTools.Field(typeof(RoundDirector), "allExtractionPointsCompleted"); hasCompletedAllTasks = (bool)fieldInfo.GetValue(RoundDirector.instance); CheckForItems(((Component)__instance).GetComponent<ValuableObject>()); KillCheck(); } } [HarmonyPatch(typeof(ExtractionPoint), "HaulGoalSetRPC")] [HarmonyPostfix] public static void HaulGoalSetRPC(ExtractionPoint __instance) { if (SemiFunc.RunIsLevel()) { CheckForItems(); KillCheck(); } } [HarmonyPatch(typeof(ExtractionPoint), "StateExtracting")] [HarmonyPostfix] public static void StateExtractingPostfix(ExtractionPoint __instance) { //IL_002e: Unknown result type (might be due to invalid IL or missing references) //IL_0034: Expected O, but got Unknown //IL_0067: Unknown result type (might be due to invalid IL or missing references) //IL_006c: Unknown result type (might be due to invalid IL or missing references) //IL_006e: Unknown result type (might be due to invalid IL or missing references) //IL_0071: Invalid comparison between Unknown and I4 if (!SemiFunc.RunIsLevel()) { return; } FieldInfo fieldInfo = AccessTools.Field(typeof(RoundDirector), "extractionPointCurrent"); ExtractionPoint val = (ExtractionPoint)fieldInfo.GetValue(RoundDirector.instance); if ((Object)(object)val != (Object)null) { ExtractionPoint component = ((Component)val).GetComponent<ExtractionPoint>(); FieldInfo fieldInfo2 = AccessTools.Field(typeof(ExtractionPoint), "currentState"); State val2 = (State)fieldInfo2.GetValue(component); if ((int)val2 == 6 && onCountdown && KillManager.counterObj.activeSelf) { onCountdown = false; KillManager.instance.StopKillThemAll(); KillManager.counterObj.SetActive(false); } } } [HarmonyPatch(typeof(RoundDirector), "ExtractionPointsUnlockRPC")] [HarmonyPostfix] public static void ExtractionPointsUnlockRPCPostfix(RoundDirector __instance) { if (!SemiFunc.RunIsLevel()) { return; } onCountdown = false; if (GameManager.instance.gameMode == 0) { KillManager.instance.StopKillThemAll(); } else if ((Object)(object)KillManager.instance != (Object)null) { PhotonView component = ((Component)KillManager.instance).GetComponent<PhotonView>(); if ((Object)(object)component != (Object)null) { component.RPC("StopKillThemAll", (RpcTarget)0, Array.Empty<object>()); } else { DebugRepo("PhotonView not found on KillManager."); } } else { DebugRepo("KillManager instance is null!"); } } [HarmonyPatch(typeof(RoundDirector), "ExtractionCompletedAllRPC")] [HarmonyPostfix] public static void ExtractionCompletedAllRPCPostfix(RoundDirector __instance) { if (!SemiFunc.RunIsLevel()) { return; } if (GameManager.instance.gameMode == 0) { KillManager.instance.CompletedAllTasks(); } else if ((Object)(object)KillManager.instance != (Object)null) { PhotonView component = ((Component)KillManager.instance).GetComponent<PhotonView>(); if ((Object)(object)component != (Object)null) { if (PhotonNetwork.IsMasterClient) { component.RPC("CompletedAllTasks", (RpcTarget)0, Array.Empty<object>()); } } else { DebugRepo("PhotonView not found on KillManager."); } } else { DebugRepo("KillManager instance is null!"); } } private static void CreateHUDElements() { //IL_0065: Unknown result type (might be due to invalid IL or missing references) //IL_0074: 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_0092: Unknown result type (might be due to invalid IL or missing references) //IL_00ce: Unknown result type (might be due to invalid IL or missing references) //IL_00dd: Unknown result type (might be due to invalid IL or missing references) //IL_00ec: Unknown result type (might be due to invalid IL or missing references) //IL_00fb: Unknown result type (might be due to invalid IL or missing references) //IL_0137: Unknown result type (might be due to invalid IL or missing references) //IL_0146: Unknown result type (might be due to invalid IL or missing references) //IL_0155: Unknown result type (might be due to invalid IL or missing references) //IL_0164: Unknown result type (might be due to invalid IL or missing references) GameObject val = GameObject.Find("Game Hud"); GameObject val2 = GameObject.Find("HealthMax"); if (!((Object)(object)val != (Object)null) || !((Object)(object)val2 != (Object)null)) { return; } TMP_FontAsset font = val2.GetComponent<TMP_Text>().font; GameObject val3 = HUDManager.instance.CreateTextGUIElement("Kill Or Die HUD", font, val.transform, _enableWordWrapping: false, (TextAlignmentOptions)514, (HorizontalAlignmentOptions)2, (VerticalAlignmentOptions)512, new Vector2(0.5f, 0.5f), new Vector2(0.5f, 0.5f), new Vector2(0.5f, 0.5f), new Vector2(0f, 0f)); val3.SetActive(false); GameObject val4 = HUDManager.instance.CreateTextGUIElement("Final Countdown HUD", font, val.transform, _enableWordWrapping: false, (TextAlignmentOptions)514, (HorizontalAlignmentOptions)2, (VerticalAlignmentOptions)512, new Vector2(0.5f, 1f), new Vector2(0.5f, 1f), new Vector2(0.5f, 1f), new Vector2(0f, 0f)); val4.SetActive(false); GameObject val5 = HUDManager.instance.CreateTextGUIElement("Die HUD", font, val.transform, _enableWordWrapping: false, (TextAlignmentOptions)514, (HorizontalAlignmentOptions)2, (VerticalAlignmentOptions)512, new Vector2(0.5f, 0.5f), new Vector2(0.5f, 0.5f), new Vector2(0.5f, 0.5f), new Vector2(0f, 0f)); val5.SetActive(false); KillManager.killOrDieObj = val3; KillManager.dieObj = val5; KillManager.counterObj = val4; if (GameManager.instance.gameMode == 0) { KillManager.instance.SetCounterTimer(counterTime); } else if (PhotonNetwork.IsMasterClient) { PhotonView component = ((Component)KillManager.instance).GetComponent<PhotonView>(); if ((Object)(object)component != (Object)null) { component.RPC("SetCounterTimer", (RpcTarget)0, new object[1] { counterTime }); } else { DebugRepo("PhotonView not found on KillManager."); } } } public static void DebugRepo(string message) { Debug.Log((object)("[No Items Left] " + message)); } } public class HUDManager : MonoBehaviour { public static HUDManager instance; private void Awake() { instance = this; } public GameObject CreateTextGUIElement(string _name = "HUDElement", TMP_FontAsset _fontAsset = null, Transform _parent = null, bool _enableWordWrapping = true, TextAlignmentOptions _alignment = 2050, HorizontalAlignmentOptions _horizontalAlignment = 1, VerticalAlignmentOptions _verticalAlignment = 2048, Vector2 _anchorMin = default(Vector2), Vector2 _anchorMax = default(Vector2), Vector2 _pivot = default(Vector2), Vector2 _anchoredPosition = default(Vector2)) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Expected O, but got Unknown //IL_002f: Unknown result type (might be due to invalid IL or missing references) //IL_0038: Unknown result type (might be due to invalid IL or missing references) //IL_0041: Unknown result type (might be due to invalid IL or missing references) //IL_0064: 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_0076: Unknown result type (might be due to invalid IL or missing references) //IL_007f: Unknown result type (might be due to invalid IL or missing references) GameObject val = new GameObject(); ((Object)val).name = _name; val.AddComponent<TextMeshProUGUI>(); TextMeshProUGUI component = val.GetComponent<TextMeshProUGUI>(); ((TMP_Text)component).font = _fontAsset; ((TMP_Text)component).enableWordWrapping = _enableWordWrapping; ((TMP_Text)component).alignment = _alignment; ((TMP_Text)component).horizontalAlignment = _horizontalAlignment; ((TMP_Text)component).verticalAlignment = _verticalAlignment; val.transform.SetParent(((Component)_parent).transform, false); RectTransform component2 = val.GetComponent<RectTransform>(); component2.anchorMin = _anchorMin; component2.anchorMax = _anchorMax; component2.pivot = _pivot; component2.anchoredPosition = _anchoredPosition; return val; } public void SetChangeText(TextMeshProUGUI element, string text, Color color, int fontSize) { //IL_000a: Unknown result type (might be due to invalid IL or missing references) ((TMP_Text)element).text = text; ((Graphic)element).color = color; ((TMP_Text)element).fontSize = fontSize; } } public class KillManager : MonoBehaviourPun { [CompilerGenerated] private sealed class <KillThemAll>d__11 : IEnumerator<object>, IDisposable, IEnumerator { private int <>1__state; private object <>2__current; public string playerName; public int messageIdx; public KillManager <>4__this; private TextMeshProUGUI <killOrDieText>5__1; private TextMeshProUGUI <counterText>5__2; private TextMeshProUGUI <dieText>5__3; private string[] <messages>5__4; private float <timer>5__5; private int <minutes>5__6; private int <seconds>5__7; private bool <hasGlitched>5__8; private float <lerpFactor>5__9; object IEnumerator<object>.Current { [DebuggerHidden] get { return <>2__current; } } object IEnumerator.Current { [DebuggerHidden] get { return <>2__current; } } [DebuggerHidden] public <KillThemAll>d__11(int <>1__state) { this.<>1__state = <>1__state; } [DebuggerHidden] void IDisposable.Dispose() { <killOrDieText>5__1 = null; <counterText>5__2 = null; <dieText>5__3 = null; <messages>5__4 = null; <>1__state = -2; } private bool MoveNext() { //IL_0245: 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_0274: Expected O, but got Unknown //IL_02a6: Unknown result type (might be due to invalid IL or missing references) //IL_02cb: Unknown result type (might be due to invalid IL or missing references) //IL_02d5: Expected O, but got Unknown //IL_0307: Unknown result type (might be due to invalid IL or missing references) //IL_032c: Unknown result type (might be due to invalid IL or missing references) //IL_0336: Expected O, but got Unknown //IL_0368: Unknown result type (might be due to invalid IL or missing references) //IL_038d: Unknown result type (might be due to invalid IL or missing references) //IL_0397: Expected O, but got Unknown //IL_03c9: 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_03f8: Expected O, but got Unknown //IL_047b: Unknown result type (might be due to invalid IL or missing references) //IL_0620: Unknown result type (might be due to invalid IL or missing references) //IL_0645: Unknown result type (might be due to invalid IL or missing references) //IL_064f: Expected O, but got Unknown //IL_054a: Unknown result type (might be due to invalid IL or missing references) //IL_054f: Unknown result type (might be due to invalid IL or missing references) //IL_055a: Unknown result type (might be due to invalid IL or missing references) switch (<>1__state) { default: return false; case 0: <>1__state = -1; <killOrDieText>5__1 = killOrDieObj.GetComponent<TextMeshProUGUI>(); <counterText>5__2 = counterObj.GetComponent<TextMeshProUGUI>(); <dieText>5__3 = dieObj.GetComponent<TextMeshProUGUI>(); <messages>5__4 = new string[16] { "Oops, <color=red>" + playerName + "</color>! All on you!", "Oh no, <color=red>" + playerName + "</color> made a mistake...", "Yeah, you can blame <color=red>" + playerName + "</color> for this.", "Be careful next time, <color=red>" + playerName + "</color>.", "Bad luck, <color=red>" + playerName + "</color>...", "Wait, who invited <color=red>" + playerName + "</color> again?", "Well done, <color=red>" + playerName + "</color>... not!", "Nice job, <color=red>" + playerName + "</color>. Now look what you’ve done!", "Everybody, a round of applause for <color=red>" + playerName + "</color>!", "Oops! That was definitely <color=red>" + playerName + "</color>'s fault.", "Uh-oh, <color=red>" + playerName + "</color> did it again...", "Quick, act natural! Maybe no one saw, <color=red>" + playerName + "</color>.", "Seriously, <color=red>" + playerName + "</color>? You had one job!", "Guess who just made history? <color=red>" + playerName + "</color>!", "RIP, whatever that was. Thanks, <color=red>" + playerName + "</color>.", "Breaking news: <color=red>" + playerName + "</color> strikes again!" }; PlayerAvatar.instance.PlayerGlitchShort(); HUDManager.instance.SetChangeText(<killOrDieText>5__1, <messages>5__4[messageIdx], Color.white, 32); ((Component)<killOrDieText>5__1).gameObject.SetActive(true); <>2__current = (object)new WaitForSeconds(3f); <>1__state = 1; return true; case 1: <>1__state = -1; ((Component)<killOrDieText>5__1).gameObject.SetActive(false); HUDManager.instance.SetChangeText(<killOrDieText>5__1, "Not enough valuables on the map.", Color.white, 32); ((Component)<killOrDieText>5__1).gameObject.SetActive(true); <>2__current = (object)new WaitForSeconds(2f); <>1__state = 2; return true; case 2: <>1__state = -1; ((Component)<killOrDieText>5__1).gameObject.SetActive(false); HUDManager.instance.SetChangeText(<killOrDieText>5__1, "Kill a <color=red>Monster</color> to get <color=green>Money</color>", Color.white, 32); ((Component)<killOrDieText>5__1).gameObject.SetActive(true); <>2__current = (object)new WaitForSeconds(3f); <>1__state = 3; return true; case 3: <>1__state = -1; ((Component)<killOrDieText>5__1).gameObject.SetActive(false); HUDManager.instance.SetChangeText(<killOrDieText>5__1, "or", Color.white, 32); ((Component)<killOrDieText>5__1).gameObject.SetActive(true); <>2__current = (object)new WaitForSeconds(1f); <>1__state = 4; return true; case 4: <>1__state = -1; ((Component)<killOrDieText>5__1).gameObject.SetActive(false); HUDManager.instance.SetChangeText(<killOrDieText>5__1, "DIE", Color.red, 100); ((Component)<killOrDieText>5__1).gameObject.SetActive(true); <>2__current = (object)new WaitForSeconds(2f); <>1__state = 5; return true; case 5: <>1__state = -1; ((Component)<killOrDieText>5__1).gameObject.SetActive(false); <timer>5__5 = countTime; <minutes>5__6 = (int)<timer>5__5 / 60; <seconds>5__7 = (int)<timer>5__5 % 60; PlayerAvatar.instance.PlayerGlitchShort(); HUDManager.instance.SetChangeText(<counterText>5__2, $"{<minutes>5__6}:{<seconds>5__7:00}", Color.white, 18); ((Component)<counterText>5__2).gameObject.SetActive(true); <hasGlitched>5__8 = false; goto IL_05c2; case 6: <>1__state = -1; <timer>5__5 -= Time.deltaTime; goto IL_05c2; case 7: { <>1__state = -1; ((Component)<dieText>5__3).gameObject.SetActive(false); if (GameManager.instance.gameMode == 0) { PlayerAvatar.instance.PlayerDeathRPC(0); } else { PlayerAvatar.instance.photonView.RPC("PlayerDeathRPC", (RpcTarget)0, new object[1] { 0 }); } ((Component)<dieText>5__3).gameObject.SetActive(false); break; } IL_05c2: if (<timer>5__5 > 0f && !hasCompletedTask) { <minutes>5__6 = (int)<timer>5__5 / 60; <seconds>5__7 = (int)<timer>5__5 % 60; ((TMP_Text)<counterText>5__2).text = $"{<minutes>5__6}:{<seconds>5__7:00}"; if (<timer>5__5 <= 11f) { if (!<hasGlitched>5__8) { <hasGlitched>5__8 = true; PlayerAvatar.instance.PlayerGlitchShort(); } <lerpFactor>5__9 = 1f - <timer>5__5 % 1f; ((Graphic)<counterText>5__2).color = Color.Lerp(Color.red, Color.white, <lerpFactor>5__9); ((TMP_Text)<counterText>5__2).text = $"{<seconds>5__7}"; ((TMP_Text)<counterText>5__2).fontSize = 32f; } <>2__current = null; <>1__state = 6; return true; } if (!hasCompletedTask) { ((Component)<counterText>5__2).gameObject.SetActive(false); PlayerAvatar.instance.PlayerGlitchShort(); HUDManager.instance.SetChangeText(<dieText>5__3, "Better luck next time! <color=red>;)</color>", Color.white, 32); ((Component)<dieText>5__3).gameObject.SetActive(true); <>2__current = (object)new WaitForSeconds(3f); <>1__state = 7; return true; } break; } return false; } bool IEnumerator.MoveNext() { //ILSpy generated this explicit interface implementation from .override directive in MoveNext return this.MoveNext(); } [DebuggerHidden] void IEnumerator.Reset() { throw new NotSupportedException(); } } public static KillManager instance; public static float countTime; public static GameObject killOrDieObj; public static GameObject counterObj; public static GameObject dieObj; public static bool hasCompletedTask; private void Awake() { instance = this; } [PunRPC] public void SetCounterTimer(float timer) { ModPatch.DebugRepo($"Setting counter timer to {timer}"); countTime = timer; } [PunRPC] public void CompletedAllTasks() { ModPatch.DebugRepo("Players completed all tasks!"); hasCompletedTask = true; ((MonoBehaviour)this).StopCoroutine(KillThemAll()); if (counterObj.activeSelf) { counterObj.SetActive(false); } } [PunRPC] public void CallKillThemAll(string playerName, int messageIdx) { hasCompletedTask = false; ((MonoBehaviour)this).StartCoroutine(KillThemAll(playerName, messageIdx)); } [PunRPC] public void StopKillThemAll() { hasCompletedTask = true; ((MonoBehaviour)this).StopCoroutine(KillThemAll()); if (counterObj.activeSelf) { counterObj.SetActive(false); } } [IteratorStateMachine(typeof(<KillThemAll>d__11))] private IEnumerator KillThemAll(string playerName = "", int messageIdx = 0) { //yield-return decompiler failed: Unexpected instruction in Iterator.Dispose() return new <KillThemAll>d__11(0) { <>4__this = this, playerName = playerName, messageIdx = messageIdx }; } } namespace REPONoItemsLeft { [BepInPlugin("FNKTLabs.REPONoItemsLeft", "No Items Left", "1.1.7")] public class ModBase : BaseUnityPlugin { private const string modGUID = "FNKTLabs.REPONoItemsLeft"; private const string modName = "No Items Left"; private const string modVersion = "1.1.7"; private Harmony _harmony = new Harmony("FNKTLabs.REPONoItemsLeft"); internal ManualLogSource _logSource; public static ConfigEntry<float> config_Timer; public void Awake() { _logSource = Logger.CreateLogSource("FNKTLabs.REPONoItemsLeft"); _logSource.LogInfo((object)"REPO No Items Left loaded!"); ConfigFile(); _harmony.PatchAll(typeof(ModBase)); _harmony.PatchAll(typeof(ModPatch)); } public void ConfigFile() { //IL_002f: Unknown result type (might be due to invalid IL or missing references) //IL_0039: Expected O, but got Unknown config_Timer = ((BaseUnityPlugin)this).Config.Bind<float>("Countdown Timer", "Time", 300f, new ConfigDescription("Sets the time players have to kill a monster and get money when there aren’t enough items and the objectives are still pending.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(10f, 600f), Array.Empty<object>())); ModPatch.counterTime = config_Timer.Value; } } } namespace REPONoItemsLeft.Patches { public class CoroutineHelper : MonoBehaviour { private static CoroutineHelper instance; public static CoroutineHelper Instance { get { //IL_0016: Unknown result type (might be due to invalid IL or missing references) //IL_001c: Expected O, but got Unknown if ((Object)(object)instance == (Object)null) { GameObject val = new GameObject("CoroutineHelper"); instance = val.AddComponent<CoroutineHelper>(); Object.DontDestroyOnLoad((Object)(object)val); } return instance; } } } }
plugins/GalaCorp-InfiniteStamina/InfiniteStamina.dll
Decompiled 2 months agousing System.Diagnostics; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Versioning; using BepInEx; using BepInEx.Logging; using HarmonyLib; using InfiniteStamina.Patches; 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("InfiniteStamina")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("InfiniteStamina")] [assembly: AssemblyCopyright("Copyright © 2025")] [assembly: AssemblyTrademark("")] [assembly: ComVisible(false)] [assembly: Guid("43e9cac9-6b1f-46f0-b1f3-f37575e133fd")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")] [assembly: AssemblyVersion("1.0.0.0")] namespace InfiniteStamina { [BepInPlugin("Galaxcito.REPO.InfiniteStamina", "Infinite Stamina", "1.0.0")] public class InfiniteStamina : BaseUnityPlugin { private const string modGUID = "Galaxcito.REPO.InfiniteStamina"; private const string modName = "Infinite Stamina"; private const string modVersion = "1.0.0"; private readonly Harmony harmony = new Harmony("Galaxcito.REPO.InfiniteStamina"); internal ManualLogSource mls; internal static InfiniteStamina instance { get; private set; } private void Awake() { if ((Object)(object)instance == (Object)null) { instance = this; } mls = ((BaseUnityPlugin)this).Logger; mls.LogInfo((object)"The mod Infinite Stamina by Galaxcito was loaded successfully :p"); harmony.PatchAll(typeof(InfiniteStamina)); harmony.PatchAll(typeof(PlayerStaminaPatch)); } } } namespace InfiniteStamina.Patches { [HarmonyPatch(typeof(PlayerController))] internal class PlayerStaminaPatch { [HarmonyPatch("Update")] [HarmonyPatch("FixedUpdate")] [HarmonyPostfix] private static void InfiniteStaminaPatch(PlayerController __instance) { if (__instance.sprinting) { __instance.EnergyCurrent = __instance.EnergyStart; } else if (__instance.Sliding) { __instance.EnergyCurrent = __instance.EnergyStart; } } } }
plugins/GalaxyMods-MoreShopItems/MoreShopItems.dll
Decompiled 2 months agousing System; using System.Diagnostics; using System.IO; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using System.Security; using System.Security.Permissions; using BepInEx; using BepInEx.Configuration; using BepInEx.Logging; using HarmonyLib; using Microsoft.CodeAnalysis; using Photon.Pun; using REPOLib.Modules; 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("MoreShopItems")] [assembly: AssemblyConfiguration("Debug")] [assembly: AssemblyFileVersion("1.2.2.0")] [assembly: AssemblyInformationalVersion("1.2.2")] [assembly: AssemblyProduct("More Shop Items")] [assembly: AssemblyTitle("MoreShopItems")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("1.2.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.Module, AllowMultiple = false, Inherited = false)] internal sealed class RefSafetyRulesAttribute : Attribute { public readonly int Version; public RefSafetyRulesAttribute(int P_0) { Version = P_0; } } } namespace MoreShopItems { [BepInPlugin("MoreShopItems", "More Shop Items", "1.2.2")] [BepInDependency(/*Could not decode attribute arguments.*/)] public class Plugin : BaseUnityPlugin { private readonly Harmony _harmony = new Harmony("MoreShopItems"); public static GameObject CustomSodaShelf; internal ConfigEntry<int> itemtargetSpawnAmount; internal int itemConsumablesAmount; internal ConfigEntry<int> itemUpgradesAmount; internal ConfigEntry<int> itemHealthPacksAmount; internal static Plugin Instance { get; private set; } internal static ManualLogSource Logger { get; private set; } private void Awake() { //IL_0054: Unknown result type (might be due to invalid IL or missing references) //IL_005e: Expected O, but got Unknown //IL_008c: Unknown result type (might be due to invalid IL or missing references) //IL_0096: Expected O, but got Unknown //IL_00c4: Unknown result type (might be due to invalid IL or missing references) //IL_00ce: Expected O, but got Unknown if ((Object)(object)Instance == (Object)null) { Instance = this; } Logger = ((BaseUnityPlugin)this).Logger; itemtargetSpawnAmount = ((BaseUnityPlugin)Instance).Config.Bind<int>("General", "Total Shop Item Count", 200, new ConfigDescription("The maximum number of items the shop will spawn.\nVanilla default: 8", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 200), Array.Empty<object>())); itemUpgradesAmount = ((BaseUnityPlugin)Instance).Config.Bind<int>("General", "Upgrade Item Count", 60, new ConfigDescription("The maximum number of upgrades the shop will spawn.\nVanilla default: 3", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 50), Array.Empty<object>())); itemHealthPacksAmount = ((BaseUnityPlugin)Instance).Config.Bind<int>("General", "Health Pack Item Count", 30, new ConfigDescription("The maximum number of health pacls the shop will spawn.\nVanilla default: 3", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 30), Array.Empty<object>())); itemConsumablesAmount = itemHealthPacksAmount.Value + itemUpgradesAmount.Value; AssetBundle val = AssetBundle.LoadFromFile(Path.Combine(Path.GetDirectoryName(((BaseUnityPlugin)Instance).Info.Location), "moreshopitems_assets.file")); CustomSodaShelf = val.LoadAsset<GameObject>("custom_soda_shelf"); NetworkPrefabs.RegisterNetworkPrefab(CustomSodaShelf); _harmony.PatchAll(typeof(ShopManagerPatch)); _harmony.PatchAll(typeof(CustomShelfPatch)); _harmony.PatchAll(typeof(ChangeAmountPatch)); Logger.LogInfo((object)"\n __ __ ___ ____ ___ ___ _ _ ___ ____ _____ _____ ___ __ __ ___ \n| V || _ || __ || __| | __|| |_| || _ || __ | |_ _||_ _|| __|| V || __|\n| |V| || | || < | __| |__ || _ || | || __| _| |_ | | | __|| |V| ||__ |\n|_| |_||___||_||_||___| |___||_| |_||___||_| |_____| |_| |___||_| |_||___| v1.2.2\n"); } } [HarmonyPatch(typeof(ShopManager), "Awake")] internal static class ShopManagerPatch { private static readonly FieldRef<ShopManager, int> itemSpawnTargetAmount_ref = AccessTools.FieldRefAccess<ShopManager, int>("itemSpawnTargetAmount"); private static readonly FieldRef<ShopManager, int> itemConsumablesAmount_ref = AccessTools.FieldRefAccess<ShopManager, int>("itemConsumablesAmount"); private static readonly FieldRef<ShopManager, int> itemUpgradesAmount_ref = AccessTools.FieldRefAccess<ShopManager, int>("itemUpgradesAmount"); private static readonly FieldRef<ShopManager, int> itemHealthPacksAmount_ref = AccessTools.FieldRefAccess<ShopManager, int>("itemHealthPacksAmount"); private static void Postfix(ShopManager __instance) { ref int reference = ref itemSpawnTargetAmount_ref.Invoke(__instance); ref int reference2 = ref itemConsumablesAmount_ref.Invoke(__instance); ref int reference3 = ref itemUpgradesAmount_ref.Invoke(__instance); ref int reference4 = ref itemHealthPacksAmount_ref.Invoke(__instance); reference = Plugin.Instance.itemtargetSpawnAmount.Value; reference2 = Plugin.Instance.itemConsumablesAmount; reference3 = Plugin.Instance.itemUpgradesAmount.Value; reference4 = Plugin.Instance.itemHealthPacksAmount.Value; } } [HarmonyPatch(typeof(ShopManager), "ShopInitialize")] internal static class CustomShelfPatch { private static GameObject shelf; private static void Prefix() { //IL_00ad: 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_0079: Unknown result type (might be due to invalid IL or missing references) //IL_0084: Unknown result type (might be due to invalid IL or missing references) //IL_01a4: Unknown result type (might be due to invalid IL or missing references) //IL_01b0: Unknown result type (might be due to invalid IL or missing references) //IL_01c4: Unknown result type (might be due to invalid IL or missing references) //IL_01c9: Unknown result type (might be due to invalid IL or missing references) //IL_014f: Unknown result type (might be due to invalid IL or missing references) //IL_015b: 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) //IL_0174: Unknown result type (might be due to invalid IL or missing references) //IL_02fe: Unknown result type (might be due to invalid IL or missing references) //IL_030a: Unknown result type (might be due to invalid IL or missing references) //IL_0314: Unknown result type (might be due to invalid IL or missing references) //IL_0319: Unknown result type (might be due to invalid IL or missing references) //IL_0325: Unknown result type (might be due to invalid IL or missing references) //IL_032f: Unknown result type (might be due to invalid IL or missing references) //IL_0334: Unknown result type (might be due to invalid IL or missing references) //IL_0340: Unknown result type (might be due to invalid IL or missing references) //IL_0354: 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) //IL_0270: Unknown result type (might be due to invalid IL or missing references) //IL_027c: Unknown result type (might be due to invalid IL or missing references) //IL_0286: Unknown result type (might be due to invalid IL or missing references) //IL_028b: Unknown result type (might be due to invalid IL or missing references) //IL_0297: Unknown result type (might be due to invalid IL or missing references) //IL_02a1: Unknown result type (might be due to invalid IL or missing references) //IL_02a6: Unknown result type (might be due to invalid IL or missing references) //IL_02b2: Unknown result type (might be due to invalid IL or missing references) //IL_02c6: Unknown result type (might be due to invalid IL or missing references) //IL_02cb: Unknown result type (might be due to invalid IL or missing references) if (!(RunManager.instance.levelCurrent.ResourcePath == "Shop")) { return; } GameObject val = GameObject.Find("Soda Shelf"); GameObject val2 = GameObject.Find("Module Switch BOT"); if ((Object)(object)val != (Object)null && !val2.GetComponent<ModulePropSwitch>().ConnectedParent.activeSelf) { if (!SemiFunc.IsMultiplayer()) { shelf = Object.Instantiate<GameObject>(Plugin.CustomSodaShelf, val.transform.position, val.transform.rotation, val2.transform); } else { shelf = PhotonNetwork.Instantiate(((Object)Plugin.CustomSodaShelf).name, val.transform.position, val.transform.rotation, (byte)0, (object[])null); SetParent(val2.transform); } val.SetActive(false); } else { GameObject val3 = GameObject.Find("Shop Magazine Stand (1)"); GameObject val4 = GameObject.Find("Shop Magazine Stand"); GameObject val5 = GameObject.Find("Module Switch (1) top"); if ((Object)(object)val3 != (Object)null && !val5.GetComponent<ModulePropSwitch>().ConnectedParent.activeSelf) { if (!SemiFunc.IsMultiplayer()) { shelf = Object.Instantiate<GameObject>(Plugin.CustomSodaShelf, val3.transform.position, val3.transform.rotation * Quaternion.Euler(0f, 90f, 0f), val5.transform.parent); } else { shelf = PhotonNetwork.Instantiate(((Object)Plugin.CustomSodaShelf).name, val3.transform.position, val3.transform.rotation * Quaternion.Euler(0f, 90f, 0f), (byte)0, (object[])null); SetParent(val5.transform); } val3.SetActive(false); if ((Object)(object)val4 != (Object)null) { val4.SetActive(false); } } else { GameObject val6 = GameObject.Find("Module Switch (2) left"); GameObject val7 = GameObject.Find("Candy Shelf"); if (!((Object)(object)val6 != (Object)null) || val6.GetComponent<ModulePropSwitch>().ConnectedParent.activeSelf) { Plugin.Logger.LogInfo((object)"Edge case found. Temporarily preventing spawn of custom shelf."); return; } if (!SemiFunc.IsMultiplayer()) { shelf = Object.Instantiate<GameObject>(Plugin.CustomSodaShelf, val6.transform.position + val6.transform.right * 0.5f - val6.transform.forward * 0.8f, val6.transform.rotation * Quaternion.Euler(0f, 180f, 0f), val5.transform.parent); } else { shelf = PhotonNetwork.Instantiate(((Object)Plugin.CustomSodaShelf).name, val6.transform.position + val6.transform.right * 0.5f - val6.transform.forward * 0.8f, val6.transform.rotation * Quaternion.Euler(0f, 180f, 0f), (byte)0, (object[])null); SetParent(val6.transform); } if ((Object)(object)val7 != (Object)null) { val7.SetActive(false); } } } Plugin.Logger.LogInfo((object)"Successfully added object(s)!"); } [PunRPC] public static void SetParent(Transform parent) { shelf.transform.SetParent(parent); } } [HarmonyPatch(typeof(ShopManager), "GetAllItemsFromStatsManager")] internal static class ChangeAmountPatch { private static void Prefix() { foreach (Item value in StatsManager.instance.itemDictionary.Values) { value.maxAmountInShop = 10; } } } public static class MyPluginInfo { public const string PLUGIN_GUID = "MoreShopItems"; public const string PLUGIN_NAME = "More Shop Items"; public const string PLUGIN_VERSION = "1.2.2"; } }
plugins/Godji-UltimateRevive/UltimateRevive.dll
Decompiled 2 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 HarmonyLib; using UltimateRevive.Patches; using UnityEngine; using UnityEngine.InputSystem; using UnityEngine.InputSystem.Controls; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)] [assembly: AssemblyTitle("UltimateRevive")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("UltimateRevive")] [assembly: AssemblyCopyright("Copyright © 2025")] [assembly: AssemblyTrademark("")] [assembly: ComVisible(false)] [assembly: Guid("f6d01380-ae72-46c1-999b-efd8e0c25027")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")] [assembly: AssemblyVersion("1.0.0.0")] namespace UltimateRevive { [BepInPlugin("Godji.UltimateRevive", "REPO Ultimate Revive", "1.0.0")] public class UltimateRevive : BaseUnityPlugin { private const string modGUID = "Godji.UltimateRevive"; private const string modName = "REPO Ultimate Revive"; private const string modVersion = "1.0.0"; private readonly Harmony harmony = new Harmony("Godji.UltimateRevive"); private static UltimateRevive Instance; internal ManualLogSource mls; private void Awake() { if ((Object)(object)Instance == (Object)null) { Instance = this; } mls = Logger.CreateLogSource("Godji.UltimateRevive"); ConfigManager.Initialize(((BaseUnityPlugin)this).Config); mls.LogInfo((object)"[Godji] Ultiumate Revive Inited."); harmony.PatchAll(typeof(UltimateRevive)); harmony.PatchAll(typeof(ShopManagerPatch)); harmony.PatchAll(typeof(PlayerControllerPatch)); harmony.PatchAll(typeof(PhysGrabCartPatch)); } } } namespace UltimateRevive.Patches { internal class ConfigManager { public static ConfigEntry<int> hpCost; public static ConfigEntry<string> reviveKey; public static void Initialize(ConfigFile cfg) { hpCost = cfg.Bind<int>("Revive HP Settings", "StaminaCost", 20, "The amount of hp consumed when reviving."); reviveKey = cfg.Bind<string>("Controls", "ReviveKey", "h", "The key used to trigger a revive."); } } [HarmonyPatch(typeof(PhysGrabCart))] internal class PhysGrabCartPatch { [HarmonyPatch("Update")] [HarmonyPostfix] private static void displayText() { //IL_00ff: 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) if (!SemiFunc.RunIsShop() && PlayerControllerPatch.isGrab) { FieldInfo fieldInfo = AccessTools.Field(typeof(PlayerAvatar), "playerName"); object value = fieldInfo.GetValue(PlayerControllerPatch.grabHead.playerAvatar); PlayerHealth playerHealth = PlayerController.instance.playerAvatarScript.playerHealth; FieldInfo fieldInfo2 = AccessTools.Field(typeof(PlayerHealth), "health"); int num = (int)fieldInfo2.GetValue(playerHealth); int value2 = ConfigManager.hpCost.Value; string value3 = ConfigManager.reviveKey.Value; if (num < value2) { Color val = default(Color); ((Color)(ref val))..ctor(1f, 0f, 0f); ItemInfoExtraUI.instance.ItemInfoText($"Your HP is below {value2}", val); } else { Color val2 = default(Color); ((Color)(ref val2))..ctor(0.2f, 0.8f, 0.1f); ItemInfoExtraUI.instance.ItemInfoText($"Press [{value3}] to revive {value} with {value2} HP", val2); } } } } [HarmonyPatch(typeof(PlayerController))] internal class PlayerControllerPatch { public static PlayerDeathHead grabHead; public static bool isGrab; [HarmonyPatch("FixedUpdate")] [HarmonyPostfix] private static void PlayerGrabHeadPatch(PlayerController __instance) { if ((Object)(object)__instance == (Object)null) { return; } if (__instance.physGrabActive && (Object)(object)__instance.physGrabObject != (Object)null) { PlayerDeathHead component = __instance.physGrabObject.GetComponent<PlayerDeathHead>(); if ((Object)(object)component != (Object)null && (Object)(object)component.playerAvatar != (Object)null) { grabHead = component; isGrab = true; } } else { isGrab = false; } } } internal class ReviveManager : MonoBehaviour { private void Update() { //IL_0017: Unknown result type (might be due to invalid IL or missing references) InputControl val = ((InputControl)Keyboard.current)[ConfigManager.reviveKey.Value]; if (!((ButtonControl)val).wasPressedThisFrame) { return; } PlayerDeathHead grabHead = PlayerControllerPatch.grabHead; bool isGrab = PlayerControllerPatch.isGrab; PlayerHealth playerHealth = PlayerController.instance.playerAvatarScript.playerHealth; FieldInfo fieldInfo = AccessTools.Field(typeof(PlayerHealth), "health"); int num = (int)fieldInfo.GetValue(playerHealth); int value = ConfigManager.hpCost.Value; if (num >= value && num >= num - value && isGrab) { FieldInfo fieldInfo2 = AccessTools.Field(typeof(PlayerDeathHead), "inExtractionPoint"); if (!(bool)fieldInfo2.GetValue(grabHead)) { fieldInfo2.SetValue(grabHead, true); grabHead.Revive(); playerHealth.Hurt(value, true, -1); fieldInfo2.SetValue(grabHead, false); } } } } [HarmonyPatch(typeof(ShopManager))] internal class ShopManagerPatch { [HarmonyPatch("Awake")] [HarmonyPostfix] private static void keyboardListener(ShopManager __instance) { if (!((Object)(object)__instance == (Object)null) && (Object)(object)((Component)__instance).gameObject.GetComponent<ReviveManager>() == (Object)null) { ((Component)__instance).gameObject.AddComponent<ReviveManager>(); Debug.Log((object)"[UltimateRevive] Added keyboard event listener"); } } } }
plugins/ironbean-LevelNumberUI/REPO Level Number.dll
Decompiled 2 months agousing System.Diagnostics; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Versioning; using BepInEx; using BepInEx.Logging; using HarmonyLib; using TMPro; 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("REPO Level Number")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("REPO Level Number")] [assembly: AssemblyCopyright("Copyright © 2025")] [assembly: AssemblyTrademark("")] [assembly: ComVisible(false)] [assembly: Guid("c7ba60f1-eeaf-4c76-9c08-97cfec43b265")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")] [assembly: AssemblyVersion("1.0.0.0")] namespace REPO_Level_Number; [BepInPlugin("ironbean.LevelNumberHUD", "Level Number HUD", "1.0.0")] public class LevelNumberHUD : BaseUnityPlugin { [HarmonyPatch(typeof(GoalUI))] internal class GoalPatch { [HarmonyPatch("Update")] [HarmonyPostfix] private static void CustomPatch(ref TextMeshProUGUI ___Text) { if (!SemiFunc.RunIsShop()) { int num = StatsManager.instance.runStats["level"] + 1; ((TMP_Text)___Text).text = "<line-height=75%>" + ((TMP_Text)___Text).text + "\n<color=#ff9600><size=28>Level " + num + "</size></color></b>"; ((TMP_Text)___Text).alignment = (TextAlignmentOptions)260; } } } [HarmonyPatch(typeof(EnergyUI))] internal class EnergyPatch { [HarmonyPatch("Update")] [HarmonyPostfix] private static void CustomPatch(ref TextMeshProUGUI ___Text) { if (SemiFunc.RunIsShop()) { int num = StatsManager.instance.runStats["level"] + 1; ((TMP_Text)___Text).text = "<line-height=75%>" + ((TMP_Text)___Text).text + "\n<color=#ff9600><size=28>Level " + num + "</size></color></b>"; } } } private const string modGUID = "ironbean.LevelNumberHUD"; private const string modName = "Level Number HUD"; private const string modVersion = "1.0.0"; private readonly Harmony harmony = new Harmony("ironbean.LevelNumberHUD"); internal static LevelNumberHUD Instance; internal static ManualLogSource mls; internal bool inShop = false; private void Awake() { if ((Object)(object)Instance == (Object)null) { Instance = this; } mls = Logger.CreateLogSource("ironbean.LevelNumberHUD"); mls.LogInfo((object)"Level Number HUD"); harmony.PatchAll(typeof(LevelNumberHUD)); harmony.PatchAll(typeof(GoalPatch)); harmony.PatchAll(typeof(EnergyPatch)); } }
plugins/Kistras-Valuables_Scanner/Kistras-Scanner.dll
Decompiled 2 months agousing System; using System.Collections.Generic; 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 BepInEx.Logging; using HarmonyLib; using Microsoft.CodeAnalysis; 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("Kistras-Scanner")] [assembly: AssemblyConfiguration("Debug")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: AssemblyInformationalVersion("1.0.0+3f5f01e16c77986a952556a0c48a74dab92c625b")] [assembly: AssemblyProduct("REPO Scanner")] [assembly: AssemblyTitle("Kistras-Scanner")] [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 REPO_Scanner { [BepInPlugin("Kistras-Scanner", "REPO Scanner", "1.0.0")] public class Plugin : BaseUnityPlugin { internal static ManualLogSource Logger; public static InputKey scanKey = (InputKey)327; private readonly Harmony harmony = new Harmony("Kistras-Scanner"); public static ConfigEntry<string> keyBind; private bool IsKeybindValid(string keybind) { return keybind.StartsWith("<Keyboard>/") && keybind.Length == 12 && keybind[11] >= 'a' && keybind[11] <= 'z'; } private void Awake() { //IL_002c: Unknown result type (might be due to invalid IL or missing references) //IL_0036: Expected O, but got Unknown Logger = ((BaseUnityPlugin)this).Logger; keyBind = ((BaseUnityPlugin)this).Config.Bind<string>("Keybinds", "Scanner Key", "<Keyboard>/f", new ConfigDescription("What you press to scan things in the format of `<Keyboard>/YOURKEY` (I.E. <Keyboard>/f)", (AcceptableValueBase)null, Array.Empty<object>())); keyBind.SettingChanged += delegate { //IL_0046: Unknown result type (might be due to invalid IL or missing references) string text = keyBind.Value.ToLower(); Logger.LogInfo((object)("Keybind changed to: " + text)); if (IsKeybindValid(keyBind.Value.ToLower())) { InputManager.instance.Rebind(scanKey, text); } else { Logger.LogInfo((object)"Keybind invalid, resetting to default"); keyBind.Value = (string)((ConfigEntryBase)keyBind).DefaultValue; } }; if (!IsKeybindValid(keyBind.Value)) { Logger.LogInfo((object)"Keybind from config invalid, resetting to default"); keyBind.Value = (string)((ConfigEntryBase)keyBind).DefaultValue; } harmony.PatchAll(typeof(Patches)); Logger.LogInfo((object)"Plugin Kistras-Scanner is loaded!"); } } [HarmonyPatch] public class Patches { private static float lastGuiCheckTime; private static bool guiCreationAttempted; [HarmonyPatch(typeof(InputManager), "InitializeInputs")] [HarmonyPostfix] private static void InputManagerInitializeInputsPostfix(InputManager __instance) { //IL_002a: Unknown result type (might be due to invalid IL or missing references) //IL_0030: Expected O, but got Unknown //IL_0077: Unknown result type (might be due to invalid IL or missing references) //IL_008c: Unknown result type (might be due to invalid IL or missing references) try { Plugin.Logger.LogInfo((object)"Setting up scan input action..."); InputAction val = new InputAction("Scan", (InputActionType)0, Plugin.keyBind.Value.ToLower(), (string)null, (string)null, (string)null); Type typeFromHandle = typeof(InputManager); FieldInfo field = typeFromHandle.GetField("inputActions", BindingFlags.Instance | BindingFlags.NonPublic); if (field == null) { Plugin.Logger.LogError((object)"Failed to get inputActions field"); return; } Dictionary<InputKey, InputAction> dictionary = (Dictionary<InputKey, InputAction>)field.GetValue(__instance); if (!dictionary.ContainsKey(Plugin.scanKey)) { dictionary.Add(Plugin.scanKey, val); val.Enable(); Plugin.Logger.LogInfo((object)"Added scan input action"); } } catch (Exception ex) { Plugin.Logger.LogError((object)("Error in InputManagerInitializeInputsPostfix: " + ex.Message)); } } [HarmonyPatch(typeof(PlayerController), "Update")] [HarmonyPostfix] private static void PlayerControllerUpdatePostfix() { //IL_0007: Unknown result type (might be due to invalid IL or missing references) Scanner.Update(); if (SemiFunc.InputDown(Plugin.scanKey)) { Scanner.Scan(); } EnsureScannerGUIExists(); } private static void EnsureScannerGUIExists() { //IL_005a: Unknown result type (might be due to invalid IL or missing references) //IL_0061: Expected O, but got Unknown if (Time.time - lastGuiCheckTime < 2f) { return; } lastGuiCheckTime = Time.time; if (!((Object)(object)ScannerGUI.Instance != (Object)null) && !((Object)(object)PlayerController.instance == (Object)null)) { if (!guiCreationAttempted) { GameObject val = new GameObject("ScannerGUI"); val.AddComponent<ScannerGUI>(); Object.DontDestroyOnLoad((Object)(object)val); guiCreationAttempted = true; } else if (Time.time - lastGuiCheckTime > 10f) { guiCreationAttempted = false; } } } } public class Scanner { private static float lastScanTime = -10f; public static readonly float scanCooldown = 10f; private static bool isInitialized = false; private static void Initialize() { if (!isInitialized) { isInitialized = true; Plugin.Logger.LogInfo((object)"Scanner initialized successfully"); } } public static void Scan() { //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_00b7: Unknown result type (might be due to invalid IL or missing references) if (Time.time - lastScanTime < scanCooldown) { return; } if ((Object)(object)LevelGenerator.Instance == (Object)null || !LevelGenerator.Instance.Generated || SemiFunc.MenuLevel()) { Plugin.Logger.LogInfo((object)"Cannot scan: No level loaded."); return; } if (!isInitialized) { Initialize(); } PlayerController instance = PlayerController.instance; if ((Object)(object)instance == (Object)null || (Object)(object)Camera.main == (Object)null) { Plugin.Logger.LogError((object)"Cannot scan: Player camera not found."); return; } Vector3 position = ((Component)Camera.main).transform.position; Collider[] array = Physics.OverlapSphere(position, 10f); Collider[] array2 = array; foreach (Collider val in array2) { if (!((Object)(object)val == (Object)null) && !((Object)(object)((Component)val).transform == (Object)null)) { ValuableObject val2 = ((Component)val).gameObject.GetComponentInParent<ValuableObject>(); if ((Object)(object)val2 == (Object)null) { val2 = ((Component)val).gameObject.GetComponentInChildren<ValuableObject>(); } if ((Object)(object)val2 != (Object)null) { val2.Discover((State)0); } } } lastScanTime = Time.time; if ((Object)(object)ScannerGUI.Instance != (Object)null) { ScannerGUI.Instance.NotifyScan(); } } public static void Update() { } public static bool IsOnCooldown() { return Time.time - lastScanTime < scanCooldown; } public static float GetRemainingCooldown() { return Mathf.Max(0f, scanCooldown - (Time.time - lastScanTime)); } } public class ScannerGUI : MonoBehaviour { private Texture2D barTexture; private Texture2D backgroundTexture; private readonly float barWidth = 400f; private readonly float barHeight = 15f; private float lastDisplayTime = -10f; private readonly float displayDuration = 3f; private readonly Color barColor = new Color(1f, 0.6f, 0.1f, 0.8f); private readonly Color readyColor = new Color(1f, 0.8f, 0.2f, 0.8f); public static ScannerGUI Instance { get; private set; } private void Awake() { if ((Object)(object)Instance != (Object)null && (Object)(object)Instance != (Object)(object)this) { Object.Destroy((Object)(object)((Component)this).gameObject); return; } Instance = this; Object.DontDestroyOnLoad((Object)(object)((Component)this).gameObject); Initialize(); } private void Initialize() { //IL_0004: Unknown result type (might be due to invalid IL or missing references) //IL_000e: Expected O, but got Unknown //IL_0016: 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_003a: Expected O, but got Unknown //IL_0042: Unknown result type (might be due to invalid IL or missing references) barTexture = new Texture2D(1, 1); barTexture.SetPixel(0, 0, Color.white); barTexture.Apply(); backgroundTexture = new Texture2D(1, 1); backgroundTexture.SetPixel(0, 0, Color.white); backgroundTexture.Apply(); } private void OnDestroy() { if ((Object)(object)Instance == (Object)(object)this) { Instance = null; } if ((Object)(object)barTexture != (Object)null) { Object.Destroy((Object)(object)barTexture); } if ((Object)(object)backgroundTexture != (Object)null) { Object.Destroy((Object)(object)backgroundTexture); } } private void OnGUI() { //IL_00b8: Unknown result type (might be due to invalid IL or missing references) //IL_00d3: Unknown result type (might be due to invalid IL or missing references) //IL_0182: 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_011b: Unknown result type (might be due to invalid IL or missing references) //IL_013e: Unknown result type (might be due to invalid IL or missing references) //IL_01af: Unknown result type (might be due to invalid IL or missing references) //IL_01c4: Unknown result type (might be due to invalid IL or missing references) //IL_01cb: Expected O, but got Unknown //IL_01f5: Unknown result type (might be due to invalid IL or missing references) //IL_0238: Unknown result type (might be due to invalid IL or missing references) if (!ShouldShowGUI()) { return; } float remainingCooldown = Scanner.GetRemainingCooldown(); float num = remainingCooldown / Scanner.scanCooldown; bool flag = Scanner.IsOnCooldown(); float num2; if (flag) { num2 = 1f; lastDisplayTime = Time.time; } else { float num3 = Time.time - lastDisplayTime; num2 = Mathf.Clamp01(1f - num3 / displayDuration); } if (!(num2 <= 0.01f)) { float num4 = ((float)Screen.width - barWidth) / 2f; float num5 = 30f; GUI.color = new Color(0.2f, 0.2f, 0.2f, 0.6f * num2); GUI.DrawTexture(new Rect(num4, num5, barWidth, barHeight), (Texture)(object)backgroundTexture); if (flag) { GUI.color = new Color(barColor.r, barColor.g, barColor.b, barColor.a * num2); GUI.DrawTexture(new Rect(num4, num5, barWidth * (1f - num), barHeight), (Texture)(object)barTexture); } else { GUI.color = new Color(readyColor.r, readyColor.g, readyColor.b, readyColor.a * num2); GUI.DrawTexture(new Rect(num4, num5, barWidth, barHeight), (Texture)(object)barTexture); } GUI.color = Color.white; GUIStyle val = new GUIStyle(GUI.skin.label); val.alignment = (TextAnchor)4; val.fontStyle = (FontStyle)1; val.normal.textColor = new Color(1f, 1f, 1f, num2); string text = (flag ? $"Scanner: {remainingCooldown:F1}s" : "Scanner Ready"); GUI.Label(new Rect(num4, num5 + barHeight + 5f, barWidth, 20f), text, val); } } private bool ShouldShowGUI() { return (Object)(object)PlayerController.instance != (Object)null && (Object)(object)LevelGenerator.Instance != (Object)null && LevelGenerator.Instance.Generated && !SemiFunc.MenuLevel(); } public void NotifyScan() { lastDisplayTime = Time.time; } } public static class MyPluginInfo { public const string PLUGIN_GUID = "Kistras-Scanner"; public const string PLUGIN_NAME = "REPO Scanner"; public const string PLUGIN_VERSION = "1.0.0"; } }
plugins/Lazarus-BetterTruckHeals/BetterTruckHeals.dll
Decompiled 2 months agousing System; using 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 HarmonyLib; 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("BetterTruckHeals")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("BetterTruckHeals")] [assembly: AssemblyCopyright("Copyright © 2025")] [assembly: AssemblyTrademark("")] [assembly: ComVisible(false)] [assembly: Guid("819aea69-b910-4066-83d4-ca334402331c")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")] [assembly: AssemblyVersion("1.0.0.0")] namespace BetterTruckHeals; [BepInPlugin("Lazarus.BetterTruckHeals", "Better Truck Heals", "1.0.0")] public class BetterTruckHeals : BaseUnityPlugin { [HarmonyPatch(typeof(PlayerAvatar), "FinalHealRPC")] public class PlayerAvatarPatch { private static readonly FieldInfo FinalHealField = typeof(PlayerAvatar).GetField("finalHeal", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); private static readonly FieldInfo IsLocalField = typeof(PlayerAvatar).GetField("isLocal", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); private static readonly FieldInfo PlayerNameField = typeof(PlayerAvatar).GetField("playerName", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); [HarmonyPrefix] private static bool Prefix(PlayerAvatar __instance) { if (FinalHealField == null || IsLocalField == null || PlayerNameField == null) { ModLogger.LogError((object)"Failed to reflect fields in PlayerAvatar. Check assembly reference."); return true; } if ((bool)FinalHealField.GetValue(__instance)) { return true; } if ((bool)IsLocalField.GetValue(__instance)) { int value = HealAmountConfig.Value; string text = (string)PlayerNameField.GetValue(__instance); ModLogger.LogInfo((object)$"Applying custom heal amount: {value} for player: {text}"); __instance.playerHealth.EyeMaterialOverride((EyeOverrideState)2, 2f, 1); TruckScreenText.instance.MessageSendCustom("", text + " {arrowright}{truck}{check}\n {point}{shades}{pointright}<b><color=#00FF00>+" + value + "</color></b>{heart}", 0); __instance.playerHealth.Heal(value, true); FinalHealField.SetValue(__instance, true); } return false; } [HarmonyPostfix] private static void Postfix(PlayerAvatar __instance) { //IL_001e: 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) TruckHealer.instance.Heal(__instance); __instance.truckReturn.Play(__instance.PlayerVisionTarget.VisionTransform.position, 1f, 1f, 1f, 1f); __instance.truckReturnGlobal.Play(__instance.PlayerVisionTarget.VisionTransform.position, 1f, 1f, 1f, 1f); ((Component)__instance.playerAvatarVisuals.effectGetIntoTruck).gameObject.SetActive(true); } } private const string PluginGUID = "Lazarus.BetterTruckHeals"; private const string PluginName = "Better Truck Heals"; private const string PluginVersion = "1.0.0"; public static ConfigEntry<int> HealAmountConfig; internal static ManualLogSource ModLogger; private void Awake() { //IL_005b: Unknown result type (might be due to invalid IL or missing references) //IL_0065: Expected O, but got Unknown //IL_00a8: Unknown result type (might be due to invalid IL or missing references) //IL_00ae: Expected O, but got Unknown ((BaseUnityPlugin)this).Logger.LogInfo((object)"John 11:11!"); ((BaseUnityPlugin)this).Logger.LogInfo((object)"WAKEY WAKEY!"); ((BaseUnityPlugin)this).Logger.LogInfo((object)"BetterTruckHeals has risen!"); HealAmountConfig = ((BaseUnityPlugin)this).Config.Bind<int>("General", "HealAmount", 50, new ConfigDescription("The amount of health the truck healer restores to the player.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 200), Array.Empty<object>())); ModLogger = ((BaseUnityPlugin)this).Logger; ModLogger.LogInfo((object)string.Format("{0} v{1} is loading with heal amount: {2}", "Better Truck Heals", "1.0.0", HealAmountConfig.Value)); Harmony val = new Harmony("Lazarus.BetterTruckHeals"); val.PatchAll(); ModLogger.LogInfo((object)"Harmony patches applied successfully!"); } }
plugins/Lazarus-NoGunSpread/NoGunSpread.dll
Decompiled 2 months agousing System.Diagnostics; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Versioning; using BepInEx; using HarmonyLib; using Unamed_mod.Patches; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)] [assembly: AssemblyTitle("Unamed mod")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Unamed mod")] [assembly: AssemblyCopyright("Copyright © 2025")] [assembly: AssemblyTrademark("")] [assembly: ComVisible(false)] [assembly: Guid("6fb9dfec-26ee-4d2d-9a4b-704ee1267f46")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")] [assembly: AssemblyVersion("1.0.0.0")] [BepInPlugin("Lazarus.NoGunSpread", "NoGunSpread", "1.0.0")] public class Class1 : BaseUnityPlugin { public const string modGUID = "Lazarus.NoGunSpread"; public const string modname = "NoGunSpread"; public const string modVersion = "1.0.0"; private readonly Harmony harmony = new Harmony("Lazarus.NoGunSpread"); public void Awake() { ((BaseUnityPlugin)this).Logger.LogInfo((object)"John 11:11!"); ((BaseUnityPlugin)this).Logger.LogInfo((object)"WAKEY WAKEY!"); ((BaseUnityPlugin)this).Logger.LogInfo((object)"NoGunSpread has risen!"); harmony.PatchAll(typeof(NoGunSpreadPatch)); } } namespace Unamed_mod.Patches; [HarmonyPatch(typeof(ItemGun))] internal class NoGunSpreadPatch { [HarmonyPatch("Update")] [HarmonyPostfix] private static void patch(ItemGun __instance) { __instance.gunRandomSpread = 0f; } }
plugins/loaforc-loaforcsSoundAPI/loaforcsSoundAPI/me.loaforc.soundapi.dll
Decompiled 2 months agousing System; using System.Buffers; using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics; 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 System.Text; using System.Threading; using System.Threading.Tasks; using BepInEx; using BepInEx.Bootstrap; using BepInEx.Configuration; using BepInEx.Logging; using HarmonyLib; using JetBrains.Annotations; using Microsoft.CodeAnalysis; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using Newtonsoft.Json.Serialization; using UnityEngine; using UnityEngine.Networking; using UnityEngine.SceneManagement; using loaforcsSoundAPI.Core; using loaforcsSoundAPI.Core.Data; using loaforcsSoundAPI.Core.JSON; using loaforcsSoundAPI.Core.Networking; using loaforcsSoundAPI.Core.Patches; using loaforcsSoundAPI.Core.Util; using loaforcsSoundAPI.Core.Util.Extensions; using loaforcsSoundAPI.Reporting; using loaforcsSoundAPI.Reporting.Data; using loaforcsSoundAPI.SoundPacks; using loaforcsSoundAPI.SoundPacks.Data; using loaforcsSoundAPI.SoundPacks.Data.Conditions; [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("me.loaforc.soundapi")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyFileVersion("2.0.5.0")] [assembly: AssemblyInformationalVersion("2.0.5+a71c7ab12852d0d18cae5bac2e2cc537f46f6fd8")] [assembly: AssemblyProduct("loaforcsSoundAPI")] [assembly: AssemblyTitle("me.loaforc.soundapi")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("2.0.5.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 loaforcsSoundAPI { [BepInPlugin("me.loaforc.soundapi", "loaforcsSoundAPI", "2.0.5")] internal class loaforcsSoundAPI : BaseUnityPlugin { private static loaforcsSoundAPI _instance; internal static ManualLogSource Logger { get; private set; } private void Awake() { _instance = this; Logger = Logger.CreateLogSource("me.loaforc.soundapi"); ((BaseUnityPlugin)this).Config.SaveOnConfigSet = false; Logger.LogInfo((object)"Setting up config"); Debuggers.Bind(((BaseUnityPlugin)this).Config); SoundReportHandler.Bind(((BaseUnityPlugin)this).Config); Logger.LogInfo((object)"Running patches"); Harmony harmony = Harmony.CreateAndPatchAll(Assembly.GetExecutingAssembly(), "me.loaforc.soundapi"); UnityObjectPatch.Init(harmony); Logger.LogInfo((object)"Registering data"); SoundAPI.RegisterAll(Assembly.GetExecutingAssembly()); SoundAPIAudioManager.SpawnManager(); SoundReplacementHandler.Register(); ((BaseUnityPlugin)this).Config.Save(); Logger.LogInfo((object)"me.loaforc.soundapi by loaforc has loaded :3"); } internal static ConfigFile GenerateConfigFile(string name) { //IL_002c: Unknown result type (might be due to invalid IL or missing references) //IL_0032: Expected O, but got Unknown return new ConfigFile(Utility.CombinePaths(new string[2] { Paths.ConfigPath, name + ".cfg" }), false, MetadataHelper.GetMetadata((object)_instance)); } } public static class SoundAPI { public const string PLUGIN_GUID = "me.loaforc.soundapi"; internal static NetworkAdapter CurrentNetworkAdapter { get; private set; } public static async Task<AudioClip> LoadAudioFileAsync(string fullPath) { if (!File.Exists(fullPath)) { throw new FileNotFoundException("'" + fullPath + "' not found."); } if (!SoundPackLoadPipeline.audioExtensions.ContainsKey(Path.GetExtension(fullPath))) { throw new NotImplementedException("Audio file extension: '" + Path.GetExtension(fullPath) + "' is not implemented."); } UnityWebRequest request = UnityWebRequestMultimedia.GetAudioClip(fullPath, SoundPackLoadPipeline.audioExtensions[Path.GetExtension(fullPath)]); await (AsyncOperation)(object)request.SendWebRequest(); AudioClip content = DownloadHandlerAudioClip.GetContent(request); request.Dispose(); return content; } public static void RegisterAll(Assembly assembly) { foreach (Type loadableType in assembly.GetLoadableTypes()) { if (loadableType.IsNested) { continue; } foreach (SoundAPIConditionAttribute conditionAttribute in loadableType.GetCustomAttributes<SoundAPIConditionAttribute>()) { if (!typeof(Condition).IsAssignableFrom(loadableType)) { loaforcsSoundAPI.Logger.LogError((object)("Condition: '" + loadableType.FullName + "' has been marked with [SoundAPICondition] but does not extend Condition!")); continue; } ConstructorInfo info = loadableType.GetConstructor(Array.Empty<Type>()); if (info == null) { loaforcsSoundAPI.Logger.LogError((object)("Condition: '" + loadableType.FullName + "' has no valid constructor! It must have a constructor with no parameters! If you need extra parameters do not mark it with [SoundAPICondition] and register it manually.")); continue; } RegisterCondition(conditionAttribute.ID, delegate { if (conditionAttribute.IsDeprecated) { if (conditionAttribute.DeprecationReason == null) { loaforcsSoundAPI.Logger.LogWarning((object)("Condition: '" + conditionAttribute.ID + "' is deprecated and may be removed in future.")); } else { loaforcsSoundAPI.Logger.LogWarning((object)("Condition: '" + conditionAttribute.ID + "' is deprecated. " + conditionAttribute.DeprecationReason)); } } return (Condition)info.Invoke(Array.Empty<object>()); }); } } } public static void RegisterCondition(string id, Func<Condition> factory) { SoundPackDataHandler.Register(id, factory); } public static void RegisterNetworkAdapter(NetworkAdapter adapter) { CurrentNetworkAdapter = adapter; loaforcsSoundAPI.Logger.LogInfo((object)("Registered network adapter: '" + CurrentNetworkAdapter.Name + "'")); CurrentNetworkAdapter.OnRegister(); } public static void RegisterSoundPack(SoundPack pack) { if (SoundPackDataHandler.LoadedPacks.Contains(pack)) { throw new InvalidOperationException("Already registered sound-pack: '" + pack.Name + "'!"); } SoundPackDataHandler.AddLoadedPack(pack); foreach (SoundReplacementCollection replacementCollection in pack.ReplacementCollections) { foreach (SoundReplacementGroup replacement in replacementCollection.Replacements) { SoundPackDataHandler.AddReplacement(replacement); } } } } internal static class MyPluginInfo { public const string PLUGIN_GUID = "me.loaforc.soundapi"; public const string PLUGIN_NAME = "loaforcsSoundAPI"; public const string PLUGIN_VERSION = "2.0.5"; } } namespace loaforcsSoundAPI.SoundPacks { internal class LoadSoundOperation { public readonly UnityWebRequest WebRequest = webRequest.webRequest; public readonly SoundInstance Sound; public bool IsReady => WebRequest.isDone; public bool IsDone { get; set; } public LoadSoundOperation(SoundInstance soundInstance, UnityWebRequestAsyncOperation webRequest) { Sound = soundInstance; base..ctor(); } } internal static class SoundPackDataHandler { private static List<SoundPack> _loadedPacks = new List<SoundPack>(); internal static Dictionary<string, List<SoundReplacementGroup>> SoundReplacements = new Dictionary<string, List<SoundReplacementGroup>>(); internal static Dictionary<string, Func<Condition>> conditionFactories = new Dictionary<string, Func<Condition>>(); internal static List<AudioClip> allLoadedClips = new List<AudioClip>(); internal static IReadOnlyList<SoundPack> LoadedPacks => _loadedPacks.AsReadOnly(); internal static void Register(string id, Func<Condition> factory) { conditionFactories[id] = factory; } public static Condition CreateCondition(string id) { if (conditionFactories.TryGetValue(id, out var value)) { return value(); } return new InvalidCondition(id); } internal static void AddLoadedPack(SoundPack pack) { _loadedPacks.Add(pack); } internal static void AddReplacement(SoundReplacementGroup group) { foreach (string match in group.Matches) { string key = match.Split(":").Last(); if (!SoundReplacements.TryGetValue(key, out var value)) { value = new List<SoundReplacementGroup>(); } if (!value.Contains(group)) { value.Add(group); SoundReplacements[key] = value; } } } } internal static class SoundPackLoadPipeline { private class SkippedResults { public int Collections; public int Groups; public int Sounds; } private static volatile int _activeThreads; private static Dictionary<string, List<string>> mappings; internal static Dictionary<string, AudioType> audioExtensions; internal static event Action OnFinishedPipeline; internal static async void StartPipeline() { Stopwatch completeLoadingTimer = Stopwatch.StartNew(); Stopwatch timer = Stopwatch.StartNew(); List<SoundPack> list = FindAndLoadPacks(); loaforcsSoundAPI.Logger.LogInfo((object)$"(Step 1) Loading Sound-pack definitions took {timer.ElapsedMilliseconds}ms"); timer.Restart(); List<LoadSoundOperation> webRequestOperations = new List<LoadSoundOperation>(); foreach (SoundPack item2 in list) { string path = Path.Combine(item2.PackFolder, "soundapi_mappings.json"); if (!File.Exists(path)) { continue; } Dictionary<string, List<string>> dictionary = JSONDataLoader.LoadFromFile<Dictionary<string, List<string>>>(path); foreach (KeyValuePair<string, List<string>> item3 in dictionary) { if (mappings.ContainsKey(item3.Key)) { mappings[item3.Key].AddRange(item3.Value); } else { mappings[item3.Key] = item3.Value; } } } loaforcsSoundAPI.Logger.LogInfo((object)$"(Step 2) Loading Sound-pack mappings ('{mappings.Count}') took {timer.ElapsedMilliseconds}ms"); timer.Restart(); SkippedResults skippedStats = new SkippedResults(); foreach (SoundPack item4 in list) { foreach (SoundReplacementCollection item5 in LoadSoundReplacementCollections(item4, ref skippedStats)) { foreach (SoundReplacementGroup replacement in item5.Replacements) { SoundPackDataHandler.AddReplacement(replacement); foreach (SoundInstance sound in replacement.Sounds) { if (sound.Condition is ConstantCondition constantCondition && !constantCondition.Value) { Debuggers.SoundReplacementLoader?.Log("skipping a sound in '" + LogFormats.FormatFilePath(item5.FilePath) + "' because sound is marked as constant and has a value of false."); skippedStats.Sounds++; } else { webRequestOperations.Add(StartWebRequestOperation(item4, sound, audioExtensions[Path.GetExtension(sound.Sound)])); } } } } } int amountOfOperations = webRequestOperations.Count; loaforcsSoundAPI.Logger.LogInfo((object)$"(Step 3) Skipped {skippedStats.Collections} collection(s), {skippedStats.Groups} replacement(s), {skippedStats.Sounds} sound(s)"); loaforcsSoundAPI.Logger.LogInfo((object)$"(Step 3) Loading sound replacement collections took {timer.ElapsedMilliseconds}ms"); if (SoundReportHandler.CurrentReport != null) { SoundReportHandler.CurrentReport.AudioClipsLoaded = amountOfOperations; } loaforcsSoundAPI.Logger.LogInfo((object)$"(Step 4) Started loading {amountOfOperations} audio file(s)"); loaforcsSoundAPI.Logger.LogInfo((object)"Waiting for splash screens to complete to continue..."); completeLoadingTimer.Stop(); await Task.Delay(1); loaforcsSoundAPI.Logger.LogInfo((object)"Splash screens done! Continuing pipeline"); loaforcsSoundAPI.Logger.LogWarning((object)"The game will freeze for a moment!"); timer.Restart(); completeLoadingTimer.Start(); bool flag = false; bool threadsShouldExit = false; ConcurrentQueue<LoadSoundOperation> queuedOperations = new ConcurrentQueue<LoadSoundOperation>(); ConcurrentBag<Exception> threadPoolExceptions = new ConcurrentBag<Exception>(); for (int i = 0; i < 16; i++) { new Thread((ThreadStart)delegate { while (queuedOperations.Count == 0 && !threadsShouldExit) { Thread.Yield(); } Interlocked.Increment(ref _activeThreads); Debuggers.SoundReplacementLoader?.Log($"active threads at {_activeThreads}"); LoadSoundOperation result; while (queuedOperations.TryDequeue(out result)) { try { AudioClip content = DownloadHandlerAudioClip.GetContent(result.WebRequest); result.Sound.Clip = content; result.WebRequest.Dispose(); Debuggers.SoundReplacementLoader?.Log("clip generated"); result.IsDone = true; } catch (Exception item) { threadPoolExceptions.Add(item); } } Interlocked.Decrement(ref _activeThreads); }).Start(); } while (webRequestOperations.Count > 0) { foreach (LoadSoundOperation item6 in from operation in webRequestOperations.ToList() where operation.IsReady select operation) { queuedOperations.Enqueue(item6); webRequestOperations.Remove(item6); } if (!flag && webRequestOperations.Count < amountOfOperations / 2) { flag = true; loaforcsSoundAPI.Logger.LogInfo((object)"(Step 5) Queued half of the needed operations!"); } Thread.Yield(); } loaforcsSoundAPI.Logger.LogInfo((object)"(Step 5) All file reads are done, waiting for the audio clips conversions."); threadsShouldExit = true; while (_activeThreads > 0 || webRequestOperations.Any((LoadSoundOperation operation) => !operation.IsDone)) { Thread.Yield(); } loaforcsSoundAPI.Logger.LogInfo((object)$"(Step 6) Took {timer.ElapsedMilliseconds}ms to finish loading audio clips from files"); if (threadPoolExceptions.Count != 0) { loaforcsSoundAPI.Logger.LogError((object)$"(Step 6) {threadPoolExceptions.Count} internal error(s) happened while loading:"); foreach (Exception item7 in threadPoolExceptions) { loaforcsSoundAPI.Logger.LogError((object)item7.ToString()); } } SoundPackLoadPipeline.OnFinishedPipeline(); mappings = null; loaforcsSoundAPI.Logger.LogDebug((object)$"Active Threads that are left over: {_activeThreads}"); loaforcsSoundAPI.Logger.LogInfo((object)$"Entire load process took an effective {completeLoadingTimer.ElapsedMilliseconds}ms"); } private static List<SoundPack> FindAndLoadPacks(string entryPoint = "sound_pack.json") { List<SoundPack> list = new List<SoundPack>(); string[] files = Directory.GetFiles(Paths.PluginPath, entryPoint, SearchOption.AllDirectories); foreach (string text in files) { Debuggers.SoundReplacementLoader?.Log("found entry point: '" + text + "'!"); SoundPack soundPack = JSONDataLoader.LoadFromFile<SoundPack>(text); if (soundPack != null) { soundPack.PackFolder = Path.GetDirectoryName(text); Debuggers.SoundReplacementLoader?.Log("json loaded, validating"); List<IValidatable.ValidationResult> results = soundPack.Validate(); if (IValidatable.LogAndCheckValidationResult("loading '" + text + "'", results, soundPack.Logger)) { ConfigFile val = loaforcsSoundAPI.GenerateConfigFile(soundPack.GUID); val.SaveOnConfigSet = false; soundPack.Bind(val); val.Save(); list.Add(soundPack); SoundPackDataHandler.AddLoadedPack(soundPack); Debuggers.SoundReplacementLoader?.Log("pack folder: " + soundPack.PackFolder); } } } Debuggers.SoundReplacementLoader?.Log($"loaded '{list.Count}' packs."); return list; } private static List<SoundReplacementCollection> LoadSoundReplacementCollections(SoundPack pack, ref SkippedResults skippedStats) { List<SoundReplacementCollection> list = new List<SoundReplacementCollection>(); if (!Directory.Exists(Path.Combine(pack.PackFolder, "replacers"))) { return list; } Debuggers.SoundReplacementLoader?.Log("start loading '" + pack.Name + "'!"); string[] files = Directory.GetFiles(Path.Combine(pack.PackFolder, "replacers"), "*.json", SearchOption.AllDirectories); foreach (string text in files) { Debuggers.SoundReplacementLoader?.Log("found replacer: '" + text + "'!"); SoundReplacementCollection soundReplacementCollection = JSONDataLoader.LoadFromFile<SoundReplacementCollection>(text); if (soundReplacementCollection == null) { continue; } soundReplacementCollection.Pack = pack; if (soundReplacementCollection.Condition is ConstantCondition constantCondition && !constantCondition.Value) { Debuggers.SoundReplacementLoader?.Log("skipping '" + LogFormats.FormatFilePath(soundReplacementCollection.FilePath) + "' because collection is marked as constant and has a value of false."); skippedStats.Collections++; } else { if (!IValidatable.LogAndCheckValidationResult("loading '" + LogFormats.FormatFilePath(text) + "'", soundReplacementCollection.Validate(), pack.Logger)) { continue; } List<IValidatable.ValidationResult> list2 = new List<IValidatable.ValidationResult>(); foreach (SoundReplacementGroup replacement in soundReplacementCollection.Replacements) { replacement.Parent = soundReplacementCollection; if (replacement.Condition is ConstantCondition constantCondition2 && !constantCondition2.Value) { Debuggers.SoundReplacementLoader?.Log("skipping a replacement in '" + LogFormats.FormatFilePath(soundReplacementCollection.FilePath) + "' because group is marked as constant and has a value of false."); skippedStats.Groups++; continue; } List<IValidatable.ValidationResult> list3 = replacement.Validate(); foreach (string item in replacement.Matches.ToList()) { if (item.StartsWith("#")) { replacement.Matches.Remove(item); Dictionary<string, List<string>> dictionary = mappings; string text2 = item; if (dictionary.TryGetValue(text2.Substring(1, text2.Length - 1), out var value)) { replacement.Matches.AddRange(value); } else { list3.Add(new IValidatable.ValidationResult(IValidatable.ResultType.FAIL, "Mapping: '" + item + "' has not been found. If it's part of a soft dependency, make sure to use a 'mod_installed' condition with 'constant' enabled.")); } } } if (list3.Count != 0) { list2.AddRange(list3); continue; } foreach (SoundInstance sound in replacement.Sounds) { sound.Parent = replacement; list3.AddRange(sound.Validate()); } if (list3.Count != 0) { list2.AddRange(list3); continue; } List<string> collection = replacement.Matches.Select((string match) => (match.Split(":").Length != 2) ? match : ("*:" + match)).ToList(); replacement.Matches.Clear(); replacement.Matches.AddRange(collection); } if (IValidatable.LogAndCheckValidationResult("loading '" + LogFormats.FormatFilePath(text) + "'", list2, pack.Logger)) { list.Add(soundReplacementCollection); } } } return list; } private static LoadSoundOperation StartWebRequestOperation(SoundPack pack, SoundInstance sound, AudioType type) { //IL_0018: Unknown result type (might be due to invalid IL or missing references) string text = Path.Combine(pack.PackFolder, "sounds", sound.Sound); UnityWebRequest audioClip = UnityWebRequestMultimedia.GetAudioClip(text, type); return new LoadSoundOperation(sound, audioClip.SendWebRequest()); } static SoundPackLoadPipeline() { SoundPackLoadPipeline.OnFinishedPipeline = delegate { }; mappings = new Dictionary<string, List<string>>(); audioExtensions = new Dictionary<string, AudioType> { { ".ogg", (AudioType)14 }, { ".wav", (AudioType)20 }, { ".mp3", (AudioType)13 } }; } } internal static class SoundReplacementHandler { private const int TOKEN_PARENT_NAME = 0; private const int TOKEN_OBJECT_NAME = 1; private const int TOKEN_CLIP_NAME = 2; private static readonly string[] _suffixesToRemove = new string[1] { "(Clone)" }; private static readonly Dictionary<int, string> _cachedObjectNames = new Dictionary<int, string>(); private static readonly StringBuilder _builder = new StringBuilder(); internal static void Register() { SceneManager.sceneLoaded += delegate(Scene scene, LoadSceneMode _) { //IL_001f: Unknown result type (might be due to invalid IL or missing references) //IL_0024: Unknown result type (might be due to invalid IL or missing references) _cachedObjectNames.Clear(); AudioSource[] array = Object.FindObjectsOfType<AudioSource>(true); foreach (AudioSource val in array) { if (!(((Component)val).gameObject.scene != scene) && val.playOnAwake && TryReplaceAudio(val, val.clip, out var replacement)) { val.Stop(); if (!((Object)(object)replacement == (Object)null)) { val.clip = replacement; } } } }; } internal static bool TryReplaceAudio(AudioSource source, AudioClip clip, out AudioClip replacement) { replacement = null; if ((Object)(object)((Component)source).gameObject == (Object)null) { return false; } AudioSourceAdditionalData orCreate = AudioSourceAdditionalData.GetOrCreate(source); if (orCreate.ReplacedWith != null && orCreate.ReplacedWith.Parent.UpdateEveryFrame) { return false; } if (orCreate.DisableReplacing) { return false; } string[] name = ArrayPool<string>.Shared.Rent(3); if (!TryProcessName(ref name, source, clip) || !TryGetReplacementClip(name, out var group, out var clip2, orCreate.CurrentContext ?? DefaultConditionContext.DEFAULT)) { ArrayPool<string>.Shared.Return(name); return false; } ArrayPool<string>.Shared.Return(name); ((Object)clip2).name = ((Object)clip).name; replacement = clip2; orCreate.ReplacedWith = group; if (group.Parent.UpdateEveryFrame) { Debuggers.UpdateEveryFrame?.Log("swapped to a clip that uses update_every_frame !!!"); } return true; } private static string TrimObjectName(GameObject gameObject) { if (_cachedObjectNames.ContainsKey(((object)gameObject).GetHashCode())) { return _cachedObjectNames[((object)gameObject).GetHashCode()]; } _builder.Clear(); _builder.Append(((Object)gameObject).name); string[] suffixesToRemove = _suffixesToRemove; foreach (string oldValue in suffixesToRemove) { _builder.Replace(oldValue, string.Empty); } for (int j = 0; j < _builder.Length; j++) { if (_builder[j] == '(') { int num = j; for (j++; j < _builder.Length && char.IsDigit(_builder[j]); j++) { } if (j < _builder.Length && _builder[j] == ')') { _builder.Remove(num, j - num + 1); j = num - 1; } } } int num2 = _builder.Length; while (num2 > 0 && _builder[num2 - 1] == ' ') { num2--; } _builder.Remove(num2, _builder.Length - num2); string text = _builder.ToString(); _cachedObjectNames[((object)gameObject).GetHashCode()] = text; return text; } private static bool TryProcessName(ref string[] name, AudioSource source, AudioClip clip) { if ((Object)(object)clip == (Object)null) { return false; } if ((Object)(object)((Component)source).transform.parent == (Object)null) { name[0] = "*"; } else { name[0] = TrimObjectName(((Component)((Component)source).transform.parent).gameObject); } name[1] = TrimObjectName(((Component)source).gameObject); name[2] = ((Object)clip).name; if (SoundReportHandler.CurrentReport != null) { string caller; try { caller = new StackTrace(fNeedFileInfo: true).GetFrame(5).GetMethod().DeclaringType.Name; } catch { caller = "unknown caller"; } SoundReport.PlayedSound playedSound = new SoundReport.PlayedSound(name[0] + ":" + name[1] + ":" + name[2], caller, source.playOnAwake); if (!SoundReportHandler.CurrentReport.PlayedSounds.Any(playedSound.Equals)) { SoundReportHandler.CurrentReport.PlayedSounds.Add(playedSound); } } Debuggers.MatchStrings?.Log(name[0] + ":" + name[1] + ":" + name[2]); return true; } private static bool TryGetReplacementClip(string[] name, out SoundReplacementGroup group, out AudioClip clip, IContext context) { group = null; clip = null; if (name == null) { return false; } Debuggers.SoundReplacementHandler?.Log("beginning replacement attempt for " + name[2]); if (!SoundPackDataHandler.SoundReplacements.TryGetValue(name[2], out var value)) { return false; } Debuggers.SoundReplacementHandler?.Log("sound dictionary hit"); value = value.Where((SoundReplacementGroup it) => it.Parent.Evaluate(context) && it.Evaluate(context) && CheckGroupMatches(it, name)).ToList(); if (value.Count == 0) { return false; } Debuggers.SoundReplacementHandler?.Log("sound group that matches"); group = value[Random.Range(0, value.Count)]; List<SoundInstance> list = group.Sounds.Where((SoundInstance it) => it.Evaluate(context)).ToList(); if (list.Count == 0) { return false; } Debuggers.SoundReplacementHandler?.Log("has valid sounds"); int totalWeight = 0; list.ForEach(delegate(SoundInstance replacement) { totalWeight += replacement.Weight; }); int num = Random.Range(0, totalWeight + 1); SoundInstance soundInstance = null; foreach (SoundInstance item in list) { soundInstance = item; num -= soundInstance.Weight; if (num <= 0) { break; } } clip = soundInstance.Clip; Debuggers.SoundReplacementHandler?.Log("done, dumping stack trace!"); Debuggers.SoundReplacementHandler?.Log(string.Join(", ", group.Matches)); Debuggers.SoundReplacementHandler?.Log(((Object)clip).name); Debuggers.SoundReplacementHandler?.Log(new StackTrace(fNeedFileInfo: true).ToString().Trim()); return true; } private static bool CheckGroupMatches(SoundReplacementGroup group, string[] a) { foreach (string match in group.Matches) { if (MatchStrings(a, match)) { return true; } } return false; } private static bool MatchStrings(string[] a, string b) { string[] array = b.Split(":"); if (array[0] != "*" && array[0] != a[0]) { return false; } if (array[1] != "*" && array[1] != a[1]) { return false; } return a[2] == array[2]; } } } namespace loaforcsSoundAPI.SoundPacks.Data { public interface IPackData { SoundPack Pack { get; internal set; } } public class SoundInstance : Conditional { [field: NonSerialized] public SoundReplacementGroup Parent { get; internal set; } public string Sound { get; private set; } public int Weight { get; private set; } [field: NonSerialized] public AudioClip Clip { get; internal set; } public override SoundPack Pack { get { return Parent.Pack; } set { if (Parent.Pack != null) { throw new InvalidOperationException("Pack has already been set."); } Parent.Pack = value; } } [JsonConstructor] internal SoundInstance() { } public SoundInstance(SoundReplacementGroup parent, int weight, AudioClip clip) { Parent = parent; Weight = weight; Clip = clip; parent.AddSoundReplacement(this); } public override List<IValidatable.ValidationResult> Validate() { List<IValidatable.ValidationResult> list = base.Validate(); if (!File.Exists(Path.Combine(Pack.PackFolder, "sounds", Sound))) { list.Add(new IValidatable.ValidationResult(IValidatable.ResultType.FAIL, "Sound '" + Sound + "' couldn't be found or doesn't exist!")); } else if (!SoundPackLoadPipeline.audioExtensions.ContainsKey(Path.GetExtension(Sound))) { list.Add(new IValidatable.ValidationResult(IValidatable.ResultType.FAIL, "Audio type: '" + Path.GetExtension(Sound) + "' is not supported!")); } return list; } } public class SoundPack : IValidatable { [NonSerialized] private readonly Dictionary<string, object> _configData = new Dictionary<string, object>(); private ManualLogSource _logger; [JsonProperty] private Dictionary<string, JObject> config { get; set; } public string Name { get; private set; } public string GUID => "soundpack." + Name; public string PackFolder { get; internal set; } [field: NonSerialized] public List<SoundReplacementCollection> ReplacementCollections { get; private set; } = new List<SoundReplacementCollection>(); public ManualLogSource Logger { get { if (_logger == null) { _logger = Logger.CreateLogSource(GUID); } return _logger; } } [JsonConstructor] internal SoundPack() { } internal void Bind(ConfigFile file) { //IL_0095: Unknown result type (might be due to invalid IL or missing references) //IL_009a: Unknown result type (might be due to invalid IL or missing references) //IL_009c: Unknown result type (might be due to invalid IL or missing references) //IL_009f: Invalid comparison between Unknown and I4 //IL_00a1: Unknown result type (might be due to invalid IL or missing references) //IL_00a5: Invalid comparison between Unknown and I4 if (config == null || config.Count == 0) { return; } loaforcsSoundAPI.Logger.LogDebug((object)"handling config"); JToken val2 = default(JToken); foreach (KeyValuePair<string, JObject> item in config) { string[] array = item.Key.Split(":"); string text = array[0]; string text2 = array[1]; JToken val = item.Value["default"]; string text3 = (item.Value.TryGetValue("description", ref val2) ? ((object)val2).ToString() : "no description defined!"); JTokenType type = val.Type; if ((int)type != 8) { if ((int)type != 9) { throw new NotImplementedException("WHAT"); } _configData[item.Key] = file.Bind<bool>(text, text2, (bool)val, text3).Value; } else { _configData[item.Key] = file.Bind<string>(text, text2, (string)val, text3).Value; } } } public SoundPack(string name, string packFolder) { Name = name; PackFolder = packFolder; } internal bool TryGetConfigValue(string id, out object returnValue) { returnValue = null; if (!_configData.TryGetValue(id, out var value)) { return false; } returnValue = value; return true; } public List<IValidatable.ValidationResult> Validate() { //IL_010c: Unknown result type (might be due to invalid IL or missing references) //IL_0113: Invalid comparison between Unknown and I4 //IL_0117: Unknown result type (might be due to invalid IL or missing references) //IL_011d: Invalid comparison between Unknown and I4 //IL_012f: Unknown result type (might be due to invalid IL or missing references) List<IValidatable.ValidationResult> list = new List<IValidatable.ValidationResult>(); if (string.IsNullOrEmpty(Name)) { list.Add(new IValidatable.ValidationResult(IValidatable.ResultType.FAIL, "'name' can not be missing or empty!")); return list; } string name = Name; foreach (char c in name) { if (!char.IsLetter(c) && c != '_') { list.Add(new IValidatable.ValidationResult(IValidatable.ResultType.FAIL, $"'name' can not contain special character '{c}'!")); } } if (config == null) { return list; } JToken val = default(JToken); foreach (KeyValuePair<string, JObject> item in config) { string[] array = item.Key.Split(":"); if (array.Length != 2) { list.Add(new IValidatable.ValidationResult(IValidatable.ResultType.FAIL, "'" + item.Key + "' is not a valid key for config! It must be 'section:name' with exactly one colon!")); } if (!item.Value.TryGetValue("default", ref val)) { list.Add(new IValidatable.ValidationResult(IValidatable.ResultType.FAIL, "'" + item.Key + "' does not have a 'default' value! This is needed to get what type the config is!")); } else if ((int)val.Type != 9 && (int)val.Type != 8) { list.Add(new IValidatable.ValidationResult(IValidatable.ResultType.FAIL, $"'{item.Key}' is of unsupported type: '{val.Type}'! Only supported types are strings/text or booleans!")); } if (!item.Value.ContainsKey("description")) { list.Add(new IValidatable.ValidationResult(IValidatable.ResultType.WARN, "'" + item.Key + "' does not have a description.")); } } return list; } } public class SoundReplacementCollection : Conditional, IFilePathAware, IPackData { [field: NonSerialized] public override SoundPack Pack { get; set; } public bool UpdateEveryFrame { get; private set; } public bool Synced { get; private set; } public List<SoundReplacementGroup> Replacements { get; private set; } = new List<SoundReplacementGroup>(); public string FilePath { get; set; } [JsonConstructor] internal SoundReplacementCollection() { } public SoundReplacementCollection(SoundPack pack) { Pack = pack; pack.ReplacementCollections.Add(this); } internal void AddSoundReplacementGroup(SoundReplacementGroup group) { Replacements.Add(group); } } public class SoundReplacementGroup : Conditional { [field: NonSerialized] public SoundReplacementCollection Parent { get; internal set; } public List<string> Matches { get; private set; } public List<SoundInstance> Sounds { get; private set; } = new List<SoundInstance>(); public override SoundPack Pack { get { return Parent.Pack; } set { if (Parent.Pack != null) { throw new InvalidOperationException("Pack has already been set."); } Parent.Pack = value; } } [JsonConstructor] internal SoundReplacementGroup() { } public SoundReplacementGroup(SoundReplacementCollection parent, List<string> matches) { Parent = parent; Matches = matches; if (SoundPackDataHandler.LoadedPacks.Contains(parent.Pack)) { throw new InvalidOperationException("SoundPack has already been registered, trying to add a new SoundReplacementGroup does not work!"); } parent.AddSoundReplacementGroup(this); } internal void AddSoundReplacement(SoundInstance sound) { Sounds.Add(sound); } public override List<IValidatable.ValidationResult> Validate() { List<IValidatable.ValidationResult> list = base.Validate(); foreach (string match in Matches) { if (string.IsNullOrEmpty(match)) { list.Add(new IValidatable.ValidationResult(IValidatable.ResultType.FAIL, "Match string can not be empty!")); continue; } string[] array = match.Split(":"); if (array.Length == 1) { list.Add(new IValidatable.ValidationResult(IValidatable.ResultType.FAIL, "'" + match + "' is not valid! If you mean to match to all Audio clips with this name you must explicitly do '*:" + match + "'.")); } if (array.Length > 3) { list.Add(new IValidatable.ValidationResult(IValidatable.ResultType.WARN, $"'{match}' has more than 3 parts! SoundAPI will handle this as '{match[0]}:{match[1]}:{match[2]}', discarding the rest!")); } } return list; } } } namespace loaforcsSoundAPI.SoundPacks.Data.Conditions { public abstract class Condition : IValidatable { [field: NonSerialized] public Conditional Parent { get; internal set; } protected SoundPack Pack => Parent.Pack; public bool? Constant { get; private set; } protected internal virtual void OnRegistered() { } public abstract bool Evaluate(IContext context); public virtual List<IValidatable.ValidationResult> Validate() { return new List<IValidatable.ValidationResult>(); } protected bool EvaluateRangeOperator(int number, string condition) { return EvaluateRangeOperator((double)number, condition); } protected bool EvaluateRangeOperator(float number, string condition) { return EvaluateRangeOperator((double)number, condition); } protected bool EvaluateRangeOperator(double value, string condition) { string[] array = condition.Split(".."); if (array.Length == 1) { if (double.TryParse(array[0], out var result)) { return value == result; } return false; } if (array.Length == 2) { double result2; if (array[0] == "") { result2 = double.MinValue; } else if (!double.TryParse(array[0], out result2)) { return false; } double result3; if (array[1] == "") { result3 = double.MaxValue; } else if (!double.TryParse(array[1], out result3)) { return false; } if (value >= result2) { return value <= result3; } return false; } return false; } protected bool ValidateRangeOperator(string condition, out IValidatable.ValidationResult result) { result = null; if (string.IsNullOrEmpty(condition)) { result = new IValidatable.ValidationResult(IValidatable.ResultType.FAIL, "Range operator can not be missing or empty!"); return false; } string[] array = condition.Split(".."); int num = array.Length; if (num <= 2) { switch (num) { case 1: { if (!double.TryParse(array[0], out var _)) { result = new IValidatable.ValidationResult(IValidatable.ResultType.FAIL, "Failed to parse: '" + array[0] + "' as a number!"); } break; } case 2: { double num2; if (array[0] == "") { num2 = double.MinValue; } else if (!double.TryParse(array[0], out num2)) { result = new IValidatable.ValidationResult(IValidatable.ResultType.FAIL, "Failed to parse: '" + array[0] + "' as a number!"); } double num3; if (array[1] == "") { num3 = double.MaxValue; } else if (!double.TryParse(array[1], out num3)) { result = new IValidatable.ValidationResult(IValidatable.ResultType.FAIL, "Failed to parse: '" + array[1] + "' as a number!"); } break; } } } else { result = new IValidatable.ValidationResult(IValidatable.ResultType.FAIL, "Range operator: '" + condition + "' uses .. more than once!"); } return result == null; } protected static void LogDebug(string name, object message) { Debuggers.ConditionsInfo?.Log($"({name}) {message}"); } } internal sealed class InvalidCondition : Condition { [CompilerGenerated] private string <type>P; public InvalidCondition(string type) { <type>P = type; base..ctor(); } public override bool Evaluate(IContext context) { return false; } public override List<IValidatable.ValidationResult> Validate() { if (string.IsNullOrEmpty(<type>P)) { return new List<IValidatable.ValidationResult>(1) { new IValidatable.ValidationResult(IValidatable.ResultType.FAIL, "Condition must have a type!") }; } return new List<IValidatable.ValidationResult>(1) { new IValidatable.ValidationResult(IValidatable.ResultType.FAIL, "'" + <type>P + "' is not a valid condition type!") }; } } internal sealed class ConstantCondition : Condition { public static ConstantCondition TRUE = new ConstantCondition(constant: true); public static ConstantCondition FALSE = new ConstantCondition(constant: false); public bool Value { get; private set; } private ConstantCondition(bool constant) { Value = constant; } public override bool Evaluate(IContext context) { return Value; } } public abstract class Condition<TContext> : Condition where TContext : IContext { public override bool Evaluate(IContext context) { if (!(context is TContext context2)) { return EvaluateFallback(context); } return EvaluateWithContext(context2); } protected abstract bool EvaluateWithContext(TContext context); protected virtual bool EvaluateFallback(IContext context) { return false; } } public abstract class Conditional : IValidatable, IPackData { public Condition Condition { get; set; } public abstract SoundPack Pack { get; set; } public bool Evaluate(IContext context) { if (Condition == null) { return true; } return Condition.Evaluate(context); } public virtual List<IValidatable.ValidationResult> Validate() { if (Condition == null) { return new List<IValidatable.ValidationResult>(); } Condition.Parent = this; Condition.OnRegistered(); return Condition.Validate(); } } public interface IContext { } internal class DefaultConditionContext : IContext { internal static readonly DefaultConditionContext DEFAULT = new DefaultConditionContext(); private DefaultConditionContext() { } } [AttributeUsage(AttributeTargets.Class, AllowMultiple = true)] [MeansImplicitUse] public class SoundAPIConditionAttribute : Attribute { public string ID { get; private set; } public bool IsDeprecated { get; private set; } public string DeprecationReason { get; private set; } public SoundAPIConditionAttribute(string id, bool deprecated = false, string deprecationReason = null) { ID = id; IsDeprecated = deprecated; DeprecationReason = deprecationReason; base..ctor(); } } } namespace loaforcsSoundAPI.SoundPacks.Conditions { public abstract class LogicGateCondition : Condition { public Condition[] Conditions { get; private set; } protected abstract string ValidateWarnMessage { get; } protected internal override void OnRegistered() { Condition[] conditions = Conditions; foreach (Condition condition in conditions) { condition.Parent = base.Parent; condition.OnRegistered(); } } public override List<IValidatable.ValidationResult> Validate() { if (Conditions.Length == 0) { return new List<IValidatable.ValidationResult>(1) { new IValidatable.ValidationResult(IValidatable.ResultType.WARN, ValidateWarnMessage) }; } return new List<IValidatable.ValidationResult>(); } protected static bool And(Condition[] conditions, IContext context) { foreach (Condition condition in conditions) { if (condition is InvalidCondition) { return false; } if (!condition.Evaluate(context)) { return false; } } return true; } protected static bool Or(Condition[] conditions, IContext context) { foreach (Condition condition in conditions) { if (condition is InvalidCondition) { return false; } if (condition.Evaluate(context)) { return true; } } return false; } } [SoundAPICondition("and", false, null)] internal class AndCondition : LogicGateCondition { protected override string ValidateWarnMessage => "'and' condition has no conditions and will always return true!"; public override bool Evaluate(IContext context) { return LogicGateCondition.And(base.Conditions, context); } } [SoundAPICondition("nand", false, null)] internal class NandCondition : LogicGateCondition { protected override string ValidateWarnMessage => "'nand' condition has no conditions and will always return false!"; public override bool Evaluate(IContext context) { return !LogicGateCondition.And(base.Conditions, context); } } [SoundAPICondition("config", false, null)] internal class ConfigCondition : Condition { public string Config { get; private set; } public object Value { get; private set; } public override bool Evaluate(IContext context) { if (!base.Pack.TryGetConfigValue(Config, out var returnValue)) { return false; } if (Value == null) { if (returnValue is bool) { return (bool)returnValue; } if (returnValue is string value) { return string.IsNullOrEmpty(value); } return false; } if (returnValue is bool flag) { return flag == (bool)Value; } if (returnValue is string text) { return text == (string)Value; } return false; } public override List<IValidatable.ValidationResult> Validate() { if (!base.Pack.TryGetConfigValue(Config, out var returnValue)) { List<IValidatable.ValidationResult> list = new List<IValidatable.ValidationResult>(1); list.Add(new IValidatable.ValidationResult(IValidatable.ResultType.FAIL, "Config '" + Config + "' does not exist on SoundPack '" + base.Pack.Name + "'")); return list; } if (Value != null && returnValue.GetType() != Value.GetType()) { return new List<IValidatable.ValidationResult>(1) { new IValidatable.ValidationResult(IValidatable.ResultType.FAIL, $"Config '{Config}' has a type of: '{returnValue.GetType()}' but the Value type is '{Value.GetType()}'!") }; } return new List<IValidatable.ValidationResult>(); } } [SoundAPICondition("counter", false, null)] public class CounterCondition : Condition { private int _count; public string Value { get; private set; } public int? ResetsAt { get; private set; } public override bool Evaluate(IContext context) { Condition.LogDebug("counter", $"counting: {_count} -> {_count + 1}"); _count++; bool flag = EvaluateRangeOperator(_count, Value); Condition.LogDebug("counter", $"is {_count} in range ({Value})? {flag}"); if (_count >= ResetsAt) { _count = 0; Condition.LogDebug("counter", "reset count to 0."); } return flag; } public override List<IValidatable.ValidationResult> Validate() { if (!ValidateRangeOperator(Value, out var result)) { return new List<IValidatable.ValidationResult>(1) { result }; } return new List<IValidatable.ValidationResult>(); } } [SoundAPICondition("mod_installed", false, null)] internal class ModInstalledCondition : Condition { public string Value { get; private set; } public override bool Evaluate(IContext context) { return Chainloader.PluginInfos.ContainsKey(Value); } public override List<IValidatable.ValidationResult> Validate() { if (string.IsNullOrEmpty(Value)) { return new List<IValidatable.ValidationResult>(1) { new IValidatable.ValidationResult(IValidatable.ResultType.FAIL, "Value on 'mod_installed' must be there and must not be empty.") }; } return new List<IValidatable.ValidationResult>(); } } [SoundAPICondition("not", false, null)] internal class NotCondition : Condition { public Condition Condition { get; private set; } protected internal override void OnRegistered() { if (Condition != null) { Condition.Parent = base.Parent; Condition.OnRegistered(); } } public override bool Evaluate(IContext context) { if (Condition is InvalidCondition) { return false; } return !Condition.Evaluate(context); } public override List<IValidatable.ValidationResult> Validate() { if (Condition == null) { return new List<IValidatable.ValidationResult>(1) { new IValidatable.ValidationResult(IValidatable.ResultType.FAIL, "'not' condition has no valid condition to invert!") }; } return new List<IValidatable.ValidationResult>(); } } [SoundAPICondition("or", false, null)] internal class OrCondition : LogicGateCondition { protected override string ValidateWarnMessage => "'or' condition has no conditions and will always return false!"; public override bool Evaluate(IContext context) { return LogicGateCondition.Or(base.Conditions, context); } } [SoundAPICondition("nor", false, null)] internal class NorCondition : LogicGateCondition { protected override string ValidateWarnMessage => "'nor' condition has no conditions and will always return true!"; public override bool Evaluate(IContext context) { return !LogicGateCondition.Or(base.Conditions, context); } } } namespace loaforcsSoundAPI.Reporting { public static class SoundReportHandler { private const string _datetimeFormat = "dd_MM_yyyy-HH_mm"; private static Action<StreamWriter, SoundReport> _reportSections = delegate { }; public static SoundReport CurrentReport { get; private set; } public static void AddReportSection(string header, Action<StreamWriter, SoundReport> callback) { _reportSections = (Action<StreamWriter, SoundReport>)Delegate.Combine(_reportSections, (Action<StreamWriter, SoundReport>)delegate(StreamWriter stream, SoundReport report) { stream.WriteLine("## " + header); callback(stream, report); stream.WriteLine(""); stream.WriteLine(""); }); } internal static void Register() { Directory.CreateDirectory(GetFolder()); CurrentReport = new SoundReport(); loaforcsSoundAPI.Logger.LogWarning((object)"SoundAPI is generating a report!"); loaforcsSoundAPI.Logger.LogInfo((object)("The report will be located at '" + LogFormats.FormatFilePath(Path.Combine(GetFolder(), GetFileName(CurrentReport, ".md"))))); Application.quitting += delegate { WriteReportToFile(CurrentReport); }; SoundPackLoadPipeline.OnFinishedPipeline += delegate { foreach (SoundPack loadedPack in SoundPackDataHandler.LoadedPacks) { CurrentReport.SoundPackNames.Add(loadedPack.Name); } }; AddReportSection("General Information", delegate(StreamWriter stream, SoundReport report) { stream.WriteLine("SoundAPI version: `2.0.5` <br/><br/>"); stream.WriteLine($"Audio-clips loaded: `{report.AudioClipsLoaded}` <br/>"); stream.WriteLine($"Match strings registered: `{SoundPackDataHandler.SoundReplacements.Values.Sum((List<SoundReplacementGroup> it) => it.Count)}` <br/>"); WriteList("Loaded sound-packs", stream, report.SoundPackNames); }); AddReportSection("Dynamic Data", delegate(StreamWriter stream, SoundReport _) { if (SoundAPI.CurrentNetworkAdapter != null) { stream.WriteLine("Network Adapter: `" + SoundAPI.CurrentNetworkAdapter.Name + "` <br/><br/>"); } WriteList("Registered Conditions", stream, SoundPackDataHandler.conditionFactories.Keys.ToList()); }); AddReportSection("All Played Sounds", delegate(StreamWriter stream, SoundReport report) { WriteList(null, stream, report.PlayedSounds.Select((SoundReport.PlayedSound it) => it.FormatForReport()).ToList()); }); } internal static void Bind(ConfigFile file) { if (file.Bind<bool>("Developer", "GenerateReports", false, "While true SoundAPI will generate a json and markdown file per session that records information SoundAPI and related mods find.").Value) { Register(); } } private static string GetFileName(SoundReport report, string extension) { return "generated_report-" + report.StartedAt.ToString("dd_MM_yyyy-HH_mm") + extension; } private static string GetFolder() { return Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "reports"); } private static void WriteReportToFile(SoundReport report) { using StreamWriter streamWriter = new StreamWriter(Path.Combine(GetFolder(), GetFileName(report, ".md"))); streamWriter.WriteLine("# Generated Report"); streamWriter.WriteLine($"At {report.StartedAt} :3"); streamWriter.WriteLine(""); _reportSections(streamWriter, report); streamWriter.Flush(); streamWriter.Close(); using StreamWriter streamWriter2 = new StreamWriter(Path.Combine(GetFolder(), GetFileName(report, ".json"))); streamWriter2.WriteLine(JsonConvert.SerializeObject((object)report, (Formatting)1)); } public static void WriteList(string header, StreamWriter stream, ICollection<string> list) { if (!string.IsNullOrEmpty(header)) { stream.WriteLine($"### {header} (`{list.Count}`)"); } stream.WriteLine(string.Join("<br/>\n", list.Select((string it) => "- " + it))); } public static void WriteEnum<T>(string header, StreamWriter stream) where T : Enum { WriteList(header, stream, (from it in Enum.GetValues(typeof(T)).OfType<T>() select it.ToString().ToLowerInvariant()).ToList()); } } } namespace loaforcsSoundAPI.Reporting.Data { public class SoundReport { public class PlayedSound { public string MatchString { get; private set; } public string Caller { get; private set; } public bool IsPlayOnAwake { get; private set; } public PlayedSound(string matchString, string caller, bool isPlayOnAwake) { MatchString = matchString; Caller = caller; IsPlayOnAwake = isPlayOnAwake; base..ctor(); } public override bool Equals(object obj) { if (!(obj is PlayedSound other)) { return false; } return Equals(other); } protected bool Equals(PlayedSound other) { if (MatchString == other.MatchString && Caller == other.Caller) { return IsPlayOnAwake == other.IsPlayOnAwake; } return false; } public override int GetHashCode() { return HashCode.Combine(MatchString, Caller, IsPlayOnAwake); } public string FormatForReport() { return $"Match String: {MatchString}, Caller: {Caller}, IsPlayOnAwake: {IsPlayOnAwake}"; } } public DateTime StartedAt { get; private set; } = DateTime.Now; public List<PlayedSound> PlayedSounds { get; private set; } = new List<PlayedSound>(); public List<string> SoundPackNames { get; private set; } = new List<string>(); public int AudioClipsLoaded { get; set; } } } namespace loaforcsSoundAPI.Core { public class AudioSourceAdditionalData { private SoundReplacementGroup _replacedWith; public AudioSource Source { get; private set; } internal SoundReplacementGroup ReplacedWith { get { return _replacedWith; } set { _replacedWith = value; if (RequiresUpdateFunction()) { if (!SoundAPIAudioManager.liveAudioSourceData.Contains(this)) { SoundAPIAudioManager.liveAudioSourceData.Add(this); } } else if (SoundAPIAudioManager.liveAudioSourceData.Contains(this)) { SoundAPIAudioManager.liveAudioSourceData.Remove(this); } } } public bool DisableReplacing { get; private set; } public IContext CurrentContext { get; set; } internal AudioSourceAdditionalData(AudioSource source) { Source = source; } internal void Update() { if (RequiresUpdateFunction() && AudioSourceIsPlaying()) { Debuggers.UpdateEveryFrame?.Log("success: updating every frame for " + ((Object)Source).name); IContext context = CurrentContext ?? DefaultConditionContext.DEFAULT; SoundInstance soundInstance = ReplacedWith.Sounds.FirstOrDefault((SoundInstance x) => x.Evaluate(context)); if (soundInstance != null && !((Object)(object)soundInstance.Clip == (Object)(object)Source.clip)) { Debuggers.UpdateEveryFrame?.Log("new clip found, swapping!!"); float time = Source.time; Source.clip = soundInstance.Clip; Source.Play(); Source.time = time; Debuggers.UpdateEveryFrame?.Log("new clip found, swapped"); } } } private bool RequiresUpdateFunction() { if (ReplacedWith != null) { return ReplacedWith.Parent.UpdateEveryFrame; } return false; } private bool AudioSourceIsPlaying() { if (Object.op_Implicit((Object)(object)Source) && ((Behaviour)Source).enabled) { return Source.isPlaying; } return false; } public static AudioSourceAdditionalData GetOrCreate(AudioSource source) { if (SoundAPIAudioManager.audioSourceData.TryGetValue(source, out var value)) { return value; } value = new AudioSourceAdditionalData(source); SoundAPIAudioManager.audioSourceData[source] = value; return value; } } internal static class Debuggers { internal static DebugLogSource AudioSourceAdditionalData; internal static DebugLogSource SoundReplacementLoader; internal static DebugLogSource SoundReplacementHandler; internal static DebugLogSource MatchStrings; internal static DebugLogSource ConditionsInfo; internal static DebugLogSource UpdateEveryFrame; internal static void Bind(ConfigFile file) { FieldInfo[] fields = typeof(Debuggers).GetFields(BindingFlags.Static | BindingFlags.NonPublic); foreach (FieldInfo fieldInfo in fields) { if (file.Bind<bool>("InternalDebugging", fieldInfo.Name, false, "Enable/Disable this DebugLogSource. Should only be true if you know what you are doing or have been asked to.").Value) { fieldInfo.SetValue(null, new DebugLogSource(fieldInfo.Name)); loaforcsSoundAPI.Logger.LogDebug((object)("created a DebugLogSource for " + fieldInfo.Name + "!")); } else { fieldInfo.SetValue(null, null); loaforcsSoundAPI.Logger.LogDebug((object)("no DebugLogSource for " + fieldInfo.Name + ".")); } } } } internal class DebugLogSource { [CompilerGenerated] private string <title>P; public DebugLogSource(string title) { <title>P = title; base..ctor(); } internal void Log(object message) { loaforcsSoundAPI.Logger.LogDebug((object)$"[Debug-{<title>P}] {message}"); } } internal class SoundAPIAudioManager : MonoBehaviour { internal static readonly Dictionary<AudioSource, AudioSourceAdditionalData> audioSourceData = new Dictionary<AudioSource, AudioSourceAdditionalData>(); internal static readonly List<AudioSourceAdditionalData> liveAudioSourceData = new List<AudioSourceAdditionalData>(); private static SoundAPIAudioManager Instance; private void Awake() { SceneManager.sceneLoaded += delegate { if (!Object.op_Implicit((Object)(object)Instance)) { SpawnManager(); } RunCleanup(); }; } internal static void SpawnManager() { //IL_0014: Unknown result type (might be due to invalid IL or missing references) //IL_001a: Expected O, but got Unknown loaforcsSoundAPI.Logger.LogInfo((object)"Starting AudioManager."); GameObject val = new GameObject("SoundAPI_AudioManager"); Object.DontDestroyOnLoad((Object)(object)val); Instance = val.AddComponent<SoundAPIAudioManager>(); } private void Update() { Debuggers.UpdateEveryFrame?.Log("sanity check: soundapi audio manager is running!"); foreach (AudioSourceAdditionalData liveAudioSourceDatum in liveAudioSourceData) { liveAudioSourceDatum.Update(); } } private void OnDisable() { loaforcsSoundAPI.Logger.LogDebug((object)"manager disabled"); } private void OnDestroy() { loaforcsSoundAPI.Logger.LogDebug((object)"manager destroyed"); } private static void RunCleanup() { loaforcsSoundAPI.Logger.LogDebug((object)"cleaning up old audio source entries"); AudioSource[] array = audioSourceData.Keys.ToArray(); foreach (AudioSource val in array) { if (!Object.op_Implicit((Object)(object)val)) { if (liveAudioSourceData.Contains(audioSourceData[val])) { liveAudioSourceData.Remove(audioSourceData[val]); } audioSourceData.Remove(val); } } } } } namespace loaforcsSoundAPI.Core.Util { public class AdaptiveConfigEntry { public AdaptiveBool State { get; private set; } public bool DefaultValue { get; private set; } public bool? OverrideValue { get; set; } public bool Value => State switch { AdaptiveBool.Enabled => true, AdaptiveBool.Disabled => false, _ => OverrideValue ?? DefaultValue, }; public AdaptiveConfigEntry(AdaptiveBool state, bool defaultValue) { State = state; DefaultValue = defaultValue; } } public enum AdaptiveBool { Automatic, Enabled, Disabled } internal static class LogFormats { internal static string FormatFilePath(string path) { return $"plugins{Path.DirectorySeparatorChar}{Path.Combine(Path.GetRelativePath(Paths.PluginPath, path))}"; } } } namespace loaforcsSoundAPI.Core.Util.Extensions { internal static class AssemblyExtensions { internal static IEnumerable<Type> GetLoadableTypes(this Assembly assembly) { if (assembly == null) { throw new ArgumentNullException("assembly"); } try { return assembly.GetTypes(); } catch (ReflectionTypeLoadException ex) { return ex.Types.Where((Type t) => t != null); } } } public static class AsyncOperationExtensions { public static TaskAwaiter GetAwaiter(this AsyncOperation asyncOp) { TaskCompletionSource<AsyncOperation> tcs = new TaskCompletionSource<AsyncOperation>(); asyncOp.completed += delegate(AsyncOperation operation) { tcs.SetResult(operation); }; return ((Task)tcs.Task).GetAwaiter(); } } public static class ConfigFileExtensions { public static AdaptiveConfigEntry BindAdaptive(this ConfigFile file, string section, string key, bool defaultValue, string description) { //IL_001c: Unknown result type (might be due to invalid IL or missing references) //IL_0026: Expected O, but got Unknown AdaptiveBool value = file.Bind<AdaptiveBool>(section, key, AdaptiveBool.Automatic, new ConfigDescription($"{description}\nAutomatic default: {defaultValue}", (AcceptableValueBase)null, Array.Empty<object>())).Value; return new AdaptiveConfigEntry(value, defaultValue); } } public static class ListExtensions { public static void AddUnique<T>(this List<T> list, T item) { if (!list.Contains(item)) { list.Add(item); } } } } namespace loaforcsSoundAPI.Core.Patches { [HarmonyPatch(typeof(AudioSource))] internal static class AudioSourcePatch { [HarmonyPrefix] [HarmonyPatch("Play", new Type[] { })] [HarmonyPatch("Play", new Type[] { typeof(ulong) })] [HarmonyPatch("Play", new Type[] { typeof(double) })] private static bool Play(AudioSource __instance) { if (SoundReplacementHandler.TryReplaceAudio(__instance, __instance.clip, out var replacement)) { if ((Object)(object)replacement == (Object)null) { return false; } __instance.clip = replacement; } return true; } [HarmonyPrefix] [HarmonyPatch("PlayOneShot", new Type[] { typeof(AudioClip), typeof(float) })] private static bool PlayOneShot(AudioSource __instance, ref AudioClip clip) { if (SoundReplacementHandler.TryReplaceAudio(__instance, clip, out var replacement)) { if ((Object)(object)replacement == (Object)null) { return false; } clip = replacement; } return true; } } [HarmonyPatch(typeof(GameObject))] internal static class GameObjectPatch { [HarmonyPostfix] [HarmonyPatch("AddComponent", new Type[] { typeof(Type) })] internal static void NewAudioSource(GameObject __instance, ref Component __result) { Component obj = __result; AudioSource val = (AudioSource)(object)((obj is AudioSource) ? obj : null); if (val != null) { AudioSourceAdditionalData.GetOrCreate(val); } } } [HarmonyPatch(typeof(Logger))] internal static class LoggerPatch { [HarmonyPrefix] [HarmonyPatch("LogMessage")] private static void ReenableAndSaveConfigs(object data) { if (data is string text && text == "Chainloader startup complete") { loaforcsSoundAPI.Logger.LogInfo((object)"Starting Sound-pack loading pipeline"); SoundPackLoadPipeline.StartPipeline(); } } } internal static class UnityObjectPatch { private static void InstantiatePatch(Object __result) { Debuggers.AudioSourceAdditionalData?.Log("aghuobr: " + __result.name); GameObject val = (GameObject)(object)((__result is GameObject) ? __result : null); if (val != null) { CheckInstantiationRecursively(val); } } internal static void Init(Harmony harmony) { //IL_0016: Unknown result type (might be due to invalid IL or missing references) //IL_001c: Expected O, but got Unknown HarmonyMethod val = new HarmonyMethod(typeof(UnityObjectPatch).GetMethod("InstantiatePatch", BindingFlags.Static | BindingFlags.NonPublic)); MethodInfo[] methods = typeof(Object).GetMethods(); foreach (MethodInfo methodInfo in methods) { if (!(methodInfo.Name != "Instantiate")) { Debuggers.AudioSourceAdditionalData?.Log($"patching {methodInfo}"); if (methodInfo.IsGenericMethod) { harmony.Patch((MethodBase)methodInfo.MakeGenericMethod(typeof(Object)), (HarmonyMethod)null, val, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); } else { harmony.Patch((MethodBase)methodInfo, (HarmonyMethod)null, val, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); } } } } private static void CheckInstantiationRecursively(GameObject gameObject) { //IL_008b: Unknown result type (might be due to invalid IL or missing references) //IL_0092: Expected O, but got Unknown AudioSourceAdditionalData audioSourceAdditionalData = default(AudioSourceAdditionalData); if (gameObject.TryGetComponent<AudioSourceAdditionalData>(ref audioSourceAdditionalData)) { return; } AudioSource[] components = gameObject.GetComponents<AudioSource>(); foreach (AudioSource val in components) { AudioSourceAdditionalData.GetOrCreate(val); if (!val.playOnAwake) { continue; } AudioClip clip = val.clip; if (SoundReplacementHandler.TryReplaceAudio(val, clip, out var replacement)) { val.Stop(); if (!((Object)(object)replacement == (Object)null)) { val.clip = replacement; val.Play(); } } else { val.clip = clip; val.Play(); } } foreach (Transform item in gameObject.transform) { Transform val2 = item; CheckInstantiationRecursively(((Component)val2).gameObject); } } } } namespace loaforcsSoundAPI.Core.Networking { public abstract class NetworkAdapter { public abstract string Name { get; } public abstract void OnRegister(); } } namespace loaforcsSoundAPI.Core.JSON { public static class JSONDataLoader { private class MatchesJSONConverter : JsonConverter { public override bool CanConvert(Type objectType) { return objectType == typeof(List<string>); } public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_000e: Invalid comparison between Unknown and I4 JToken val = JToken.Load(reader); if ((int)val.Type == 2) { return val.ToObject<List<string>>(); } return new List<string> { ((object)val).ToString() }; } public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { serializer.Serialize(writer, value); } } private class IncludePrivatePropertiesContractResolver : DefaultContractResolver { internal IncludePrivatePropertiesContractResolver() { //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_0011: Expected O, but got Unknown ((DefaultContractResolver)this).NamingStrategy = (NamingStrategy)new SnakeCaseNamingStrategy(); } protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) JsonProperty val = ((DefaultContractResolver)this).CreateProperty(member, memberSerialization); if (!val.Writable && member is PropertyInfo propertyInfo) { val.Writable = propertyInfo.GetSetMethod(nonPublic: true) != null; } return val; } } private class ConditionConverter : JsonConverter<Condition> { public override Condition ReadJson(JsonReader reader, Type objectType, Condition existingValue, bool hasExistingValue, JsonSerializer serializer) { JObject val = JObject.Load(reader); string text = ((object)val["type"])?.ToString(); if (string.IsNullOrEmpty(text)) { return new InvalidCondition(null); } Condition condition = SoundPackDataHandler.CreateCondition(text); if (condition == null) { return null; } serializer.Populate(((JToken)val).CreateReader(), (object)condition); if (condition.Constant == true) { if (!condition.Evaluate(DefaultConditionContext.DEFAULT)) { return ConstantCondition.FALSE; } return ConstantCondition.TRUE; } return condition; } public override void WriteJson(JsonWriter writer, Condition value, JsonSerializer serializer) { throw new NotImplementedException("no."); } } private static readonly JsonSerializerSettings _settings = new JsonSerializerSettings { ContractResolver = (IContractResolver)(object)new IncludePrivatePropertiesContractResolver(), Converters = new List<JsonConverter>(2) { (JsonConverter)(object)new MatchesJSONConverter(), (JsonConverter)(object)new ConditionConverter() } }; public static T LoadFromFile<T>(string path) { //IL_0061: Expected O, but got Unknown string text = File.ReadAllText(path); try { T val = JsonConvert.DeserializeObject<T>(text, _settings); if ((object)val is IFilePathAware filePathAware) { filePathAware.FilePath = path; } if ((object)val is Conditional conditional && conditional.Condition != null) { conditional.Condition.Parent = conditional; conditional.Condition.OnRegistered(); } return val; } catch (JsonReaderException val2) { JsonReaderException val3 = val2; loaforcsSoundAPI.Logger.LogError((object)$"Failed to read json file: 'plugins{Path.DirectorySeparatorChar}{Path.GetRelativePath(Paths.PluginPath, path)}'"); loaforcsSoundAPI.Logger.LogError((object)((Exception)(object)val3).Message); string[] array = text.Split("\n"); int num = int.MaxValue; for (int i = Mathf.Max(0, val3.LineNumber - 3); i < Mathf.Min(array.Length, val3.LineNumber + 3); i++) { int num2 = array[i].TakeWhile(char.IsWhiteSpace).Count(); num = Mathf.Min(num, num2); } for (int j = Mathf.Max(0, val3.LineNumber - 3); j < Mathf.Min(array.Length, val3.LineNumber + 3); j++) { string text2 = $"{(j + 1).ToString(),-5}| "; string text3 = array[j]; int num3 = Mathf.Min(array[j].Length, num); string text4 = text2 + text3.Substring(num3, text3.Length - num3).TrimEnd(); if (j + 1 == val3.LineNumber) { text4 += " // <- HERE"; } loaforcsSoundAPI.Logger.LogError((object)text4); } } return default(T); } } } namespace loaforcsSoundAPI.Core.Data { public interface IFilePathAware { string FilePath { get; internal set; } } public interface IValidatable { public enum ResultType { WARN, FAIL } public class ValidationResult { public ResultType Status { get; private set; } public string Reason { get; private set; } public ValidationResult(ResultType resultType, string reason = null) { Status = resultType; Reason = reason ?? string.Empty; base..ctor(); } } private static readonly StringBuilder _stringBuilder = new StringBuilder(); List<ValidationResult> Validate(); internal static bool LogAndCheckValidationResult(string context, List<ValidationResult> results, ManualLogSource logger) { if (results.Count == 0) { return true; } int num = 0; int num2 = 0; foreach (ValidationResult result in results) { switch (result.Status) { case ResultType.WARN: num++; break; case ResultType.FAIL: num2++; break; default: throw new ArgumentOutOfRangeException(); } } _stringBuilder.Clear(); if (num2 != 0) { _stringBuilder.Append(num2); _stringBuilder.Append(" fail(s)"); } if (num != 0) { if (num2 != 0) { _stringBuilder.Append(" and "); } _stringBuilder.Append(num); _stringBuilder.Append(" warning(s)"); } _stringBuilder.Append(" while "); _stringBuilder.Append(context); _stringBuilder.Append(": "); if (num2 != 0) { logger.LogError((object)_stringBuilder); } else { logger.LogWarning((object)_stringBuilder); } foreach (ValidationResult result2 in results) { switch (result2.Status) { case ResultType.WARN: logger.LogWarning((object)("WARN: " + result2.Reason)); break; case ResultType.FAIL: logger.LogError((object)("FAIL: " + result2.Reason)); break; default: throw new ArgumentOutOfRangeException(); } } return num2 != 0; } } }
plugins/Magic_Wesley-Wesleys_Valuables/WesleysItemProj.dll
Decompiled 2 months agousing System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using BepInEx; using REPOLib.Modules; 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("WesleysItemProj")] [assembly: AssemblyConfiguration("Debug")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: AssemblyInformationalVersion("1.0.0")] [assembly: AssemblyProduct("WesleysItemProj")] [assembly: AssemblyTitle("WesleysItemProj")] [assembly: AssemblyVersion("1.0.0.0")] namespace WesleysItemProj; [BepInPlugin("MagicWesley.WesleysItems", "WesleysItems", "0.1.0")] [BepInDependency(/*Could not decode attribute arguments.*/)] public class WesleysItems : BaseUnityPlugin { private void Awake() { string directoryName = Path.GetDirectoryName(((BaseUnityPlugin)this).Info.Location); string text = Path.Combine(directoryName, "wesleysitems_itemprefabs"); AssetBundle val = AssetBundle.LoadFromFile(text); GameObject val2 = val.LoadAsset<GameObject>("BeholdersEye"); GameObject val3 = val.LoadAsset<GameObject>("BiomontyDisplay"); GameObject val4 = val.LoadAsset<GameObject>("Pickle"); GameObject val5 = val.LoadAsset<GameObject>("PickleJar"); GameObject val6 = val.LoadAsset<GameObject>("SpikyEye"); GameObject val7 = val.LoadAsset<GameObject>("BananaHolder"); GameObject val8 = val.LoadAsset<GameObject>("Webley"); List<string> list = new List<string> { "Valuables - Arctic" }; List<string> list2 = new List<string> { "Valuables - Wizard", "Valuables - Manor" }; List<string> list3 = new List<string> { "Valuables - Manor" }; List<string> list4 = new List<string> { "Valuables - Wizard", "Valuables - Manor", "Valuables - Arctic", "Valuables - Generic" }; Valuables.RegisterValuable(val2, list2); Valuables.RegisterValuable(val3, list2); Valuables.RegisterValuable(val4, list4); Valuables.RegisterValuable(val5, list4); Valuables.RegisterValuable(val6, list2); Valuables.RegisterValuable(val7, list3); Valuables.RegisterValuable(val8, list); } }
plugins/MrDj200-VoiceThreshold/VoiceThreshold.dll
Decompiled 2 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 BepInEx.Logging; using HarmonyLib; using Microsoft.CodeAnalysis; using Photon.Pun; using Photon.Voice.Unity; 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("VoiceThreshold")] [assembly: AssemblyConfiguration("Debug")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: AssemblyInformationalVersion("1.0.0")] [assembly: AssemblyProduct("Voice Threshold")] [assembly: AssemblyTitle("VoiceThreshold")] [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 VoiceThreshold { [BepInPlugin("VoiceThreshold", "Voice Threshold", "1.0.0")] public class Plugin : BaseUnityPlugin { [HarmonyPatch] public class Patches { [HarmonyPatch(typeof(PlayerVoiceChat), "Awake")] [HarmonyPostfix] private static void PlayerVoiceChatAwakePatch(PlayerVoiceChat __instance) { PhotonView component = ((Component)__instance).GetComponent<PhotonView>(); Recorder component2 = ((Component)__instance).GetComponent<Recorder>(); if ((Object)(object)component != (Object)null && component.IsMine && (Object)(object)component2 != (Object)null) { recorder = component2; component2.VoiceDetection = configUseThreshold.Value; component2.VoiceDetectionThreshold = configThresholdValue.Value; } } } internal static ManualLogSource Logger; public static ConfigEntry<float> configThresholdValue; public static ConfigEntry<bool> configUseThreshold; public static Recorder recorder; private readonly Harmony _harmony = new Harmony("VoiceThreshold"); public Plugin() { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Expected O, but got Unknown //IL_0046: Unknown result type (might be due to invalid IL or missing references) //IL_0050: Expected O, but got Unknown configThresholdValue = ((BaseUnityPlugin)this).Config.Bind<float>("Settings", "ThresholdValue", 0.01f, new ConfigDescription("The threshold value for the voice", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 1f), Array.Empty<object>())); configUseThreshold = ((BaseUnityPlugin)this).Config.Bind<bool>("Settings", "UseThreshold", true, "Whether to use the threshold value"); configThresholdValue.SettingChanged += ThresholdChanged; configUseThreshold.SettingChanged += UseThresholdChanged; } private void Awake() { Logger = ((BaseUnityPlugin)this).Logger; Logger.LogInfo((object)"Plugin VoiceThreshold is loaded!"); _harmony.PatchAll(); } private void OnDestroy() { Harmony harmony = _harmony; if (harmony != null) { harmony.UnpatchSelf(); } Logger.LogInfo((object)"Cleaning up my shit!"); } private void ThresholdChanged(object sender, EventArgs e) { if (e is SettingChangedEventArgs && (Object)(object)recorder != (Object)null) { SettingChangedEventArgs val = (SettingChangedEventArgs)(object)((e is SettingChangedEventArgs) ? e : null); float voiceDetectionThreshold = (float)val.ChangedSetting.BoxedValue; recorder.VoiceDetectionThreshold = voiceDetectionThreshold; } } private void UseThresholdChanged(object sender, EventArgs e) { if (e is SettingChangedEventArgs && (Object)(object)recorder != (Object)null) { SettingChangedEventArgs val = (SettingChangedEventArgs)(object)((e is SettingChangedEventArgs) ? e : null); bool voiceDetection = (bool)val.ChangedSetting.BoxedValue; recorder.VoiceDetection = voiceDetection; } } } public static class MyPluginInfo { public const string PLUGIN_GUID = "VoiceThreshold"; public const string PLUGIN_NAME = "Voice Threshold"; public const string PLUGIN_VERSION = "1.0.0"; } }
plugins/nickklmao-FreecamSpectate/FreecamSpectate.dll
Decompiled 2 months agousing System; using System.Diagnostics; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using BepInEx; using BepInEx.Logging; using FreecamSpectate; using HarmonyLib; using Microsoft.CodeAnalysis; using MonoMod.RuntimeDetour; using UnityEngine; using UnityEngine.InputSystem; using UnityEngine.InputSystem.Controls; [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("FreecamSpectate")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: AssemblyInformationalVersion("1.0.0")] [assembly: AssemblyProduct("FreecamSpectate")] [assembly: AssemblyTitle("FreecamSpectate")] [assembly: AssemblyVersion("1.0.0.0")] [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; } } } internal static class ReflectionHelper { internal readonly struct ReflectedMember<T> { private readonly Delegate invokeDelegate; private readonly Delegate setDelegate; internal T value { get { return (T)(invokeDelegate?.DynamicInvoke()); } set { setDelegate?.DynamicInvoke(value); } } internal ReflectedMember(Delegate invokeDelegate, Delegate setDelegate) { this.invokeDelegate = invokeDelegate; this.setDelegate = setDelegate; } internal T Invoke(object arg) { return (T)(invokeDelegate?.DynamicInvoke(arg)); } internal T Invoke(params object[] args) { return (T)(invokeDelegate?.DynamicInvoke(new object[1] { args })); } } internal readonly struct ReflectedMember { private readonly Delegate invokeDelegate; internal ReflectedMember(Delegate invokeDelegate) { this.invokeDelegate = invokeDelegate; } internal void Invoke(params object[] args) { invokeDelegate?.DynamicInvoke(new object[1] { args }); } } private const BindingFlags allBindingFlags = BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic; internal static ReflectedMember<T> GetPrivateMember<T>(this object instance, string memberName, params Type[] methodArguments) { Type type = instance.GetType(); if (instance is Type type2) { type = type2; instance = null; } MemberInfo[] member = type.GetMember(memberName, BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); MemberInfo memberInfo = member.Length switch { 0 => throw new NullReferenceException("Member \"" + memberName + "\" cannot be found."), 1 => member[0], _ => member.Cast<MethodInfo>().SingleOrDefault((MethodInfo methodInfo) => (from paramInfo in methodInfo.GetParameters() select paramInfo.ParameterType).SequenceEqual(methodArguments)), }; FieldInfo fieldInfo = memberInfo as FieldInfo; if ((object)fieldInfo == null) { PropertyInfo propertyInfo = memberInfo as PropertyInfo; if ((object)propertyInfo == null) { MethodInfo methodInfo2 = memberInfo as MethodInfo; if ((object)methodInfo2 != null) { return new ReflectedMember<T>((Func<object[], object>)((object[] args) => methodInfo2.Invoke(instance, args)), null); } return default(ReflectedMember<T>); } return new ReflectedMember<T>((Func<object>)(() => propertyInfo.GetValue(instance)), (Action<T>)delegate(T value) { propertyInfo.SetValue(instance, value); }); } return new ReflectedMember<T>((Func<object>)(() => fieldInfo.GetValue(instance)), (Action<T>)delegate(T value) { fieldInfo.SetValue(instance, value); }); } internal static ReflectedMember GetPrivateMember(this object instance, string memberName, params Type[] methodArguments) { Type type = instance.GetType(); if (instance is Type type2) { type = type2; instance = null; } try { MethodInfo method = type.GetMethod(memberName, BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); return new ReflectedMember((Func<object[], object>)((object[] args) => method.Invoke(instance, args))); } catch (Exception ex) { Entry.logger.LogMessage((object)ex); throw; } } } namespace FreecamSpectate { [BepInPlugin("nickklmao.freecamspectate", "Freecam Spectate", "1.0.2")] internal sealed class Entry : BaseUnityPlugin { internal static readonly ManualLogSource logger = Logger.CreateLogSource("Freecam Spectate"); private static bool freecamToggle; private static bool isDownLatest; private static void StateNormal_Hook(Action<SpectateCamera> orig, SpectateCamera self) { //IL_0218: Unknown result type (might be due to invalid IL or missing references) //IL_0222: Unknown result type (might be due to invalid IL or missing references) //IL_0227: Unknown result type (might be due to invalid IL or missing references) //IL_01da: Unknown result type (might be due to invalid IL or missing references) //IL_01f0: 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_010f: Unknown result type (might be due to invalid IL or missing references) //IL_02ff: Unknown result type (might be due to invalid IL or missing references) //IL_0304: Unknown result type (might be due to invalid IL or missing references) //IL_030b: Unknown result type (might be due to invalid IL or missing references) //IL_0316: Unknown result type (might be due to invalid IL or missing references) //IL_031b: Unknown result type (might be due to invalid IL or missing references) //IL_0322: Unknown result type (might be due to invalid IL or missing references) //IL_0327: Unknown result type (might be due to invalid IL or missing references) //IL_032c: Unknown result type (might be due to invalid IL or missing references) //IL_0333: 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_033d: Unknown result type (might be due to invalid IL or missing references) //IL_0354: Unknown result type (might be due to invalid IL or missing references) //IL_036b: Unknown result type (might be due to invalid IL or missing references) //IL_0370: Unknown result type (might be due to invalid IL or missing references) //IL_037e: Unknown result type (might be due to invalid IL or missing references) //IL_0389: Unknown result type (might be due to invalid IL or missing references) //IL_038e: Unknown result type (might be due to invalid IL or missing references) //IL_0390: Unknown result type (might be due to invalid IL or missing references) //IL_03a0: Unknown result type (might be due to invalid IL or missing references) if (((ButtonControl)Keyboard.current[(Key)40]).wasPressedThisFrame) { freecamToggle = !freecamToggle; } if (!freecamToggle) { orig(self); return; } ReflectionHelper.ReflectedMember<bool> privateMember = self.GetPrivateMember<bool>("stateImpulse", Array.Empty<Type>()); Camera value = self.GetPrivateMember<Camera>("MainCamera", Array.Empty<Type>()).value; PlayerAvatar value2 = self.GetPrivateMember<PlayerAvatar>("player", Array.Empty<Type>()).value; ReflectionHelper.ReflectedMember privateMember2 = self.GetPrivateMember("PlayerSwitch"); if (privateMember.value) { privateMember2.Invoke(true); if (!Object.op_Implicit((Object)(object)value2)) { return; } RenderSettings.fog = true; value.fieldOfView = self.GetPrivateMember<float>("previousFieldOfView", Array.Empty<Type>()).value; self.GetPrivateMember<Camera>("TopCamera", Array.Empty<Type>()).value.fieldOfView = value.fieldOfView; ((Component)value).transform.localPosition = Vector3.zero; ((Component)value).transform.localRotation = Quaternion.identity; AudioManager.instance.AudioListener.TargetPositionTransform = ((Component)value).transform; privateMember.value = false; } float num = SemiFunc.InputMouseX(); float num2 = SemiFunc.InputMouseY(); float num3 = CameraAim.Instance.AimSpeedMouse * 1.5f; ReflectionHelper.ReflectedMember<float> privateMember3 = self.GetPrivateMember<float>("normalAimHorizontal", Array.Empty<Type>()); ReflectionHelper.ReflectedMember<float> privateMember4 = self.GetPrivateMember<float>("normalAimVertical", Array.Empty<Type>()); privateMember3.value += num * num3; privateMember4.value -= num2 * num3; privateMember4.value = Mathf.Clamp(privateMember4.value, -90f, 90f); if (Mouse.current.middleButton.wasPressedThisFrame) { ((Component)self).transform.position = value2.spectatePoint.position; ((Component)self).transform.rotation = self.normalTransformDistance.rotation; } else { ((Component)self).transform.rotation = Quaternion.Euler(privateMember4.value, privateMember3.value, 0f); Vector2 val = SemiFunc.InputMovement(); if (((ButtonControl)Keyboard.current[(Key)31]).wasPressedThisFrame || InputManager.instance.KeyDown((InputKey)12)) { isDownLatest = true; } if (((ButtonControl)Keyboard.current[(Key)19]).wasPressedThisFrame || InputManager.instance.KeyDown((InputKey)1)) { isDownLatest = false; } bool num4 = ((ButtonControl)Keyboard.current[(Key)31]).isPressed || InputManager.instance.KeyHold((InputKey)12); bool flag = ((ButtonControl)Keyboard.current[(Key)19]).isPressed || InputManager.instance.KeyHold((InputKey)1); float num5 = (num4 ? ((!flag) ? (-1f) : (isDownLatest ? (-1f) : 1f)) : ((!flag) ? 0f : 1f)); float num6 = num5; Vector3 val2 = ((Component)self).transform.forward * val.y + ((Component)self).transform.right * val.x + Vector3.up * num6; if (((Vector3)(ref val2)).sqrMagnitude > 1f) { ((Vector3)(ref val2)).Normalize(); } val2 *= (SemiFunc.InputHold((InputKey)15) ? 2f : 1f); ((Component)self).transform.position = Vector3.Lerp(((Component)self).transform.position, ((Component)self).transform.position + val2, Time.deltaTime * 10f); } value.nearClipPlane = (RenderSettings.fogStartDistance = 0.1f); value.farClipPlane = 10000f; if (SemiFunc.InputDown((InputKey)23)) { privateMember2.Invoke(true); } else if (SemiFunc.InputDown((InputKey)24)) { privateMember2.Invoke(false); } if (Object.op_Implicit((Object)(object)value2) && value2.GetPrivateMember<bool>("voiceChatFetched", Array.Empty<Type>()).value) { value2.GetPrivateMember<PlayerVoiceChat>("voiceChat", Array.Empty<Type>()).value.SpatialDisable(0.1f); } } private void Awake() { //IL_0055: Unknown result type (might be due to invalid IL or missing references) logger.LogMessage((object)((Object)((Component)this).gameObject).name); logger.LogDebug((object)"Hooking `SpectateCamera.StateNormal`"); new Hook((MethodBase)AccessTools.Method(typeof(SpectateCamera), "StateNormal", (Type[])null, (Type[])null), (Delegate)new Action<Action<SpectateCamera>, SpectateCamera>(StateNormal_Hook)); logger.LogMessage((object)"While spectating, you can press \"Z\" to toggle freecam. Middle mouse button will teleport your camera back to the player you're spectating."); } } }
plugins/nickklmao-JustRetry/JustRetry.dll
Decompiled 2 months agousing System; using System.Collections; using System.Diagnostics; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using BepInEx; using BepInEx.Configuration; using BepInEx.Logging; using HarmonyLib; using Microsoft.CodeAnalysis; using Mono.Cecil.Cil; using MonoMod.Cil; using MonoMod.RuntimeDetour; 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("JustRetry")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: AssemblyInformationalVersion("1.0.0")] [assembly: AssemblyProduct("JustRetry")] [assembly: AssemblyTitle("JustRetry")] [assembly: AssemblyVersion("1.0.0.0")] [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 JustRetry { [BepInPlugin("nickklmao.justretry", "Just Retry", "1.0.2")] internal sealed class Entry : BaseUnityPlugin { [CompilerGenerated] private static class <>O { public static Manipulator <0>__RunManager_ChangeLevelILHook; public static Action<Action<RoundDirector, int>, RoundDirector, int> <1>__RoundDirector_StartRoundLogicHook; } private const string MOD_NAME = "Just Retry"; internal static readonly ManualLogSource logger = Logger.CreateLogSource("Just Retry"); private static readonly FieldInfo playerHealthHealthFieldInfo = AccessTools.Field(typeof(PlayerHealth), "health"); private static ConfigEntry<bool> enabled; private static ConfigEntry<int> retryHP; private static bool isRestarting; private static void RunManager_ChangeLevelILHook(ILContext il) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Expected O, but got Unknown //IL_004c: 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_0092: Unknown result type (might be due to invalid IL or missing references) //IL_00c1: Unknown result type (might be due to invalid IL or missing references) ILCursor val = new ILCursor(il); val.GotoNext(new Func<Instruction, bool>[1] { (Instruction instruction) => ILPatternMatchingExt.MatchStfld<RunManager>(instruction, "gameOver") }); val.Index -= 2; int index = val.Index; val.Emit(OpCodes.Ldarg_2); val.EmitDelegate<Func<bool, bool>>((Func<bool, bool>)delegate(bool levelFailed) { if (!levelFailed || !enabled.Value) { return false; } isRestarting = true; RunManager.instance.RestartScene(); return true; }); ILLabel val2 = val.DefineLabel(); val.Emit(OpCodes.Brfalse_S, (object)val2); val.Emit(OpCodes.Ret); val.MarkLabel(val2); val.Index -= 8; ILLabel val3 = val.DefineLabel(); val.Remove(); val.Emit(OpCodes.Brfalse_S, (object)val3); val.Index = index; val.MarkLabel(val3); } private static void RoundDirector_StartRoundLogicHook(Action<RoundDirector, int> orig, RoundDirector self, int value) { orig(self, value); if (isRestarting && SemiFunc.IsMasterClientOrSingleplayer()) { ((MonoBehaviour)self).StartCoroutine(HealPlayers()); isRestarting = false; } static IEnumerator HealPlayers() { yield return (object)new WaitForSeconds(5f); foreach (PlayerHealth item in from player in SemiFunc.PlayerGetAll() select player.playerHealth) { int num = (int)playerHealthHealthFieldInfo.GetValue(item); if (num < retryHP.Value) { item.HealOther(retryHP.Value - num, true); } } } } private void Awake() { //IL_0040: Unknown result type (might be due to invalid IL or missing references) //IL_004a: Expected O, but got Unknown //IL_008f: Unknown result type (might be due to invalid IL or missing references) //IL_0084: Unknown result type (might be due to invalid IL or missing references) //IL_0089: Unknown result type (might be due to invalid IL or missing references) //IL_008f: Expected O, but got Unknown //IL_00d5: Unknown result type (might be due to invalid IL or missing references) enabled = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "Enabled", true, (ConfigDescription)null); retryHP = ((BaseUnityPlugin)this).Config.Bind<int>("General", "Retry HP", 100, new ConfigDescription("The health you'll respawn with after retrying", (AcceptableValueBase)(object)new AcceptableValueRange<int>(1, 100), Array.Empty<object>())); logger.LogDebug((object)"Hooking `RunManager.ChangeLevel`"); MethodInfo methodInfo = AccessTools.Method(typeof(RunManager), "ChangeLevel", (Type[])null, (Type[])null); object obj = <>O.<0>__RunManager_ChangeLevelILHook; if (obj == null) { Manipulator val = RunManager_ChangeLevelILHook; <>O.<0>__RunManager_ChangeLevelILHook = val; obj = (object)val; } new ILHook((MethodBase)methodInfo, (Manipulator)obj); logger.LogDebug((object)"Hooking `RoundDirector.StartRoundLogic`"); new Hook((MethodBase)AccessTools.Method(typeof(RoundDirector), "StartRoundLogic", (Type[])null, (Type[])null), (Delegate)new Action<Action<RoundDirector, int>, RoundDirector, int>(RoundDirector_StartRoundLogicHook)); } } }
plugins/nickklmao-MenuLib/MenuLib.dll
Decompiled 2 months agousing System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using System.Text.RegularExpressions; using BepInEx; using BepInEx.Logging; using HarmonyLib; using MenuLib.Enums; using MenuLib.MonoBehaviors; using Microsoft.CodeAnalysis; using Mono.Cecil.Cil; using MonoMod.Cil; using MonoMod.RuntimeDetour; using TMPro; using UnityEngine; using UnityEngine.Events; using UnityEngine.InputSystem; using UnityEngine.UI; [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("MenuLib")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: AssemblyInformationalVersion("1.0.0+098b3c976f2cd64f9f2d7bb4b348f83ece79f575")] [assembly: AssemblyProduct("MenuLib")] [assembly: AssemblyTitle("MenuLib")] [assembly: AssemblyVersion("1.0.0.0")] [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 MenuLib { [BepInPlugin("nickklmao.menulib", "Menu Lib", "1.0.5")] internal sealed class Entry : BaseUnityPlugin { [CompilerGenerated] private static class <>O { public static Action<Action<MenuManager>, MenuManager> <0>__MenuManager_StartHook; public static Action<Action<MenuPageMain>, MenuPageMain> <1>__MenuPageMain_StartHook; public static Action<Action<MenuPageEsc>, MenuPageEsc> <2>__MenuPageEsc_StartHook; public static Manipulator <3>__SemiFunc_UIMouseHoverILHook; } private const string MOD_NAME = "Menu Lib"; internal static readonly ManualLogSource logger = Logger.CreateLogSource("Menu Lib"); private static void MenuManager_StartHook(Action<MenuManager> orig, MenuManager self) { orig(self); MenuAPI.Initialize(); } private static void MenuPageMain_StartHook(Action<MenuPageMain> orig, MenuPageMain self) { orig(self); MenuAPI.addToMainMenuEvent?.Invoke(self); } private static void MenuPageEsc_StartHook(Action<MenuPageEsc> orig, MenuPageEsc self) { orig(self); MenuAPI.addToEscapeMenuEvent?.Invoke(self); } private static void SemiFunc_UIMouseHoverILHook(ILContext il) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Expected O, but got Unknown //IL_004e: Unknown result type (might be due to invalid IL or missing references) //IL_0087: Unknown result type (might be due to invalid IL or missing references) //IL_0094: Unknown result type (might be due to invalid IL or missing references) //IL_00a0: Unknown result type (might be due to invalid IL or missing references) ILCursor val = new ILCursor(il); ILLabel val4 = default(ILLabel); val.GotoNext(new Func<Instruction, bool>[1] { (Instruction instruction) => ILPatternMatchingExt.MatchBrfalse(instruction, ref val4) && val4.Target.OpCode == OpCodes.Ldarg_1 }); val.Index += 2; val.RemoveRange(27); val.Emit(OpCodes.Ldloc_0); val.EmitDelegate<Func<MenuScrollBox, Vector2, bool>>((Func<MenuScrollBox, Vector2, bool>)delegate(MenuScrollBox menuScrollBox, Vector2 vector) { //IL_0010: Unknown result type (might be due to invalid IL or missing references) //IL_0016: Expected O, but got Unknown //IL_0017: 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_0030: Unknown result type (might be due to invalid IL or missing references) //IL_0039: Unknown result type (might be due to invalid IL or missing references) RectTransform val3 = (RectTransform)((Component)menuScrollBox).transform.Find("Mask"); float y = ((Transform)val3).position.y; float num = y + val3.sizeDelta.y; return vector.y > y && vector.y < num; }); ILLabel val2 = val.DefineLabel(); val.Emit(OpCodes.Brtrue_S, (object)val2); val.Emit(OpCodes.Ldc_I4_0); val.Emit(OpCodes.Ret); val.MarkLabel(val2); } private void Awake() { //IL_0040: 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) //IL_00cc: Unknown result type (might be due to invalid IL or missing references) //IL_0112: Unknown result type (might be due to invalid IL or missing references) //IL_0107: Unknown result type (might be due to invalid IL or missing references) //IL_010c: Unknown result type (might be due to invalid IL or missing references) //IL_0112: Expected O, but got Unknown logger.LogDebug((object)"Hooking `MenuManager.Start`"); new Hook((MethodBase)AccessTools.Method(typeof(MenuManager), "Start", (Type[])null, (Type[])null), (Delegate)new Action<Action<MenuManager>, MenuManager>(MenuManager_StartHook)); logger.LogDebug((object)"Hooking `MenuPageMain.Start`"); new Hook((MethodBase)AccessTools.Method(typeof(MenuPageMain), "Start", (Type[])null, (Type[])null), (Delegate)new Action<Action<MenuPageMain>, MenuPageMain>(MenuPageMain_StartHook)); logger.LogDebug((object)"Hooking `MenuPageEsc.Start`"); new Hook((MethodBase)AccessTools.Method(typeof(MenuPageEsc), "Start", (Type[])null, (Type[])null), (Delegate)new Action<Action<MenuPageEsc>, MenuPageEsc>(MenuPageEsc_StartHook)); logger.LogDebug((object)"Hooking `SemiFunc.UIMouseHover`"); MethodInfo methodInfo = AccessTools.Method(typeof(SemiFunc), "UIMouseHover", (Type[])null, (Type[])null); object obj = <>O.<3>__SemiFunc_UIMouseHoverILHook; if (obj == null) { Manipulator val = SemiFunc_UIMouseHoverILHook; <>O.<3>__SemiFunc_UIMouseHoverILHook = val; obj = (object)val; } new ILHook((MethodBase)methodInfo, (Manipulator)obj); } } public static class MenuAPI { internal static Action<MenuPageMain> addToMainMenuEvent; internal static Action<MenuPageEsc> addToEscapeMenuEvent; private static bool initialized; private static MenuButtonPopUp menuButtonPopup; internal static RectTransform pageDimmer { get; private set; } internal static RectTransform simplePageTemplate { get; private set; } internal static RectTransform buttonTemplate { get; private set; } internal static RectTransform popupPageTemplate { get; private set; } internal static RectTransform toggleTemplate { get; private set; } internal static RectTransform sliderTemplate { get; private set; } internal static RectTransform keybindTemplate { get; private set; } public static void AddElementToMainMenu(REPOElement repoElement, Vector2 newPosition) { //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) addToMainMenuEvent = (Action<MenuPageMain>)Delegate.Combine(addToMainMenuEvent, (Action<MenuPageMain>)delegate(MenuPageMain instance) { //IL_001d: Unknown result type (might be due to invalid IL or missing references) ((Transform)repoElement.Instantiate()).SetParent(((Component)instance).transform); repoElement.SetPosition(newPosition); repoElement.afterBeingParented?.Invoke(((Component)instance).GetComponent<MenuPage>()); }); } public static void AddElementToEscapeMenu(REPOElement repoElement, Vector2 newPosition) { //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) addToEscapeMenuEvent = (Action<MenuPageEsc>)Delegate.Combine(addToEscapeMenuEvent, (Action<MenuPageEsc>)delegate(MenuPageEsc instance) { //IL_001d: Unknown result type (might be due to invalid IL or missing references) ((Transform)repoElement.Instantiate()).SetParent(((Component)instance).transform); repoElement.SetPosition(newPosition); repoElement.afterBeingParented?.Invoke(((Component)instance).GetComponent<MenuPage>()); }); } public static void OpenPopup(string header, Color headerColor, string content, string buttonText, Action onClick) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) MenuManager.instance.PagePopUp(header, headerColor, content, buttonText); } public static void OpenPopup(string header, Color headerColor, string content, string leftButtonText, Action onLeftClicked, string rightButtonText, Action onRightClicked = null) { //IL_0025: Unknown result type (might be due to invalid IL or missing references) //IL_002f: Expected O, but got Unknown //IL_0034: Unknown result type (might be due to invalid IL or missing references) //IL_003e: Expected O, but got Unknown //IL_0054: Unknown result type (might be due to invalid IL or missing references) //IL_005e: Expected O, but got Unknown //IL_0089: Unknown result type (might be due to invalid IL or missing references) //IL_0074: Unknown result type (might be due to invalid IL or missing references) //IL_007e: Expected O, but got Unknown if (!Object.op_Implicit((Object)(object)menuButtonPopup)) { menuButtonPopup = ((Component)MenuManager.instance).gameObject.AddComponent<MenuButtonPopUp>(); } menuButtonPopup.option1Event = new UnityEvent(); menuButtonPopup.option2Event = new UnityEvent(); if (onLeftClicked != null) { menuButtonPopup.option1Event.AddListener(new UnityAction(onLeftClicked.Invoke)); } if (onRightClicked != null) { menuButtonPopup.option2Event.AddListener(new UnityAction(onRightClicked.Invoke)); } MenuManager.instance.PagePopUpTwoOptions(menuButtonPopup, header, headerColor, content, leftButtonText, rightButtonText); } internal static void Initialize() { //IL_0030: 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_0036: Unknown result type (might be due to invalid IL or missing references) //IL_0058: Expected I4, but got Unknown //IL_005e: Unknown result type (might be due to invalid IL or missing references) //IL_0068: Expected O, but got Unknown //IL_0077: Unknown result type (might be due to invalid IL or missing references) //IL_0081: Expected O, but got Unknown //IL_008a: Unknown result type (might be due to invalid IL or missing references) //IL_0094: Expected O, but got Unknown //IL_0097: Unknown result type (might be due to invalid IL or missing references) //IL_00a1: Expected O, but got Unknown //IL_00ae: Unknown result type (might be due to invalid IL or missing references) //IL_00b8: Expected O, but got Unknown //IL_00c3: Unknown result type (might be due to invalid IL or missing references) //IL_00cd: Expected O, but got Unknown //IL_00da: Unknown result type (might be due to invalid IL or missing references) //IL_00e4: Expected O, but got Unknown if (initialized) { return; } foreach (MenuPages menuPage in MenuManager.instance.menuPages) { Transform transform = menuPage.menuPage.transform; MenuPageIndex menuPageIndex = menuPage.menuPageIndex; switch ((int)menuPageIndex) { case 0: simplePageTemplate = (RectTransform)transform; buttonTemplate = (RectTransform)((Transform)simplePageTemplate).Find("Menu Button - Quit game"); break; case 2: pageDimmer = (RectTransform)transform.GetChild(0); break; case 4: popupPageTemplate = (RectTransform)transform; break; case 5: toggleTemplate = (RectTransform)transform.Find("Menu Scroll Box/Mask/Scroller/Bool Setting - Push to Talk"); sliderTemplate = (RectTransform)transform.Find("Menu Scroll Box/Mask/Scroller/Slider - microphone"); break; case 6: keybindTemplate = (RectTransform)transform.Find("Scroll Box/Mask/Scroller/Big Button move forward"); break; } } initialized = true; } } public struct Padding { public readonly float left; public readonly float top; public readonly float right; public readonly float bottom; public Padding(float left, float top, float right, float bottom) { this.left = left; this.top = top; this.right = right; this.bottom = bottom; } } public sealed class REPOButton : REPOElement { internal MenuButton menuButton; private TextMeshProUGUI buttonTextTMP; private Button button; public string text { get; private set; } public Action onClick { get; private set; } public REPOButton(string text, Action onClick) { this.text = text; this.onClick = onClick; } public REPOButton SetText(string newText) { //IL_0025: Unknown result type (might be due to invalid IL or missing references) if (Object.op_Implicit((Object)(object)buttonTextTMP)) { ((TMP_Text)buttonTextTMP).text = newText; transform.sizeDelta = ((TMP_Text)buttonTextTMP).GetPreferredValues(); } text = newText; return this; } public REPOButton SetOnClick(Action newOnClick) { //IL_0016: Unknown result type (might be due to invalid IL or missing references) //IL_0020: Expected O, but got Unknown //IL_0032: Unknown result type (might be due to invalid IL or missing references) //IL_003c: Expected O, but got Unknown if (Object.op_Implicit((Object)(object)button) && newOnClick != null) { button.onClick = new ButtonClickedEvent(); ((UnityEvent)button.onClick).AddListener(new UnityAction(newOnClick.Invoke)); } onClick = newOnClick; return this; } public override RectTransform GetReference() { return MenuAPI.buttonTemplate; } public override void SetDefaults() { menuButton = ((Component)transform).GetComponent<MenuButton>(); ref TextMeshProUGUI reference = ref buttonTextTMP; object? value = AccessTools.Field(typeof(MenuButton), "buttonText").GetValue(menuButton); reference = (TextMeshProUGUI)((value is TextMeshProUGUI) ? value : null); button = ((Component)transform).GetComponent<Button>(); ((Object)transform).name = "Menu Button - " + text; SetText(text); SetOnClick(onClick); Object.Destroy((Object)(object)((Component)transform).GetComponent<MenuButtonPopUp>()); afterBeingParented = delegate(MenuPage menuPage) { AccessTools.Field(typeof(MenuButton), "parentPage").SetValue(menuButton, menuPage); }; } } public abstract class REPOElement { public Action<MenuPage> afterBeingParented; internal RectTransform transform; public Vector2 position { get; private set; } public REPOElement SetPosition(Vector2 newLocalPosition) { //IL_001f: Unknown result type (might be due to invalid IL or missing references) //IL_0013: 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) if (Object.op_Implicit((Object)(object)transform)) { ((Transform)transform).localPosition = Vector2.op_Implicit(newLocalPosition); } position = newLocalPosition; return this; } public abstract RectTransform GetReference(); public virtual void SetDefaults() { } public RectTransform Instantiate() { transform = Object.Instantiate<RectTransform>(GetReference()); SetDefaults(); return transform; } } public sealed class REPOKeybind : REPOElement { private REPOMenuKeybind menuKeybind; private readonly Key defaultValue; public string labelText { get; private set; } public Action<Key> onValueChanged { get; private set; } public REPOKeybind(string labelText, Action<Key> onValueChanged, Key defaultValue) { //IL_0015: 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) this.labelText = labelText; this.onValueChanged = onValueChanged; this.defaultValue = defaultValue; } public REPOKeybind SetLabelText(string newLabelText) { if (Object.op_Implicit((Object)(object)menuKeybind)) { menuKeybind.SetHeader(newLabelText); } labelText = newLabelText; return this; } public REPOKeybind SetOnValueChanged(Action<Key> newOnValueChanged) { if (Object.op_Implicit((Object)(object)menuKeybind)) { menuKeybind.onValueChanged = newOnValueChanged; } onValueChanged = newOnValueChanged; return this; } public override RectTransform GetReference() { return MenuAPI.keybindTemplate; } public override void SetDefaults() { //IL_003d: 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_004f: 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_00af: Unknown result type (might be due to invalid IL or missing references) ((Object)transform).name = "Keybind - " + labelText; menuKeybind = ((Component)transform).gameObject.AddComponent<REPOMenuKeybind>(); RectTransform obj = transform; Vector2 sizeDelta = transform.sizeDelta; sizeDelta.y = 20f; obj.sizeDelta = sizeDelta; menuKeybind.Initialize(defaultValue); SetLabelText(labelText); SetOnValueChanged(onValueChanged); ((TMP_Text)menuKeybind.headerTMP).alignment = (TextAlignmentOptions)513; ((TMP_Text)menuKeybind.headerTMP).rectTransform.sizeDelta = new Vector2(200f, 40f); Object.Destroy((Object)(object)((Component)transform).GetComponent<MenuKeybind>()); afterBeingParented = delegate(MenuPage menuPage) { MenuButton[] componentsInChildren = ((Component)transform).GetComponentsInChildren<MenuButton>(); foreach (MenuButton obj2 in componentsInChildren) { AccessTools.Field(typeof(MenuButton), "parentPage").SetValue(obj2, menuPage); } }; } } public sealed class REPOPopupPage : REPOSimplePage { private RectTransform backgroundPanelTransform; private RectTransform maskTransform; private RectTransform scrollBarTransform; private RectTransform headerTransform; private RectTransform hoverAreaTransform; private RectTransform scrollBarOutlineTransform; private RectTransform scrollBarFillTransform; private RectTransform scrollBarBackgroundTransform; private Transform pageDimmerTransform; private Transform contentTransform; private MenuScrollBox menuScrollBox; public Vector2 localPosition { get; private set; } = new Vector2(195.64f, 190.6f); public bool backgroundDimming { get; private set; } public Vector2 panelSize { get; private set; } = new Vector2(250f, 342f); public Padding? maskPadding { get; private set; } public REPOPopupPage(string text, Action<REPOPopupPage> setup = null) : base(text, null) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: 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) //IL_0025: Unknown result type (might be due to invalid IL or missing references) setup?.Invoke(this); } public new REPOPopupPage SetPosition(Vector2 newLocalPosition) { //IL_0025: Unknown result type (might be due to invalid IL or missing references) //IL_0013: 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) if (Object.op_Implicit((Object)(object)backgroundPanelTransform)) { ((Transform)backgroundPanelTransform).localPosition = Vector2.op_Implicit(newLocalPosition); } UpdateOtherElements(); localPosition = newLocalPosition; return this; } public REPOPopupPage SetSize(Vector2 newPanelSize) { //IL_0020: Unknown result type (might be due to invalid IL or missing references) //IL_0013: Unknown result type (might be due to invalid IL or missing references) if (Object.op_Implicit((Object)(object)backgroundPanelTransform)) { backgroundPanelTransform.sizeDelta = newPanelSize; } UpdateOtherElements(); panelSize = newPanelSize; return this; } public REPOPopupPage SetBackgroundDimming(bool newBackgroundDimming) { if (Object.op_Implicit((Object)(object)transform)) { if (!newBackgroundDimming) { if (Object.op_Implicit((Object)(object)pageDimmerTransform)) { Object.Destroy((Object)(object)((Component)pageDimmerTransform).gameObject); } } else if (!Object.op_Implicit((Object)(object)pageDimmerTransform)) { pageDimmerTransform = (Transform)(object)Object.Instantiate<RectTransform>(MenuAPI.pageDimmer, (Transform)(object)transform); pageDimmerTransform.SetAsFirstSibling(); } } backgroundDimming = newBackgroundDimming; return this; } public REPOPopupPage SetMaskPadding(Padding? padding) { maskPadding = padding; UpdateOtherElements(); return this; } public REPOPopupPage AddElementToScrollView(REPOElement repoElement, Vector2 newPosition) { //IL_0015: 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) initializeButtons = (Action)Delegate.Combine(initializeButtons, (Action)delegate { //IL_0022: Unknown result type (might be due to invalid IL or missing references) ((Transform)repoElement.Instantiate()).SetParent(contentTransform); repoElement.SetPosition(newPosition); repoElement.afterBeingParented?.Invoke(menuPage); }); return this; } public void ClearButtons() { initializeButtons = null; } public override RectTransform GetReference() { return MenuAPI.popupPageTemplate; } public override void SetDefaults() { //IL_0022: Unknown result type (might be due to invalid IL or missing references) //IL_002c: Expected O, but got Unknown //IL_003d: Unknown result type (might be due to invalid IL or missing references) //IL_0047: Expected O, but got Unknown //IL_0064: Unknown result type (might be due to invalid IL or missing references) //IL_006e: Expected O, but got Unknown //IL_007a: Unknown result type (might be due to invalid IL or missing references) //IL_0084: Expected O, but got Unknown //IL_0090: Unknown result type (might be due to invalid IL or missing references) //IL_009a: Expected O, but got Unknown //IL_00ab: Unknown result type (might be due to invalid IL or missing references) //IL_00b5: Expected O, but got Unknown //IL_00c6: Unknown result type (might be due to invalid IL or missing references) //IL_00d0: Expected O, but got Unknown //IL_00e1: Unknown result type (might be due to invalid IL or missing references) //IL_00eb: Expected O, but got Unknown //IL_011d: Unknown result type (might be due to invalid IL or missing references) //IL_013c: Unknown result type (might be due to invalid IL or missing references) //IL_0177: Unknown result type (might be due to invalid IL or missing references) //IL_017d: Unknown result type (might be due to invalid IL or missing references) //IL_0185: Unknown result type (might be due to invalid IL or missing references) menuPage = ((Component)transform).GetComponent<MenuPage>(); backgroundPanelTransform = (RectTransform)((Transform)transform).Find("Panel"); headerTransform = (RectTransform)((Transform)transform).Find("Header"); Transform val = ((Transform)transform).Find("Menu Scroll Box"); hoverAreaTransform = (RectTransform)val.Find("ScrollBoxHoverArea"); maskTransform = (RectTransform)val.Find("Mask"); scrollBarTransform = (RectTransform)val.Find("Scroll Bar"); scrollBarOutlineTransform = (RectTransform)((Transform)scrollBarTransform).Find("Scroll Bar Bg (1)"); scrollBarFillTransform = (RectTransform)((Transform)scrollBarTransform).Find("Scroll Bar Bg (2)"); scrollBarBackgroundTransform = (RectTransform)((Transform)scrollBarTransform).Find("Scroll Bar Bg"); ((Object)transform).name = "Menu Page " + base.text; ((Transform)transform).SetParent(((Component)MenuHolder.instance).transform); SetPosition(localPosition); SetBackgroundDimming(backgroundDimming); menuPage.menuPageIndex = (MenuPageIndex)(-1); menuPage.disableIntroAnimation = false; SetText(base.text); RectTransform obj = backgroundPanelTransform; RectTransform obj2 = backgroundPanelTransform; Vector2 val2 = default(Vector2); ((Vector2)(ref val2))..ctor(0.5f, 0.5f); obj2.anchorMin = val2; obj.anchorMax = val2; SetSize(panelSize); contentTransform = ((Transform)maskTransform).Find("Scroller"); for (int num = contentTransform.childCount - 1; num >= 0; num--) { Transform child = contentTransform.GetChild(num); if (num >= 2) { Object.Destroy((Object)(object)((Component)child).gameObject); } } initializeButtons?.Invoke(); menuScrollBox = ((Component)val).GetComponent<MenuScrollBox>(); menuScrollBox.heightPadding = 50f; ((MonoBehaviour)menuScrollBox).StartCoroutine(ResetScrollBox(menuScrollBox)); ((Component)transform).gameObject.AddComponent<MenuPageSettings>(); IEnumerator ResetScrollBox(MenuScrollBox menuScrollBoxInstance) { yield return null; float num2 = scrollBarBackgroundTransform.sizeDelta.y - menuScrollBoxInstance.scrollHandle.sizeDelta.y * 0.5f; RectTransform scrollHandle = menuScrollBoxInstance.scrollHandle; Vector3 val3 = ((Transform)menuScrollBoxInstance.scrollHandle).localPosition; val3.y = num2; ((Transform)scrollHandle).localPosition = val3; AccessTools.Field(typeof(MenuScrollBox), "scrollHandleTargetPosition").SetValue(menuScrollBoxInstance, num2); AccessTools.Method(typeof(MenuScrollBox), "Start", (Type[])null, (Type[])null).Invoke(menuScrollBoxInstance, null); } } private void UpdateOtherElements() { //IL_0014: Unknown result type (might be due to invalid IL or missing references) //IL_0019: Unknown result type (might be due to invalid IL or missing references) //IL_001a: 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) //IL_0025: Unknown result type (might be due to invalid IL or missing references) //IL_003f: Unknown result type (might be due to invalid IL or missing references) //IL_0049: Unknown result type (might be due to invalid IL or missing references) //IL_0055: Unknown result type (might be due to invalid IL or missing references) //IL_006b: Unknown result type (might be due to invalid IL or missing references) //IL_0070: Unknown result type (might be due to invalid IL or missing references) //IL_009a: Unknown result type (might be due to invalid IL or missing references) //IL_009f: 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_00b0: Unknown result type (might be due to invalid IL or missing references) //IL_00b5: 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) //IL_00bb: Unknown result type (might be due to invalid IL or missing references) //IL_00c2: Unknown result type (might be due to invalid IL or missing references) //IL_00d5: Unknown result type (might be due to invalid IL or missing references) //IL_00d6: Unknown result type (might be due to invalid IL or missing references) //IL_00d7: Unknown result type (might be due to invalid IL or missing references) //IL_00de: Unknown result type (might be due to invalid IL or missing references) //IL_0132: Unknown result type (might be due to invalid IL or missing references) //IL_0137: Unknown result type (might be due to invalid IL or missing references) //IL_0141: Unknown result type (might be due to invalid IL or missing references) //IL_0157: 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) //IL_0179: Unknown result type (might be due to invalid IL or missing references) //IL_018f: Unknown result type (might be due to invalid IL or missing references) //IL_01af: Unknown result type (might be due to invalid IL or missing references) //IL_01b4: 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_01d4: Unknown result type (might be due to invalid IL or missing references) //IL_01f4: Unknown result type (might be due to invalid IL or missing references) //IL_01f9: Unknown result type (might be due to invalid IL or missing references) //IL_0203: 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_0239: Unknown result type (might be due to invalid IL or missing references) //IL_023e: Unknown result type (might be due to invalid IL or missing references) //IL_0248: Unknown result type (might be due to invalid IL or missing references) //IL_025e: Unknown result type (might be due to invalid IL or missing references) //IL_0271: Unknown result type (might be due to invalid IL or missing references) //IL_0276: Unknown result type (might be due to invalid IL or missing references) //IL_0280: Unknown result type (might be due to invalid IL or missing references) //IL_0296: Unknown result type (might be due to invalid IL or missing references) //IL_02b1: Unknown result type (might be due to invalid IL or missing references) //IL_02b6: 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_02c8: Unknown result type (might be due to invalid IL or missing references) //IL_02cc: Unknown result type (might be due to invalid IL or missing references) //IL_02d7: Unknown result type (might be due to invalid IL or missing references) //IL_02f0: Unknown result type (might be due to invalid IL or missing references) //IL_02f5: Unknown result type (might be due to invalid IL or missing references) //IL_02f9: Unknown result type (might be due to invalid IL or missing references) //IL_030a: Unknown result type (might be due to invalid IL or missing references) //IL_030c: Unknown result type (might be due to invalid IL or missing references) //IL_030d: Unknown result type (might be due to invalid IL or missing references) //IL_0314: Unknown result type (might be due to invalid IL or missing references) //IL_0327: Unknown result type (might be due to invalid IL or missing references) //IL_032c: Unknown result type (might be due to invalid IL or missing references) //IL_0330: Unknown result type (might be due to invalid IL or missing references) //IL_033b: 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_0366: Unknown result type (might be due to invalid IL or missing references) //IL_036b: Unknown result type (might be due to invalid IL or missing references) //IL_037e: Unknown result type (might be due to invalid IL or missing references) //IL_0383: Unknown result type (might be due to invalid IL or missing references) //IL_0399: Unknown result type (might be due to invalid IL or missing references) //IL_039e: Unknown result type (might be due to invalid IL or missing references) //IL_03a8: Unknown result type (might be due to invalid IL or missing references) //IL_03c0: Unknown result type (might be due to invalid IL or missing references) if (!Object.op_Implicit((Object)(object)backgroundPanelTransform)) { return; } Vector2 sizeDelta = backgroundPanelTransform.sizeDelta; Vector2 val = sizeDelta * 0.5f; if (Object.op_Implicit((Object)(object)headerTransform)) { ((Transform)headerTransform).position = ((Transform)backgroundPanelTransform).position + new Vector3(0f, val.y - headerTransform.sizeDelta.y * 0.35f, 0f); } if (Object.op_Implicit((Object)(object)maskTransform)) { RectTransform obj = hoverAreaTransform; Vector3 val3 = (((Transform)maskTransform).position = ((Transform)backgroundPanelTransform).position - new Vector3(val.x, val.y, 0f)); ((Transform)obj).position = val3; RectTransform obj2 = hoverAreaTransform; Vector2 sizeDelta2 = (maskTransform.sizeDelta = sizeDelta); obj2.sizeDelta = sizeDelta2; Padding padding = maskPadding ?? new Padding(0f, 80f, 0f, 0f); if (padding.left != 0f) { RectTransform obj3 = maskTransform; sizeDelta2 = maskTransform.sizeDelta; sizeDelta2.x = maskTransform.sizeDelta.x - padding.left; obj3.sizeDelta = sizeDelta2; RectTransform obj4 = maskTransform; val3 = ((Transform)maskTransform).position; val3.x = ((Transform)maskTransform).position.x + padding.left; ((Transform)obj4).position = val3; } if (padding.top != 0f) { RectTransform obj5 = maskTransform; sizeDelta2 = maskTransform.sizeDelta; sizeDelta2.y = maskTransform.sizeDelta.y - padding.top; obj5.sizeDelta = sizeDelta2; } if (padding.right != 0f) { RectTransform obj6 = maskTransform; sizeDelta2 = maskTransform.sizeDelta; sizeDelta2.x = maskTransform.sizeDelta.x - padding.right; obj6.sizeDelta = sizeDelta2; } if (padding.bottom != 0f) { RectTransform obj7 = maskTransform; sizeDelta2 = maskTransform.sizeDelta; sizeDelta2.y = maskTransform.sizeDelta.y - padding.bottom; obj7.sizeDelta = sizeDelta2; RectTransform obj8 = maskTransform; val3 = ((Transform)maskTransform).position; val3.y = ((Transform)maskTransform).position.y + padding.bottom; ((Transform)obj8).position = val3; } if (Object.op_Implicit((Object)(object)scrollBarTransform)) { Vector2 sizeDelta3 = maskTransform.sizeDelta; RectTransform obj9 = scrollBarTransform; sizeDelta2 = scrollBarTransform.sizeDelta; sizeDelta2.y = sizeDelta3.y; obj9.sizeDelta = sizeDelta2; RectTransform obj10 = scrollBarBackgroundTransform; RectTransform obj11 = scrollBarFillTransform; Vector2 sizeDelta4 = scrollBarFillTransform.sizeDelta; sizeDelta4.y = sizeDelta3.y - 4f; sizeDelta2 = (obj11.sizeDelta = sizeDelta4); obj10.sizeDelta = sizeDelta2; RectTransform obj12 = scrollBarOutlineTransform; sizeDelta2 = scrollBarOutlineTransform.sizeDelta; sizeDelta2.y = sizeDelta3.y; obj12.sizeDelta = sizeDelta2; float num = scrollBarTransform.sizeDelta.x * 0.5f; ((Transform)scrollBarTransform).position = ((Transform)maskTransform).position + new Vector3(sizeDelta3.x - num, 0f, 0f); RectTransform obj13 = hoverAreaTransform; sizeDelta2 = hoverAreaTransform.sizeDelta; sizeDelta2.x = hoverAreaTransform.sizeDelta.x + num + 4f; obj13.sizeDelta = sizeDelta2; } } } } public class REPOSimplePage : REPOElement { internal MenuPage menuPage; internal Action initializeButtons; public string text { get; private set; } public REPOSimplePage(string text, Action<REPOSimplePage> onSetup) { this.text = text; onSetup?.Invoke(this); } public REPOSimplePage SetText(string newText) { if (Object.op_Implicit((Object)(object)menuPage?.menuHeader)) { ((TMP_Text)menuPage.menuHeader).text = newText; } text = newText; return this; } public REPOSimplePage AddElementToPage(REPOElement repoElement, Vector2 newPosition) { //IL_0015: 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) initializeButtons = (Action)Delegate.Combine(initializeButtons, (Action)delegate { //IL_0022: Unknown result type (might be due to invalid IL or missing references) ((Transform)repoElement.Instantiate()).SetParent((Transform)(object)transform); repoElement.SetPosition(newPosition); repoElement.afterBeingParented?.Invoke(menuPage); }); return this; } public void OpenPage(bool addOnTop) { Instantiate(); if (addOnTop) { OpenPageOnTop(); } else { OpenPageNormal(); } } public void ClosePage(bool closePagesAddedOnTop) { //IL_004c: Unknown result type (might be due to invalid IL or missing references) if (closePagesAddedOnTop) { MenuManager.instance.PageCloseAllAddedOnTop(); } menuPage.PageStateSet((PageState)2); object? value = AccessTools.Field(typeof(MenuPage), "pageUnderThisPage").GetValue(menuPage); MenuPage val = (MenuPage)((value is MenuPage) ? value : null); if (Object.op_Implicit((Object)(object)val)) { MenuManager.instance.PageSetCurrent(val.menuPageIndex, val); } } public override RectTransform GetReference() { return MenuAPI.simplePageTemplate; } public override void SetDefaults() { //IL_0048: Unknown result type (might be due to invalid IL or missing references) menuPage = ((Component)transform).GetComponent<MenuPage>(); ((Object)transform).name = "Menu Page " + text; ((Transform)transform).SetParent(((Component)MenuHolder.instance).transform); menuPage.menuPageIndex = (MenuPageIndex)(-1); menuPage.disableIntroAnimation = false; SetText(text); for (int num = ((Transform)transform).childCount - 1; num >= 0; num--) { Transform child = ((Transform)transform).GetChild(num); if (((Object)child).name.Contains("Menu Button")) { Object.Destroy((Object)(object)((Component)child).gameObject); } } Object.Destroy((Object)(object)((Component)transform).GetComponent<MenuPageMain>()); initializeButtons?.Invoke(); } private void OpenPageNormal() { //IL_0064: Unknown result type (might be due to invalid IL or missing references) //IL_00e1: Unknown result type (might be due to invalid IL or missing references) object? value = AccessTools.Field(typeof(MenuManager), "currentMenuPage").GetValue(MenuManager.instance); MenuPage val = (MenuPage)((value is MenuPage) ? value : null); AccessTools.Method(typeof(MenuManager), "PageInactiveAdd", (Type[])null, (Type[])null).Invoke(MenuManager.instance, new object[1] { val }); if (val != null) { val.PageStateSet((PageState)3); } ((Component)menuPage).transform.localPosition = Vector3.zero; MenuManager.instance.PageAdd(menuPage); ((MonoBehaviour)menuPage).StartCoroutine(AccessTools.Method(typeof(MenuPage), "LateStart", (Type[])null, (Type[])null).Invoke(menuPage, null) as IEnumerator); AccessTools.Field(typeof(MenuPage), "addedPageOnTop").SetValue(menuPage, false); MenuManager.instance.PageSetCurrent(menuPage.menuPageIndex, menuPage); AccessTools.Field(typeof(MenuPage), "pageIsOnTopOfOtherPage").SetValue(menuPage, true); AccessTools.Field(typeof(MenuPage), "pageUnderThisPage").SetValue(menuPage, val); } private void OpenPageOnTop() { //IL_0060: Unknown result type (might be due to invalid IL or missing references) object? value = AccessTools.Field(typeof(MenuManager), "currentMenuPage").GetValue(MenuManager.instance); MenuPage val = (MenuPage)((value is MenuPage) ? value : null); if (AccessTools.Field(typeof(MenuManager), "addedPagesOnTop").GetValue(MenuManager.instance) is List<MenuPage> list && !list.Contains(val)) { ((Component)menuPage).transform.localPosition = Vector3.zero; MenuManager.instance.PageAdd(menuPage); ((MonoBehaviour)menuPage).StartCoroutine(AccessTools.Method(typeof(MenuPage), "LateStart", (Type[])null, (Type[])null).Invoke(menuPage, null) as IEnumerator); AccessTools.Field(typeof(MenuPage), "addedPageOnTop").SetValue(menuPage, false); AccessTools.Field(typeof(MenuPage), "parentPage").SetValue(menuPage, val); if (!list.Contains(val)) { list.Add(menuPage); } } } } public sealed class REPOSlider : REPOElement { internal REPOMenuSliderFloat menuSliderFloat; private readonly float defaultValue; public string text { get; private set; } public string description { get; private set; } public float min { get; private set; } public float max { get; private set; } public int precision { get; private set; } public REPOBarState barState { get; private set; } public bool scrollIsEnabled { get; private set; } public int scrollMaxVisibleCharacter { get; private set; } = 99999; public float scrollSpeedInSecondsPerCharacter { get; private set; } public float scrollInitialWaitTime { get; private set; } public float scrollStartWaitTime { get; private set; } public float scrollEndWaitTime { get; private set; } public string[] options { get; private set; } public Action<float> onValueChanged { get; private set; } public Action<int> onOptionChanged { get; private set; } public REPOSlider(string text, string description, Action<float> onValueChanged, float min, float max, int precision, float defaultValue) { this.text = text; this.description = description; this.onValueChanged = onValueChanged; this.min = min; this.max = max; this.precision = precision; this.defaultValue = defaultValue; } public REPOSlider(string text, string description, Action<int> onOptionChanged, string defaultOption, params string[] options) { this.text = text; this.description = description; this.onOptionChanged = onOptionChanged; int num = Array.IndexOf(options, defaultOption); if (num == -1) { num = 0; } defaultValue = num; this.options = options; max = (float)options.Length - 1f; } public REPOSlider SetText(string newText) { if (Object.op_Implicit((Object)(object)menuSliderFloat)) { menuSliderFloat.SetHeader(newText); } text = newText; return this; } public REPOSlider SetDescription(string newDescription) { if (Object.op_Implicit((Object)(object)menuSliderFloat)) { menuSliderFloat.SetDescriptionText(newDescription); } description = newDescription; return this; } public REPOSlider SetMin(float newMin) { if (Object.op_Implicit((Object)(object)menuSliderFloat)) { menuSliderFloat.min = newMin; } min = newMin; return this; } public REPOSlider SetMax(float newMax) { if (Object.op_Implicit((Object)(object)menuSliderFloat)) { menuSliderFloat.max = newMax; } max = newMax; return this; } public REPOSlider SetPrecision(int newPrecision) { if (Object.op_Implicit((Object)(object)menuSliderFloat)) { menuSliderFloat.decimalPlaces = newPrecision; menuSliderFloat.precision = (float)Math.Pow(10.0, -newPrecision); } precision = newPrecision; return this; } public REPOSlider SetBarState(REPOBarState newBarState) { menuSliderFloat?.UpdateBarState(newBarState); barState = newBarState; return this; } public REPOSlider SetScrollSettings(int newScrollMaxVisibleCharacter, float newScrollSpeedInSecondsPerCharacter, float newScrollInitialWaitTime, float newScrollStartWaitTime, float newScrollEndWaitTime) { REPOTextScroller rEPOTextScroller = menuSliderFloat?.textScroller; if (rEPOTextScroller != null) { ((TMP_Text)menuSliderFloat.descriptionTextTMP).maxVisibleCharacters = (rEPOTextScroller.maxCharacters = newScrollMaxVisibleCharacter); rEPOTextScroller.scrollingSpeedInSecondsPerCharacter = newScrollSpeedInSecondsPerCharacter; rEPOTextScroller.initialWaitTime = newScrollInitialWaitTime; rEPOTextScroller.startWaitTime = newScrollStartWaitTime; rEPOTextScroller.endWaitTime = newScrollEndWaitTime; } scrollMaxVisibleCharacter = newScrollMaxVisibleCharacter; scrollSpeedInSecondsPerCharacter = newScrollSpeedInSecondsPerCharacter; scrollInitialWaitTime = newScrollInitialWaitTime; scrollStartWaitTime = newScrollStartWaitTime; scrollEndWaitTime = newScrollEndWaitTime; return this; } [Obsolete("This will be removed in the future, use SetScroll instead.")] public REPOSlider ToggleScroll(bool state) { return SetScroll(state); } public REPOSlider SetScroll(bool state) { if (Object.op_Implicit((Object)(object)menuSliderFloat?.textScroller)) { REPOTextScroller textScroller = menuSliderFloat.textScroller; ((MonoBehaviour)textScroller).StopAllCoroutines(); if (state) { ((TMP_Text)menuSliderFloat.descriptionTextTMP).alignment = (TextAlignmentOptions)513; ((MonoBehaviour)textScroller).StartCoroutine(textScroller.Animate()); } else { ((TMP_Text)menuSliderFloat.descriptionTextTMP).alignment = (TextAlignmentOptions)514; } } scrollIsEnabled = state; return this; } public REPOSlider SetOnValueChanged(Action<float> newOnValueChanged) { if (Object.op_Implicit((Object)(object)menuSliderFloat)) { menuSliderFloat.onValueChanged = newOnValueChanged; } onValueChanged = newOnValueChanged; return this; } public REPOSlider SetOnOptionChanged(Action<int> newOnOptionChanged) { if (Object.op_Implicit((Object)(object)menuSliderFloat)) { menuSliderFloat.onOptionChanged = newOnOptionChanged; } onOptionChanged = newOnOptionChanged; return this; } public REPOSlider SetOptions(params string[] newOptions) { if (Object.op_Implicit((Object)(object)menuSliderFloat)) { menuSliderFloat.options = newOptions; } options = newOptions; return this; } public override RectTransform GetReference() { return MenuAPI.sliderTemplate; } public override void SetDefaults() { Object.Destroy((Object)(object)((Component)transform).GetComponent<MenuSliderMicrophone>()); Object.Destroy((Object)(object)((Component)transform).GetComponent<MenuSlider>()); menuSliderFloat = ((Component)transform).gameObject.AddComponent<REPOMenuSliderFloat>(); ((Object)transform).name = "Slider - " + text; SetMin(min); SetMax(max); SetPrecision(precision); SetOnValueChanged(onValueChanged); SetOnOptionChanged(onOptionChanged); SetOptions(options); menuSliderFloat.Initialize(defaultValue); SetText(text); SetDescription(description); SetScrollSettings(scrollMaxVisibleCharacter, scrollSpeedInSecondsPerCharacter, scrollInitialWaitTime, scrollStartWaitTime, scrollEndWaitTime); SetScroll(scrollIsEnabled); SetBarState(barState); afterBeingParented = delegate(MenuPage menuPage) { menuSliderFloat.menuPage = menuPage; MenuButton[] componentsInChildren = ((Component)transform).GetComponentsInChildren<MenuButton>(); foreach (MenuButton obj in componentsInChildren) { AccessTools.Field(typeof(MenuButton), "parentPage").SetValue(obj, menuPage); } }; } } public sealed class REPOToggle : REPOElement { private MenuTwoOptions menuTwoOptions; private TextMeshProUGUI toggleTextTMP; private TextMeshProUGUI onTextTMP; private TextMeshProUGUI offTextTMP; private readonly bool defaultValue; public string labelText { get; private set; } public string onText { get; private set; } public string offText { get; private set; } public Action<bool> onClick { get; private set; } public REPOToggle(string labelText, Action<bool> onClick, string onText, string offText, bool defaultValue) { this.labelText = labelText; this.onClick = onClick; this.onText = onText; this.offText = offText; this.defaultValue = defaultValue; } public REPOToggle SetLabelText(string newLabelText) { if (Object.op_Implicit((Object)(object)toggleTextTMP)) { ((TMP_Text)toggleTextTMP).text = newLabelText; } labelText = newLabelText; return this; } public REPOToggle SetOnText(string newOnText) { if (Object.op_Implicit((Object)(object)onTextTMP)) { ((TMP_Text)onTextTMP).text = newOnText; } onText = newOnText; return this; } public REPOToggle SetOffText(string newOffText) { if (Object.op_Implicit((Object)(object)offTextTMP)) { ((TMP_Text)offTextTMP).text = newOffText; } offText = newOffText; return this; } public REPOToggle SetOnClick(Action<bool> newOnClick) { //IL_0020: Unknown result type (might be due to invalid IL or missing references) //IL_002a: Expected O, but got Unknown //IL_003c: Unknown result type (might be due to invalid IL or missing references) //IL_0046: 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 //IL_0068: Unknown result type (might be due to invalid IL or missing references) //IL_0072: Expected O, but got Unknown if (Object.op_Implicit((Object)(object)menuTwoOptions)) { menuTwoOptions.onOption1 = (UnityEvent)new ButtonClickedEvent(); menuTwoOptions.onOption1.AddListener((UnityAction)delegate { newOnClick?.Invoke(obj: true); }); menuTwoOptions.onOption2 = (UnityEvent)new ButtonClickedEvent(); menuTwoOptions.onOption2.AddListener((UnityAction)delegate { newOnClick?.Invoke(obj: false); }); } onClick = newOnClick; return this; } public override RectTransform GetReference() { return MenuAPI.toggleTemplate; } public override void SetDefaults() { //IL_008d: 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) //IL_00a0: Unknown result type (might be due to invalid IL or missing references) //IL_00b5: Unknown result type (might be due to invalid IL or missing references) menuTwoOptions = ((Component)transform).GetComponent<MenuTwoOptions>(); toggleTextTMP = ((Component)transform).GetComponentInChildren<TextMeshProUGUI>(); onTextTMP = menuTwoOptions.option1TextMesh; offTextTMP = menuTwoOptions.option2TextMesh; ((Object)transform).name = "Toggle Button - " + labelText; menuTwoOptions.customEvents = true; menuTwoOptions.settingSet = false; RectTransform rectTransform = ((TMP_Text)toggleTextTMP).rectTransform; Vector2 sizeDelta = ((TMP_Text)toggleTextTMP).rectTransform.sizeDelta; sizeDelta.y = ((TMP_Text)toggleTextTMP).rectTransform.sizeDelta.y - 4f; rectTransform.sizeDelta = sizeDelta; SetLabelText(labelText); SetOnText(onText); SetOffText(offText); Object.Destroy((Object)(object)((Component)transform).GetComponent<AudioButtonPushToTalk>()); ((MonoBehaviour)menuTwoOptions).StartCoroutine(SetupLate()); afterBeingParented = delegate(MenuPage menuPage) { MenuButton[] componentsInChildren = ((Component)transform).GetComponentsInChildren<MenuButton>(); foreach (MenuButton obj in componentsInChildren) { AccessTools.Field(typeof(MenuButton), "parentPage").SetValue(obj, menuPage); } }; IEnumerator SetupLate() { yield return null; if (defaultValue) { menuTwoOptions.OnOption1(); } else { menuTwoOptions.OnOption2(); } SetOnClick(onClick); } } } } namespace MenuLib.MonoBehaviors { internal sealed class REPOMenuKeybind : MonoBehaviour { internal Action<Key> onValueChanged; internal TextMeshProUGUI headerTMP; private MenuPage menuPage; private MenuBigButton menuBigButton; private TextMeshProUGUI buttonTMP; private Button button; private Key currentKey; private RebindingOperation currentRebindingOperation; private float timeSinceRebind; private static Key ParseKeyName(string keyName) { //IL_0190: 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_0192: Unknown result type (might be due to invalid IL or missing references) //IL_0193: Unknown result type (might be due to invalid IL or missing references) //IL_0196: Unknown result type (might be due to invalid IL or missing references) //IL_0126: Unknown result type (might be due to invalid IL or missing references) //IL_012a: Unknown result type (might be due to invalid IL or missing references) //IL_0121: Unknown result type (might be due to invalid IL or missing references) //IL_012e: Unknown result type (might be due to invalid IL or missing references) //IL_016e: Unknown result type (might be due to invalid IL or missing references) //IL_013c: Unknown result type (might be due to invalid IL or missing references) //IL_0141: Unknown result type (might be due to invalid IL or missing references) //IL_0146: Unknown result type (might be due to invalid IL or missing references) //IL_014b: Unknown result type (might be due to invalid IL or missing references) //IL_0150: Unknown result type (might be due to invalid IL or missing references) //IL_0155: Unknown result type (might be due to invalid IL or missing references) //IL_015a: Unknown result type (might be due to invalid IL or missing references) //IL_015f: Unknown result type (might be due to invalid IL or missing references) //IL_0164: Unknown result type (might be due to invalid IL or missing references) //IL_0169: 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_01b3: Unknown result type (might be due to invalid IL or missing references) //IL_0173: Unknown result type (might be due to invalid IL or missing references) //IL_0178: Unknown result type (might be due to invalid IL or missing references) //IL_0187: Unknown result type (might be due to invalid IL or missing references) //IL_0182: Unknown result type (might be due to invalid IL or missing references) //IL_0137: Unknown result type (might be due to invalid IL or missing references) //IL_017d: 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) Debug.Log((object)keyName); Key result = (Key)(keyName switch { "-" => 13, "+" => 80, "," => 7, "." => 8, "=" => 14, "`" => 4, "0" => 50, "1" => 41, "2" => 42, "3" => 43, "4" => 44, "5" => 45, "6" => 46, "7" => 47, "8" => 48, "9" => 49, "/" => 9, "\\" => 10, "Right Alt" => 54, "Left Control" => 55, "Right Control" => 56, "Left System" => 57, "Right System" => 58, _ => 0, }); if ((int)result != 0) { return result; } if (!Enum.TryParse<Key>(keyName.Replace(" ", string.Empty), out result)) { return (Key)0; } return result; } internal void Initialize(Key startingValue) { //IL_0065: Unknown result type (might be due to invalid IL or missing references) //IL_006f: Expected O, but got Unknown //IL_0081: Unknown result type (might be due to invalid IL or missing references) //IL_008b: Expected O, but got Unknown //IL_008c: 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) menuPage = ((Component)this).GetComponentInParent<MenuPage>(); menuBigButton = ((Component)this).GetComponent<MenuBigButton>(); headerTMP = ((Component)this).GetComponentInChildren<TextMeshProUGUI>(); ref TextMeshProUGUI reference = ref buttonTMP; object? value = AccessTools.Field(typeof(MenuButton), "buttonText").GetValue(menuBigButton.menuButton); reference = (TextMeshProUGUI)((value is TextMeshProUGUI) ? value : null); button = ((Component)this).GetComponentInChildren<Button>(); button.onClick = new ButtonClickedEvent(); ((UnityEvent)button.onClick).AddListener(new UnityAction(OnClick)); currentKey = startingValue; UpdateKeybindLabel(); } internal void SetHeader(string label) { ((TMP_Text)headerTMP).text = label; } internal void UpdateKeybindLabel() { string text = ((object)(Key)(ref currentKey)).ToString(); text = text.Replace("Digit", string.Empty).Replace("Numpad", string.Empty).Replace("Slash", "/") .Replace("Backslash", "\\"); text = Regex.Replace(text, "([a-z])([A-Z])", "$1 $2"); ((TMP_Text)buttonTMP).text = (menuBigButton.buttonName = text); } private void Update() { if (currentRebindingOperation != null) { timeSinceRebind += Time.deltaTime; if (Mouse.current.leftButton.wasPressedThisFrame && !(timeSinceRebind <= 0.1f)) { currentRebindingOperation.Cancel(); currentRebindingOperation = null; } } } private void OnClick() { //IL_0025: Unknown result type (might be due to invalid IL or missing references) //IL_0039: Unknown result type (might be due to invalid IL or missing references) //IL_0043: Expected O, but got Unknown RebindingOperation obj = currentRebindingOperation; if (obj != null) { obj.Cancel(); } menuBigButton.state = (State)1; InputAction templateAction = new InputAction("Template Action", (InputActionType)1, "<Keyboard>/anyKey", (string)null, (string)null, (string)null); templateAction.Disable(); currentRebindingOperation = InputActionRebindingExtensions.PerformInteractiveRebinding(templateAction, -1).WithCancelingThrough("<Keyboard>/escape").WithControlsExcluding("Mouse") .OnMatchWaitForAnother(0.1f) .OnComplete((Action<RebindingOperation>)delegate(RebindingOperation operation) { //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_0011: Unknown result type (might be due to invalid IL or missing references) //IL_0015: Unknown result type (might be due to invalid IL or missing references) //IL_001a: 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) //IL_002e: Unknown result type (might be due to invalid IL or missing references) //IL_004a: 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) REPOMenuKeybind rEPOMenuKeybind = this; InputBinding val = templateAction.bindings[0]; rEPOMenuKeybind.currentKey = ParseKeyName(InputControlPath.ToHumanReadableString(((InputBinding)(ref val)).effectivePath, (HumanReadableStringOptions)2, (InputControl)null)); onValueChanged?.Invoke(currentKey); menuBigButton.state = (State)0; MenuManager.instance.MenuEffectClick((MenuClickEffectType)1, menuPage, 0.2f, -1f, false); UpdateKeybindLabel(); operation.Dispose(); templateAction.Dispose(); }) .OnCancel((Action<RebindingOperation>)delegate(RebindingOperation operation) { //IL_000c: Unknown result type (might be due to invalid IL or missing references) menuBigButton.state = (State)0; MenuManager.instance.MenuEffectClick((MenuClickEffectType)2, menuPage, 0.2f, -1f, false); UpdateKeybindLabel(); operation.Dispose(); templateAction.Disable(); }) .Start(); timeSinceRebind = 0f; } } internal sealed class REPOMenuSliderFloat : MonoBehaviour { private static readonly FieldInfo getMenuID = AccessTools.Field(typeof(MenuSelectableElement), "menuID"); internal MenuPage menuPage; internal REPOTextScroller textScroller; internal TextMeshProUGUI descriptionTextTMP; internal REPOBarState barState; internal Action<float> onValueChanged; internal Action<int> onOptionChanged; internal string[] options; internal string displayPrefix; internal string displayPostfix; internal float min; internal float max; internal float precision; internal int decimalPlaces; private TextMeshProUGUI headerTMP; private TextMeshProUGUI barTMP; private TextMeshProUGUI maskedTMP; private MenuSelectableElement menuSelectableElement; private RectTransform rectTransform; private RectTransform maskedRectTransform; private RectTransform barRectTransform; private RectTransform barSizeRectTransform; private RectTransform bigTextOutline; private RectTransform bigTextFill; private Transform barPointer; private Vector2 barSizeDelta = new Vector2(0f, 10f); private float currentValue; private float previousValue; private bool isHovering; private bool hasValueChanged => Mathf.Abs(currentValue - previousValue) >= Mathf.Epsilon; internal void Initialize(float defaultValue) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_0011: Expected O, but got Unknown //IL_0032: 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_0072: Expected O, but got Unknown //IL_011f: Unknown result type (might be due to invalid IL or missing references) //IL_0124: Unknown result type (might be due to invalid IL or missing references) //IL_0130: Unknown result type (might be due to invalid IL or missing references) //IL_0131: Unknown result type (might be due to invalid IL or missing references) //IL_0135: Unknown result type (might be due to invalid IL or missing references) //IL_0146: Unknown result type (might be due to invalid IL or missing references) //IL_015e: Unknown result type (might be due to invalid IL or missing references) //IL_0168: Expected O, but got Unknown //IL_0185: Unknown result type (might be due to invalid IL or missing references) //IL_018f: 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_020f: Unknown result type (might be due to invalid IL or missing references) //IL_0219: Expected O, but got Unknown //IL_0229: Unknown result type (might be due to invalid IL or missing references) //IL_0239: 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_0277: 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 rectTransform = (RectTransform)((Component)this).transform; headerTMP = ((Component)this).GetComponentInChildren<TextMeshProUGUI>(); ((TMP_Text)headerTMP).rectTransform.sizeDelta = new Vector2(200f, 40f); barTMP = ((Component)((Component)this).transform.Find("Bar Text")).GetComponent<TextMeshProUGUI>(); maskedRectTransform = (RectTransform)((Component)this).transform.Find("MaskedText"); maskedTMP = ((Component)maskedRectTransform).GetComponentInChildren<TextMeshProUGUI>(); descriptionTextTMP = ((Component)((Component)this).transform.Find("Big Setting Text")).GetComponent<TextMeshProUGUI>(); ((TMP_Text)descriptionTextTMP).alignment = (TextAlignmentOptions)513; TextMeshProUGUI obj = descriptionTextTMP; bool enableAutoSizing = (((TMP_Text)descriptionTextTMP).enableWordWrapping = false); ((TMP_Text)obj).enableAutoSizing = enableAutoSizing; ((TMP_Text)descriptionTextTMP).overflowMode = (TextOverflowModes)2; TextMeshProUGUI obj2 = descriptionTextTMP; ((TMP_Text)obj2).fontSize = ((TMP_Text)obj2).fontSize - 5f; textScroller = ((Component)descriptionTextTMP).gameObject.AddComponent<REPOTextScroller>(); textScroller.textMeshPro = (TMP_Text)(object)descriptionTextTMP; Vector2 sizeDelta = ((TMP_Text)descriptionTextTMP).rectTransform.sizeDelta; RectTransform obj3 = ((TMP_Text)descriptionTextTMP).rectTransform; Vector2 sizeDelta2 = sizeDelta; sizeDelta2.y = sizeDelta.y - 4f; obj3.sizeDelta = sizeDelta2; barSizeRectTransform = (RectTransform)((Component)this).transform.Find("BarSize"); Transform val = ((Component)this).transform.Find("SliderBG"); bigTextOutline = (RectTransform)val.Find("RawImage (3)"); bigTextFill = (RectTransform)val.Find("RawImage (2)"); Object.Destroy((Object)(object)((Component)val.Find("RawImage (4)")).gameObject); Object.Destroy((Object)(object)((Component)val.Find("RawImage (5)")).gameObject); menuSelectableElement = ((Component)this).GetComponent<MenuSelectableElement>(); barPointer = ((Component)this).transform.Find("Bar Pointer"); Transform val2 = ((Component)this).transform.Find("Bar"); barRectTransform = (RectTransform)((Component)val2.GetChild(0)).transform; barRectTransform.pivot = new Vector2(0f, 0.5f); ((Transform)barRectTransform).localPosition = Vector3.zero; Object.Destroy((Object)(object)((Component)val2.Find("Extra Bar")).gameObject); Button[] componentsInChildren = ((Component)this).GetComponentsInChildren<Button>(); ((UnityEvent)componentsInChildren[0].onClick).AddListener(new UnityAction(Decrement)); ((UnityEvent)componentsInChildren[1].onClick).AddListener(new UnityAction(Increment)); previousValue = (currentValue = defaultValue); string text = precision.ToString(CultureInfo.InvariantCulture); int num = text.IndexOf('.'); if (num == -1) { decimalPlaces = 0; } else { decimalPlaces = text.Length - num - 1; } UpdateBarPosition(); UpdateBarLabel(); } internal void SetHeader(string text) { ((TMP_Text)headerTMP).text = text; } internal void SetDescriptionText(string text) { //IL_004e: 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_0018: Unknown result type (might be due to invalid IL or missing references) //IL_0032: Unknown result type (might be due to invalid IL or missing references) if (!string.IsNullOrEmpty(text)) { bigTextOutline.sizeDelta = new Vector2(108f, 29.5f); bigTextFill.sizeDelta = new Vector2(109.8f, 32f); } else { bigTextOutline.sizeDelta = new Vector2(108f, 15.5f); bigTextFill.sizeDelta = new Vector2(109.8f, 15.5f); } ((TMP_Text)descriptionTextTMP).text = text; } internal void UpdateBarState(REPOBarState newBarState) { barState = newBarState; UpdateBarPosition(); } private void Update() { //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_00c9: 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_0080: Unknown result type (might be due to invalid IL or missing references) if (SemiFunc.UIMouseHover(menuPage, barSizeRectTransform, getMenuID.GetValue(menuSelectableElement) as string, 5f, 5f)) { if (!isHovering) { MenuManager.instance.MenuEffectHover(SemiFunc.MenuGetPitchFromYPos(rectTransform), -1f); isHovering = true; } SemiFunc.MenuSelectionBoxTargetSet(menuPage, barSizeRectTransform, new Vector2(-3f, 0f), new Vector2(20f, 10f)); OnHover(); } else { isHovering = false; if (((Component)barPointer).gameObject.activeSelf) { Vector3 localPosition = barPointer.localPosition; localPosition.x = -1000f; barPointer.localPosition = localPosition; ((Component)barPointer).gameObject.SetActive(false); } } if (hasValueChanged) { UpdateBarPosition(); UpdateBarLabel(); previousValue = currentValue; if (options != null) { onOptionChanged?.Invoke(Convert.ToInt32(currentValue)); } else { onValueChanged?.Invoke(currentValue); } } } private void OnHover() { //IL_0029: 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_0070: Unknown result type (might be due to invalid IL or missing references) //IL_0081: 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_00a3: Unknown result type (might be due to invalid IL or missing references) //IL_00b3: Unknown result type (might be due to invalid IL or missing references) //IL_00d6: Unknown result type (might be due to invalid IL or missing references) //IL_00db: Unknown result type (might be due to invalid IL or missing references) //IL_00e5: Unknown result type (might be due to invalid IL or missing references) if (!((Component)barPointer).gameObject.activeSelf) { ((Component)barPointer).gameObject.SetActive(true); } float x = SemiFunc.UIMouseGetLocalPositionWithinRectTransform(barSizeRectTransform).x; float num = max - min; float num2 = precision / num; float num3 = Mathf.Round(Mathf.Clamp01(x / barSizeRectTransform.sizeDelta.x) / num2) * num2; float x2 = Mathf.Clamp(((Transform)barSizeRectTransform).localPosition.x + num3 * barSizeRectTransform.sizeDelta.x, ((Transform)barSizeRectTransform).localPosition.x, ((Transform)barSizeRectTransform).localPosition.x + barSizeRectTransform.sizeDelta.x) - 2f; Transform obj = barPointer; Vector3 localPosition = barPointer.localPosition; localPosition.x = x2; obj.localPosition = localPosition; if (Input.GetMouseButton(0)) { currentValue = min + num3 * num; if (hasValueChanged) { MenuManager.instance.MenuEffectClick((MenuClickEffectType)4, menuPage, -1f, -1f, false); } } } private void UpdateBarPosition() { switch (barState) { case REPOBarState.UpdateWithValue: SetBarPosition((currentValue - min) / (max - min)); break; case REPOBarState.StaticAtMinimum: SetBarPosition(0f); break; case REPOBarState.StaticAtMaximum: SetBarPosition(1f); break; } } private void SetBarPosition(float normalizedValue) { //IL_001f: Unknown result type (might be due to invalid IL or missing references) //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_0025: Unknown result type (might be due to invalid IL or missing references) //IL_002b: Unknown result type (might be due to invalid IL or missing references) barSizeDelta.x = normalizedValue * 100f; RectTransform obj = maskedRectTransform; Vector2 sizeDelta = (barRectTransform.sizeDelta = barSizeDelta); obj.sizeDelta = sizeDelta; } private void Increment() { float num = ((options != null) ? 1f : precision); float num2 = currentValue + num; if (Math.Abs(max - currentValue) < float.Epsilon) { num2 = min; } else if (num2 > max) { num2 = max; } currentValue = num2; } private void Decrement() { float num = ((options != null) ? 1f : precision); float num2 = currentValue - num; if (Math.Abs(currentValue - min) < float.Epsilon) { num2 = max; } else if (num2 < min) { num2 = min; } currentValue = num2; } private void UpdateBarLabel() { if (options != null) { TextMeshProUGUI obj = barTMP; string text2 = (((TMP_Text)maskedTMP).text = (displayPrefix ?? (displayPrefix = string.Empty)) + options[Convert.ToInt32(currentValue)] + (displayPostfix ?? (displayPostfix = string.Empty))); ((TMP_Text)obj).text = text2; } else { string s = currentValue.ToString(CultureInfo.InvariantCulture); s = (int.TryParse(s, out var result) ? result.ToString() : currentValue.ToString($"F{decimalPlaces}", CultureInfo.InvariantCulture)); TextMeshProUGUI obj2 = barTMP; string text2 = (((TMP_Text)maskedTMP).text = (displayPrefix ?? (displayPrefix = string.Empty)) + s + (displayPostfix ?? (displayPostfix = string.Empty))); ((TMP_Text)obj2).text = text2; } } } public sealed class REPOTextScroller : MonoBehaviour { public TMP_Text textMeshPro; public int maxCharacters; public float initialWaitTime = 5f; public float startWaitTime = 3f; public float scrollingSpeedInSecondsPerCharacter = 0.5f; public float endWaitTime = 3f; private bool isInitial = true; public IEnumerator Animate() { while (true) { textMeshPro.firstVisibleCharacter = 0; textMeshPro.maxVisibleCharacters = maxCharacters; if (isInitial) { yield return (object)new WaitForSeconds(initialWaitTime); isInitial = false; } else { yield return (object)new WaitForSeconds(startWaitTime); } while (textMeshPro.maxVisibleCharacters < textMeshPro.text.Length) { TMP_Text obj = textMeshPro; int firstVisibleCharacter = obj.firstVisibleCharacter; obj.firstVisibleCharacter = firstVisibleCharacter + 1; TMP_Text obj2 = textMeshPro; firstVisibleCharacter = obj2.maxVisibleCharacters; obj2.maxVisibleCharacters = firstVisibleCharacter + 1; yield return (object)new WaitForSeconds(scrollingSpeedInSecondsPerCharacter); } yield return (object)new WaitForSeconds(endWaitTime); } } } } namespace MenuLib.Enums { public enum REPOBarState { UpdateWithValue, StaticAtMinimum, StaticAtMaximum } }
plugins/nickklmao-NoLimitChatbox/NoLimitChatbox.dll
Decompiled 2 months agousing System; using System.Diagnostics; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using BepInEx; using BepInEx.Logging; using HarmonyLib; using Microsoft.CodeAnalysis; using Mono.Cecil.Cil; using MonoMod.Cil; using MonoMod.RuntimeDetour; using TMPro; 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("NoLimitChatbox")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: AssemblyInformationalVersion("1.0.0")] [assembly: AssemblyProduct("NoLimitChatbox")] [assembly: AssemblyTitle("NoLimitChatbox")] [assembly: AssemblyVersion("1.0.0.0")] [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 NoLimitChatbox { [BepInPlugin("nickklmao.nolimitchatbox", "No Limit Chatbox", "1.0.1")] internal sealed class Entry : BaseUnityPlugin { [CompilerGenerated] private static class <>O { public static Action<Action<ChatManager>, ChatManager> <0>__ChatManager_AwakeHook; public static Manipulator <1>__ChatManager_StateActiveILHook; } private const string MOD_NAME = "No Limit Chatbox"; internal static readonly ManualLogSource logger = Logger.CreateLogSource("No Limit Chatbox"); private static void ChatManager_StateActiveILHook(ILContext il) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Expected O, but got Unknown ILCursor val = new ILCursor(il); val.GotoNext(new Func<Instruction, bool>[1] { (Instruction instruction) => ILPatternMatchingExt.MatchLdcI4(instruction, 50) }); val.Index -= 3; val.RemoveRange(29); } private static void ChatManager_AwakeHook(Action<ChatManager> orig, ChatManager self) { //IL_001e: Unknown result type (might be due to invalid IL or missing references) //IL_0023: 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) orig(self); ((TMP_Text)self.chatText).enableWordWrapping = true; Vector2 sizeDelta = ((TMP_Text)self.chatText).rectTransform.sizeDelta; sizeDelta.x = 534f; ((TMP_Text)self.chatText).rectTransform.sizeDelta = sizeDelta; } private void Awake() { //IL_0040: 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) //IL_007b: 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: Expected O, but got Unknown logger.LogDebug((object)"Hooking `ChatManager.StateActive`"); new Hook((MethodBase)AccessTools.Method(typeof(ChatManager), "Awake", (Type[])null, (Type[])null), (Delegate)new Action<Action<ChatManager>, ChatManager>(ChatManager_AwakeHook)); logger.LogDebug((object)"Hooking `ChatManager.StateActive`"); MethodInfo methodInfo = AccessTools.Method(typeof(ChatManager), "StateActive", (Type[])null, (Type[])null); object obj = <>O.<1>__ChatManager_StateActiveILHook; if (obj == null) { Manipulator val = ChatManager_StateActiveILHook; <>O.<1>__ChatManager_StateActiveILHook = val; obj = (object)val; } new ILHook((MethodBase)methodInfo, (Manipulator)obj); } } }
plugins/nickklmao-PlayerCount/PlayerCount.dll
Decompiled 2 months agousing System; using System.Diagnostics; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using BepInEx; using BepInEx.Logging; using HarmonyLib; using Microsoft.CodeAnalysis; using MonoMod.RuntimeDetour; using Photon.Pun; using Photon.Realtime; using TMPro; using UnityEngine; using UnityEngine.UI; [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("PlayerCount")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: AssemblyInformationalVersion("1.0.0")] [assembly: AssemblyProduct("PlayerCount")] [assembly: AssemblyTitle("PlayerCount")] [assembly: AssemblyVersion("1.0.0.0")] [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 PlayerCount { [BepInPlugin("nickklmao.playercount", "Player Count", "1.0.0")] internal sealed class Entry : BaseUnityPlugin { private const string MOD_NAME = "Player Count"; internal static readonly ManualLogSource logger = Logger.CreateLogSource("Player Count"); private static void MenuPageLobby_AwakeHook(Action<MenuPageLobby> orig, MenuPageLobby self) { //IL_0037: Unknown result type (might be due to invalid IL or missing references) //IL_005f: Unknown result type (might be due to invalid IL or missing references) orig(self); Transform obj = Object.Instantiate<Transform>(((Component)self).transform.Find("Menu Button - Leave/ButtonText"), ((Component)self).transform.Find("Panel")); obj.localPosition = new Vector3(-154f, 10f); TextMeshProUGUI component = ((Component)obj).GetComponent<TextMeshProUGUI>(); ((TMP_Text)component).alignment = (TextAlignmentOptions)516; ((TMP_Text)component).fontSize = 20f; ((Graphic)component).color = Color.white; ((Component)obj).gameObject.AddComponent<PlayerCountBehavior>().tmp = component; } private static void MenuPageEsc_AwakeHook(Action<MenuPageEsc> orig, MenuPageEsc self) { //IL_0037: Unknown result type (might be due to invalid IL or missing references) //IL_005f: Unknown result type (might be due to invalid IL or missing references) orig(self); Transform obj = Object.Instantiate<Transform>(((Component)self).transform.Find("Menu Button - Settings/ButtonText"), ((Component)self).transform.Find("Panel")); obj.localPosition = new Vector3(396f, -44.5f); TextMeshProUGUI component = ((Component)obj).GetComponent<TextMeshProUGUI>(); ((TMP_Text)component).alignment = (TextAlignmentOptions)513; ((TMP_Text)component).fontSize = 20f; ((Graphic)component).color = Color.white; ((Component)obj).gameObject.AddComponent<PlayerCountBehavior>().tmp = component; } private void Awake() { //IL_0040: 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) logger.LogDebug((object)"Hooking `MenuPageLobby.Awake`"); new Hook((MethodBase)AccessTools.Method(typeof(MenuPageLobby), "Awake", (Type[])null, (Type[])null), (Delegate)new Action<Action<MenuPageLobby>, MenuPageLobby>(MenuPageLobby_AwakeHook)); logger.LogDebug((object)"Hooking `MenuPageEsc.Start`"); new Hook((MethodBase)AccessTools.Method(typeof(MenuPageEsc), "Start", (Type[])null, (Type[])null), (Delegate)new Action<Action<MenuPageEsc>, MenuPageEsc>(MenuPageEsc_AwakeHook)); } } internal sealed class PlayerCountBehavior : MonoBehaviour { internal TextMeshProUGUI tmp; private void Update() { if (Object.op_Implicit((Object)(object)tmp)) { Room currentRoom = PhotonNetwork.CurrentRoom; ((TMP_Text)tmp).text = $"Players: {((currentRoom != null) ? currentRoom.PlayerCount : 0)}/{((currentRoom != null) ? currentRoom.MaxPlayers : 6)}"; } } } }
plugins/nickklmao-REPOConfig/REPOConfig.dll
Decompiled 2 months agousing System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using System.Text.RegularExpressions; using BepInEx; using BepInEx.Bootstrap; using BepInEx.Configuration; using BepInEx.Logging; using HarmonyLib; using MenuLib; using Microsoft.CodeAnalysis; using MonoMod.RuntimeDetour; using UnityEngine; using UnityEngine.InputSystem; [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("REPOConfig")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: AssemblyInformationalVersion("1.0.0+dd224d59738fc6afffca4118070ebec3f29df414")] [assembly: AssemblyProduct("REPOConfig")] [assembly: AssemblyTitle("REPOConfig")] [assembly: AssemblyVersion("1.0.0.0")] [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 REPOConfig { [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field)] [Obsolete("This attribute will be removes soon.")] public class REPOConfigEntryAttribute : Attribute { public REPOConfigEntryAttribute(string displayName) { } public REPOConfigEntryAttribute(string displayName, int min, int max, string prefix = "", string postfix = "") { } public REPOConfigEntryAttribute(string displayName, float min, float max, string prefix = "", string postfix = "") { } public REPOConfigEntryAttribute(string displayName, float min, float max, int precision = 2, string prefix = "", string postfix = "") { } public REPOConfigEntryAttribute(string displayName, string prefix = "", string postfix = "") { } public REPOConfigEntryAttribute(string displayName, params string[] customOptions) { } } internal sealed class ConfigMenu { private static readonly Dictionary<ConfigEntryBase, object> changedEntries = new Dictionary<ConfigEntryBase, object>(); private static REPOButton currentPageModButton; internal static void Initialize() { //IL_0024: 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_003d: Expected O, but got Unknown //IL_0061: Unknown result type (might be due to invalid IL or missing references) //IL_0070: Unknown result type (might be due to invalid IL or missing references) //IL_007a: Expected O, but got Unknown MenuAPI.AddElementToMainMenu((REPOElement)new REPOButton("Mods", (Action)delegate { ((REPOSimplePage)CreateConfigMenu()).OpenPage(false); }), new Vector2(48.3f, 55.5f)); MenuAPI.AddElementToEscapeMenu((REPOElement)new REPOButton("Mods", (Action)delegate { ((REPOSimplePage)CreateConfigMenu()).OpenPage(false); }), new Vector2(126f, 86f)); } private static REPOPopupPage CreateConfigMenu() { //IL_001d: Unknown result type (might be due to invalid IL or missing references) //IL_003c: 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_0076: Unknown result type (might be due to invalid IL or missing references) //IL_0080: Expected O, but got Unknown //IL_00cc: Unknown result type (might be due to invalid IL or missing references) changedEntries.Clear(); currentPageModButton = null; REPOPopupPage mainModPage = new REPOPopupPage("Mods", (Action<REPOPopupPage>)null).SetBackgroundDimming(true).SetMaskPadding((Padding?)new Padding(0f, 70f, 20f, 50f)); ((REPOSimplePage)mainModPage).AddElementToPage((REPOElement)new REPOButton("Back", (Action)delegate { //IL_0032: Unknown result type (might be due to invalid IL or missing references) Action action = delegate { ((REPOSimplePage)mainModPage).ClosePage(true); changedEntries.Clear(); currentPageModButton = null; }; if (changedEntries.Count > 0) { MenuAPI.OpenPopup("Unsaved Changes", Color.red, "You have unsaved changes, are you sure you want to exit?", "Yes", action, "No", (Action)null); } else { action(); } }), new Vector2(77f, 34f)); Dictionary<string, ConfigEntryBase[]> modConfigEntries = GetModConfigEntries(); string[] array = modConfigEntries.Keys.ToArray(); for (int i = 0; i < array.Length; i++) { string text = array[i]; ConfigEntryBase[] configEntryBases = modConfigEntries[text]; CreateModPage(text, configEntryBases, out var modButton); mainModPage.AddElementToScrollView((REPOElement)(object)modButton, new Vector2(0f, -80f + (float)i * -34f)); } return mainModPage; } private static Dictionary<string, ConfigEntryBase[]> GetModConfigEntries() { Dictionary<string, ConfigEntryBase[]> dictionary = new Dictionary<string, ConfigEntryBase[]>(); foreach (PluginInfo value in Chainloader.PluginInfos.Values) { List<ConfigEntryBase> list = new List<ConfigEntryBase>(); foreach (ConfigEntryBase item in ((IEnumerable<KeyValuePair<ConfigDefinition, ConfigEntryBase>>)value.Instance.Config).Select((KeyValuePair<ConfigDefinition, ConfigEntryBase> configEntry) => configEntry.Value)) { ConfigDescription description = item.Description; object[] array = ((description != null) ? description.Tags : null); if (array == null || (!array.Contains("HideREPOConfig") && !array.Contains("HideFromREPOConfig"))) { list.Add(item); } } if (list.Count > 0) { dictionary.TryAdd(FixNaming(value.Metadata.Name), list.ToArray()); } } return dictionary; } private static void CreateModPage(string modName, ConfigEntryBase[] configEntryBases, out REPOButton modButton) { //IL_003a: Unknown result type (might be due to invalid IL or missing references) //IL_0044: Expected O, but got Unknown //IL_006d: 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) //IL_0074: Expected O, but got Unknown //IL_0075: Expected O, but got Unknown REPOPopupPage modPage2 = new REPOPopupPage(modName, (Action<REPOPopupPage>)delegate(REPOPopupPage modPage) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0021: Unknown result type (might be due to invalid IL or missing references) //IL_0041: Unknown result type (might be due to invalid IL or missing references) modPage.SetPosition(new Vector2(500.52f, 190.6f)); modPage.SetSize(new Vector2(310f, 342f)); modPage.SetMaskPadding((Padding?)new Padding(0f, 70f, 0f, 50f)); }); string text = modName; if (text.Length > 19) { text = text.Substring(0, 16) + "..."; } REPOButton val = new REPOButton(text, (Action)null); REPOButton val2 = val; modButton = val; REPOButton modButtonTemp = val2; modButton.SetOnClick((Action)delegate { //IL_0040: Unknown result type (might be due to invalid IL or missing references) if (currentPageModButton != modButtonTemp) { Action action = delegate { //IL_0030: 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_0066: Expected O, but got Unknown //IL_009d: Unknown result type (might be due to invalid IL or missing references) //IL_00b9: Unknown result type (might be due to invalid IL or missing references) //IL_01dc: Unknown result type (might be due to invalid IL or missing references) //IL_01e7: Unknown result type (might be due to invalid IL or missing references) //IL_01f1: Expected O, but got Unknown //IL_0228: Unknown result type (might be due to invalid IL or missing references) //IL_022f: Expected O, but got Unknown //IL_0345: Unknown result type (might be due to invalid IL or missing references) //IL_034c: Expected O, but got Unknown //IL_02f0: Unknown result type (might be due to invalid IL or missing references) //IL_05d9: Unknown result type (might be due to invalid IL or missing references) //IL_05de: Unknown result type (might be due to invalid IL or missing references) //IL_05e5: Expected O, but got Unknown //IL_054a: Unknown result type (might be due to invalid IL or missing references) //IL_0551: Expected O, but got Unknown //IL_0596: Unknown result type (might be due to invalid IL or missing references) //IL_049b: Unknown result type (might be due to invalid IL or missing references) //IL_06d2: Unknown result type (might be due to invalid IL or missing references) //IL_06d9: Expected O, but got Unknown //IL_0631: Unknown result type (might be due to invalid IL or missing references) //IL_071e: Unknown result type (might be due to invalid IL or missing references) MenuManager.instance.PageCloseAllAddedOnTop(); modPage2.ClearButtons(); changedEntries.Clear(); currentPageModButton = modButtonTemp; REPOButton val3 = new REPOButton("Save Changes", (Action)null).SetOnClick((Action)delegate { foreach (KeyValuePair<ConfigEntryBase, object> changedEntry in changedEntries) { changedEntry.Key.BoxedValue = changedEntry.Value; } changedEntries.Clear(); }); REPOButton val4 = new REPOButton("Reset", (Action)null); val4.SetOnClick((Action)delegate { //IL_0010: Unknown result type (might be due to invalid IL or missing references) MenuAPI.OpenPopup("Reset " + modName, Color.red, "Reset all of " + modName + (modName.ToLower().EndsWith('s') ? "'" : "'s") + " settings?", "Yes", (Action)delegate { ConfigEntryBase[] array = configEntryBases; foreach (ConfigEntryBase obj2 in array) { obj2.BoxedValue = obj2.DefaultValue; } changedEntries.Clear(); currentPageModButton = null; modButtonTemp.onClick(); }, "No", (Action)null); }); ((REPOSimplePage)modPage2).AddElementToPage((REPOElement)(object)val3, new Vector2(365f, 34f)); ((REPOSimplePage)modPage2).AddElementToPage((REPOElement)(object)val4, new Vector2(560f, 34f)); float num = -80f; for (int i = 0; i < configEntryBases.Length; i++) { ConfigEntryBase configEntryBase = configEntryBases[i]; string text2 = FixNaming(configEntryBase.Definition.Key); string text3 = configEntryBase.Description.Description.Replace('\n', ' '); ConfigEntryBase val5 = configEntryBase; ConfigEntry<bool> val6 = val5 as ConfigEntry<bool>; if (val6 == null) { ConfigEntry<int> val7 = val5 as ConfigEntry<int>; if (val7 == null) { ConfigEntry<float> val8 = val5 as ConfigEntry<float>; if (val8 == null) { ConfigEntry<string> val9 = val5 as ConfigEntry<string>; if (val9 == null) { ConfigEntry<Key> val10 = val5 as ConfigEntry<Key>; if (val10 == null) { if (val5 != null && configEntryBase.SettingType.IsSubclassOf(typeof(Enum))) { Type enumType = configEntryBase.SettingType; string[] values = Enum.GetNames(enumType); REPOSlider val11 = new REPOSlider(text2, text3, (Action<int>)delegate(int @int) { changedEntries[configEntryBase] = Enum.Parse(enumType, values[@int]); }, configEntryBase.BoxedValue.ToString(), values); if (text3.Length > 43) { val11.SetScrollSettings(43, Entry.descriptionScrollSpeed.Value, 5f, 3f, 5f); val11.SetScroll(true); } modPage2.AddElementToScrollView((REPOElement)(object)val11, new Vector2(15f, num)); num -= (string.IsNullOrEmpty(val11.description) ? 34f : 54f); } } else { REPOKeybind val12 = new REPOKeybind(text2, (Action<Key>)delegate(Key key) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) changedEntries[(ConfigEntryBase)(object)val10] = key; }, val10.Value); ConfigEntryBase? obj = configEntryBases.ElementAtOrDefault(i - 1); num = ((!(((obj != null) ? obj.SettingType : null) == typeof(Key))) ? (num - 5f) : (num - 11f)); modPage2.AddElementToScrollView((REPOElement)(object)val12, new Vector2(15f, num)); num -= 36f; } } else { AcceptableValueBase acceptableValues = ((ConfigEntryBase)val9).Description.AcceptableValues; AcceptableValueList<string> valueList = acceptableValues as AcceptableValueList<string>; if (valueList != null && valueList.AcceptableValues.Length != 0) { REPOSlider val13 = new REPOSlider(text2, text3, (Action<int>)delegate(int @int) { changedEntries[(ConfigEntryBase)(object)val9] = valueList.AcceptableValues[@int]; }, val9.Value, valueList.AcceptableValues); if (text3.Length > 43) { val13.SetScrollSettings(43, Entry.descriptionScrollSpeed.Value, 5f, 3f, 5f); val13.SetScroll(true); } modPage2.AddElementToScrollView((REPOElement)(object)val13, new Vector2(15f, num)); num -= (string.IsNullOrEmpty(val13.description) ? 34f : 54f); } } } else { REPOSlider val14 = new REPOSlider(text2, text3, (Action<float>)delegate(float f) { changedEntries[(ConfigEntryBase)(object)val8] = f; }, 0f, 0f, 0, val8.Value); if (text3.Length > 43) { val14.SetScrollSettings(43, Entry.descriptionScrollSpeed.Value, 5f, 3f, 5f); val14.SetScroll(true); } float num2 = (float)((ConfigEntryBase)val8).DefaultValue; AcceptableValueBase acceptableValues = ((ConfigEntryBase)val8).Description.AcceptableValues; if (!(acceptableValues is AcceptableValueRange<float> val15)) { if (acceptableValues is AcceptableValueRange<int> val16) { val14.SetMin((float)val16.MinValue); val14.SetMax((float)val16.MaxValue); } else { float num3 = ((num2 == 0f) ? 10f : ((!(num2 < 1f)) ? (num2 * 2f) : 2f)); float num4 = num3; val14.SetMin(0f - num4); val14.SetMax(num4); } } else { val14.SetMin(val15.MinValue); val14.SetMax(val15.MaxValue); } string text4 = num2.ToString(CultureInfo.InvariantCulture); int num5 = text4.IndexOf('.'); if (num5 == -1) { val14.SetPrecision(0); } else { val14.SetPrecision(text4.Length - num5 - 1); } modPage2.AddElementToScrollView((REPOElement)(object)val14, new Vector2(15f, num)); num -= (string.IsNullOrEmpty(val14.description) ? 34f : 54f); } } else { REPOSlider val17 = new REPOSlider(text2, text3, (Action<float>)delegate(float f) { changedEntries[(ConfigEntryBase)(object)val7] = Convert.ToInt32(f); }, 0f, 1f, 0, (float)val7.Value); if (text3.Length > 43) { val17.SetScrollSettings(43, Entry.descriptionScrollSpeed.Value, 5f, 3f, 5f); val17.SetScroll(true); } if (((ConfigEntryBase)val7).Description.AcceptableValues is AcceptableValueRange<int> val18) { val17.SetMin((float)val18.MinValue); val17.SetMax((float)val18.MaxValue); } else { int num6 = (int)((ConfigEntryBase)val7).DefaultValue; int num7 = ((num6 != 0) ? (num6 * 2) : 10); int num8 = num7; val17.SetMin((float)(-num8)); val17.SetMax((float)num8); } modPage2.AddElementToScrollView((REPOElement)(object)val17, new Vector2(15f, num)); num -= (string.IsNullOrEmpty(val17.description) ? 34f : 54f); } } else { modPage2.AddElementToScrollView((REPOElement)new REPOToggle(text2, (Action<bool>)delegate(bool b) { changedEntries[(ConfigEntryBase)(object)val6] = b; }, "ON", "OFF", val6.Value), new Vector2(120f, num)); num -= 30f; } } ((REPOSimplePage)modPage2).OpenPage(true); }; if (changedEntries.Count > 0) { MenuAPI.OpenPopup("Unsaved Changes", Color.red, "You have unsaved changes, are you sure you want to exit?", "Yes", action, "No", (Action)null); } else { action(); } } }); } private static string FixNaming(string input) { input = Regex.Replace(input, "([a-z])([A-Z])", "$1 $2"); input = Regex.Replace(input, "([A-Z])([A-Z][a-z])", "$1 $2"); input = Regex.Replace(input, "\\s+", " "); input = Regex.Replace(input, "([A-Z]\\.)\\s([A-Z]\\.)", "$1$2"); return input.Trim(); } } [BepInPlugin("nickklmao.repoconfig", "REPO Config", "1.1.6")] [BepInDependency(/*Could not decode attribute arguments.*/)] internal sealed class Entry : BaseUnityPlugin { private const string MOD_NAME = "REPO Config"; internal static readonly ManualLogSource logger = Logger.CreateLogSource("REPO Config"); internal static ConfigEntry<float> descriptionScrollSpeed; private static ConfigEntry<bool> showInGame; private static void MenuPageMain_StartHook(Action<MenuPageMain> orig, MenuPageMain self) { //IL_0082: Unknown result type (might be due to invalid IL or missing references) //IL_0087: 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) IOrderedEnumerable<Transform> orderedEnumerable = from Transform transform in (IEnumerable)((Component)self).transform where ((Object)transform).name.Contains("Menu Button") orderby transform.localPosition.y descending select transform; float num = 224f; foreach (Transform item in orderedEnumerable) { if (((Object)item).name.Contains("Quit")) { num -= 34f; } Vector3 localPosition = item.localPosition; localPosition.y = num; item.localPosition = localPosition; num -= 34f; } orig(self); } private void Awake() { //IL_002e: Unknown result type (might be due to invalid IL or missing references) //IL_0038: 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_00be: Unknown result type (might be due to invalid IL or missing references) descriptionScrollSpeed = ((BaseUnityPlugin)this).Config.Bind<float>("General", "Description Scroll Speed", 0.15f, new ConfigDescription("How fast descriptions scroll. (Seconds per character)", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.1f, 2f), Array.Empty<object>())); showInGame = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "Show In Game", true, new ConfigDescription(string.Empty, (AcceptableValueBase)null, new object[1] { "HideFromREPOConfig" })); if (showInGame.Value) { logger.LogDebug((object)"Hooking `MenuPageMain.Start`"); new Hook((MethodBase)AccessTools.Method(typeof(MenuPageMain), "Start", (Type[])null, (Type[])null), (Delegate)new Action<Action<MenuPageMain>, MenuPageMain>(MenuPageMain_StartHook)); ConfigMenu.Initialize(); } } } }
plugins/Oksamies-UltrawideOrLongFix/UltrawideOrLongFix.dll
Decompiled 2 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 BepInEx.Logging; using HarmonyLib; 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: IgnoresAccessChecksTo("Assembly-CSharp")] [assembly: AssemblyCompany("UltrawideOrLongFix")] [assembly: AssemblyConfiguration("Debug")] [assembly: AssemblyFileVersion("0.1.0.0")] [assembly: AssemblyInformationalVersion("0.1.0")] [assembly: AssemblyProduct("UltrawideOrLongFix")] [assembly: AssemblyTitle("UltrawideOrLongFix")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("0.1.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 UltrawideOrLongFix { [BepInPlugin("Oksamies.UltrawideOrLongFix", "UltrawideOrLongFix", "0.1.4")] public class Plugin : BaseUnityPlugin { [HarmonyPatch(typeof(GraphicsManager), "Update")] public class GraphicsManagerUpdatePatch { public static void Prefix() { //IL_010c: 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_00ce: 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) if (!(GraphicsManager.instance.fullscreenCheckTimer <= 0f)) { return; } currentAspectRatio = (float)Screen.width / (float)Screen.height; if (!configAspectRatioFix.Value) { return; } GameObject val = GameObject.Find("Render Texture Overlay"); GameObject val2 = GameObject.Find("Render Texture Main"); if (Object.op_Implicit((Object)(object)val) && Object.op_Implicit((Object)(object)val2)) { RectTransform component = val.gameObject.GetComponent<RectTransform>(); RectTransform component2 = val2.gameObject.GetComponent<RectTransform>(); if (Object.op_Implicit((Object)(object)component) && Object.op_Implicit((Object)(object)component2)) { if (currentAspectRatio > defaultAspectRatio) { component.sizeDelta = new Vector2(428f * currentAspectRatio, 428f); component2.sizeDelta = new Vector2(428f * currentAspectRatio, 428f); } else { component.sizeDelta = new Vector2(750f, 750f / currentAspectRatio); component2.sizeDelta = new Vector2(750f, 750f / currentAspectRatio); } previousAspectRatio = currentAspectRatio; if (!configFieldOfViewFix.Value) { } } } previousAspectRatio = currentAspectRatio; } } [HarmonyPatch(typeof(CameraZoom), "Update")] public class CameraZoomAwakePatch { public static void Prefix(CameraZoom __instance) { if (SemiFunc.MenuLevel()) { sceneFoV = 33f; } else { sceneFoV = 70f; menuFoVSet = false; } if ((!configFieldOfViewFix.Value || fovSetOnce) && (!configFieldOfViewFix.Value || currentAspectRatio == defaultAspectRatio) && (!SemiFunc.MenuLevel() || menuFoVSet)) { return; } if (configAutoFieldOfView.Value) { if (currentAspectRatio != defaultAspectRatio && (previousAspectRatio != currentAspectRatio || !fovSetOnce)) { if (SemiFunc.MenuLevel()) { CameraNoPlayerTarget.instance.cam.fieldOfView = 33f / (defaultAspectRatio / currentAspectRatio); } else { __instance.playerZoomDefault = 70f / (defaultAspectRatio / currentAspectRatio); __instance.zoomPrev = 70f / (defaultAspectRatio / currentAspectRatio); __instance.zoomCurrent = __instance.zoomPrev; } } } else if (SemiFunc.MenuLevel()) { CameraNoPlayerTarget.instance.cam.fieldOfView = 33f / (33f / configFieldOfView.Value); menuFoVSet = true; } else { __instance.playerZoomDefault = configFieldOfView.Value; __instance.zoomPrev = configFieldOfView.Value; __instance.zoomCurrent = __instance.zoomPrev; } previousAspectRatio = currentAspectRatio; } } public const string modGUID = "Oksamies.UltrawideOrLongFix"; public const string modName = "UltrawideOrLongFix"; public const string modVersion = "0.1.4"; public static ConfigEntry<bool> configAspectRatioFix; public static ConfigEntry<bool> configFieldOfViewFix; public static ConfigEntry<float> configFieldOfView; public static ConfigEntry<bool> configAutoFieldOfView; public static float previousAspectRatio; public static float currentAspectRatio; public static readonly float defaultAspectRatio = 1.7777778f; public static bool fovSetOnce = false; public static float sceneFoV = 33f; public static bool menuFoVSet = false; private readonly Harmony harmony = new Harmony("Oksamies.UltrawideOrLongFix"); public static ManualLogSource mls; private void Awake() { mls = Logger.CreateLogSource("Oksamies.UltrawideOrLongFix"); configAspectRatioFix = ((BaseUnityPlugin)this).Config.Bind<bool>("Gameplay", "Aspect-ratio fix on/off", true, "In case aspect-ratio fix is broken or you want to disable aspect-ratio fixing, turn this to false"); configFieldOfViewFix = ((BaseUnityPlugin)this).Config.Bind<bool>("Gameplay", "Field of View Fix on/off", true, "In case field of view fix is broken or you want to disable FOV fixing, turn this to false"); configFieldOfView = ((BaseUnityPlugin)this).Config.Bind<float>("Gameplay", "Field of View", 70f, "Set this and turn Auto Field of View off to control it manually."); configAutoFieldOfView = ((BaseUnityPlugin)this).Config.Bind<bool>("Gameplay", "Auto Field of View", true, "Automatically try to figure out a proper field of view for the window"); mls.LogInfo((object)"Oksamies.UltrawideOrLongFix is now awake!"); harmony.PatchAll(); } } public static class PluginInfo { public const string PLUGIN_GUID = "UltrawideOrLongFix"; public const string PLUGIN_NAME = "UltrawideOrLongFix"; public const string PLUGIN_VERSION = "0.1.0"; } } namespace System.Runtime.CompilerServices { [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)] internal sealed class IgnoresAccessChecksToAttribute : Attribute { public IgnoresAccessChecksToAttribute(string assemblyName) { } } }
plugins/Pisimist29-Beer_Valuable/ValuableBeerPotion.dll
Decompiled 2 months agousing System; using System.Collections.Generic; using System.Diagnostics; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using BepInEx; using BepInEx.Logging; using HarmonyLib; using UnityEngine; using UnityEngine.Events; using ValuableBeerPotionMod; [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: AssemblyVersion("0.0.0.0")] public class ValuableBeerPotion : MonoBehaviour { public enum State { Idle, Active } private PhysGrabObject physGrabObject; private List<string> transitiveVerbs = new List<string>(); private List<string> intransitiveVerbs = new List<string>(); private List<string> adjectives = new List<string>(); private List<string> intensifiers = new List<string>(); private List<string> nouns = new List<string>(); private List<string> adverbs = new List<string>(); private float coolDownUntilNextSentence = 3f; private ParticleSystem particles; private bool particlesPlaying; public Renderer LovePotionRenderer; private State currentState; private string playerName = "[playerName]"; private void Start() { particles = ((Component)this).GetComponentInChildren<ParticleSystem>(); physGrabObject = ((Component)this).GetComponent<PhysGrabObject>(); InitializeWordLists(); } private void Update() { //IL_001c: Unknown result type (might be due to invalid IL or missing references) //IL_006a: Unknown result type (might be due to invalid IL or missing references) LovePotionRenderer.material.mainTextureOffset = new Vector2(0f, Time.time * 0.1f); LovePotionRenderer.material.mainTextureScale = new Vector2(2f + Mathf.Sin(Time.time * 1f) * 0.25f, 2f + Mathf.Sin(Time.time * 1f) * 0.25f); if (physGrabObject.grabbed) { if (!particlesPlaying) { particles.Play(); particlesPlaying = true; } } else if (particlesPlaying) { particles.Stop(); particlesPlaying = false; } if (SemiFunc.IsMultiplayer()) { switch (currentState) { case State.Idle: StateIdle(); break; case State.Active: StateActive(); break; } } } private void StateIdle() { //IL_00b1: Unknown result type (might be due to invalid IL or missing references) //IL_00b9: Unknown result type (might be due to invalid IL or missing references) //IL_00bf: Unknown result type (might be due to invalid IL or missing references) //IL_01cd: Unknown result type (might be due to invalid IL or missing references) //IL_0108: Unknown result type (might be due to invalid IL or missing references) //IL_0114: Unknown result type (might be due to invalid IL or missing references) if (coolDownUntilNextSentence > 0f && physGrabObject.grabbed) { coolDownUntilNextSentence -= Time.deltaTime; } else { if (!Object.op_Implicit((Object)(object)PhysGrabber.instance) || !PhysGrabber.instance.grabbed || !Object.op_Implicit((Object)(object)PhysGrabber.instance.grabbedPhysGrabObject()) || !((Object)(object)PhysGrabber.instance.grabbedPhysGrabObject() == (Object)(object)physGrabObject)) { return; } bool flag; if (!SemiFunc.IsMultiplayer()) { playerName = "this beer"; flag = true; } else { List<PlayerAvatar> list = SemiFunc.PlayerGetAllPlayerAvatarWithinRange(10f, ((Component)PhysGrabber.instance).transform.position, false, default(LayerMask)); PlayerAvatar val = null; float num = float.MaxValue; foreach (PlayerAvatar item in list) { if (!((Object)(object)item == (Object)(object)PlayerAvatar.instance)) { float num2 = Vector3.Distance(((Component)PhysGrabber.instance).transform.position, ((Component)item).transform.position); if (num2 < num) { num = num2; val = item; } } } flag = true; if ((Object)(object)val != (Object)null) { playerName = val.playerName(); } else { playerName = "this beer"; } } if (flag) { string text = GenerateAffectionateSentence(); currentState = State.Active; Color val2 = default(Color); ((Color)(ref val2))..ctor(1f, 0.9f, 0.5f, 1f); ChatManager.instance.PossessChatScheduleStart(10); ChatManager.instance.PossessChat((PossessChatID)1, text, 1f, val2, 0f, false, 0, (UnityEvent)null); ChatManager.instance.PossessChatScheduleEnd(); } } } private void StateActive() { if (PhysGrabber.instance.grabbed && Object.op_Implicit((Object)(object)PhysGrabber.instance.grabbedPhysGrabObject()) && (Object)(object)PhysGrabber.instance.grabbedPhysGrabObject() != (Object)(object)physGrabObject) { currentState = State.Idle; coolDownUntilNextSentence = Random.Range(5f, 15f); } else if (!ChatManager.instance.StateIsPossessed()) { currentState = State.Idle; coolDownUntilNextSentence = Random.Range(5f, 15f); } } private void InitializeWordLists() { transitiveVerbs.AddRange(new string[11] { "drink with", "toast with", "savor with", "clink glasses with", "share a pint with", "enjoy a brew with", "down a cold one with", "quaff with", "imbibe with", "raise a glass with", "chug with" }); intransitiveVerbs.AddRange(new string[12] { "bubble", "foam", "fizz", "ferment", "brew", "carbonate", "age", "mature", "condition", "sparkle", "chill", "refresh" }); adjectives.AddRange(new string[27] { "hops-olutely amazing", "brew-tiful", "beer-y special", "lager-ly unique", "ale-some", "pint-sized perfection", "malt-nificent", "stout-standing", "golden", "bubbly", "frothylicious", "beer-y good", "refreshing", "crisp", "zesty", "hoppy", "malty", "smooth", "rich", "robust", "full-bodied", "light", "dark", "amber", "craft", "draught", "cask-conditioned" }); intensifiers.AddRange(new string[59] { "totally", "super", "uber", "mega", "super mega", "seriously", "majorly", "absolutely", "completely", "utterly", "incredibly", "madly", "sooo", "really", "so", "sooooooooo", "unbelievably", "very", "extra", "extremely", "really really", "fiercely", "greatly", "hugely", "immensely", "intensely", "massively", "so so soooo", "really really really", "simply", "supremely", "surprisingly", "super mega ultra", "ultra", "unusually", "way way", "way", "insanely", "freakishly", "extra extra", "overwhelmingly", "reeeaaally", "weirdly", "suuuuper", "way waaaay", "crazy", "like suuuuuper", "really sooo", "literally", "for reeeaal soo", "honestly", "kinda", "sort of", "basically", "downright", "very very", "genuinely", "truly", "sincerely" }); nouns.AddRange(new string[3] { "beer", "wheat beer", "craft beer" }); adverbs.AddRange(new string[59] { "totally", "super", "uber", "mega", "super mega", "seriously", "majorly", "absolutely", "completely", "utterly", "incredibly", "madly", "sooo", "really", "so", "sooooooooo", "unbelievably", "very", "extra", "extremely", "really really", "fiercely", "greatly", "hugely", "immensely", "intensely", "massively", "so so soooo", "really really really", "simply", "supremely", "surprisingly", "super mega ultra", "ultra", "unusually", "way way", "way", "insanely", "freakishly", "extra extra", "overwhelmingly", "reeeaaally", "weirdly", "suuuuper", "way waaaay", "crazy", "like suuuuuper", "really sooo", "literally", "for reeeaal soo", "honestly", "kinda", "sort of", "basically", "downright", "very very", "genuinely", "truly", "sincerely" }); } private string GenerateAffectionateSentence() { List<string> list = new List<string> { "{playerName} go to drink this {noun}.", "Every time I see {playerName}, this {noun} {intransitiveVerb}.", "{playerName} and this {noun} are a {adjective} match.", "Got me {adverb} craving a {adjective} {noun} with {playerName}.", "Just want to {transitiveVerb} a {adjective} {noun}.", "Oh my, {playerName} and a {adjective} {noun}, {intensifier} perfect!", "{playerName} is as {adjective} as my favorite {noun}.", "{playerName}, you are the {noun} to my {adjective} day!", "This {noun} is so {adjective}, especially with {playerName}.", "Can't stop thinking about sharing a {adjective} {noun} with {playerName}.", "{playerName}'s choice of {noun} is always so {adjective}.", "Dreaming of a {adjective} {noun} with {playerName} right now.", "With {playerName}, every {noun} tastes {intensifier} {adjective}.", "{playerName}, you make me want a {intensifier} {adjective} {noun}.", "Life is {intensifier} {adjective} with {playerName} and a good {noun}.", "{playerName} knows how to pick a {intensifier} {adjective} {noun}.", "A {adjective} {noun} with {playerName} is all I need.", "{playerName} turns every {noun} into a {adjective} experience.", "I want to beat my wife and go play gambling" }; string text = list[Random.Range(0, list.Count)]; string text2 = text.Replace("{playerName}", playerName); if (text.Contains("{transitiveVerb}")) { string newValue = transitiveVerbs[Random.Range(0, transitiveVerbs.Count)]; text2 = text2.Replace("{transitiveVerb}", newValue); } if (text.Contains("{intransitiveVerb}")) { string text3 = intransitiveVerbs[Random.Range(0, intransitiveVerbs.Count)]; if (text2.Contains("{intransitiveVerb}s")) { text3 = ((!text3.EndsWith("e")) ? (text3 + "es") : (text3 + "s")); text2 = text2.Replace("{intransitiveVerb}s", text3); } else { text2 = text2.Replace("{intransitiveVerb}", text3); } } if (text.Contains("{adjective}")) { string newValue2 = adjectives[Random.Range(0, adjectives.Count)]; text2 = text2.Replace("{adjective}", newValue2); } if (text.Contains("{intensifier}")) { string newValue3 = intensifiers[Random.Range(0, intensifiers.Count)]; text2 = text2.Replace("{intensifier}", newValue3); } if (text.Contains("{adverb}")) { string newValue4 = adverbs[Random.Range(0, adverbs.Count)]; text2 = text2.Replace("{adverb}", newValue4); } if (text.Contains("{noun}")) { string newValue5 = nouns[Random.Range(0, nouns.Count)]; text2 = text2.Replace("{noun}", newValue5); } return char.ToUpper(text2[0]) + text2.Substring(1); } } namespace ValuableBeerPotionMod; [BepInPlugin("com.modder.valuablebeerpotion", "Valuable Beer Potion Mod", "1.0.0")] public class ValuableBeerPotionPlugin : BaseUnityPlugin { public static ManualLogSource Log; private void Awake() { Log = ((BaseUnityPlugin)this).Logger; Log.LogInfo((object)"ValuableBeerPotion Mod: Starting initialization"); ValuableBeerPotionPatch.Initialize(); Log.LogInfo((object)"ValuableBeerPotion Mod: Initialization complete"); } } [HarmonyPatch] public class ValuableBeerPotionPatch { public static class PlayerAvatarAccessor { private static FieldInfo playerNameField; static PlayerAvatarAccessor() { Type typeFromHandle = typeof(PlayerAvatar); playerNameField = typeFromHandle.GetField("_playerName", BindingFlags.Instance | BindingFlags.NonPublic) ?? typeFromHandle.GetField("playerName", BindingFlags.Instance | BindingFlags.NonPublic) ?? typeFromHandle.GetField("m_playerName", BindingFlags.Instance | BindingFlags.NonPublic); if (playerNameField == null) { Debug.LogError((object)"ValuableBeerPotion Patch: Couldn't find playerName field in PlayerAvatar class"); } else { Debug.Log((object)("ValuableBeerPotion Patch: Found playerName field: " + playerNameField.Name)); } } public static string GetPlayerName(PlayerAvatar playerAvatar) { if (playerNameField != null && (Object)(object)playerAvatar != (Object)null) { try { return (string)playerNameField.GetValue(playerAvatar); } catch (Exception ex) { Debug.LogError((object)("ValuableBeerPotion Patch: Error accessing playerName: " + ex.Message)); } } return "Unknown Player"; } } public static class PhysGrabberAccessor { private static FieldInfo grabbedPhysGrabObjectField; static PhysGrabberAccessor() { Type typeFromHandle = typeof(PhysGrabber); grabbedPhysGrabObjectField = typeFromHandle.GetField("_grabbedPhysGrabObject", BindingFlags.Instance | BindingFlags.NonPublic) ?? typeFromHandle.GetField("grabbedPhysGrabObject", BindingFlags.Instance | BindingFlags.NonPublic) ?? typeFromHandle.GetField("m_grabbedPhysGrabObject", BindingFlags.Instance | BindingFlags.NonPublic); if (grabbedPhysGrabObjectField == null) { Debug.LogError((object)"ValuableBeerPotion Patch: Couldn't find grabbedPhysGrabObject field in PhysGrabber class"); } else { Debug.Log((object)("ValuableBeerPotion Patch: Found grabbedPhysGrabObject field: " + grabbedPhysGrabObjectField.Name)); } } public static PhysGrabObject GetGrabbedPhysGrabObject(PhysGrabber physGrabber) { //IL_0029: Unknown result type (might be due to invalid IL or missing references) //IL_002f: Expected O, but got Unknown if (grabbedPhysGrabObjectField != null && (Object)(object)physGrabber != (Object)null) { try { return (PhysGrabObject)grabbedPhysGrabObjectField.GetValue(physGrabber); } catch (Exception ex) { Debug.LogError((object)("ValuableBeerPotion Patch: Error accessing grabbedPhysGrabObject: " + ex.Message)); } } return null; } } public static void Initialize() { //IL_0011: Unknown result type (might be due to invalid IL or missing references) //IL_0017: Expected O, but got Unknown Debug.Log((object)"ValuableBeerPotion Patch: Initializing"); Harmony val = new Harmony("com.modder.valuablebeerpotion"); val.PatchAll(typeof(ValuableBeerPotionPatch)); Debug.Log((object)"ValuableBeerPotion Patch: Initialized successfully"); } [HarmonyPatch(typeof(ValuableBeerPotion), "StateIdle")] [HarmonyPrefix] public static bool Prefix_StateIdle(ValuableBeerPotion __instance, ref float ___coolDownUntilNextSentence, PhysGrabObject ___physGrabObject, ref string ___playerName, ref ValuableBeerPotion.State ___currentState) { //IL_00a0: Unknown result type (might be due to invalid IL or missing references) //IL_00a8: Unknown result type (might be due to invalid IL or missing references) //IL_00ae: Unknown result type (might be due to invalid IL or missing references) //IL_01d3: Unknown result type (might be due to invalid IL or missing references) //IL_00f7: Unknown result type (might be due to invalid IL or missing references) //IL_0103: Unknown result type (might be due to invalid IL or missing references) if (___coolDownUntilNextSentence > 0f && ___physGrabObject.grabbed) { ___coolDownUntilNextSentence -= Time.deltaTime; return false; } if (Object.op_Implicit((Object)(object)PhysGrabber.instance) && PhysGrabber.instance.grabbed) { PhysGrabObject grabbedPhysGrabObject = PhysGrabberAccessor.GetGrabbedPhysGrabObject(PhysGrabber.instance); if (Object.op_Implicit((Object)(object)grabbedPhysGrabObject) && (Object)(object)grabbedPhysGrabObject == (Object)(object)___physGrabObject) { bool flag; if (!SemiFunc.IsMultiplayer()) { ___playerName = "this beer"; flag = true; } else { List<PlayerAvatar> list = SemiFunc.PlayerGetAllPlayerAvatarWithinRange(10f, ((Component)PhysGrabber.instance).transform.position, false, default(LayerMask)); PlayerAvatar val = null; float num = float.MaxValue; foreach (PlayerAvatar item in list) { if (!((Object)(object)item == (Object)(object)PlayerAvatar.instance)) { float num2 = Vector3.Distance(((Component)PhysGrabber.instance).transform.position, ((Component)item).transform.position); if (num2 < num) { num = num2; val = item; } } } flag = true; if ((Object)(object)val != (Object)null) { ___playerName = PlayerAvatarAccessor.GetPlayerName(val); } else { ___playerName = "this beer"; } } if (flag) { MethodInfo method = typeof(ValuableBeerPotion).GetMethod("GenerateAffectionateSentence", BindingFlags.Instance | BindingFlags.NonPublic); string text = (string)method.Invoke(__instance, null); ___currentState = ValuableBeerPotion.State.Active; Color val2 = default(Color); ((Color)(ref val2))..ctor(1f, 0.9f, 0.5f, 1f); ChatManager.instance.PossessChatScheduleStart(10); ChatManager.instance.PossessChat((PossessChatID)1, text, 1f, val2, 0f, false, 0, (UnityEvent)null); ChatManager.instance.PossessChatScheduleEnd(); } } } return false; } [HarmonyPatch(typeof(ValuableBeerPotion), "StateActive")] [HarmonyPrefix] public static bool Prefix_StateActive(ValuableBeerPotion __instance, ref float ___coolDownUntilNextSentence, PhysGrabObject ___physGrabObject, ref ValuableBeerPotion.State ___currentState) { if (PhysGrabber.instance.grabbed) { PhysGrabObject grabbedPhysGrabObject = PhysGrabberAccessor.GetGrabbedPhysGrabObject(PhysGrabber.instance); if (Object.op_Implicit((Object)(object)grabbedPhysGrabObject) && (Object)(object)grabbedPhysGrabObject != (Object)(object)___physGrabObject) { ___currentState = ValuableBeerPotion.State.Idle; ___coolDownUntilNextSentence = Random.Range(5f, 15f); return false; } } if (!ChatManager.instance.StateIsPossessed()) { ___currentState = ValuableBeerPotion.State.Idle; ___coolDownUntilNextSentence = Random.Range(5f, 15f); return false; } return false; } } public static class RepoExtensions { private static FieldInfo _playerNameField; private static FieldInfo _grabbedPhysGrabObjectField; static RepoExtensions() { try { Type typeFromHandle = typeof(PlayerAvatar); _playerNameField = typeFromHandle.GetField("_playerName", BindingFlags.Instance | BindingFlags.NonPublic) ?? typeFromHandle.GetField("playerName", BindingFlags.Instance | BindingFlags.NonPublic) ?? typeFromHandle.GetField("m_playerName", BindingFlags.Instance | BindingFlags.NonPublic); if (_playerNameField == null) { Debug.LogError((object)"RepoExtensions: Couldn't find playerName field in PlayerAvatar class"); } else { Debug.Log((object)("RepoExtensions: Found playerName field: " + _playerNameField.Name)); } } catch (Exception ex) { Debug.LogError((object)("RepoExtensions: Error initializing playerName field: " + ex.Message)); } try { Type typeFromHandle2 = typeof(PhysGrabber); _grabbedPhysGrabObjectField = typeFromHandle2.GetField("_grabbedPhysGrabObject", BindingFlags.Instance | BindingFlags.NonPublic) ?? typeFromHandle2.GetField("grabbedPhysGrabObject", BindingFlags.Instance | BindingFlags.NonPublic) ?? typeFromHandle2.GetField("m_grabbedPhysGrabObject", BindingFlags.Instance | BindingFlags.NonPublic); if (_grabbedPhysGrabObjectField == null) { Debug.LogError((object)"RepoExtensions: Couldn't find grabbedPhysGrabObject field in PhysGrabber class"); } else { Debug.Log((object)("RepoExtensions: Found grabbedPhysGrabObject field: " + _grabbedPhysGrabObjectField.Name)); } } catch (Exception ex2) { Debug.LogError((object)("RepoExtensions: Error initializing grabbedPhysGrabObject field: " + ex2.Message)); } } public static string playerName(this PlayerAvatar playerAvatar) { if (_playerNameField != null && (Object)(object)playerAvatar != (Object)null) { try { return (string)_playerNameField.GetValue(playerAvatar); } catch (Exception ex) { Debug.LogError((object)("RepoExtensions: Error accessing playerName: " + ex.Message)); } } return "Unknown Player"; } public static PhysGrabObject grabbedPhysGrabObject(this PhysGrabber physGrabber) { //IL_0029: Unknown result type (might be due to invalid IL or missing references) //IL_002f: Expected O, but got Unknown if (_grabbedPhysGrabObjectField != null && (Object)(object)physGrabber != (Object)null) { try { return (PhysGrabObject)_grabbedPhysGrabObjectField.GetValue(physGrabber); } catch (Exception ex) { Debug.LogError((object)("RepoExtensions: Error accessing grabbedPhysGrabObject: " + ex.Message)); } } return null; } }
plugins/prxphet-BetterTumble/BetterTumble.dll
Decompiled 2 months agousing System; using 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 BetterTumble.Patches; using HarmonyLib; using UnityEngine; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: AssemblyTitle("BetterTumble")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("BetterTumble")] [assembly: AssemblyCopyright("Copyright © 2025")] [assembly: AssemblyTrademark("")] [assembly: ComVisible(false)] [assembly: Guid("badd1d9d-fcf5-4063-9e9e-7230de898e99")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")] [assembly: AssemblyVersion("1.0.0.0")] namespace BetterTumble { [BepInPlugin("prxphet.BetterTumble", "Better Tumble", "1.0.3")] public class BetterTumbleBase : BaseUnityPlugin { private const string modGUID = "prxphet.BetterTumble"; private const string modName = "Better Tumble"; private const string modVersion = "1.0.3"; private readonly Harmony harmony = new Harmony("prxphet.BetterTumble"); private static BetterTumbleBase Instance; internal static ManualLogSource mls; public static ConfigEntry<bool> NoSelfDamage; public static ConfigEntry<int> DamageScale; private void Awake() { //IL_0070: Unknown result type (might be due to invalid IL or missing references) //IL_007a: Expected O, but got Unknown if ((Object)(object)Instance == (Object)null) { Instance = this; } mls = Logger.CreateLogSource("prxphet.BetterTumble"); mls.LogInfo((object)"BetterTumble is active"); NoSelfDamage = ((BaseUnityPlugin)this).Config.Bind<bool>("Gameplay", "Disable self-damage", true, (ConfigDescription)null); DamageScale = ((BaseUnityPlugin)this).Config.Bind<int>("Gameplay", "Damage scale", 3, new ConfigDescription("", (AcceptableValueBase)(object)new AcceptableValueRange<int>(1, 100), Array.Empty<object>())); harmony.PatchAll(typeof(BetterTumbleBase)); harmony.PatchAll(typeof(PlayerTumblePatch)); harmony.PatchAll(typeof(HurtColliderPatch)); } } } namespace BetterTumble.Patches { [HarmonyPatch(typeof(HurtCollider))] internal class HurtColliderPatch { private static bool applied; [HarmonyPatch("EnemyHurt")] [HarmonyPrefix] private static void EnemyHurtPrefix(HurtCollider __instance) { if (!applied && __instance.enemyDamage > 0) { if (Object.op_Implicit((Object)(object)((Component)__instance).GetComponentInParent<PlayerTumble>())) { __instance.enemyDamage *= BetterTumbleBase.DamageScale.Value; } applied = true; } } } [HarmonyPatch(typeof(PlayerTumble))] internal class PlayerTumblePatch { [HarmonyPatch("HitEnemy")] [HarmonyPrefix] private static bool HitEnemyPrefix() { if (BetterTumbleBase.NoSelfDamage.Value) { return false; } return true; } } }
plugins/Rebateman-LateJoin/LateJoin.dll
Decompiled 2 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 ExitGames.Client.Photon; using HarmonyLib; using Microsoft.CodeAnalysis; using MonoMod.RuntimeDetour; using Photon.Pun; using Photon.Realtime; 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(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")] [assembly: AssemblyCompany("LateJoin")] [assembly: AssemblyConfiguration("Debug")] [assembly: AssemblyFileVersion("0.1.1.0")] [assembly: AssemblyInformationalVersion("0.1.1+bab70bccf3337fbc8e229143cdce3eeb6a090559")] [assembly: AssemblyProduct("LateJoin")] [assembly: AssemblyTitle("LateJoin")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("0.1.1.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 LateJoin { [BepInPlugin("rebateman.latejoin", "Late Join", "0.1.2")] internal sealed class Entry : BaseUnityPlugin { private const string MOD_NAME = "Late Join"; internal static readonly ManualLogSource logger = Logger.CreateLogSource("Late Join"); private static void RunManager_ChangeLevelHook(Action<RunManager, bool, bool, ChangeLevelType> orig, RunManager self, bool _completedLevel, bool _levelFailed, ChangeLevelType _changeLevelType) { //IL_0018: 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_00be: Unknown result type (might be due to invalid IL or missing references) if (_levelFailed || !PhotonNetwork.IsMasterClient) { orig(self, _completedLevel, _levelFailed, _changeLevelType); return; } object value = AccessTools.Field(typeof(RunManager), "runManagerPUN").GetValue(self); object? value2 = AccessTools.Field(typeof(RunManagerPUN), "photonView").GetValue(value); PhotonView val = (PhotonView)((value2 is PhotonView) ? value2 : null); PhotonNetwork.RemoveBufferedRPCs(val.ViewID, (string)null, (int[])null); PhotonView[] array = Object.FindObjectsOfType<PhotonView>(); foreach (PhotonView val2 in array) { Scene scene = ((Component)val2).gameObject.scene; if (((Scene)(ref scene)).buildIndex != -1) { ClearPhotonCache(val2); } } orig(self, _completedLevel, arg3: false, _changeLevelType); bool flag = SemiFunc.RunIsLobbyMenu() || SemiFunc.RunIsLobby(); if (flag) { SteamManager.instance.UnlockLobby(); } else { SteamManager.instance.LockLobby(); } PhotonNetwork.CurrentRoom.IsOpen = flag; } private static void PlayerAvatar_SpawnHook(Action<PlayerAvatar, Vector3, Quaternion> orig, PlayerAvatar self, Vector3 position, Quaternion rotation) { //IL_0028: 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 (!(bool)AccessTools.Field(typeof(PlayerAvatar), "spawned").GetValue(self)) { orig(self, position, rotation); } } private static void LevelGenerator_StartHook(Action<LevelGenerator> orig, LevelGenerator self) { if ((PhotonNetwork.IsMasterClient && SemiFunc.RunIsShop()) || SemiFunc.RunIsLobby()) { PhotonNetwork.RemoveBufferedRPCs(self.PhotonView.ViewID, (string)null, (int[])null); } orig(self); } private static void PlayerAvatar_StartHook(Action<PlayerAvatar> orig, PlayerAvatar self) { orig(self); if ((PhotonNetwork.IsMasterClient || SemiFunc.RunIsLobby()) && SemiFunc.RunIsShop()) { self.photonView.RPC("LoadingLevelAnimationCompletedRPC", (RpcTarget)3, Array.Empty<object>()); } } private static void ClearPhotonCache(PhotonView photonView) { //IL_0088: Unknown result type (might be due to invalid IL or missing references) //IL_00ac: Unknown result type (might be due to invalid IL or missing references) object? value = AccessTools.Field(typeof(PhotonNetwork), "removeFilter").GetValue(null); Hashtable val = (Hashtable)((value is Hashtable) ? value : null); object value2 = AccessTools.Field(typeof(PhotonNetwork), "keyByteSeven").GetValue(null); object? value3 = AccessTools.Field(typeof(PhotonNetwork), "ServerCleanOptions").GetValue(null); RaiseEventOptions val2 = (RaiseEventOptions)((value3 is RaiseEventOptions) ? value3 : null); MethodInfo methodInfo = AccessTools.Method(typeof(PhotonNetwork), "RaiseEventInternal", (Type[])null, (Type[])null); val[value2] = photonView.InstantiationId; val2.CachingOption = (EventCaching)6; methodInfo.Invoke(null, new object[4] { (byte)202, val, val2, SendOptions.SendReliable }); } private void Awake() { //IL_0042: Unknown result type (might be due to invalid IL or missing references) //IL_0089: Unknown result type (might be due to invalid IL or missing references) //IL_00d0: Unknown result type (might be due to invalid IL or missing references) //IL_0117: Unknown result type (might be due to invalid IL or missing references) logger.LogDebug((object)"Hooking `RunManager.ChangeLevel`"); new Hook((MethodBase)AccessTools.Method(typeof(RunManager), "ChangeLevel", (Type[])null, (Type[])null), (Delegate)new Action<Action<RunManager, bool, bool, ChangeLevelType>, RunManager, bool, bool, ChangeLevelType>(RunManager_ChangeLevelHook)); logger.LogDebug((object)"Hooking `PlayerAvatar.Spawn`"); new Hook((MethodBase)AccessTools.Method(typeof(PlayerAvatar), "Spawn", (Type[])null, (Type[])null), (Delegate)new Action<Action<PlayerAvatar, Vector3, Quaternion>, PlayerAvatar, Vector3, Quaternion>(PlayerAvatar_SpawnHook)); logger.LogDebug((object)"Hooking `LevelGenerator.Start`"); new Hook((MethodBase)AccessTools.Method(typeof(LevelGenerator), "Start", (Type[])null, (Type[])null), (Delegate)new Action<Action<LevelGenerator>, LevelGenerator>(LevelGenerator_StartHook)); logger.LogDebug((object)"Hooking `PlayerAvatar.Start`"); new Hook((MethodBase)AccessTools.Method(typeof(PlayerAvatar), "Start", (Type[])null, (Type[])null), (Delegate)new Action<Action<PlayerAvatar>, PlayerAvatar>(PlayerAvatar_StartHook)); } } public static class MyPluginInfo { public const string PLUGIN_GUID = "LateJoin"; public const string PLUGIN_NAME = "LateJoin"; public const string PLUGIN_VERSION = "0.1.1"; } }
plugins/SharkLucas-SyncHostUpgrades/SyncHostUpgrades.dll
Decompiled 2 months agousing System; using System.Collections.Generic; using System.Diagnostics; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using BepInEx; using BepInEx.Configuration; using HarmonyLib; using Microsoft.CodeAnalysis; using Photon.Pun; 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("SyncHostUpgrades")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: AssemblyInformationalVersion("1.0.0+d1169f47f709005def97c8080dffab3bf9994b2a")] [assembly: AssemblyProduct("SyncHostUpgrades")] [assembly: AssemblyTitle("SyncHostUpgrades")] [assembly: AssemblyVersion("1.0.0.0")] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)] internal sealed class NullableAttribute : Attribute { public readonly byte[] NullableFlags; public NullableAttribute(byte P_0) { NullableFlags = new byte[1] { P_0 }; } public NullableAttribute(byte[] P_0) { NullableFlags = P_0; } } [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)] internal sealed class NullableContextAttribute : Attribute { public readonly byte Flag; public NullableContextAttribute(byte P_0) { Flag = P_0; } } } namespace SyncHostUpgrades { [BepInPlugin("SharkLucas.REPO.SyncHostUpgrades", "R.E.P.O. Sync Host Upgrades", "1.0.0")] public class SyncHostUpgrades : BaseUnityPlugin { public ConfigEntry<bool>? SyncHealth; public ConfigEntry<bool>? SyncStamina; public ConfigEntry<bool>? SyncExtraJump; public ConfigEntry<bool>? SyncMapPlayerCount; public ConfigEntry<bool>? SyncGrabRange; public ConfigEntry<bool>? SyncGrabStrength; public ConfigEntry<bool>? SyncGrabThrow; public ConfigEntry<bool>? SyncSprintSpeed; public ConfigEntry<bool>? SyncTumbleLaunch; private static readonly FieldRef<PlayerAvatar, bool> isLocalRef = AccessTools.FieldRefAccess<PlayerAvatar, bool>("isLocal"); private static readonly FieldRef<PlayerAvatar, string> playerNameRef = AccessTools.FieldRefAccess<PlayerAvatar, string>("playerName"); private static readonly FieldRef<PlayerAvatar, string> steamIDRef = AccessTools.FieldRefAccess<PlayerAvatar, string>("steamID"); private static PlayerAvatar? cachedLocalPlayer = null; private static float lastCheckTime = 0f; public static SyncHostUpgrades? Instance { get; private set; } private void Awake() { //IL_0134: Unknown result type (might be due to invalid IL or missing references) Instance = this; SyncHealth = ((BaseUnityPlugin)this).Config.Bind<bool>("Sync", "Health", true, "Sync Max Health"); SyncStamina = ((BaseUnityPlugin)this).Config.Bind<bool>("Sync", "Stamina", true, "Sync Max Stamina"); SyncExtraJump = ((BaseUnityPlugin)this).Config.Bind<bool>("Sync", "Extra Jump", true, "Sync Extra Jump Count"); SyncTumbleLaunch = ((BaseUnityPlugin)this).Config.Bind<bool>("Sync", "Tumble Launch", true, "Sync Tumble Launch Count"); SyncMapPlayerCount = ((BaseUnityPlugin)this).Config.Bind<bool>("Sync", "Map Player Count", true, "Sync Map Player Count"); SyncSprintSpeed = ((BaseUnityPlugin)this).Config.Bind<bool>("Sync", "Sprint Speed", false, "Sync Sprint Speed"); SyncGrabStrength = ((BaseUnityPlugin)this).Config.Bind<bool>("Sync", "Grab Strength", true, "Sync Grab Strength"); SyncGrabRange = ((BaseUnityPlugin)this).Config.Bind<bool>("Sync", "Grab Range", true, "Sync Grab Range"); SyncGrabThrow = ((BaseUnityPlugin)this).Config.Bind<bool>("Sync", "Grab Throw", true, "Sync Grab Throw"); new Harmony("REPO.SyncHostUpgrades").PatchAll(); ((BaseUnityPlugin)this).Logger.LogInfo((object)"SyncHostUpgrades loaded!"); ((Object)((Component)this).gameObject).hideFlags = (HideFlags)4; } private void Update() { if (!PhotonNetwork.IsMasterClient) { return; } PlayerAvatar localPlayer = GetLocalPlayer(); if (!((Object)(object)localPlayer != (Object)null)) { return; } Dictionary<string, int> dictionary = StatsManager.instance.FetchPlayerUpgrades(steamIDRef.Invoke(localPlayer)); foreach (PlayerAvatar item in SemiFunc.PlayerGetAll()) { if (isLocalRef.Invoke(item)) { continue; } string text = steamIDRef.Invoke(item); Dictionary<string, int> dictionary2 = StatsManager.instance.FetchPlayerUpgrades(text); foreach (string key in dictionary.Keys) { bool flag = false; switch (key) { case "Health": flag = SyncHealth?.Value ?? false; break; case "Stamina": flag = SyncStamina?.Value ?? false; break; case "Extra Jump": flag = SyncExtraJump?.Value ?? false; break; case "Launch": flag = SyncTumbleLaunch?.Value ?? false; break; case "Map Player Count": flag = SyncMapPlayerCount?.Value ?? false; break; case "Speed": flag = SyncSprintSpeed?.Value ?? false; break; case "Strength": flag = SyncGrabStrength?.Value ?? false; break; case "Range": flag = SyncGrabRange?.Value ?? false; break; case "Throw": flag = SyncGrabThrow?.Value ?? false; break; } if (!flag || !dictionary.TryGetValue(key, out var value) || value <= dictionary2[key]) { continue; } int num = value - dictionary2[key]; for (int i = 0; i < num; i++) { switch (key) { case "Health": if (PhotonNetwork.IsMasterClient) { PunManager.instance.UpgradePlayerHealth(text); } break; case "Stamina": if (PhotonNetwork.IsMasterClient) { PunManager.instance.UpgradePlayerEnergy(text); } break; case "Extra Jump": if (PhotonNetwork.IsMasterClient) { PunManager.instance.UpgradePlayerExtraJump(text); } break; case "Launch": if (PhotonNetwork.IsMasterClient) { PunManager.instance.UpgradePlayerTumbleLaunch(text); } break; case "Map Player Count": if (PhotonNetwork.IsMasterClient) { PunManager.instance.UpgradeMapPlayerCount(text); } break; case "Speed": if (PhotonNetwork.IsMasterClient) { PunManager.instance.UpgradePlayerSprintSpeed(text); } break; case "Strength": if (PhotonNetwork.IsMasterClient) { PunManager.instance.UpgradePlayerGrabStrength(text); } break; case "Range": if (PhotonNetwork.IsMasterClient) { PunManager.instance.UpgradePlayerGrabRange(text); } break; case "Throw": if (PhotonNetwork.IsMasterClient) { PunManager.instance.UpgradePlayerThrowStrength(text); } break; } } ((BaseUnityPlugin)this).Logger.LogInfo((object)$"为玩家 {playerNameRef.Invoke(item)} 同步升级: {key}, 从 {dictionary2[key]} 到 {value}"); } } } public static PlayerAvatar? GetLocalPlayer() { if ((Object)(object)cachedLocalPlayer != (Object)null && Time.time - lastCheckTime < 1f) { return cachedLocalPlayer; } lastCheckTime = Time.time; foreach (PlayerAvatar item in SemiFunc.PlayerGetAll()) { if (isLocalRef.Invoke(item)) { cachedLocalPlayer = item; return item; } } return cachedLocalPlayer; } } }
plugins/Snowlance-NoDamageInShop/NoDamageInShop.dll
Decompiled 2 months agousing System; using System.Diagnostics; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using BepInEx; using BepInEx.Logging; using HarmonyLib; 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("NoDamageInShop")] [assembly: AssemblyConfiguration("Debug")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: AssemblyInformationalVersion("1.0.0")] [assembly: AssemblyProduct("NoDamageInShop")] [assembly: AssemblyTitle("NoDamageInShop")] [assembly: AssemblyVersion("1.0.0.0")] 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; } } } [BepInPlugin("Snowlance.NoDamageInShop", "NoDamageInShop", "1.0.0")] public class Plugin : BaseUnityPlugin { public const string modGUID = "Snowlance.NoDamageInShop"; public const string modName = "NoDamageInShop"; public const string modVersion = "1.0.0"; public static Plugin PluginInstance; public static ManualLogSource LoggerInstance; private readonly Harmony harmony = new Harmony("Snowlance.NoDamageInShop"); public void Awake() { if ((Object)(object)PluginInstance == (Object)null) { PluginInstance = this; } LoggerInstance = ((BaseUnityPlugin)PluginInstance).Logger; harmony.PatchAll(); ((BaseUnityPlugin)this).Logger.LogInfo((object)"Snowlance.NoDamageInShop v1.0.0 has loaded!"); } } namespace NoDamageInShop { [HarmonyPatch(typeof(PlayerHealth))] internal class PlayerHealthPatch { private static ManualLogSource logger = Plugin.LoggerInstance; [HarmonyPrefix] [HarmonyPatch("Hurt")] public static bool HurtPrefix() { if ((Object)(object)RunManager.instance.levelCurrent == (Object)(object)RunManager.instance.levelShop) { return false; } return true; } } }
plugins/SteamBlizzard-YippeeDuck/YippieDuck.dll
Decompiled 2 months agousing System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Versioning; using BepInEx; using BepInEx.Logging; using HarmonyLib; using UnityEngine; using YippeeDuck.Patches; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)] [assembly: AssemblyTitle("YippeeDuck")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("YippeeDuck")] [assembly: AssemblyCopyright("Copyright © 2025")] [assembly: AssemblyTrademark("")] [assembly: ComVisible(false)] [assembly: Guid("ece73a37-42f8-4194-ad23-e0a852e0eeb8")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")] [assembly: AssemblyVersion("1.0.0.0")] namespace YippeeDuck { [BepInPlugin("SteamBlizzard.YippeeDuck", "Yippee Duck", "1.0.0")] public class YippeeDuckBase : BaseUnityPlugin { private const string modUID = "SteamBlizzard.YippeeDuck"; private const string modName = "Yippee Duck"; private const string modVersion = "1.0.0"; private readonly Harmony harmony = new Harmony("SteamBlizzard.YippeeDuck"); internal static YippeeDuckBase instance; internal ManualLogSource logger; internal static List<AudioClip> sounds; internal static AssetBundle bundle; private void Awake() { logger = Logger.CreateLogSource("Yippee Duck"); logger.LogInfo((object)"Loading Yippee Duck mod..."); if ((Object)(object)instance == (Object)null) { instance = this; } else { Object.Destroy((Object)(object)this); } harmony.PatchAll(typeof(YippeeDuckBase)); harmony.PatchAll(typeof(EnemyDuckAnimPatch)); sounds = new List<AudioClip>(); string location = ((BaseUnityPlugin)instance).Info.Location; location = location.TrimEnd("YippeeDuck.dll".ToCharArray()); bundle = AssetBundle.LoadFromFile(location + "yippeeduck"); if ((Object)(object)bundle == (Object)null) { logger.LogError((object)"Failed to load asset bundle!"); return; } sounds = bundle.LoadAllAssets<AudioClip>().ToList(); logger.LogInfo((object)("Loaded " + sounds.Count + " sounds from asset bundle! First sound: " + ((Object)sounds[0]).name)); logger.LogInfo((object)"Successfully started Yippee Duck mod!"); } } } namespace YippeeDuck.Patches { [HarmonyPatch(typeof(EnemyDuckAnim))] internal class EnemyDuckAnimPatch { [HarmonyPatch("Awake")] [HarmonyPostfix] private static void ReplaceAudio(EnemyDuckAnim __instance) { __instance.quackSound.Sounds = YippeeDuckBase.sounds.ToArray(); YippeeDuckBase.instance.logger.LogInfo((object)"Replaced audio for EnemyDuck"); } } }
plugins/Tidaleus-MoreReviveHP/More Revive HP.dll
Decompiled 2 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 HarmonyLib; using More_Revive_HP.Patches; 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("More Revive HP")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("More Revive HP")] [assembly: AssemblyCopyright("Copyright © 2025")] [assembly: AssemblyTrademark("")] [assembly: ComVisible(false)] [assembly: Guid("46ab4f67-24f2-4385-81cf-415d36226ff4")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")] [assembly: AssemblyVersion("1.0.0.0")] [BepInPlugin("Tidaleus.MoreReviveHP", "More Revive HP", "1.0.1")] public class Plugin : BaseUnityPlugin { public const string modGUID = "Tidaleus.MoreReviveHP"; public const string modName = "More Revive HP"; public const string modVersion = "1.0.1"; private readonly Harmony harmony = new Harmony("Tidaleus.MoreReviveHP"); private static Plugin Instance; private ConfigEntry<int> ExtraHealth; private void Awake() { ((BaseUnityPlugin)this).Logger.LogInfo((object)"Tidaleus.MoreReviveHP has loaded"); if ((Object)(object)Instance == (Object)null) { Instance = this; } ExtraHealth = ((BaseUnityPlugin)this).Config.Bind<int>("General", "ExtraHealth", 19, "Extra Health to add to the 1 you spawn with, therefore make this something 1 through 99."); harmony.PatchAll(typeof(Plugin)); harmony.PatchAll(typeof(PlayerAvatarPatch)); } public static int GetExtraHealth() { return Instance.ExtraHealth.Value; } } namespace More_Revive_HP.Patches; [HarmonyPatch(typeof(PlayerAvatar), "ReviveRPC")] internal class PlayerAvatarPatch { private static void Postfix(PlayerAvatar __instance, bool _revivedByTruck) { int extraHealth = Plugin.GetExtraHealth(); if (__instance.photonView.IsMine) { __instance.playerHealth.HealOther(extraHealth, true); } } }
plugins/TitanVortex-BigNuke/BigNuke.dll
Decompiled 2 months agousing System; using System.Diagnostics; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using BepInEx; using BepInEx.Configuration; using BepInEx.Logging; using Microsoft.CodeAnalysis; using REPOLib.Modules; using UnityEngine; using UnityEngine.Events; [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("BigNuke")] [assembly: AssemblyConfiguration("Debug")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: AssemblyInformationalVersion("1.0.0")] [assembly: AssemblyProduct("BigNuke")] [assembly: AssemblyTitle("BigNuke")] [assembly: AssemblyVersion("1.0.0.0")] [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 Vortex.BigNuke { [BepInPlugin("Vortex.BigNuke", "BigNuke", "1.0.1")] [BepInDependency(/*Could not decode attribute arguments.*/)] public class BigNuke : BaseUnityPlugin { private const string modUID = "Vortex.BigNuke"; private const string modName = "BigNuke"; private const string modVersion = "1.0.1"; public int explosionPlayerDamage = 100; public int explosionEnemyDamage = 500; public ConfigEntry<float> explosionRange; public ConfigEntry<int> maxHitCount; public ConfigEntry<int> minValue; public ConfigEntry<int> maxValue; internal static BigNuke instance; internal ManualLogSource logger = Logger.CreateLogSource("BigNuke"); internal static GameObject NukeModel; private void Awake() { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_0011: Expected O, but got Unknown //IL_0021: Unknown result type (might be due to invalid IL or missing references) //IL_002b: Expected O, but got Unknown //IL_015c: Unknown result type (might be due to invalid IL or missing references) //IL_0167: Expected O, but got Unknown //IL_0199: Unknown result type (might be due to invalid IL or missing references) //IL_01a4: Expected O, but got Unknown //IL_01ca: Unknown result type (might be due to invalid IL or missing references) //IL_01d5: Expected O, but got Unknown if ((Object)instance == (Object)null) { instance = this; } else { Object.Destroy((Object)this); } logger.LogInfo((object)$"{((BaseUnityPlugin)this).Info.Metadata.GUID} v{((BaseUnityPlugin)this).Info.Metadata.Version}: Instance set."); explosionRange = ((BaseUnityPlugin)this).Config.Bind<float>("Explosion", "Range", 5f, "The range of the explosion. (For comparison: explosive grenade range is 1)"); maxHitCount = ((BaseUnityPlugin)this).Config.Bind<int>("Explosion", "Max Hit Count", 3, "The amount of heavy hits required to trigger the explosion. (0 means only explode on destroy)"); minValue = ((BaseUnityPlugin)this).Config.Bind<int>("Explosion", "Min Nuke Sell Value", 8000, "The minimum value of the nuke when sold."); maxValue = ((BaseUnityPlugin)this).Config.Bind<int>("Explosion", "Max Nuke Sell Value", 12000, "The maximum value of the nuke when sold."); logger.LogInfo((object)$"{((BaseUnityPlugin)this).Info.Metadata.GUID} v{((BaseUnityPlugin)this).Info.Metadata.Version}: Config loaded."); string location = ((BaseUnityPlugin)instance).Info.Location; location = location.TrimEnd("BigNuke.dll".ToCharArray()); AssetBundle val = AssetBundle.LoadFromFile(location + "nuke"); if ((Object)val == (Object)null) { logger.LogError((object)"Failed to load asset bundle!"); return; } NukeModel = val.LoadAsset<GameObject>("Valuable Nuke"); if ((Object)NukeModel == (Object)null) { logger.LogError((object)"Failed to load model!"); return; } NukeValuable nukeValuable = NukeModel.AddComponent<NukeValuable>(); if ((Object)nukeValuable == (Object)null) { logger.LogError((object)"Failed to add NukeValuable component!"); return; } Valuables.RegisterValuable(NukeModel); logger.LogInfo((object)$"{((BaseUnityPlugin)this).Info.Metadata.GUID} v{((BaseUnityPlugin)this).Info.Metadata.Version}: Nuke registered."); } } public class NukeValuable : Trap { private ParticleScriptExplosion particleScriptExplosion; private int HitCount; public Transform Center; public override void Start() { //IL_0009: Unknown result type (might be due to invalid IL or missing references) //IL_0014: Expected O, but got Unknown //IL_007e: Unknown result type (might be due to invalid IL or missing references) //IL_0089: Expected O, but got Unknown //IL_00bb: Unknown result type (might be due to invalid IL or missing references) //IL_00c5: Expected O, but got Unknown //IL_00d3: Unknown result type (might be due to invalid IL or missing references) //IL_00dd: Expected O, but got Unknown PhysGrabObjectImpactDetector component = ((Component)this).GetComponent<PhysGrabObjectImpactDetector>(); if ((Object)component == (Object)null) { BigNuke.instance.logger.LogError((object)"Failed to get PhysGrabObjectImpactDetector component!"); return; } Value val = ScriptableObject.CreateInstance<Value>(); val.valueMin = Math.Max(0, BigNuke.instance.minValue.Value); val.valueMax = Math.Max(val.valueMin, BigNuke.instance.maxValue.Value); ValuableObject component2 = ((Component)this).GetComponent<ValuableObject>(); if ((Object)component2 == (Object)null) { BigNuke.instance.logger.LogError((object)"Failed to get ValuableObject component!"); return; } component2.valuePreset = val; component.onBreakHeavy.AddListener(new UnityAction(PotentialExplode)); component.onDestroy.AddListener(new UnityAction(Explode)); ((Trap)this).Start(); particleScriptExplosion = ((Component)this).GetComponent<ParticleScriptExplosion>(); Center = ((Component)this).transform.Find("Object/Center"); } public void Explode() { //IL_000d: Unknown result type (might be due to invalid IL or missing references) particleScriptExplosion.Spawn(Center.position, Math.Max(1f, BigNuke.instance.explosionRange.Value), BigNuke.instance.explosionPlayerDamage, BigNuke.instance.explosionEnemyDamage, 1f, false, false, 1f); } public void PotentialExplode() { if (base.isLocal && BigNuke.instance.maxHitCount.Value > 0) { if (HitCount >= BigNuke.instance.maxHitCount.Value - 1) { Explode(); } else { HitCount++; } } } } }
plugins/Tolian-REPODiscordRichPresence/DiscordRPC.dll
Decompiled 2 months agousing System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using System.IO; using System.IO.Pipes; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Versioning; using System.Text; using System.Threading; using DiscordRPC.Converters; using DiscordRPC.Events; using DiscordRPC.Exceptions; using DiscordRPC.Helper; using DiscordRPC.IO; using DiscordRPC.Logging; using DiscordRPC.Message; using DiscordRPC.RPC; using DiscordRPC.RPC.Commands; using DiscordRPC.RPC.Payload; using DiscordRPC.Registry; using Microsoft.Win32; using Newtonsoft.Json; using Newtonsoft.Json.Linq; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: AssemblyTitle("Discord RPC")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Discord RPC")] [assembly: AssemblyCopyright("Copyright © 2021")] [assembly: AssemblyTrademark("")] [assembly: ComVisible(false)] [assembly: Guid("819d20d6-8d88-45c1-a4d2-aa21f10abd19")] [assembly: AssemblyFileVersion("1.3.0.28")] [assembly: TargetFramework(".NETStandard,Version=v2.0", FrameworkDisplayName = ".NET Standard 2.0")] [assembly: AssemblyVersion("1.3.0.28")] namespace DiscordRPC { public class Configuration { [JsonProperty("api_endpoint")] public string ApiEndpoint { get; set; } [JsonProperty("cdn_host")] public string CdnHost { get; set; } [JsonProperty("environment")] public string Environment { get; set; } } public sealed class DiscordRpcClient : IDisposable { private ILogger _logger; private RpcConnection connection; private bool _shutdownOnly = true; private object _sync = new object(); public bool HasRegisteredUriScheme { get; private set; } public string ApplicationID { get; private set; } public string SteamID { get; private set; } public int ProcessID { get; private set; } public int MaxQueueSize { get; private set; } public bool IsDisposed { get; private set; } public ILogger Logger { get { return _logger; } set { _logger = value; if (connection != null) { connection.Logger = value; } } } public bool AutoEvents { get; private set; } public bool SkipIdenticalPresence { get; set; } public int TargetPipe { get; private set; } public RichPresence CurrentPresence { get; private set; } public EventType Subscription { get; private set; } public User CurrentUser { get; private set; } public Configuration Configuration { get; private set; } public bool IsInitialized { get; private set; } public bool ShutdownOnly { get { return _shutdownOnly; } set { _shutdownOnly = value; if (connection != null) { connection.ShutdownOnly = value; } } } public event OnReadyEvent OnReady; public event OnCloseEvent OnClose; public event OnErrorEvent OnError; public event OnPresenceUpdateEvent OnPresenceUpdate; public event OnSubscribeEvent OnSubscribe; public event OnUnsubscribeEvent OnUnsubscribe; public event OnJoinEvent OnJoin; public event OnSpectateEvent OnSpectate; public event OnJoinRequestedEvent OnJoinRequested; public event OnConnectionEstablishedEvent OnConnectionEstablished; public event OnConnectionFailedEvent OnConnectionFailed; public event OnRpcMessageEvent OnRpcMessage; public DiscordRpcClient(string applicationID) : this(applicationID, -1, null, autoEvents: true, null) { } public DiscordRpcClient(string applicationID, int pipe = -1, ILogger logger = null, bool autoEvents = true, INamedPipeClient client = null) { if (string.IsNullOrEmpty(applicationID)) { throw new ArgumentNullException("applicationID"); } ApplicationID = applicationID.Trim(); TargetPipe = pipe; ProcessID = Process.GetCurrentProcess().Id; HasRegisteredUriScheme = false; AutoEvents = autoEvents; SkipIdenticalPresence = true; _logger = logger ?? new NullLogger(); connection = new RpcConnection(ApplicationID, ProcessID, TargetPipe, client ?? new ManagedNamedPipeClient(), (!autoEvents) ? 128u : 0u) { ShutdownOnly = _shutdownOnly, Logger = _logger }; connection.OnRpcMessage += delegate(object sender, IMessage msg) { if (this.OnRpcMessage != null) { this.OnRpcMessage(this, msg); } if (AutoEvents) { ProcessMessage(msg); } }; } public IMessage[] Invoke() { if (AutoEvents) { Logger.Error("Cannot Invoke client when AutomaticallyInvokeEvents has been set."); return new IMessage[0]; } IMessage[] array = connection.DequeueMessages(); foreach (IMessage message in array) { ProcessMessage(message); } return array; } private void ProcessMessage(IMessage message) { if (message == null) { return; } switch (message.Type) { case MessageType.PresenceUpdate: lock (_sync) { if (message is PresenceMessage presenceMessage) { if (presenceMessage.Presence == null) { CurrentPresence = null; } else if (CurrentPresence == null) { CurrentPresence = new RichPresence().Merge(presenceMessage.Presence); } else { CurrentPresence.Merge(presenceMessage.Presence); } presenceMessage.Presence = CurrentPresence; } } if (this.OnPresenceUpdate != null) { this.OnPresenceUpdate(this, message as PresenceMessage); } break; case MessageType.Ready: if (message is ReadyMessage readyMessage) { lock (_sync) { Configuration = readyMessage.Configuration; CurrentUser = readyMessage.User; } SynchronizeState(); } if (this.OnReady != null) { this.OnReady(this, message as ReadyMessage); } break; case MessageType.Close: if (this.OnClose != null) { this.OnClose(this, message as CloseMessage); } break; case MessageType.Error: if (this.OnError != null) { this.OnError(this, message as ErrorMessage); } break; case MessageType.JoinRequest: if (Configuration != null && message is JoinRequestMessage joinRequestMessage) { joinRequestMessage.User.SetConfiguration(Configuration); } if (this.OnJoinRequested != null) { this.OnJoinRequested(this, message as JoinRequestMessage); } break; case MessageType.Subscribe: lock (_sync) { SubscribeMessage subscribeMessage = message as SubscribeMessage; Subscription |= subscribeMessage.Event; } if (this.OnSubscribe != null) { this.OnSubscribe(this, message as SubscribeMessage); } break; case MessageType.Unsubscribe: lock (_sync) { UnsubscribeMessage unsubscribeMessage = message as UnsubscribeMessage; Subscription &= ~unsubscribeMessage.Event; } if (this.OnUnsubscribe != null) { this.OnUnsubscribe(this, message as UnsubscribeMessage); } break; case MessageType.Join: if (this.OnJoin != null) { this.OnJoin(this, message as JoinMessage); } break; case MessageType.Spectate: if (this.OnSpectate != null) { this.OnSpectate(this, message as SpectateMessage); } break; case MessageType.ConnectionEstablished: if (this.OnConnectionEstablished != null) { this.OnConnectionEstablished(this, message as ConnectionEstablishedMessage); } break; case MessageType.ConnectionFailed: if (this.OnConnectionFailed != null) { this.OnConnectionFailed(this, message as ConnectionFailedMessage); } break; default: Logger.Error("Message was queued with no appropriate handle! {0}", message.Type); break; } } public void Respond(JoinRequestMessage request, bool acceptRequest) { if (IsDisposed) { throw new ObjectDisposedException("Discord IPC Client"); } if (connection == null) { throw new ObjectDisposedException("Connection", "Cannot initialize as the connection has been deinitialized"); } if (!IsInitialized) { throw new UninitializedException(); } connection.EnqueueCommand(new RespondCommand { Accept = acceptRequest, UserID = request.User.ID.ToString() }); } public void SetPresence(RichPresence presence) { if (IsDisposed) { throw new ObjectDisposedException("Discord IPC Client"); } if (connection == null) { throw new ObjectDisposedException("Connection", "Cannot initialize as the connection has been deinitialized"); } if (!IsInitialized) { Logger.Warning("The client is not yet initialized, storing the presence as a state instead."); } if (presence == null) { if (!SkipIdenticalPresence || CurrentPresence != null) { connection.EnqueueCommand(new PresenceCommand { PID = ProcessID, Presence = null }); } } else { if (presence.HasSecrets() && !HasRegisteredUriScheme) { throw new BadPresenceException("Cannot send a presence with secrets as this object has not registered a URI scheme. Please enable the uri scheme registration in the DiscordRpcClient constructor."); } if (presence.HasParty() && presence.Party.Max < presence.Party.Size) { throw new BadPresenceException("Presence maximum party size cannot be smaller than the current size."); } if (presence.HasSecrets() && !presence.HasParty()) { Logger.Warning("The presence has set the secrets but no buttons will show as there is no party available."); } if (!SkipIdenticalPresence || !presence.Matches(CurrentPresence)) { connection.EnqueueCommand(new PresenceCommand { PID = ProcessID, Presence = presence.Clone() }); } } lock (_sync) { CurrentPresence = presence?.Clone(); } } public RichPresence Update(Action<RichPresence> func) { if (!IsInitialized) { throw new UninitializedException(); } RichPresence richPresence; lock (_sync) { richPresence = ((CurrentPresence == null) ? new RichPresence() : CurrentPresence.Clone()); } func(richPresence); SetPresence(richPresence); return richPresence; } public RichPresence UpdateType(ActivityType type) { return Update(delegate(RichPresence p) { p.Type = type; }); } public RichPresence UpdateButtons(Button[] buttons = null) { return Update(delegate(RichPresence p) { p.Buttons = buttons; }); } public RichPresence SetButton(Button button, int index = 0) { return Update(delegate(RichPresence p) { p.Buttons[index] = button; }); } public RichPresence UpdateDetails(string details) { return Update(delegate(RichPresence p) { p.Details = details; }); } public RichPresence UpdateState(string state) { return Update(delegate(RichPresence p) { p.State = state; }); } public RichPresence UpdateParty(Party party) { return Update(delegate(RichPresence p) { p.Party = party; }); } public RichPresence UpdatePartySize(int size) { return Update(delegate(RichPresence p) { if (p.Party == null) { throw new BadPresenceException("Cannot set the size of the party if the party does not exist"); } p.Party.Size = size; }); } public RichPresence UpdatePartySize(int size, int max) { return Update(delegate(RichPresence p) { if (p.Party == null) { throw new BadPresenceException("Cannot set the size of the party if the party does not exist"); } p.Party.Size = size; p.Party.Max = max; }); } public RichPresence UpdateLargeAsset(string key = null, string tooltip = null) { return Update(delegate(RichPresence p) { if (p.Assets == null) { p.Assets = new Assets(); } p.Assets.LargeImageKey = key ?? p.Assets.LargeImageKey; p.Assets.LargeImageText = tooltip ?? p.Assets.LargeImageText; }); } public RichPresence UpdateSmallAsset(string key = null, string tooltip = null) { return Update(delegate(RichPresence p) { if (p.Assets == null) { p.Assets = new Assets(); } p.Assets.SmallImageKey = key ?? p.Assets.SmallImageKey; p.Assets.SmallImageText = tooltip ?? p.Assets.SmallImageText; }); } public RichPresence UpdateSecrets(Secrets secrets) { return Update(delegate(RichPresence p) { p.Secrets = secrets; }); } public RichPresence UpdateStartTime() { return UpdateStartTime(DateTime.UtcNow); } public RichPresence UpdateStartTime(DateTime time) { return Update(delegate(RichPresence p) { if (p.Timestamps == null) { p.Timestamps = new Timestamps(); } p.Timestamps.Start = time; }); } public RichPresence UpdateEndTime() { return UpdateEndTime(DateTime.UtcNow); } public RichPresence UpdateEndTime(DateTime time) { return Update(delegate(RichPresence p) { if (p.Timestamps == null) { p.Timestamps = new Timestamps(); } p.Timestamps.End = time; }); } public RichPresence UpdateClearTime() { return Update(delegate(RichPresence p) { p.Timestamps = null; }); } public void ClearPresence() { if (IsDisposed) { throw new ObjectDisposedException("Discord IPC Client"); } if (!IsInitialized) { throw new UninitializedException(); } if (connection == null) { throw new ObjectDisposedException("Connection", "Cannot initialize as the connection has been deinitialized"); } SetPresence(null); } public bool RegisterUriScheme(string steamAppID = null, string executable = null) { UriSchemeRegister uriSchemeRegister = new UriSchemeRegister(_logger, ApplicationID, steamAppID, executable); return HasRegisteredUriScheme = uriSchemeRegister.RegisterUriScheme(); } public void Subscribe(EventType type) { SetSubscription(Subscription | type); } [Obsolete("Replaced with Unsubscribe", true)] public void Unubscribe(EventType type) { SetSubscription(Subscription & ~type); } public void Unsubscribe(EventType type) { SetSubscription(Subscription & ~type); } public void SetSubscription(EventType type) { if (IsInitialized) { SubscribeToTypes(Subscription & ~type, isUnsubscribe: true); SubscribeToTypes(~Subscription & type, isUnsubscribe: false); } else { Logger.Warning("Client has not yet initialized, but events are being subscribed too. Storing them as state instead."); } lock (_sync) { Subscription = type; } } private void SubscribeToTypes(EventType type, bool isUnsubscribe) { if (type != 0) { if (IsDisposed) { throw new ObjectDisposedException("Discord IPC Client"); } if (!IsInitialized) { throw new UninitializedException(); } if (connection == null) { throw new ObjectDisposedException("Connection", "Cannot initialize as the connection has been deinitialized"); } if (!HasRegisteredUriScheme) { throw new InvalidConfigurationException("Cannot subscribe/unsubscribe to an event as this application has not registered a URI Scheme. Call RegisterUriScheme()."); } if ((type & EventType.Spectate) == EventType.Spectate) { connection.EnqueueCommand(new SubscribeCommand { Event = ServerEvent.ActivitySpectate, IsUnsubscribe = isUnsubscribe }); } if ((type & EventType.Join) == EventType.Join) { connection.EnqueueCommand(new SubscribeCommand { Event = ServerEvent.ActivityJoin, IsUnsubscribe = isUnsubscribe }); } if ((type & EventType.JoinRequest) == EventType.JoinRequest) { connection.EnqueueCommand(new SubscribeCommand { Event = ServerEvent.ActivityJoinRequest, IsUnsubscribe = isUnsubscribe }); } } } public void SynchronizeState() { if (!IsInitialized) { throw new UninitializedException(); } SetPresence(CurrentPresence); if (HasRegisteredUriScheme) { SubscribeToTypes(Subscription, isUnsubscribe: false); } } public bool Initialize() { if (IsDisposed) { throw new ObjectDisposedException("Discord IPC Client"); } if (IsInitialized) { throw new UninitializedException("Cannot initialize a client that is already initialized"); } if (connection == null) { throw new ObjectDisposedException("Connection", "Cannot initialize as the connection has been deinitialized"); } return IsInitialized = connection.AttemptConnection(); } public void Deinitialize() { if (!IsInitialized) { throw new UninitializedException("Cannot deinitialize a client that has not been initalized."); } connection.Close(); IsInitialized = false; } public void Dispose() { if (!IsDisposed) { if (IsInitialized) { Deinitialize(); } IsDisposed = true; } } } [Flags] public enum EventType { None = 0, Spectate = 1, Join = 2, JoinRequest = 4 } [Serializable] [JsonObject(/*Could not decode attribute arguments.*/)] public class BaseRichPresence { protected internal string _state; protected internal string _details; [JsonProperty(/*Could not decode attribute arguments.*/)] public string State { get { return _state; } set { if (!ValidateString(value, out _state, 128, Encoding.UTF8)) { throw new StringOutOfRangeException("State", 0, 128); } } } [JsonProperty(/*Could not decode attribute arguments.*/)] public string Details { get { return _details; } set { if (!ValidateString(value, out _details, 128, Encoding.UTF8)) { throw new StringOutOfRangeException(128); } } } [JsonProperty(/*Could not decode attribute arguments.*/)] public Timestamps Timestamps { get; set; } [JsonProperty(/*Could not decode attribute arguments.*/)] public Assets Assets { get; set; } [JsonProperty(/*Could not decode attribute arguments.*/)] public Party Party { get; set; } [JsonProperty(/*Could not decode attribute arguments.*/)] public Secrets Secrets { get; set; } [JsonProperty(/*Could not decode attribute arguments.*/)] public ActivityType Type { get; set; } [JsonProperty(/*Could not decode attribute arguments.*/)] [Obsolete("This was going to be used, but was replaced by JoinSecret instead")] private bool Instance { get; set; } public bool HasTimestamps() { if (Timestamps != null) { if (!Timestamps.Start.HasValue) { return Timestamps.End.HasValue; } return true; } return false; } public bool HasAssets() { return Assets != null; } public bool HasParty() { if (Party != null) { return Party.ID != null; } return false; } public bool HasSecrets() { if (Secrets != null) { if (Secrets.JoinSecret == null) { return Secrets.SpectateSecret != null; } return true; } return false; } internal static bool ValidateString(string str, out string result, int bytes, Encoding encoding) { result = str; if (str == null) { return true; } string str2 = str.Trim(); if (!str2.WithinLength(bytes, encoding)) { return false; } result = str2.GetNullOrString(); return true; } public static implicit operator bool(BaseRichPresence presesnce) { return presesnce != null; } internal virtual bool Matches(RichPresence other) { if (other == null) { return false; } if (State != other.State || Details != other.Details || Type != other.Type) { return false; } if (Timestamps != null) { if (other.Timestamps == null || other.Timestamps.StartUnixMilliseconds != Timestamps.StartUnixMilliseconds || other.Timestamps.EndUnixMilliseconds != Timestamps.EndUnixMilliseconds) { return false; } } else if (other.Timestamps != null) { return false; } if (Secrets != null) { if (other.Secrets == null || other.Secrets.JoinSecret != Secrets.JoinSecret || other.Secrets.MatchSecret != Secrets.MatchSecret || other.Secrets.SpectateSecret != Secrets.SpectateSecret) { return false; } } else if (other.Secrets != null) { return false; } if (Party != null) { if (other.Party == null || other.Party.ID != Party.ID || other.Party.Max != Party.Max || other.Party.Size != Party.Size || other.Party.Privacy != Party.Privacy) { return false; } } else if (other.Party != null) { return false; } if (Assets != null) { if (other.Assets == null || other.Assets.LargeImageKey != Assets.LargeImageKey || other.Assets.LargeImageText != Assets.LargeImageText || other.Assets.SmallImageKey != Assets.SmallImageKey || other.Assets.SmallImageText != Assets.SmallImageText) { return false; } } else if (other.Assets != null) { return false; } return Instance == other.Instance; } public RichPresence ToRichPresence() { RichPresence richPresence = new RichPresence(); richPresence.State = State; richPresence.Details = Details; richPresence.Type = Type; richPresence.Party = ((!HasParty()) ? Party : null); richPresence.Secrets = ((!HasSecrets()) ? Secrets : null); if (HasAssets()) { richPresence.Assets = new Assets { SmallImageKey = Assets.SmallImageKey, SmallImageText = Assets.SmallImageText, LargeImageKey = Assets.LargeImageKey, LargeImageText = Assets.LargeImageText }; } if (HasTimestamps()) { richPresence.Timestamps = new Timestamps(); if (Timestamps.Start.HasValue) { richPresence.Timestamps.Start = Timestamps.Start; } if (Timestamps.End.HasValue) { richPresence.Timestamps.End = Timestamps.End; } } return richPresence; } } [Serializable] public class Secrets { private string _matchSecret; private string _joinSecret; private string _spectateSecret; [Obsolete("This feature has been deprecated my Mason in issue #152 on the offical library. Was originally used as a Notify Me feature, it has been replaced with Join / Spectate.")] [JsonProperty(/*Could not decode attribute arguments.*/)] public string MatchSecret { get { return _matchSecret; } set { if (!BaseRichPresence.ValidateString(value, out _matchSecret, 128, Encoding.UTF8)) { throw new StringOutOfRangeException(128); } } } [JsonProperty(/*Could not decode attribute arguments.*/)] public string JoinSecret { get { return _joinSecret; } set { if (!BaseRichPresence.ValidateString(value, out _joinSecret, 128, Encoding.UTF8)) { throw new StringOutOfRangeException(128); } } } [JsonProperty(/*Could not decode attribute arguments.*/)] public string SpectateSecret { get { return _spectateSecret; } set { if (!BaseRichPresence.ValidateString(value, out _spectateSecret, 128, Encoding.UTF8)) { throw new StringOutOfRangeException(128); } } } public static Encoding Encoding => Encoding.UTF8; public static int SecretLength => 128; public static string CreateSecret(Random random) { byte[] array = new byte[SecretLength]; random.NextBytes(array); return Encoding.GetString(array); } public static string CreateFriendlySecret(Random random) { string text = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; StringBuilder stringBuilder = new StringBuilder(); for (int i = 0; i < SecretLength; i++) { stringBuilder.Append(text[random.Next(text.Length)]); } return stringBuilder.ToString(); } } [Serializable] public class Assets { private string _largeimagekey; private bool _islargeimagekeyexternal; private string _largeimagetext; private string _smallimagekey; private bool _issmallimagekeyexternal; private string _smallimagetext; private ulong? _largeimageID; private ulong? _smallimageID; [JsonProperty(/*Could not decode attribute arguments.*/)] public string LargeImageKey { get { return _largeimagekey; } set { if (!BaseRichPresence.ValidateString(value, out _largeimagekey, 256, Encoding.UTF8)) { throw new StringOutOfRangeException(256); } _islargeimagekeyexternal = _largeimagekey?.StartsWith("mp:external/") ?? false; _largeimageID = null; } } [JsonIgnore] public bool IsLargeImageKeyExternal => _islargeimagekeyexternal; [JsonProperty(/*Could not decode attribute arguments.*/)] public string LargeImageText { get { return _largeimagetext; } set { if (!BaseRichPresence.ValidateString(value, out _largeimagetext, 128, Encoding.UTF8)) { throw new StringOutOfRangeException(128); } } } [JsonProperty(/*Could not decode attribute arguments.*/)] public string SmallImageKey { get { return _smallimagekey; } set { if (!BaseRichPresence.ValidateString(value, out _smallimagekey, 256, Encoding.UTF8)) { throw new StringOutOfRangeException(256); } _issmallimagekeyexternal = _smallimagekey?.StartsWith("mp:external/") ?? false; _smallimageID = null; } } [JsonIgnore] public bool IsSmallImageKeyExternal => _issmallimagekeyexternal; [JsonProperty(/*Could not decode attribute arguments.*/)] public string SmallImageText { get { return _smallimagetext; } set { if (!BaseRichPresence.ValidateString(value, out _smallimagetext, 128, Encoding.UTF8)) { throw new StringOutOfRangeException(128); } } } [JsonIgnore] public ulong? LargeImageID => _largeimageID; [JsonIgnore] public ulong? SmallImageID => _smallimageID; internal void Merge(Assets other) { _smallimagetext = other._smallimagetext; _largeimagetext = other._largeimagetext; if (ulong.TryParse(other._largeimagekey, out var result)) { _largeimageID = result; } else { _largeimagekey = other._largeimagekey; _largeimageID = null; } if (ulong.TryParse(other._smallimagekey, out var result2)) { _smallimageID = result2; return; } _smallimagekey = other._smallimagekey; _smallimageID = null; } } [Serializable] public class Timestamps { public static Timestamps Now => new Timestamps(DateTime.UtcNow); [JsonIgnore] public DateTime? Start { get; set; } [JsonIgnore] public DateTime? End { get; set; } [JsonProperty(/*Could not decode attribute arguments.*/)] public ulong? StartUnixMilliseconds { get { if (!Start.HasValue) { return null; } return ToUnixMilliseconds(Start.Value); } set { Start = (value.HasValue ? new DateTime?(FromUnixMilliseconds(value.Value)) : null); } } [JsonProperty(/*Could not decode attribute arguments.*/)] public ulong? EndUnixMilliseconds { get { if (!End.HasValue) { return null; } return ToUnixMilliseconds(End.Value); } set { End = (value.HasValue ? new DateTime?(FromUnixMilliseconds(value.Value)) : null); } } public static Timestamps FromTimeSpan(double seconds) { return FromTimeSpan(TimeSpan.FromSeconds(seconds)); } public static Timestamps FromTimeSpan(TimeSpan timespan) { return new Timestamps { Start = DateTime.UtcNow, End = DateTime.UtcNow + timespan }; } public Timestamps() { Start = null; End = null; } public Timestamps(DateTime start) { Start = start; End = null; } public Timestamps(DateTime start, DateTime end) { Start = start; End = end; } public static DateTime FromUnixMilliseconds(ulong unixTime) { return new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddMilliseconds(Convert.ToDouble(unixTime)); } public static ulong ToUnixMilliseconds(DateTime date) { DateTime dateTime = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); return Convert.ToUInt64((date - dateTime).TotalMilliseconds); } } [Serializable] public class Party { public enum PrivacySetting { Private, Public } private string _partyid; [JsonProperty(/*Could not decode attribute arguments.*/)] public string ID { get { return _partyid; } set { _partyid = value.GetNullOrString(); } } [JsonIgnore] public int Size { get; set; } [JsonIgnore] public int Max { get; set; } [JsonProperty(/*Could not decode attribute arguments.*/)] public PrivacySetting Privacy { get; set; } [JsonProperty(/*Could not decode attribute arguments.*/)] private int[] _size { get { int num = Math.Max(1, Size); return new int[2] { num, Math.Max(num, Max) }; } set { if (value.Length != 2) { Size = 0; Max = 0; } else { Size = value[0]; Max = value[1]; } } } } public class Button { private string _label; private string _url; [JsonProperty("label")] public string Label { get { return _label; } set { if (!BaseRichPresence.ValidateString(value, out _label, 32, Encoding.UTF8)) { throw new StringOutOfRangeException(32); } } } [JsonProperty("url")] public string Url { get { return _url; } set { if (!BaseRichPresence.ValidateString(value, out _url, 512, Encoding.UTF8)) { throw new StringOutOfRangeException(512); } if (!Uri.TryCreate(_url, UriKind.Absolute, out Uri _)) { throw new ArgumentException("Url must be a valid URI"); } } } } public enum ActivityType { Playing = 0, Listening = 2, Watching = 3, Competing = 5 } public sealed class RichPresence : BaseRichPresence { [JsonProperty(/*Could not decode attribute arguments.*/)] public Button[] Buttons { get; set; } public bool HasButtons() { if (Buttons != null) { return Buttons.Length != 0; } return false; } public RichPresence WithState(string state) { base.State = state; return this; } public RichPresence WithDetails(string details) { base.Details = details; return this; } public RichPresence WithType(ActivityType type) { base.Type = type; return this; } public RichPresence WithTimestamps(Timestamps timestamps) { base.Timestamps = timestamps; return this; } public RichPresence WithAssets(Assets assets) { base.Assets = assets; return this; } public RichPresence WithParty(Party party) { base.Party = party; return this; } public RichPresence WithSecrets(Secrets secrets) { base.Secrets = secrets; return this; } public RichPresence Clone() { return new RichPresence { State = ((_state != null) ? (_state.Clone() as string) : null), Details = ((_details != null) ? (_details.Clone() as string) : null), Type = base.Type, Buttons = ((!HasButtons()) ? null : (Buttons.Clone() as Button[])), Secrets = ((!HasSecrets()) ? null : new Secrets { JoinSecret = ((base.Secrets.JoinSecret != null) ? (base.Secrets.JoinSecret.Clone() as string) : null), SpectateSecret = ((base.Secrets.SpectateSecret != null) ? (base.Secrets.SpectateSecret.Clone() as string) : null) }), Timestamps = ((!HasTimestamps()) ? null : new Timestamps { Start = base.Timestamps.Start, End = base.Timestamps.End }), Assets = ((!HasAssets()) ? null : new Assets { LargeImageKey = ((base.Assets.LargeImageKey != null) ? (base.Assets.LargeImageKey.Clone() as string) : null), LargeImageText = ((base.Assets.LargeImageText != null) ? (base.Assets.LargeImageText.Clone() as string) : null), SmallImageKey = ((base.Assets.SmallImageKey != null) ? (base.Assets.SmallImageKey.Clone() as string) : null), SmallImageText = ((base.Assets.SmallImageText != null) ? (base.Assets.SmallImageText.Clone() as string) : null) }), Party = ((!HasParty()) ? null : new Party { ID = base.Party.ID, Size = base.Party.Size, Max = base.Party.Max, Privacy = base.Party.Privacy }) }; } internal RichPresence Merge(BaseRichPresence presence) { _state = presence.State; _details = presence.Details; base.Type = presence.Type; base.Party = presence.Party; base.Timestamps = presence.Timestamps; base.Secrets = presence.Secrets; if (presence.HasAssets()) { if (!HasAssets()) { base.Assets = presence.Assets; } else { base.Assets.Merge(presence.Assets); } } else { base.Assets = null; } return this; } internal override bool Matches(RichPresence other) { if (!base.Matches(other)) { return false; } if ((Buttons == null) ^ (other.Buttons == null)) { return false; } if (Buttons != null) { if (Buttons.Length != other.Buttons.Length) { return false; } for (int i = 0; i < Buttons.Length; i++) { Button button = Buttons[i]; Button button2 = other.Buttons[i]; if (button.Label != button2.Label || button.Url != button2.Url) { return false; } } } return true; } public static implicit operator bool(RichPresence presesnce) { return presesnce != null; } } internal sealed class RichPresenceResponse : BaseRichPresence { [JsonProperty("application_id")] public string ClientID { get; private set; } [JsonProperty("name")] public string Name { get; private set; } } public class User { public enum AvatarFormat { PNG, JPEG, WebP, GIF } public enum AvatarSize { x16 = 0x10, x32 = 0x20, x64 = 0x40, x128 = 0x80, x256 = 0x100, x512 = 0x200, x1024 = 0x400, x2048 = 0x800 } [Flags] public enum Flag { None = 0, Employee = 1, Partner = 2, HypeSquad = 4, BugHunter = 8, HouseBravery = 0x40, HouseBrilliance = 0x80, HouseBalance = 0x100, EarlySupporter = 0x200, TeamUser = 0x400 } public enum PremiumType { None, NitroClassic, Nitro } [JsonProperty("id")] public ulong ID { get; private set; } [JsonProperty("username")] public string Username { get; private set; } [JsonProperty("discriminator")] [Obsolete("Discord no longer uses discriminators.")] public int Discriminator { get; private set; } [JsonProperty("global_name")] public string DisplayName { get; private set; } [JsonProperty("avatar")] public string Avatar { get; private set; } [JsonProperty(/*Could not decode attribute arguments.*/)] public Flag Flags { get; private set; } [JsonProperty(/*Could not decode attribute arguments.*/)] public PremiumType Premium { get; private set; } public string CdnEndpoint { get; private set; } internal User() { CdnEndpoint = "cdn.discordapp.com"; } internal void SetConfiguration(Configuration configuration) { CdnEndpoint = configuration.CdnHost; } public string GetAvatarURL(AvatarFormat format) { return GetAvatarURL(format, AvatarSize.x128); } public string GetAvatarURL(AvatarFormat format, AvatarSize size) { string text = $"/avatars/{ID}/{Avatar}"; if (string.IsNullOrEmpty(Avatar)) { if (format != 0) { throw new BadImageFormatException("The user has no avatar and the requested format " + format.ToString() + " is not supported. (Only supports PNG)."); } int num = (int)((ID >> 22) % 6); if (Discriminator > 0) { num = Discriminator % 5; } text = $"/embed/avatars/{num}"; } return $"https://{CdnEndpoint}{text}{GetAvatarExtension(format)}?size={(int)size}"; } public string GetAvatarExtension(AvatarFormat format) { return "." + format.ToString().ToLowerInvariant(); } public override string ToString() { if (!string.IsNullOrEmpty(DisplayName)) { return DisplayName; } if (Discriminator != 0) { return Username + "#" + Discriminator.ToString("D4"); } return Username; } } } namespace DiscordRPC.RPC { internal class RpcConnection : IDisposable { public static readonly int VERSION = 1; public static readonly int POLL_RATE = 1000; private static readonly bool CLEAR_ON_SHUTDOWN = true; private static readonly bool LOCK_STEP = false; private ILogger _logger; private RpcState _state; private readonly object l_states = new object(); private Configuration _configuration; private readonly object l_config = new object(); private volatile bool aborting; private volatile bool shutdown; private string applicationID; private int processID; private long nonce; private Thread thread; private INamedPipeClient namedPipe; private int targetPipe; private readonly object l_rtqueue = new object(); private readonly uint _maxRtQueueSize; private Queue<ICommand> _rtqueue; private readonly object l_rxqueue = new object(); private readonly uint _maxRxQueueSize; private Queue<IMessage> _rxqueue; private AutoResetEvent queueUpdatedEvent = new AutoResetEvent(initialState: false); private BackoffDelay delay; public ILogger Logger { get { return _logger; } set { _logger = value; if (namedPipe != null) { namedPipe.Logger = value; } } } public RpcState State { get { lock (l_states) { return _state; } } } public Configuration Configuration { get { Configuration configuration = null; lock (l_config) { return _configuration; } } } public bool IsRunning => thread != null; public bool ShutdownOnly { get; set; } public event OnRpcMessageEvent OnRpcMessage; public RpcConnection(string applicationID, int processID, int targetPipe, INamedPipeClient client, uint maxRxQueueSize = 128u, uint maxRtQueueSize = 512u) { this.applicationID = applicationID; this.processID = processID; this.targetPipe = targetPipe; namedPipe = client; ShutdownOnly = true; Logger = new ConsoleLogger(); delay = new BackoffDelay(500, 60000); _maxRtQueueSize = maxRtQueueSize; _rtqueue = new Queue<ICommand>((int)(_maxRtQueueSize + 1)); _maxRxQueueSize = maxRxQueueSize; _rxqueue = new Queue<IMessage>((int)(_maxRxQueueSize + 1)); nonce = 0L; } private long GetNextNonce() { nonce++; return nonce; } internal void EnqueueCommand(ICommand command) { Logger.Trace("Enqueue Command: {0}", command.GetType().FullName); if (aborting || shutdown) { return; } lock (l_rtqueue) { if (_rtqueue.Count == _maxRtQueueSize) { Logger.Error("Too many enqueued commands, dropping oldest one. Maybe you are pushing new presences to fast?"); _rtqueue.Dequeue(); } _rtqueue.Enqueue(command); } } private void EnqueueMessage(IMessage message) { try { if (this.OnRpcMessage != null) { this.OnRpcMessage(this, message); } } catch (Exception ex) { Logger.Error("Unhandled Exception while processing event: {0}", ex.GetType().FullName); Logger.Error(ex.Message); Logger.Error(ex.StackTrace); } if (_maxRxQueueSize == 0) { Logger.Trace("Enqueued Message, but queue size is 0."); return; } Logger.Trace("Enqueue Message: {0}", message.Type); lock (l_rxqueue) { if (_rxqueue.Count == _maxRxQueueSize) { Logger.Warning("Too many enqueued messages, dropping oldest one."); _rxqueue.Dequeue(); } _rxqueue.Enqueue(message); } } internal IMessage DequeueMessage() { lock (l_rxqueue) { if (_rxqueue.Count == 0) { return null; } return _rxqueue.Dequeue(); } } internal IMessage[] DequeueMessages() { lock (l_rxqueue) { IMessage[] result = _rxqueue.ToArray(); _rxqueue.Clear(); return result; } } private void MainLoop() { Logger.Info("RPC Connection Started"); if (Logger.Level <= LogLevel.Trace) { Logger.Trace("============================"); Logger.Trace("Assembly: " + Assembly.GetAssembly(typeof(RichPresence)).FullName); Logger.Trace("Pipe: " + namedPipe.GetType().FullName); Logger.Trace("Platform: " + Environment.OSVersion.ToString()); Logger.Trace("applicationID: " + applicationID); Logger.Trace("targetPipe: " + targetPipe); ILogger logger = Logger; int pOLL_RATE = POLL_RATE; logger.Trace("POLL_RATE: " + pOLL_RATE); ILogger logger2 = Logger; uint maxRtQueueSize = _maxRtQueueSize; logger2.Trace("_maxRtQueueSize: " + maxRtQueueSize); ILogger logger3 = Logger; maxRtQueueSize = _maxRxQueueSize; logger3.Trace("_maxRxQueueSize: " + maxRtQueueSize); Logger.Trace("============================"); } while (!aborting && !shutdown) { try { if (namedPipe == null) { Logger.Error("Something bad has happened with our pipe client!"); aborting = true; return; } Logger.Trace("Connecting to the pipe through the {0}", namedPipe.GetType().FullName); if (namedPipe.Connect(targetPipe)) { Logger.Trace("Connected to the pipe. Attempting to establish handshake..."); EnqueueMessage(new ConnectionEstablishedMessage { ConnectedPipe = namedPipe.ConnectedPipe }); EstablishHandshake(); Logger.Trace("Connection Established. Starting reading loop..."); bool flag = true; while (flag && !aborting && !shutdown && namedPipe.IsConnected) { if (namedPipe.ReadFrame(out var frame)) { Logger.Trace("Read Payload: {0}", frame.Opcode); switch (frame.Opcode) { case Opcode.Close: { ClosePayload @object = frame.GetObject<ClosePayload>(); Logger.Warning("We have been told to terminate by discord: ({0}) {1}", @object.Code, @object.Reason); EnqueueMessage(new CloseMessage { Code = @object.Code, Reason = @object.Reason }); flag = false; break; } case Opcode.Ping: Logger.Trace("PING"); frame.Opcode = Opcode.Pong; namedPipe.WriteFrame(frame); break; case Opcode.Pong: Logger.Trace("PONG"); break; case Opcode.Frame: { if (shutdown) { Logger.Warning("Skipping frame because we are shutting down."); break; } if (frame.Data == null) { Logger.Error("We received no data from the frame so we cannot get the event payload!"); break; } EventPayload eventPayload = null; try { eventPayload = frame.GetObject<EventPayload>(); } catch (Exception ex) { Logger.Error("Failed to parse event! {0}", ex.Message); Logger.Error("Data: {0}", frame.Message); } try { if (eventPayload != null) { ProcessFrame(eventPayload); } } catch (Exception ex2) { Logger.Error("Failed to process event! {0}", ex2.Message); Logger.Error("Data: {0}", frame.Message); } break; } default: Logger.Error("Invalid opcode: {0}", frame.Opcode); flag = false; break; } } if (!aborting && namedPipe.IsConnected) { ProcessCommandQueue(); queueUpdatedEvent.WaitOne(POLL_RATE); } } Logger.Trace("Left main read loop for some reason. Aborting: {0}, Shutting Down: {1}", aborting, shutdown); } else { Logger.Error("Failed to connect for some reason."); EnqueueMessage(new ConnectionFailedMessage { FailedPipe = targetPipe }); } if (!aborting && !shutdown) { long num = delay.NextDelay(); Logger.Trace("Waiting {0}ms before attempting to connect again", num); Thread.Sleep(delay.NextDelay()); } } catch (Exception ex3) { Logger.Error("Unhandled Exception: {0}", ex3.GetType().FullName); Logger.Error(ex3.Message); Logger.Error(ex3.StackTrace); } finally { if (namedPipe.IsConnected) { Logger.Trace("Closing the named pipe."); namedPipe.Close(); } SetConnectionState(RpcState.Disconnected); } } Logger.Trace("Left Main Loop"); if (namedPipe != null) { namedPipe.Dispose(); } Logger.Info("Thread Terminated, no longer performing RPC connection."); } private void ProcessFrame(EventPayload response) { //IL_01c6: Unknown result type (might be due to invalid IL or missing references) Logger.Info("Handling Response. Cmd: {0}, Event: {1}", response.Command, response.Event); if (response.Event.HasValue && response.Event.Value == ServerEvent.Error) { Logger.Error("Error received from the RPC"); ErrorMessage @object = response.GetObject<ErrorMessage>(); Logger.Error("Server responded with an error message: ({0}) {1}", @object.Code.ToString(), @object.Message); EnqueueMessage(@object); } else if (State == RpcState.Connecting && response.Command == Command.Dispatch && response.Event.HasValue && response.Event.Value == ServerEvent.Ready) { Logger.Info("Connection established with the RPC"); SetConnectionState(RpcState.Connected); delay.Reset(); ReadyMessage object2 = response.GetObject<ReadyMessage>(); lock (l_config) { _configuration = object2.Configuration; object2.User.SetConfiguration(_configuration); } EnqueueMessage(object2); } else if (State == RpcState.Connected) { switch (response.Command) { case Command.Dispatch: ProcessDispatch(response); break; case Command.SetActivity: { if (response.Data == null) { EnqueueMessage(new PresenceMessage()); break; } RichPresenceResponse object3 = response.GetObject<RichPresenceResponse>(); EnqueueMessage(new PresenceMessage(object3)); break; } case Command.Subscribe: case Command.Unsubscribe: { ((Collection<JsonConverter>)(object)new JsonSerializer().Converters).Add((JsonConverter)(object)new EnumSnakeCaseConverter()); ServerEvent value = response.GetObject<EventPayload>().Event.Value; if (response.Command == Command.Subscribe) { EnqueueMessage(new SubscribeMessage(value)); } else { EnqueueMessage(new UnsubscribeMessage(value)); } break; } case Command.SendActivityJoinInvite: Logger.Trace("Got invite response ack."); break; case Command.CloseActivityJoinRequest: Logger.Trace("Got invite response reject ack."); break; default: Logger.Error("Unkown frame was received! {0}", response.Command); break; } } else { Logger.Trace("Received a frame while we are disconnected. Ignoring. Cmd: {0}, Event: {1}", response.Command, response.Event); } } private void ProcessDispatch(EventPayload response) { if (response.Command == Command.Dispatch && response.Event.HasValue) { switch (response.Event.Value) { case ServerEvent.ActivitySpectate: { SpectateMessage object3 = response.GetObject<SpectateMessage>(); EnqueueMessage(object3); break; } case ServerEvent.ActivityJoin: { JoinMessage object2 = response.GetObject<JoinMessage>(); EnqueueMessage(object2); break; } case ServerEvent.ActivityJoinRequest: { JoinRequestMessage @object = response.GetObject<JoinRequestMessage>(); EnqueueMessage(@object); break; } default: Logger.Warning("Ignoring {0}", response.Event.Value); break; } } } private void ProcessCommandQueue() { if (State != RpcState.Connected) { return; } if (aborting) { Logger.Warning("We have been told to write a queue but we have also been aborted."); } bool flag = true; ICommand command = null; while (flag && namedPipe.IsConnected) { lock (l_rtqueue) { flag = _rtqueue.Count > 0; if (!flag) { break; } command = _rtqueue.Peek(); } if (shutdown || (!aborting && LOCK_STEP)) { flag = false; } IPayload payload = command.PreparePayload(GetNextNonce()); Logger.Trace("Attempting to send payload: {0}", payload.Command); PipeFrame frame = default(PipeFrame); if (command is CloseCommand) { SendHandwave(); Logger.Trace("Handwave sent, ending queue processing."); lock (l_rtqueue) { _rtqueue.Dequeue(); break; } } if (aborting) { Logger.Warning("- skipping frame because of abort."); lock (l_rtqueue) { _rtqueue.Dequeue(); } continue; } frame.SetObject(Opcode.Frame, payload); Logger.Trace("Sending payload: {0}", payload.Command); if (namedPipe.WriteFrame(frame)) { Logger.Trace("Sent Successfully."); lock (l_rtqueue) { _rtqueue.Dequeue(); } continue; } Logger.Warning("Something went wrong during writing!"); break; } } private void EstablishHandshake() { Logger.Trace("Attempting to establish a handshake..."); if (State != 0) { Logger.Error("State must be disconnected in order to start a handshake!"); return; } Logger.Trace("Sending Handshake..."); if (!namedPipe.WriteFrame(new PipeFrame(Opcode.Handshake, new Handshake { Version = VERSION, ClientID = applicationID }))) { Logger.Error("Failed to write a handshake."); } else { SetConnectionState(RpcState.Connecting); } } private void SendHandwave() { Logger.Info("Attempting to wave goodbye..."); if (State == RpcState.Disconnected) { Logger.Error("State must NOT be disconnected in order to send a handwave!"); } else if (!namedPipe.WriteFrame(new PipeFrame(Opcode.Close, new Handshake { Version = VERSION, ClientID = applicationID }))) { Logger.Error("failed to write a handwave."); } } public bool AttemptConnection() { Logger.Info("Attempting a new connection"); if (thread != null) { Logger.Error("Cannot attempt a new connection as the previous connection thread is not null!"); return false; } if (State != 0) { Logger.Warning("Cannot attempt a new connection as the previous connection hasn't changed state yet."); return false; } if (aborting) { Logger.Error("Cannot attempt a new connection while aborting!"); return false; } thread = new Thread(MainLoop); thread.Name = "Discord IPC Thread"; thread.IsBackground = true; thread.Start(); return true; } private void SetConnectionState(RpcState state) { Logger.Trace("Setting the connection state to {0}", state.ToString().ToSnakeCase().ToUpperInvariant()); lock (l_states) { _state = state; } } public void Shutdown() { Logger.Trace("Initiated shutdown procedure"); shutdown = true; lock (l_rtqueue) { _rtqueue.Clear(); if (CLEAR_ON_SHUTDOWN) { _rtqueue.Enqueue(new PresenceCommand { PID = processID, Presence = null }); } _rtqueue.Enqueue(new CloseCommand()); } queueUpdatedEvent.Set(); } public void Close() { if (thread == null) { Logger.Error("Cannot close as it is not available!"); return; } if (aborting) { Logger.Error("Cannot abort as it has already been aborted"); return; } if (ShutdownOnly) { Shutdown(); return; } Logger.Trace("Updating Abort State..."); aborting = true; queueUpdatedEvent.Set(); } public void Dispose() { ShutdownOnly = false; Close(); } } internal enum RpcState { Disconnected, Connecting, Connected } } namespace DiscordRPC.RPC.Payload { internal class ClosePayload : IPayload { [JsonProperty("code")] public int Code { get; set; } [JsonProperty("message")] public string Reason { get; set; } [JsonConstructor] public ClosePayload() { Code = -1; Reason = ""; } } internal enum Command { [EnumValue("DISPATCH")] Dispatch, [EnumValue("SET_ACTIVITY")] SetActivity, [EnumValue("SUBSCRIBE")] Subscribe, [EnumValue("UNSUBSCRIBE")] Unsubscribe, [EnumValue("SEND_ACTIVITY_JOIN_INVITE")] SendActivityJoinInvite, [EnumValue("CLOSE_ACTIVITY_JOIN_REQUEST")] CloseActivityJoinRequest, [Obsolete("This value is appart of the RPC API and is not supported by this library.", true)] Authorize, [Obsolete("This value is appart of the RPC API and is not supported by this library.", true)] Authenticate, [Obsolete("This value is appart of the RPC API and is not supported by this library.", true)] GetGuild, [Obsolete("This value is appart of the RPC API and is not supported by this library.", true)] GetGuilds, [Obsolete("This value is appart of the RPC API and is not supported by this library.", true)] GetChannel, [Obsolete("This value is appart of the RPC API and is not supported by this library.", true)] GetChannels, [Obsolete("This value is appart of the RPC API and is not supported by this library.", true)] SetUserVoiceSettings, [Obsolete("This value is appart of the RPC API and is not supported by this library.", true)] SelectVoiceChannel, [Obsolete("This value is appart of the RPC API and is not supported by this library.", true)] GetSelectedVoiceChannel, [Obsolete("This value is appart of the RPC API and is not supported by this library.", true)] SelectTextChannel, [Obsolete("This value is appart of the RPC API and is not supported by this library.", true)] GetVoiceSettings, [Obsolete("This value is appart of the RPC API and is not supported by this library.", true)] SetVoiceSettings, [Obsolete("This value is appart of the RPC API and is not supported by this library.", true)] CaptureShortcut } internal abstract class IPayload { [JsonProperty("cmd")] [JsonConverter(typeof(EnumSnakeCaseConverter))] public Command Command { get; set; } [JsonProperty("nonce")] public string Nonce { get; set; } protected IPayload() { } protected IPayload(long nonce) { Nonce = nonce.ToString(); } public override string ToString() { return $"Payload || Command: {Command}, Nonce: {Nonce}"; } } internal class ArgumentPayload : IPayload { [JsonProperty(/*Could not decode attribute arguments.*/)] public JObject Arguments { get; set; } public ArgumentPayload() { Arguments = null; } public ArgumentPayload(long nonce) : base(nonce) { Arguments = null; } public ArgumentPayload(object args, long nonce) : base(nonce) { SetObject(args); } public void SetObject(object obj) { Arguments = JObject.FromObject(obj); } public T GetObject<T>() { return ((JToken)Arguments).ToObject<T>(); } public override string ToString() { return "Argument " + base.ToString(); } } internal class EventPayload : IPayload { [JsonProperty(/*Could not decode attribute arguments.*/)] public JObject Data { get; set; } [JsonProperty("evt")] [JsonConverter(typeof(EnumSnakeCaseConverter))] public ServerEvent? Event { get; set; } public EventPayload() { Data = null; } public EventPayload(long nonce) : base(nonce) { Data = null; } public T GetObject<T>() { if (Data == null) { return default(T); } return ((JToken)Data).ToObject<T>(); } public override string ToString() { return "Event " + base.ToString() + ", Event: " + (Event.HasValue ? Event.ToString() : "N/A"); } } internal enum ServerEvent { [EnumValue("READY")] Ready, [EnumValue("ERROR")] Error, [EnumValue("ACTIVITY_JOIN")] ActivityJoin, [EnumValue("ACTIVITY_SPECTATE")] ActivitySpectate, [EnumValue("ACTIVITY_JOIN_REQUEST")] ActivityJoinRequest } } namespace DiscordRPC.RPC.Commands { internal class CloseCommand : ICommand { [JsonProperty("close_reason")] public string value = "Unity 5.5 doesn't handle thread aborts. Can you please close me discord?"; [JsonProperty("pid")] public int PID { get; set; } public IPayload PreparePayload(long nonce) { return new ArgumentPayload { Command = Command.Dispatch, Nonce = null, Arguments = null }; } } internal interface ICommand { IPayload PreparePayload(long nonce); } internal class PresenceCommand : ICommand { [JsonProperty("pid")] public int PID { get; set; } [JsonProperty("activity")] public RichPresence Presence { get; set; } public IPayload PreparePayload(long nonce) { return new ArgumentPayload(this, nonce) { Command = Command.SetActivity }; } } internal class RespondCommand : ICommand { [JsonProperty("user_id")] public string UserID { get; set; } [JsonIgnore] public bool Accept { get; set; } public IPayload PreparePayload(long nonce) { return new ArgumentPayload(this, nonce) { Command = (Accept ? Command.SendActivityJoinInvite : Command.CloseActivityJoinRequest) }; } } internal class SubscribeCommand : ICommand { public ServerEvent Event { get; set; } public bool IsUnsubscribe { get; set; } public IPayload PreparePayload(long nonce) { return new EventPayload(nonce) { Command = (IsUnsubscribe ? Command.Unsubscribe : Command.Subscribe), Event = Event }; } } } namespace DiscordRPC.Registry { internal interface IUriSchemeCreator { bool RegisterUriScheme(UriSchemeRegister register); } internal class MacUriSchemeCreator : IUriSchemeCreator { private ILogger logger; public MacUriSchemeCreator(ILogger logger) { this.logger = logger; } public bool RegisterUriScheme(UriSchemeRegister register) { string executablePath = register.ExecutablePath; if (string.IsNullOrEmpty(executablePath)) { logger.Error("Failed to register because the application could not be located."); return false; } logger.Trace("Registering Steam Command"); string text = executablePath; if (register.UsingSteamApp) { text = "steam://rungameid/" + register.SteamAppID; } else { logger.Warning("This library does not fully support MacOS URI Scheme Registration."); } string text2 = "~/Library/Application Support/discord/games"; if (!Directory.CreateDirectory(text2).Exists) { logger.Error("Failed to register because {0} does not exist", text2); return false; } string text3 = text2 + "/" + register.ApplicationID + ".json"; File.WriteAllText(text3, "{ \"command\": \"" + text + "\" }"); logger.Trace("Registered {0}, {1}", text3, text); return true; } } internal class UnixUriSchemeCreator : IUriSchemeCreator { private ILogger logger; public UnixUriSchemeCreator(ILogger logger) { this.logger = logger; } public bool RegisterUriScheme(UriSchemeRegister register) { string environmentVariable = Environment.GetEnvironmentVariable("HOME"); if (string.IsNullOrEmpty(environmentVariable)) { logger.Error("Failed to register because the HOME variable was not set."); return false; } string executablePath = register.ExecutablePath; if (string.IsNullOrEmpty(executablePath)) { logger.Error("Failed to register because the application was not located."); return false; } string text = null; text = ((!register.UsingSteamApp) ? executablePath : ("xdg-open steam://rungameid/" + register.SteamAppID)); string text2 = $"[Desktop Entry]\nName=Game {register.ApplicationID}\nExec={text} %u\nType=Application\nNoDisplay=true\nCategories=Discord;Games;\nMimeType=x-scheme-handler/discord-{register.ApplicationID}"; string text3 = "/discord-" + register.ApplicationID + ".desktop"; string text4 = environmentVariable + "/.local/share/applications"; if (!Directory.CreateDirectory(text4).Exists) { logger.Error("Failed to register because {0} does not exist", text4); return false; } File.WriteAllText(text4 + text3, text2); if (!RegisterMime(register.ApplicationID)) { logger.Error("Failed to register because the Mime failed."); return false; } logger.Trace("Registered {0}, {1}, {2}", text4 + text3, text2, text); return true; } private bool RegisterMime(string appid) { string arguments = string.Format("default discord-{0}.desktop x-scheme-handler/discord-{0}", appid); Process process = Process.Start("xdg-mime", arguments); process.WaitForExit(); return process.ExitCode >= 0; } } internal class UriSchemeRegister { private ILogger _logger; public string ApplicationID { get; set; } public string SteamAppID { get; set; } public bool UsingSteamApp { get { if (!string.IsNullOrEmpty(SteamAppID)) { return SteamAppID != ""; } return false; } } public string ExecutablePath { get; set; } public UriSchemeRegister(ILogger logger, string applicationID, string steamAppID = null, string executable = null) { _logger = logger; ApplicationID = applicationID.Trim(); SteamAppID = steamAppID?.Trim(); ExecutablePath = executable ?? GetApplicationLocation(); } public bool RegisterUriScheme() { IUriSchemeCreator uriSchemeCreator = null; switch (Environment.OSVersion.Platform) { case PlatformID.Win32S: case PlatformID.Win32Windows: case PlatformID.Win32NT: case PlatformID.WinCE: _logger.Trace("Creating Windows Scheme Creator"); uriSchemeCreator = new WindowsUriSchemeCreator(_logger); break; case PlatformID.Unix: if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) { _logger.Trace("Creating MacOSX Scheme Creator"); uriSchemeCreator = new MacUriSchemeCreator(_logger); } else { _logger.Trace("Creating Unix Scheme Creator"); uriSchemeCreator = new UnixUriSchemeCreator(_logger); } break; default: _logger.Error("Unkown Platform: {0}", Environment.OSVersion.Platform); throw new PlatformNotSupportedException("Platform does not support registration."); } if (uriSchemeCreator.RegisterUriScheme(this)) { _logger.Info("URI scheme registered."); return true; } return false; } public static string GetApplicationLocation() { return Process.GetCurrentProcess().MainModule.FileName; } } internal class WindowsUriSchemeCreator : IUriSchemeCreator { private ILogger logger; public WindowsUriSchemeCreator(ILogger logger) { this.logger = logger; } public bool RegisterUriScheme(UriSchemeRegister register) { if (Environment.OSVersion.Platform == PlatformID.Unix || Environment.OSVersion.Platform == PlatformID.MacOSX) { throw new PlatformNotSupportedException("URI schemes can only be registered on Windows"); } string executablePath = register.ExecutablePath; if (executablePath == null) { logger.Error("Failed to register application because the location was null."); return false; } string scheme = "discord-" + register.ApplicationID; string friendlyName = "Run game " + register.ApplicationID + " protocol"; string defaultIcon = executablePath; string command = executablePath; if (register.UsingSteamApp) { string steamLocation = GetSteamLocation(); if (steamLocation != null) { command = $"\"{steamLocation}\" steam://rungameid/{register.SteamAppID}"; } } CreateUriScheme(scheme, friendlyName, defaultIcon, command); return true; } private void CreateUriScheme(string scheme, string friendlyName, string defaultIcon, string command) { using (RegistryKey registryKey = Microsoft.Win32.Registry.CurrentUser.CreateSubKey("SOFTWARE\\Classes\\" + scheme)) { registryKey.SetValue("", "URL:" + friendlyName); registryKey.SetValue("URL Protocol", ""); using (RegistryKey registryKey2 = registryKey.CreateSubKey("DefaultIcon")) { registryKey2.SetValue("", defaultIcon); } using RegistryKey registryKey3 = registryKey.CreateSubKey("shell\\open\\command"); registryKey3.SetValue("", command); } logger.Trace("Registered {0}, {1}, {2}", scheme, friendlyName, command); } public string GetSteamLocation() { using RegistryKey registryKey = Microsoft.Win32.Registry.CurrentUser.OpenSubKey("Software\\Valve\\Steam"); if (registryKey == null) { return null; } return registryKey.GetValue("SteamExe") as string; } } } namespace DiscordRPC.Message { public class CloseMessage : IMessage { public override MessageType Type => MessageType.Close; public string Reason { get; internal set; } public int Code { get; internal set; } internal CloseMessage() { } internal CloseMessage(string reason) { Reason = reason; } } public class ConnectionEstablishedMessage : IMessage { public override MessageType Type => MessageType.ConnectionEstablished; public int ConnectedPipe { get; internal set; } } public class ConnectionFailedMessage : IMessage { public override MessageType Type => MessageType.ConnectionFailed; public int FailedPipe { get; internal set; } } public class ErrorMessage : IMessage { public override MessageType Type => MessageType.Error; [JsonProperty("code")] public ErrorCode Code { get; internal set; } [JsonProperty("message")] public string Message { get; internal set; } } public enum ErrorCode { Success = 0, PipeException = 1, ReadCorrupt = 2, NotImplemented = 10, UnkownError = 1000, InvalidPayload = 4000, InvalidCommand = 4002, InvalidEvent = 4004 } public abstract class IMessage { private DateTime _timecreated; public abstract MessageType Type { get; } public DateTime TimeCreated => _timecreated; public IMessage() { _timecreated = DateTime.Now; } } public class JoinMessage : IMessage { public override MessageType Type => MessageType.Join; [JsonProperty("secret")] public string Secret { get; internal set; } } public class JoinRequestMessage : IMessage { public override MessageType Type => MessageType.JoinRequest; [JsonProperty("user")] public User User { get; internal set; } } public enum MessageType { Ready, Close, Error, PresenceUpdate, Subscribe, Unsubscribe, Join, Spectate, JoinRequest, ConnectionEstablished, ConnectionFailed } public class PresenceMessage : IMessage { public override MessageType Type => MessageType.PresenceUpdate; public BaseRichPresence Presence { get; internal set; } public string Name { get; internal set; } public string ApplicationID { get; internal set; } internal PresenceMessage() : this(null) { } internal PresenceMessage(RichPresenceResponse rpr) { if (rpr == null) { Presence = null; Name = "No Rich Presence"; ApplicationID = ""; } else { Presence = rpr; Name = rpr.Name; ApplicationID = rpr.ClientID; } } } public class ReadyMessage : IMessage { public override MessageType Type => MessageType.Ready; [JsonProperty("config")] public Configuration Configuration { get; set; } [JsonProperty("user")] public User User { get; set; } [JsonProperty("v")] public int Version { get; set; } } public class SpectateMessage : JoinMessage { public override MessageType Type => MessageType.Spectate; } public class SubscribeMessage : IMessage { public override MessageType Type => MessageType.Subscribe; public EventType Event { get; internal set; } internal SubscribeMessage(ServerEvent evt) { switch (evt) { default: Event = EventType.Join; break; case ServerEvent.ActivityJoinRequest: Event = EventType.JoinRequest; break; case ServerEvent.ActivitySpectate: Event = EventType.Spectate; break; } } } public class UnsubscribeMessage : IMessage { public override MessageType Type => MessageType.Unsubscribe; public EventType Event { get; internal set; } internal UnsubscribeMessage(ServerEvent evt) { switch (evt) { default: Event = EventType.Join; break; case ServerEvent.ActivityJoinRequest: Event = EventType.JoinRequest; break; case ServerEvent.ActivitySpectate: Event = EventType.Spectate; break; } } } } namespace DiscordRPC.Logging { public class ConsoleLogger : ILogger { public LogLevel Level { get; set; } public bool Coloured { get; set; } [Obsolete("Use Coloured")] public bool Colored { get { return Coloured; } set { Coloured = value; } } public ConsoleLogger() { Level = LogLevel.Info; Coloured = false; } public ConsoleLogger(LogLevel level) : this() { Level = level; } public ConsoleLogger(LogLevel level, bool coloured) { Level = level; Coloured = coloured; } public void Trace(string message, params object[] args) { if (Level <= LogLevel.Trace) { if (Coloured) { Console.ForegroundColor = ConsoleColor.Gray; } string text = "TRACE: " + message; if (args.Length != 0) { Console.WriteLine(text, args); } else { Console.WriteLine(text); } } } public void Info(string message, params object[] args) { if (Level <= LogLevel.Info) { if (Coloured) { Console.ForegroundColor = ConsoleColor.White; } string text = "INFO: " + message; if (args.Length != 0) { Console.WriteLine(text, args); } else { Console.WriteLine(text); } } } public void Warning(string message, params object[] args) { if (Level <= LogLevel.Warning) { if (Coloured) { Console.ForegroundColor = ConsoleColor.Yellow; } string text = "WARN: " + message; if (args.Length != 0) { Console.WriteLine(text, args); } else { Console.WriteLine(text); } } } public void Error(string message, params object[] args) { if (Level <= LogLevel.Error) { if (Coloured) { Console.ForegroundColor = ConsoleColor.Red; } string text = "ERR : " + message; if (args.Length != 0) { Console.WriteLine(text, args); } else { Console.WriteLine(text); } } } } public class FileLogger : ILogger { private object filelock; public LogLevel Level { get; set; } public string File { get; set; } public FileLogger(string path) : this(path, LogLevel.Info) { } public FileLogger(string path, LogLevel level) { Level = level; File = path; filelock = new object(); } public void Trace(string message, params object[] args) { if (Level > LogLevel.Trace) { return; } lock (filelock) { System.IO.File.AppendAllText(File, "\r\nTRCE: " + ((args.Length != 0) ? string.Format(message, args) : message)); } } public void Info(string message, params object[] args) { if (Level > LogLevel.Info) { return; } lock (filelock) { System.IO.File.AppendAllText(File, "\r\nINFO: " + ((args.Length != 0) ? string.Format(message, args) : message)); } } public void Warning(string message, params object[] args) { if (Level > LogLevel.Warning) { return; } lock (filelock) { System.IO.File.AppendAllText(File, "\r\nWARN: " + ((args.Length != 0) ? string.Format(message, args) : message)); } } public void Error(string message, params object[] args) { if (Level > LogLevel.Error) { return; } lock (filelock) { System.IO.File.AppendAllText(File, "\r\nERR : " + ((args.Length != 0) ? string.Format(message, args) : message)); } } } public interface ILogger { LogLevel Level { get; set; } void Trace(string message, params object[] args); void Info(string message, params object[] args); void Warning(string message, params object[] args); void Error(string message, params object[] args); } public enum LogLevel { Trace = 1, Info = 2, Warning = 3, Error = 4, None = 256 } public class NullLogger : ILogger { public LogLevel Level { get; set; } public void Trace(string message, params object[] args) { } public void Info(string message, params object[] args) { } public void Warning(string message, params object[] args) { } public void Error(string message, params object[] args) { } } } namespace DiscordRPC.IO { internal class Handshake { [JsonProperty("v")] public int Version { get; set; } [JsonProperty("client_id")] public string ClientID { get; set; } } public interface INamedPipeClient : IDisposable { ILogger Logger { get; set; } bool IsConnected { get; } int ConnectedPipe { get; } bool Connect(int pipe); bool ReadFrame(out PipeFrame frame); bool WriteFrame(PipeFrame frame); void Close(); } public sealed class ManagedNamedPipeClient : INamedPipeClient, IDisposable { private const string PIPE_NAME = "discord-ipc-{0}"; private int _connectedPipe; private NamedPipeClientStream _stream; private byte[] _buffer = new byte[PipeFrame.MAX_SIZE]; private Queue<PipeFrame> _framequeue = new Queue<PipeFrame>(); private object _framequeuelock = new object(); private volatile bool _isDisposed; private volatile bool _isClosed = true; private object l_stream = new object(); public ILogger Logger { get; set; } public bool IsConnected { get { if (_isClosed) { return false; } lock (l_stream) { return _stream != null && _stream.IsConnected; } } } public int ConnectedPipe => _connectedPipe; public ManagedNamedPipeClient() { _buffer = new byte[PipeFrame.MAX_SIZE]; Logger = new NullLogger(); _stream = null; } public bool Connect(int pipe) { Logger.Trace("ManagedNamedPipeClient.Connection({0})", pipe); if (_isDisposed) { throw new ObjectDisposedException("NamedPipe"); } if (pipe > 9) { throw new ArgumentOutOfRangeException("pipe", "Argument cannot be greater than 9"); } if (pipe < 0) { for (int i = 0; i < 10; i++) { if (AttemptConnection(i) || AttemptConnection(i, isSandbox: true)) { BeginReadStream(); return true; } } } else if (AttemptConnection(pipe) || AttemptConnection(pipe, isSandbox: true)) { BeginReadStream(); return true; } return false; } private bool AttemptConnection(int pipe, bool isSandbox = false) { if (_isDisposed) { throw new ObjectDisposedException("_stream"); } string text = (isSandbox ? GetPipeSandbox() : ""); if (isSandbox && text == null) { Logger.Trace("Skipping sandbox connection."); return false; } Logger.Trace("Connection Attempt {0} ({1})", pipe, text); string pipeName = GetPipeName(pipe, text); try { lock (l_stream) { Logger.Info("Attempting to connect to '{0}'", pipeName); _stream = new NamedPipeClientStream(".", pipeName, PipeDirection.InOut, PipeOptions.Asynchronous); _stream.Connect(0); Logger.Trace("Waiting for connection..."); do { Thread.Sleep(10); } while (!_stream.IsConnected); } Logger.Info("Connected to '{0}'", pipeName); _connectedPipe = pipe; _isClosed = false; } catch (Exception ex) { Logger.Error("Failed connection to {0}. {1}", pipeName, ex.Message); Close(); } Logger.Trace("Done. Result: {0}", _isClosed); return !_isClosed; } private void BeginReadStream() { if (_isClosed) { return; } try { lock (l_stream) { if (_stream != null && _stream.IsConnected) { Logger.Trace("Begining Read of {0} bytes", _buffer.Length); _stream.BeginRead(_buffer, 0, _buffer.Length, EndReadStream, _stream.IsConnected); } } } catch (ObjectDisposedException) { Logger.Warning("Attempted to start reading from a disposed pipe"); } catch (InvalidOperationException) { Logger.Warning("Attempted to start reading from a closed pipe"); } catch (Exception ex3) { Logger.Error("An exception occured while starting to read a stream: {0}", ex3.Message); Logger.Error(ex3.StackTrace); } } private void EndReadStream(IAsyncResult callback) { Logger.Trace("Ending Read"); int num = 0; try { lock (l_stream) { if (_stream == null || !_stream.IsConnected) { return; } num = _stream.EndRead(callback); } } catch (IOException) { Logger.Warning("Attempted to end reading from a closed pipe"); return; } catch (NullReferenceException) { Logger.Warning("Attempted to read from a null pipe"); return; } catch (ObjectDisposedException) { Logger.Warning("Attemped to end reading from a disposed pipe"); return; } catch (Exception ex4) { Logger.Error("An exception occured while ending a read of a stream: {0}", ex4.Message); Logger.Error(ex4.StackTrace); return; } Logger.Trace("Read {0} bytes", num); if (num > 0) { using MemoryStream stream = new MemoryStream(_buffer, 0, num); try { PipeFrame item = default(PipeFrame); if (item.ReadStream(stream)) { Logger.Trace("Read a frame: {0}", item.Opcode); lock (_framequeuelock) { _framequeue.Enqueue(item); } } else { Logger.Error("Pipe failed to read from the data received by the stream."); Close(); } } catch (Exception ex5) { Logger.Error("A exception has occured while trying to parse the pipe data: {0}", ex5.Message); Close(); } } else if (IsUnix()) { Logger.Error("Empty frame was read on {0}, aborting.", Environment.OSVersion); Close(); } else { Logger.Warning("Empty frame was read. Please send report to Lachee."); } if (!_isClosed && IsConnected) { Logger.Trace("Starting another read"); BeginReadStream(); } } public bool ReadFrame(out PipeFrame frame) { if (_isDisposed) { throw new ObjectDisposedException("_stream"); } lock (_framequeuelock) { if (_framequeue.Count == 0) { frame = default(PipeFrame); return false; } frame = _framequeue.Dequeue(); return true; } } public bool WriteFrame(PipeFrame frame) { if (_isDisposed) { throw new ObjectDisposedException("_stream"); } if (_isClosed || !IsConnected) { Logger.Error("Failed to write frame because the stream is closed"); return false; } try { frame.WriteStream(_stream); return true; } catch (IOException ex) { Logger.Error("Failed to write frame because of a IO Exception: {0}", ex.Message); } catch (ObjectDisposedException) { Logger.Warning("Failed to write frame as the stream was already disposed"); } catch (InvalidOperationException) { Logger.Warning("Failed to write frame because of a invalid operation"); } return false; } public void Close() { if (_isClosed) { Logger.Warning("Tried to close a already closed pipe."); return; } try { lock (l_stream) { if (_stream != null) { try { _stream.Flush(); _stream.Dispose(); } catch (Exception) { } _stream = null; _isClosed = true; } else { Logger.Warning("Stream was closed, but no stream was available to begin with!"); } } } catch (ObjectDisposedException) { Logger.Warning("Tried to dispose already disposed stream"); } finally { _isClosed = true; _connectedPipe = -1; } } public void Dispose() { if (_isDisposed) { return; } if (!_isClosed) { Close(); } lock (l_stream) { if (_stream != null) { _stream.Dispose(); _stream = null; } } _isDisposed = true; } public static string GetPipeName(int pipe, string sandbox) { if (!IsUnix()) { return sandbox + $"discord-ipc-{pipe}"; } return Path.Combine(GetTemporaryDirectory(), sandbox + $"discord-ipc-{pipe}"); } public static string GetPipeName(int pipe) { return GetPipeName(pipe, ""); } public static string GetPipeSandbox() { if (Environment.OSVersion.Platform != PlatformID.Unix) { return null; } return "snap.discord/"; } private static string GetTemporaryDirectory() { object obj = null ?? Environment.GetEnvironmentVariable("XDG_RUNTIME_DIR"); if (obj == null) { obj = Environment.GetEnvironmentVariable("TMPDIR"); } if (obj == null) { obj = Environment.GetEnvironmentVariable("TMP"); } if (obj == null) { obj = Environment.GetEnvironmentVariable("TEMP"); } if (obj == null) { obj = "/tmp"; } return (string)obj; } public static bool IsUnix() { PlatformID platform = Environment.OSVersion.Platform; if (platform != PlatformID.Unix && platform != PlatformID.MacOSX) { return false; } return true; } } public enum Opcode : uint { Handshake, Frame, Close, Ping, Pong } public struct PipeFrame : IEquatable<PipeFrame> { public static readonly int MAX_SIZE = 16384; public Opcode Opcode { get; set; } public uint Length => (uint)Data.Length; public byte[] Data { get; set; } public string Message { get { return GetMessage(); } set { SetMessage(value); } } public Encoding MessageEncoding => Encoding.UTF8; public PipeFrame(Opcode opcode, object data) { Opcode = opcode; Data = null; SetObject(data); } private void SetMessage(string str) { Data = MessageEncoding.GetBytes(str); } private string GetMessage() { return MessageEncoding.GetString(Data); } public void SetObject(object obj) { string message = JsonConvert.SerializeObject(obj); SetMessage(message); } public void SetObject(Opcode opcode, object obj) { Opcode = opcode; SetObject(obj); } public T GetObject<T>() { return JsonConvert.DeserializeObject<T>(GetMessage()); } public bool ReadStream(Stream stream) { if (!TryReadUInt32(stream, out var value)) { return false; } if (!TryReadUInt32(stream, out var value2)) { return false; } uint num = value2; using MemoryStream memoryStream = new MemoryStream(); uint num2 = (uint)Min(2048, value2); byte[] array = new byte[num2]; int count; while ((count = stream.Read(array, 0, Min(array.Length, num))) > 0) { num -= num2; memoryStream.Write(array, 0, count); } byte[] array2 = memoryStream.ToArray(); if (array2.LongLength != value2) { return false; } Opcode = (Opcode)value; Data = array2; return true; } private int Min(int a, uint b) { if (b >= a) { return a; } return (int)b; } private bool TryReadUInt32(Stream stream, out uint value) { byte[] array = new byte[4]; if (stream.Read(array, 0, array.Length) != 4) { value = 0u; return false; } value = BitConverter.ToUInt32(array, 0); return true; } public void WriteStream(Stream stream) { byte[] bytes = BitConverter.GetBytes((uint)Opcode); byte[] bytes2 = BitConverter.GetBytes(Length); byte[] array = new byte[bytes.Length + bytes2.Length + Data.Length]; bytes.CopyTo(array, 0); bytes2.CopyTo(array, bytes.Length); Data.CopyTo(array, bytes.Length + bytes2.Length); stream.Write(array, 0, array.Length); } public bool Equals(PipeFrame other) { if (Opcode == other.Opcode && Length == other.Length) { return Data == other.Data; } return false; } } } namespace DiscordRPC.Helper { internal class BackoffDelay { private int _current; private int _fails; public int Maximum { get; private set; } public int Minimum { get; private set; } public int Current => _current; public int Fails => _fails; public Random Random { get; set; } private BackoffDelay() { } public BackoffDelay(int min, int max) : this(min, max, new Random()) { } public BackoffDelay(int min, int max, Random random) { Minimum = min; Maximum = max; _current = min; _fails = 0; Random = random; } public void Reset() { _fails = 0; _current = Minimum; } public int NextDelay() { _fails++; double num = (float)(Maximum - Minimum) / 100f; _current = (int)Math.Floor(num * (double)_fails) + Minimum; return Math.Min(Math.Max(_current, Minimum), Maximum); } } public static class StringTools { public static string GetNullOrString(this string str) { if (str.Length != 0 && !string.IsNullOrEmpty(str.Trim())) { return str; } return null; } public static bool WithinLength(this string str, int bytes) { return str.WithinLength(bytes, Encoding.UTF8); } public static bool WithinLength(this string str, int bytes, Encoding encoding) { return encoding.GetByteCount(str) <= bytes; } public static string ToCamelCase(this string str) { return (from s in str?.ToLowerInvariant().Split(new string[2] { "_", " " }, StringSplitOptions.RemoveEmptyEntries) select char.ToUpper(s[0]) + s.Substring(1, s.Length - 1)).Aggregate(string.Empty, (string s1, string s2) => s1 + s2); } public static string ToSnakeCase(this string str) { if (str == null) { return null; } return string.Concat(str.Select((char x, int i) => (i <= 0 || !char.IsUpper(x)) ? x.ToString() : ("_" + x)).ToArray()).ToUpperInvariant(); } } } namespace DiscordRPC.Exceptions { public class BadPresenceException : Exception { internal BadPresenceException(string message) : base(message) { } } public class InvalidConfigurationException : Exception { internal InvalidConfigurationException(string message) : base(message) { } } [Obsolete("Not actually used anywhere")] public class InvalidPipeException : Exception { internal InvalidPipeException(string message) : base(message) { } } public class StringOutOfRangeException : Exception { public int MaximumLength { get; private set; } public int MinimumLength { get; private set; } internal StringOutOfRangeException(string message, int min, int max) : base(message) { MinimumLength = min; MaximumLength = max; } internal StringOutOfRangeException(int minumum, int max) : this($"Length of string is out of range. Expected a value between {minumum} and {max}", minumum, max) { } internal StringOutOfRangeException(int max) : this($"Length of string is out of range. Expected a value with a maximum length of {max}", 0, max) { } } public class UninitializedException : Exception { internal UninitializedException(string message) : base(message) { } internal UninitializedException() : this("Cannot perform action because the client has not been initialized yet or has been deinitialized.") { } } } namespace DiscordRPC.Events { public delegate void OnReadyEvent(object sender, ReadyMessage args); public delegate void OnCloseEvent(object sender, CloseMessage args); public delegate void OnErrorEvent(object sender, ErrorMessage args); public delegate void OnPresenceUpdateEvent(object sender, PresenceMessage args); public delegate void OnSubscribeEvent(object sender, SubscribeMessage args); public delegate void OnUnsubscribeEvent(object sender, UnsubscribeMessage args); public delegate void OnJoinEvent(object sender, JoinMessage args); public delegate void OnSpectateEvent(object sender, SpectateMessage args); public delegate void OnJoinRequestedEvent(object sender, JoinRequestMessage args); public delegate void OnConnectionEstablishedEvent(object sender, ConnectionEstablishedMessage args); public delegate void OnConnectionFailedEvent(object sender, ConnectionFailedMessage args); public delegate void OnRpcMessageEvent(object sender, IMessage msg); } namespace DiscordRPC.Converters { internal class EnumSnakeCaseConverter : JsonConverter { public override bool CanConvert(Type objectType) { return objectType.IsEnum; } public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { if (reader.Value == null) { return null; } object obj = null; if (TryParseEnum(objectType, (string)reader.Value, out obj)) { return obj; } return existingValue; } public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { Type type = value.GetType(); string text = Enum.GetName(type, value); MemberInfo[] members = type.GetMembers(BindingFlags.Static | BindingFlags.Public); foreach (MemberInfo memberInfo in members) { if (memberInfo.Name.Equals(text)) { object[] customAttributes = memberInfo.GetCustomAttributes(typeof(EnumValueAttribute), inherit: true); if (customAttributes.Length != 0) { text = ((EnumValueAttribute)customAttributes[0]).Value; } } } writer.WriteValue(text); } public bool TryParseEnum(Type enumType, string str, out object obj) { if (str == null) { obj = null; return false; } Type type = enumType; if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>)) { type = type.GetGenericArguments().First(); } if (!type.IsEnum) { obj = null; return false; } MemberInfo[] members = type.GetMembers(BindingFlags.Static | BindingFlags.Public); foreach (MemberInfo memberInfo in members) { object[] customAttributes = memberInfo.GetCustomAttributes(typeof(EnumValueAttribute), inherit: true); for (int j = 0; j < customAttributes.Length; j++) { EnumValueAttribute enumValueAttribute = (EnumValueAttribute)customAttributes[j]; if (str.Equals(enumValueAttribute.Value)) { obj = Enum.Parse(type, memberInfo.Name, ignoreCase: true); return true; } } } obj = null; return false; } } internal class EnumValueAttribute : Attribute { public string Value { get; set; } public EnumValueAttribute(string value) { Value = value; } } }
plugins/Tolian-REPODiscordRichPresence/REPO Discord Rich Presence.dll
Decompiled 2 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 BepInEx.Logging; using DiscordRPC; using DiscordRPC.Events; using DiscordRPC.Logging; using DiscordRPC.Message; 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("REPO Discord Rich Presence")] [assembly: AssemblyConfiguration("Debug")] [assembly: AssemblyDescription("A template for Lethal Company")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: AssemblyInformationalVersion("1.0.0+2552219502c74d4cb77103fbff9cb2c148e691c9")] [assembly: AssemblyProduct("REPO Discord Rich Presence")] [assembly: AssemblyTitle("REPO Discord Rich Presence")] [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 REPO_Discord_Rich_Presence { public static class PluginInfo { public const string PLUGIN_GUID = "REPO Discord Rich Presence"; public const string PLUGIN_NAME = "REPO Discord Rich Presence"; public const string PLUGIN_VERSION = "1.0.0"; } } namespace REPOPresence { public class ConfigManager { public static ConfigManager Instance { get; private set; } public static ConfigEntry<long> AppID { get; private set; } public static ConfigEntry<bool> AllowJoin { get; private set; } public static ConfigEntry<bool> JoinOnlyInPublicLobby { get; private set; } public static ConfigEntry<bool> DisplayLivingPlayers { get; private set; } public static ConfigEntry<string> MainMenuLargeImage { get; private set; } public static ConfigEntry<string> InLobbyLargeImage { get; private set; } public static ConfigEntry<string> InGameLargeImage { get; private set; } public static ConfigEntry<string> InGameLargeText { get; private set; } public static ConfigEntry<string> ActivityState { get; private set; } public static ConfigEntry<string> ActivityDetails { get; private set; } public static ConfigEntry<bool> Debug { get; private set; } public static void Init(ConfigFile config) { Instance = new ConfigManager(config); } private ConfigManager(ConfigFile config) { AppID = config.Bind<long>("General", "1349755295974428692", 1349755295974428692L, "The Discord App ID for this game."); AllowJoin = config.Bind<bool>("Party", "AllowJoin", true, "Allow players to join your game from Discord."); JoinOnlyInPublicLobby = config.Bind<bool>("Party", "JoinOnlyInPublicLobby", false, "Only allow players to join your game from Discord if your lobby is public."); ActivityDetails = config.Bind<string>("Presence", "ActivityDetails", "Playing REPO", "The details of the rich presence."); ActivityState = config.Bind<string>("Presence", "ActivityState", "In Main Menu", "The state of the rich presence."); MainMenuLargeImage = config.Bind<string>("Presence.MainMenu", "LargeImage", "57dabf5f530a90fdca068426714bc61f20b3e22ae4a5526b32d490d86fc8a33c", "The large image key for the rich presence."); InLobbyLargeImage = config.Bind<string>("Presence.InLobby", "LargeImage", "57dabf5f530a90fdca068426714bc61f20b3e22ae4a5526b32d490d86fc8a33c", "The large image key for the rich presence."); InGameLargeImage = config.Bind<string>("Presence.InGame", "LargeImage", "57dabf5f530a90fdca068426714bc61f20b3e22ae4a5526b32d490d86fc8a33c", "The large image key for the rich presence."); InGameLargeText = config.Bind<string>("Presence.InGame", "LargeText", "In Game", "The large image tooltip for the rich presence."); Debug = config.Bind<bool>("Debug", "Debug logs", false, "Enable debug logging."); } } public class DiscordManager : MonoBehaviour { [Serializable] [CompilerGenerated] private sealed class <>c { public static readonly <>c <>9 = new <>c(); public static OnReadyEvent <>9__3_0; public static OnErrorEvent <>9__3_1; internal void <InitializeDiscordRPC>b__3_0(object sender, ReadyMessage e) { REPOPresencePlugin.logger.LogInfo((object)("Discord RPC Ready. Logged in as: " + e.User.Username)); } internal void <InitializeDiscordRPC>b__3_1(object sender, ErrorMessage e) { REPOPresencePlugin.logger.LogError((object)("Discord RPC Error: " + e.Message)); } } private static DiscordRpcClient client; private static RichPresence presence; private void Start() { InitializeDiscordRPC(); SetDefaultPresence(); } private void InitializeDiscordRPC() { //IL_0023: Unknown result type (might be due to invalid IL or missing references) //IL_0028: 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_0034: Expected O, but got Unknown //IL_003a: 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 //IL_0099: 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) //IL_00af: 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_00c1: 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_00d7: Unknown result type (might be due to invalid IL or missing references) //IL_00e8: Expected O, but got Unknown //IL_00e9: Unknown result type (might be due to invalid IL or missing references) //IL_00ef: Unknown result type (might be due to invalid IL or missing references) //IL_00f9: Expected O, but got Unknown //IL_00ff: Expected O, but got Unknown //IL_0116: Unknown result type (might be due to invalid IL or missing references) //IL_0120: Expected O, but got Unknown //IL_007d: 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: Expected O, but got Unknown REPOPresencePlugin.logger.LogInfo((object)"Initializing Discord RPC..."); client = new DiscordRpcClient(ConfigManager.AppID.Value.ToString()) { Logger = (ILogger)new ConsoleLogger((LogLevel)3) }; DiscordRpcClient obj = client; object obj2 = <>c.<>9__3_0; if (obj2 == null) { OnReadyEvent val = delegate(object sender, ReadyMessage e) { REPOPresencePlugin.logger.LogInfo((object)("Discord RPC Ready. Logged in as: " + e.User.Username)); }; <>c.<>9__3_0 = val; obj2 = (object)val; } obj.OnReady += (OnReadyEvent)obj2; DiscordRpcClient obj3 = client; object obj4 = <>c.<>9__3_1; if (obj4 == null) { OnErrorEvent val2 = delegate(object sender, ErrorMessage e) { REPOPresencePlugin.logger.LogError((object)("Discord RPC Error: " + e.Message)); }; <>c.<>9__3_1 = val2; obj4 = (object)val2; } obj3.OnError += (OnErrorEvent)obj4; client.Initialize(); presence = new RichPresence { Details = ConfigManager.ActivityDetails.Value, State = ConfigManager.ActivityState.Value, Assets = new Assets { LargeImageKey = ConfigManager.MainMenuLargeImage.Value, LargeImageText = "R.E.P.O" }, Timestamps = new Timestamps(DateTime.UtcNow) }; client.SetPresence(presence); Application.logMessageReceived += new LogCallback(HandleLog); REPOPresencePlugin.logger.LogInfo((object)"Discord RPC Initialized."); } private void SetDefaultPresence() { SetPresence("In Main Menu", "Just Chill", ConfigManager.MainMenuLargeImage.Value); } private void HandleLog(string logString, string stackTrace, LogType type) { if (logString.Contains("Changed level to: Level - Lobby Menu")) { SetPresence("In Lobby", "Waiting for players", ConfigManager.InLobbyLargeImage.Value); } else if (logString.Contains("Changed level to: Level - ")) { string text = logString.Split(new string[1] { "Changed level to: Level - " }, StringSplitOptions.None)[1]; SetPresence("In Game: " + text, "Playing", ConfigManager.InGameLargeImage.Value); } else if (logString.Contains("Created lobby on Network Connect") || logString.Contains("Steam: Hosting lobby")) { SetPresence("In Lobby", "Waiting for players", ConfigManager.InLobbyLargeImage.Value); } else if (logString.Contains("Leave to Main Menu")) { SetPresence("In Main Menu", "Just Chill", ConfigManager.MainMenuLargeImage.Value); } } private void SetPresence(string details, string state, string largeImageKey) { if (presence != null) { ((BaseRichPresence)presence).Details = details; ((BaseRichPresence)presence).State = state; ((BaseRichPresence)presence).Assets.LargeImageKey = largeImageKey; client.SetPresence(presence); REPOPresencePlugin.logger.LogInfo((object)("Presence set: " + details + ", " + state)); } } private void OnDestroy() { //IL_0047: Unknown result type (might be due to invalid IL or missing references) //IL_0051: Expected O, but got Unknown REPOPresencePlugin.logger.LogInfo((object)"OnDestroy called. Checking if Discord RPC needs to be disposed."); if (client != null) { client.Dispose(); client = null; REPOPresencePlugin.logger.LogInfo((object)"Discord RPC client disposed."); } Application.logMessageReceived -= new LogCallback(HandleLog); } } public static class MyPluginInfo { public const string PLUGIN_GUID = "com.tolian.repopresence"; public const string PLUGIN_NAME = "R.E.P.O Discord Presence"; public const string PLUGIN_VERSION = "0.1.2"; } [BepInPlugin("com.tolian.repopresence", "R.E.P.O Discord Presence", "0.1.2")] [BepInProcess("REPO.exe")] public class REPOPresencePlugin : BaseUnityPlugin { internal static ManualLogSource logger; private ConfigManager configManager; private void Awake() { //IL_0018: Unknown result type (might be due to invalid IL or missing references) //IL_001e: Expected O, but got Unknown logger = ((BaseUnityPlugin)this).Logger; ConfigManager.Init(((BaseUnityPlugin)this).Config); GameObject val = new GameObject(); val.AddComponent<DiscordManager>(); Object.DontDestroyOnLoad((Object)(object)val); ((Object)val).hideFlags = (HideFlags)61; logger.LogInfo((object)"Plugin com.tolian.repopresence is loaded!"); } } }
plugins/VyrusGames-Puppet/PuppetEnemy/PuppetEnemy.dll
Decompiled 2 months agousing System; using System.Diagnostics; using System.IO; 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 Microsoft.CodeAnalysis; using Photon.Pun; using REPOLib.Modules; using UnityEngine; using UnityEngine.AI; [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: IgnoresAccessChecksTo("")] [assembly: AssemblyCompany("Vyrus Games")] [assembly: AssemblyConfiguration("Debug")] [assembly: AssemblyFileVersion("1.1.0.0")] [assembly: AssemblyInformationalVersion("1.1.0+c4fea7fe65d0249f99d561d5796c7aaf6ee415fa")] [assembly: AssemblyProduct("PuppetEnemy")] [assembly: AssemblyTitle("PuppetEnemy")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("1.1.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 PuppetEnemy { [BepInPlugin("VyrusGames.PuppetEnemy", "PuppetEnemy", "1.1.0")] [BepInDependency(/*Could not decode attribute arguments.*/)] public class PuppetEnemy : BaseUnityPlugin { internal static PuppetEnemy Instance { get; private set; } internal static ManualLogSource Logger => Instance._logger; private ManualLogSource _logger => ((BaseUnityPlugin)this).Logger; internal Harmony? Harmony { get; set; } private void Awake() { Instance = this; ((Component)this).gameObject.transform.parent = null; ((Object)((Component)this).gameObject).hideFlags = (HideFlags)61; Patch(); Logger.LogInfo((object)$"{((BaseUnityPlugin)this).Info.Metadata.GUID} v{((BaseUnityPlugin)this).Info.Metadata.Version} has loaded!"); } internal void Patch() { //IL_001a: Unknown result type (might be due to invalid IL or missing references) //IL_001f: Unknown result type (might be due to invalid IL or missing references) //IL_0021: Expected O, but got Unknown //IL_0026: Expected O, but got Unknown if (Harmony == null) { Harmony val = new Harmony(((BaseUnityPlugin)this).Info.Metadata.GUID); Harmony val2 = val; Harmony = val; } Logger.LogInfo((object)"Patching PuppetEnemy..."); Logger.LogInfo((object)"Loading assets..."); LoadAssets(); Harmony.PatchAll(); } internal void Unpatch() { Harmony? harmony = Harmony; if (harmony != null) { harmony.UnpatchSelf(); } } private static void LoadAssets() { AssetBundle val = LoadAssetBundle("puppet"); Logger.LogInfo((object)"Loading Puppet enemy setup..."); EnemySetup val2 = val.LoadAsset<EnemySetup>("Assets/REPO/Mods/plugins/PuppetEnemy/Enemy - Puppet.asset"); Enemies.RegisterEnemy(val2); Logger.LogDebug((object)"Loaded Puppet enemy!"); } public static AssetBundle LoadAssetBundle(string name) { Logger.LogDebug((object)("Loading Asset Bundle: " + name)); AssetBundle val = null; string text = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), name); return AssetBundle.LoadFromFile(text); } } } namespace PuppetEnemy.AI { public class EnemyPuppet : MonoBehaviour { public enum State { Spawn, Idle, Roam, Curious, Investigate, Leave, Stun } private Enemy _enemy; private PhotonView _photonView; private PlayerAvatar _targetPlayer; private bool _stateImpulse; private bool _deathImpulse; private Quaternion _horizontalRotationTarget = Quaternion.identity; private Vector3 _agentDestination; private Vector3 _targetPosition; private bool _hurtImpulse; private float hurtLerp; private int _hurtAmount; private Material _hurtableMaterial; private float _pitCheckTimer; private bool _pitCheck; private float _talkTimer; private bool _talkImpulse; [Header("State")] [SerializeField] public State currentState; [SerializeField] public float stateTimer; [Header("Animation")] [SerializeField] private EnemyPuppetAnimationController animator; [SerializeField] private SkinnedMeshRenderer _renderer; [SerializeField] private AnimationCurve hurtCurve; [Header("Rotation and LookAt")] public SpringQuaternion horizontalRotationSpring; public SpringQuaternion headLookAtSpring; public Transform headLookAtTarget; public Transform headLookAtSource; private EnemyNavMeshAgent _navMeshAgent => EnemyUtil.GetEnemyNavMeshAgent(_enemy); private EnemyRigidbody _rigidbody => EnemyUtil.GetEnemyRigidbody(_enemy); private EnemyParent _enemyParent => EnemyUtil.GetEnemyParent(_enemy); private EnemyVision _vision => EnemyUtil.GetEnemyVision(_enemy); private EnemyStateInvestigate _investigate => EnemyUtil.GetEnemyStateInvestigate(_enemy); public Enemy Enemy => _enemy; public bool DeathImpulse { get { return _deathImpulse; } set { _deathImpulse = value; } } private void Awake() { _enemy = ((Component)this).GetComponent<Enemy>(); _photonView = ((Component)this).GetComponent<PhotonView>(); _hurtAmount = Shader.PropertyToID("_ColorOverlayAmount"); if ((Object)(object)_renderer != (Object)null) { _hurtableMaterial = ((Renderer)_renderer).sharedMaterial; } hurtCurve = AssetManager.instance.animationCurveImpact; Debug.Log((object)"THE CHUD HAS ARRIVED!!"); } private void Update() { if ((GameManager.Multiplayer() && !PhotonNetwork.IsMasterClient) || !LevelGenerator.Instance.Generated) { return; } if (!_enemy.IsStunned()) { if (_enemy.IsStunned()) { UpdateState(State.Stun); } switch (currentState) { case State.Spawn: StateSpawn(); break; case State.Idle: StateIdle(); break; case State.Roam: StateRoam(); break; case State.Curious: StateCurious(); break; case State.Investigate: StateInvestigate(); break; case State.Leave: StateLeave(); break; case State.Stun: StateStun(); break; default: throw new ArgumentOutOfRangeException(); } RotationLogic(); TargetingLogic(); } HurtEffect(); if (_talkTimer > 0f) { _talkTimer -= Time.deltaTime; } else { _talkImpulse = true; } } private void LateUpdate() { HeadLookAtLogic(); } private void UpdateState(State _newState) { if (currentState != _newState) { currentState = _newState; stateTimer = 0f; _stateImpulse = true; if (GameManager.Multiplayer()) { _photonView.RPC("UpdateStateRPC", (RpcTarget)0, new object[1] { currentState }); } else { UpdateStateRPC(currentState); } } } [PunRPC] private void UpdateStateRPC(State _state) { currentState = _state; } [PunRPC] private void UpdatePlayerTargetRPC(int viewID) { foreach (PlayerAvatar item in SemiFunc.PlayerGetList()) { if (item.photonView.ViewID == viewID) { _targetPlayer = item; break; } } } private void TargetingLogic() { //IL_002b: 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_0045: Unknown result type (might be due to invalid IL or missing references) //IL_004a: Unknown result type (might be due to invalid IL or missing references) //IL_004f: 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_0072: 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_00dc: Unknown result type (might be due to invalid IL or missing references) //IL_00e1: Unknown result type (might be due to invalid IL or missing references) //IL_00ed: 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_00d3: Unknown result type (might be due to invalid IL or missing references) //IL_00d8: Unknown result type (might be due to invalid IL or missing references) if (currentState == State.Curious && Object.op_Implicit((Object)(object)_targetPlayer)) { Vector3 val = ((Component)_targetPlayer).transform.position + ((Component)_targetPlayer).transform.forward * 1.5f; if (_pitCheckTimer <= 0f) { _pitCheckTimer = 0.1f; _pitCheck = !Physics.Raycast(val + Vector3.up, Vector3.down, 4f, LayerMask.GetMask(new string[1] { "Default" })); } else { _pitCheckTimer -= Time.deltaTime; } if (_pitCheck) { val = ((Component)_targetPlayer).transform.position; } _targetPosition = Vector3.Lerp(_targetPosition, val, 20f * Time.deltaTime); } } private void RotationLogic() { //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_000c: 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) //IL_0014: Unknown result type (might be due to invalid IL or missing references) //IL_002f: 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_0037: Unknown result type (might be due to invalid IL or missing references) //IL_003c: Unknown result type (might be due to invalid IL or missing references) //IL_0041: Unknown result type (might be due to invalid IL or missing references) //IL_0057: Unknown result type (might be due to invalid IL or missing references) //IL_0066: Unknown result type (might be due to invalid IL or missing references) //IL_00f8: Unknown result type (might be due to invalid IL or missing references) //IL_0102: Unknown result type (might be due to invalid IL or missing references) Vector3 val = EnemyUtil.GetAgentVelocity(_navMeshAgent); val = ((Vector3)(ref val)).normalized; if (((Vector3)(ref val)).magnitude > 0.1f) { val = EnemyUtil.GetAgentVelocity(_navMeshAgent); _horizontalRotationTarget = Quaternion.LookRotation(((Vector3)(ref val)).normalized); ((Quaternion)(ref _horizontalRotationTarget)).eulerAngles = new Vector3(0f, ((Quaternion)(ref _horizontalRotationTarget)).eulerAngles.y, 0f); } if (currentState == State.Spawn || currentState == State.Idle || currentState == State.Roam || currentState == State.Investigate || currentState == State.Leave) { horizontalRotationSpring.speed = 5f; horizontalRotationSpring.damping = 0.7f; } else { horizontalRotationSpring.speed = 10f; horizontalRotationSpring.damping = 0.8f; } ((Component)this).transform.rotation = SemiFunc.SpringQuaternionGet(horizontalRotationSpring, _horizontalRotationTarget, -1f); } private void HeadLookAtLogic() { //IL_00b8: Unknown result type (might be due to invalid IL or missing references) //IL_00c2: Unknown result type (might be due to invalid IL or missing references) //IL_0053: 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) //IL_0063: 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_0069: Unknown result type (might be due to invalid IL or missing references) //IL_0070: Unknown result type (might be due to invalid IL or missing references) //IL_007a: Unknown result type (might be due to invalid IL or missing references) //IL_007f: Unknown result type (might be due to invalid IL or missing references) //IL_008c: 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_0097: Unknown result type (might be due to invalid IL or missing references) if (currentState == State.Curious && !_enemy.IsStunned() && currentState != State.Stun && Object.op_Implicit((Object)(object)_targetPlayer) && !EnemyUtil.IsPlayerDisabled(_targetPlayer)) { Vector3 val = _targetPlayer.PlayerVisionTarget.VisionTransform.position - headLookAtTarget.position; val = SemiFunc.ClampDirection(val, headLookAtTarget.forward, 60f); headLookAtSource.rotation = SemiFunc.SpringQuaternionGet(headLookAtSpring, Quaternion.LookRotation(val), -1f); } else { headLookAtSource.rotation = SemiFunc.SpringQuaternionGet(headLookAtSpring, headLookAtTarget.rotation, -1f); } } private void HurtEffect() { if (!_hurtImpulse) { return; } hurtLerp += 2.5f * Time.deltaTime; hurtLerp = Mathf.Clamp01(hurtLerp); if ((Object)(object)_hurtableMaterial != (Object)null) { _hurtableMaterial.SetFloat(_hurtAmount, hurtCurve.Evaluate(hurtLerp)); } if (hurtLerp > 1f) { _hurtImpulse = false; if ((Object)(object)_hurtableMaterial != (Object)null) { _hurtableMaterial.SetFloat(_hurtAmount, 0f); } } } private void StateSpawn() { //IL_001d: Unknown result type (might be due to invalid IL or missing references) if (_stateImpulse) { _navMeshAgent.Warp(((Component)_rigidbody).transform.position); _navMeshAgent.ResetPath(); _stateImpulse = false; stateTimer = 2f; } if (stateTimer > 0f) { stateTimer -= Time.deltaTime; } else { UpdateState(State.Idle); } } private void StateIdle() { //IL_0039: Unknown result type (might be due to invalid IL or missing references) if (_stateImpulse) { _stateImpulse = false; stateTimer = Random.Range(4f, 8f); _navMeshAgent.Warp(((Component)_rigidbody).transform.position); _navMeshAgent.ResetPath(); } if (!SemiFunc.EnemySpawnIdlePause()) { stateTimer -= Time.deltaTime; if (stateTimer <= 0f) { UpdateState(State.Roam); } if (SemiFunc.EnemyForceLeave(_enemy)) { UpdateState(State.Leave); } } } private void StateRoam() { //IL_012e: Unknown result type (might be due to invalid IL or missing references) //IL_0041: Unknown result type (might be due to invalid IL or missing references) //IL_006c: 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_009f: Unknown result type (might be due to invalid IL or missing references) //IL_00a4: 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) //IL_00bf: Unknown result type (might be due to invalid IL or missing references) //IL_00ee: Unknown result type (might be due to invalid IL or missing references) //IL_00f3: Unknown result type (might be due to invalid IL or missing references) if (_stateImpulse) { bool flag = false; _talkTimer = Random.Range(5f, 15f); stateTimer = Random.Range(4f, 8f); LevelPoint val = SemiFunc.LevelPointGet(((Component)this).transform.position, 10f, 25f); if (!Object.op_Implicit((Object)(object)val)) { val = SemiFunc.LevelPointGet(((Component)this).transform.position, 0f, 999f); } NavMeshHit val2 = default(NavMeshHit); if (Object.op_Implicit((Object)(object)val) && NavMesh.SamplePosition(((Component)val).transform.position + Random.insideUnitSphere * 3f, ref val2, 5f, -1) && Physics.Raycast(((NavMeshHit)(ref val2)).position, Vector3.down, 5f, LayerMask.GetMask(new string[1] { "Default" }))) { _agentDestination = ((NavMeshHit)(ref val2)).position; flag = true; } if (!flag) { return; } EnemyUtil.SetNotMovingTimer(_rigidbody, 0f); _stateImpulse = false; } else { _navMeshAgent.SetDestination(_agentDestination); if (EnemyUtil.GetNotMovingTimer(_rigidbody) > 2f) { stateTimer -= Time.deltaTime; } if (stateTimer <= 0f) { UpdateState(State.Idle); } } if (SemiFunc.EnemyForceLeave(_enemy)) { UpdateState(State.Leave); } if (_talkImpulse) { _talkImpulse = false; animator.PlayRoamSound(); _talkTimer = Random.Range(15f, 20f); } } private void StateCurious() { //IL_0045: Unknown result type (might be due to invalid IL or missing references) //IL_00e8: Unknown result type (might be due to invalid IL or missing references) //IL_0104: Unknown result type (might be due to invalid IL or missing references) //IL_010f: Unknown result type (might be due to invalid IL or missing references) //IL_0121: Unknown result type (might be due to invalid IL or missing references) if (_stateImpulse) { _stateImpulse = false; stateTimer = Random.Range(24f, 30f); _talkTimer = Random.Range(5f, 15f); } _navMeshAgent.SetDestination(_targetPosition); stateTimer -= Time.deltaTime; _vision.StandOverride(0.25f); if (stateTimer <= 0f || !Object.op_Implicit((Object)(object)_targetPlayer) || EnemyUtil.IsPlayerDisabled(_targetPlayer)) { UpdateState(State.Idle); return; } if (_talkImpulse) { _talkImpulse = false; animator.PlayCuriousSound(); _talkTimer = Random.Range(15f, 20f); } NavMeshHit val = default(NavMeshHit); if (_navMeshAgent.CanReach(_targetPosition, 1f) && Vector3.Distance(((Component)_rigidbody).transform.position, _navMeshAgent.GetPoint()) < 2f && !NavMesh.SamplePosition(_targetPosition, ref val, 0.5f, -1)) { UpdateState(State.Roam); } } private void StateInvestigate() { //IL_0045: 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_00ec: Unknown result type (might be due to invalid IL or missing references) //IL_00f7: Unknown result type (might be due to invalid IL or missing references) //IL_0109: Unknown result type (might be due to invalid IL or missing references) if (_stateImpulse) { _stateImpulse = false; stateTimer = Random.Range(24f, 30f); _talkTimer = Random.Range(5f, 15f); } _navMeshAgent.SetDestination(_targetPosition); stateTimer -= Time.deltaTime; _vision.StandOverride(0.25f); if (stateTimer <= 0f) { UpdateState(State.Idle); return; } if (_talkImpulse) { _talkImpulse = false; animator.PlayVisionSound(); _talkTimer = Random.Range(15f, 20f); } NavMeshHit val = default(NavMeshHit); if (_navMeshAgent.CanReach(_targetPosition, 1f) && Vector3.Distance(((Component)_rigidbody).transform.position, _navMeshAgent.GetPoint()) < 2f && !NavMesh.SamplePosition(_targetPosition, ref val, 0.5f, -1)) { UpdateState(State.Roam); } } private void StateLeave() { //IL_0037: 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_0170: Unknown result type (might be due to invalid IL or missing references) //IL_0063: 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_0087: Unknown result type (might be due to invalid IL or missing references) //IL_0091: 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) //IL_00ac: 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) //IL_00e0: Unknown result type (might be due to invalid IL or missing references) //IL_00e5: Unknown result type (might be due to invalid IL or missing references) //IL_0101: Unknown result type (might be due to invalid IL or missing references) if (_stateImpulse) { _talkTimer = Random.Range(5f, 15f); stateTimer = 5f; bool flag = false; LevelPoint val = SemiFunc.LevelPointGetPlayerDistance(((Component)this).transform.position, 30f, 50f, false); if (!Object.op_Implicit((Object)(object)val)) { val = SemiFunc.LevelPointGetFurthestFromPlayer(((Component)this).transform.position, 5f); } NavMeshHit val2 = default(NavMeshHit); if (Object.op_Implicit((Object)(object)val) && NavMesh.SamplePosition(((Component)val).transform.position + Random.insideUnitSphere * 1f, ref val2, 5f, -1) && Physics.Raycast(((NavMeshHit)(ref val2)).position, Vector3.down, 5f, LayerMask.GetMask(new string[1] { "Default" }))) { _agentDestination = ((NavMeshHit)(ref val2)).position; flag = true; } if (flag) { _enemy.NavMeshAgent.SetDestination(_agentDestination); EnemyUtil.SetNotMovingTimer(_rigidbody, 0f); _stateImpulse = false; } } else { if (EnemyUtil.GetNotMovingTimer(_rigidbody) > 2f) { stateTimer -= Time.deltaTime; } SemiFunc.EnemyCartJump(_enemy); if (Vector3.Distance(((Component)this).transform.position, _agentDestination) < 1f || stateTimer <= 0f) { SemiFunc.EnemyCartJumpReset(_enemy); UpdateState(State.Idle); } } if (_talkImpulse) { _talkImpulse = false; animator.PlayRoamSound(); _talkTimer = Random.Range(15f, 20f); } } private void StateStun() { if (_stateImpulse) { _stateImpulse = false; } if (!_enemy.IsStunned()) { UpdateState(State.Idle); } } public void OnSpawn() { if (SemiFunc.IsMasterClientOrSingleplayer() && SemiFunc.EnemySpawn(_enemy)) { UpdateState(State.Spawn); } } public void OnInvestigate() { //IL_0035: Unknown result type (might be due to invalid IL or missing references) //IL_003a: Unknown result type (might be due to invalid IL or missing references) if (SemiFunc.IsMasterClientOrSingleplayer() && (currentState == State.Idle || currentState == State.Roam || currentState == State.Investigate)) { _targetPosition = EnemyUtil.GetOnInvestigateTriggeredPosition(_investigate); UpdateState(State.Investigate); } } public void OnVision() { if ((currentState == State.Idle || currentState == State.Roam || currentState == State.Investigate) && !_enemy.IsStunned() && SemiFunc.IsMasterClientOrSingleplayer()) { _targetPlayer = EnemyUtil.GetVisionTriggeredPlayer(_vision); if (SemiFunc.IsMultiplayer()) { _photonView.RPC("UpdatePlayerTargetRPC", (RpcTarget)0, new object[1] { _photonView.ViewID }); } UpdateState(State.Curious); animator.PlayVisionSound(); } } public void OnHurt() { _hurtImpulse = true; animator.PlayHurtSound(); } public void OnDeath() { _deathImpulse = true; animator.PlayDeathSound(); if (SemiFunc.IsMasterClientOrSingleplayer()) { _enemyParent.SpawnedTimerSet(0f); } } } public class EnemyPuppetAnimationController : MonoBehaviour { [Header("References")] public EnemyPuppet controller; public Animator animator; [Header("Particles")] public ParticleSystem[] deathParticles; [Header("Sounds")] [SerializeField] private Sound roamSounds; [SerializeField] private Sound visionSounds; [SerializeField] private Sound curiousSounds; [SerializeField] private Sound hurtSounds; [SerializeField] private Sound deathSound; private void Awake() { animator = ((Component)this).GetComponent<Animator>(); } private void Update() { //IL_0063: 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) if (controller.DeathImpulse) { controller.DeathImpulse = false; animator.SetTrigger("Dies"); } if (!controller.Enemy.IsStunned()) { Animator obj = animator; Vector3 agentVelocity = EnemyUtil.GetAgentVelocity(EnemyUtil.GetEnemyNavMeshAgent(controller.Enemy)); obj.SetFloat("Walking", ((Vector3)(ref agentVelocity)).magnitude); } } public void SetDespawn() { EnemyUtil.GetEnemyParent(controller.Enemy).Despawn(); } public void DeathParticlesImpulse() { ParticleSystem[] array = deathParticles; for (int i = 0; i < array.Length; i++) { array[i].Play(); } } public void PlayRoamSound() { //IL_0017: Unknown result type (might be due to invalid IL or missing references) roamSounds.Play(controller.Enemy.CenterTransform.position, 1f, 1f, 1f, 1f); } public void PlayVisionSound() { //IL_0017: Unknown result type (might be due to invalid IL or missing references) visionSounds.Play(controller.Enemy.CenterTransform.position, 1f, 1f, 1f, 1f); } public void PlayCuriousSound() { //IL_0017: Unknown result type (might be due to invalid IL or missing references) curiousSounds.Play(controller.Enemy.CenterTransform.position, 1f, 1f, 1f, 1f); } public void PlayHurtSound() { //IL_0017: Unknown result type (might be due to invalid IL or missing references) hurtSounds.Play(controller.Enemy.CenterTransform.position, 1f, 1f, 1f, 1f); } public void PlayDeathSound() { //IL_0017: Unknown result type (might be due to invalid IL or missing references) deathSound.Play(controller.Enemy.CenterTransform.position, 1f, 1f, 1f, 1f); } } public class EnemyUtil { public static EnemyNavMeshAgent GetEnemyNavMeshAgent(Enemy enemy) { //IL_0029: Unknown result type (might be due to invalid IL or missing references) //IL_002f: Expected O, but got Unknown Type type = ((object)enemy).GetType(); FieldInfo field = type.GetField("NavMeshAgent", BindingFlags.Instance | BindingFlags.NonPublic); if (field != null) { return (EnemyNavMeshAgent)field.GetValue(enemy); } Debug.LogError((object)"NavMeshAgent field not found!"); return null; } public static EnemyRigidbody GetEnemyRigidbody(Enemy enemy) { //IL_0029: Unknown result type (might be due to invalid IL or missing references) //IL_002f: Expected O, but got Unknown Type type = ((object)enemy).GetType(); FieldInfo field = type.GetField("Rigidbody", BindingFlags.Instance | BindingFlags.NonPublic); if (field != null) { return (EnemyRigidbody)field.GetValue(enemy); } Debug.LogError((object)"Rigidbody field not found!"); return null; } public static EnemyParent GetEnemyParent(Enemy enemy) { //IL_0029: Unknown result type (might be due to invalid IL or missing references) //IL_002f: Expected O, but got Unknown Type type = ((object)enemy).GetType(); FieldInfo field = type.GetField("EnemyParent", BindingFlags.Instance | BindingFlags.NonPublic); if (field != null) { return (EnemyParent)field.GetValue(enemy); } Debug.LogError((object)"EnemyParent field not found!"); return null; } public static EnemyVision GetEnemyVision(Enemy enemy) { //IL_0029: Unknown result type (might be due to invalid IL or missing references) //IL_002f: Expected O, but got Unknown Type type = ((object)enemy).GetType(); FieldInfo field = type.GetField("Vision", BindingFlags.Instance | BindingFlags.NonPublic); if (field != null) { return (EnemyVision)field.GetValue(enemy); } Debug.LogError((object)"Vision field not found!"); return null; } public static EnemyStateInvestigate GetEnemyStateInvestigate(Enemy enemy) { //IL_0029: Unknown result type (might be due to invalid IL or missing references) //IL_002f: Expected O, but got Unknown Type type = ((object)enemy).GetType(); FieldInfo field = type.GetField("StateInvestigate", BindingFlags.Instance | BindingFlags.NonPublic); if (field != null) { return (EnemyStateInvestigate)field.GetValue(enemy); } Debug.LogError((object)"StateInvestigate field not found!"); return null; } public static bool IsEnemyJumping(Enemy enemy) { Type type = ((object)enemy).GetType(); FieldInfo field = type.GetField("Jump", BindingFlags.Instance | BindingFlags.NonPublic); if (field != null) { Type fieldType = field.FieldType; FieldInfo field2 = fieldType.GetField("jumping", BindingFlags.Instance | BindingFlags.NonPublic); if (field2 != null) { return (bool)field2.GetValue(field.GetValue(enemy)); } Debug.LogError((object)"Jumping field not found!"); return false; } Debug.LogError((object)"Jump field not found!"); return false; } public static bool IsPlayerDisabled(PlayerAvatar playerTarget) { Type type = ((object)playerTarget).GetType(); FieldInfo field = type.GetField("isDisabled", BindingFlags.Instance | BindingFlags.NonPublic); if (field != null) { return (bool)field.GetValue(playerTarget); } Debug.LogError((object)"isDisabled field not found!"); return false; } public static Vector3 GetAgentVelocity(EnemyNavMeshAgent agent) { //IL_003d: 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_0029: Unknown result type (might be due to invalid IL or missing references) //IL_002e: 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) Type type = ((object)agent).GetType(); FieldInfo field = type.GetField("AgentVelocity", BindingFlags.Instance | BindingFlags.NonPublic); if (field != null) { return (Vector3)field.GetValue(agent); } Debug.LogError((object)"AgentVelocity field not found!"); return Vector3.zero; } public static Vector3 GetOnInvestigateTriggeredPosition(EnemyStateInvestigate investigate) { //IL_003d: 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_0029: Unknown result type (might be due to invalid IL or missing references) //IL_002e: 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) Type type = ((object)investigate).GetType(); FieldInfo field = type.GetField("onInvestigateTriggeredPosition", BindingFlags.Instance | BindingFlags.NonPublic); if (field != null) { return (Vector3)field.GetValue(investigate); } Debug.LogError((object)"onInvestigateTriggeredPosition field not found!"); return Vector3.zero; } public static PlayerAvatar GetVisionTriggeredPlayer(EnemyVision vision) { //IL_0029: Unknown result type (might be due to invalid IL or missing references) //IL_002f: Expected O, but got Unknown Type type = ((object)vision).GetType(); FieldInfo field = type.GetField("onVisionTriggeredPlayer", BindingFlags.Instance | BindingFlags.NonPublic); if (field != null) { return (PlayerAvatar)field.GetValue(vision); } Debug.LogError((object)"onVisionTriggeredPlayer field not found!"); return null; } public static float GetNotMovingTimer(EnemyRigidbody rb) { Type type = ((object)rb).GetType(); FieldInfo field = type.GetField("notMovingTimer", BindingFlags.Instance | BindingFlags.NonPublic); if (field != null) { return (float)field.GetValue(rb); } Debug.LogError((object)"NotMovingTimer field not found!"); return 0f; } public static void SetNotMovingTimer(EnemyRigidbody rb, float value) { Type type = ((object)rb).GetType(); FieldInfo field = type.GetField("notMovingTimer", BindingFlags.Instance | BindingFlags.NonPublic); if (field != null) { field.SetValue(rb, value); } else { Debug.LogError((object)"NotMovingTimer field not found!"); } } } }
plugins/x753_REPO-CustomColors/CustomColors.dll
Decompiled 2 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 HarmonyLib; using Microsoft.CodeAnalysis; using Photon.Pun; using TMPro; using UnityEngine; using UnityEngine.UI; [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("CustomColors")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyDescription("A mod for REPO that lets you change your color with RGB sliders")] [assembly: AssemblyFileVersion("1.1.0.0")] [assembly: AssemblyInformationalVersion("1.1.0+8cf8840b649c95c8908af583284670bc38b18726")] [assembly: AssemblyProduct("CustomColors")] [assembly: AssemblyTitle("CustomColors")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("1.1.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 CustomColors { [BepInPlugin("x753.CustomColors", "CustomColors", "1.1.0")] public class CustomColorsMod : BaseUnityPlugin { [HarmonyPatch(typeof(PlayerAvatar), "Awake")] private class PlayerAvatar_Awake_Patch { [HarmonyPostfix] public static void PlayerAvatar_Awake_Postfix(PlayerAvatar __instance) { ((Component)__instance).gameObject.AddComponent<ModdedColorPlayerAvatar>(); } } public class ModdedColorPlayerAvatar : MonoBehaviour, IPunObservable { public Color moddedColor; public static Color LocalColor = new Color(1f, 0f, 0f); public PlayerAvatar avatar; public PlayerAvatarVisuals visuals; public Material bodyMaterial; public void OnPhotonSerializeView(PhotonStream stream, PhotonMessageInfo info) { throw new NotImplementedException(); } private void Awake() { avatar = ((Component)this).gameObject.GetComponent<PlayerAvatar>(); visuals = avatar.playerAvatarVisuals; } public static void LocalPlayerAvatarSetColor() { //IL_009b: Unknown result type (might be due to invalid IL or missing references) //IL_00a1: Expected O, but got Unknown if (!GameManager.Multiplayer()) { ((Component)PlayerAvatar.instance).GetComponent<ModdedColorPlayerAvatar>().ModdedSetColorRPC(LocalColor.r, LocalColor.g, LocalColor.b); } else { PlayerAvatar.instance.photonView.RPC("ModdedSetColorRPC", (RpcTarget)3, new object[3] { LocalColor.r, LocalColor.g, LocalColor.b }); } ES3Settings val = new ES3Settings("ModSettingsData.es3", new Enum[1] { (Enum)(object)(Location)0 }); ES3.Save<string>("PlayerBodyColorR", LocalColor.r.ToString(), val); ES3.Save<string>("PlayerBodyColorG", LocalColor.g.ToString(), val); ES3.Save<string>("PlayerBodyColorB", LocalColor.b.ToString(), val); } [PunRPC] public void ModdedSetColorRPC(float r, float g, float b) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_0017: Unknown result type (might be due to invalid IL or missing references) //IL_0018: Unknown result type (might be due to invalid IL or missing references) //IL_0051: 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) Color val = default(Color); ((Color)(ref val))..ctor(r, g, b); moddedColor = val; visuals.color = val; if ((Object)(object)bodyMaterial == (Object)null) { bodyMaterial = avatar.playerHealth.bodyMaterial; } bodyMaterial.SetColor(Shader.PropertyToID("_AlbedoColor"), val); if (SemiFunc.RunIsLobbyMenu() && Object.op_Implicit((Object)(object)MenuPageLobby.instance)) { foreach (MenuPlayerListed menuPlayerListed in MenuPageLobby.instance.menuPlayerListedList) { if ((Object)(object)menuPlayerListed.playerAvatar == (Object)(object)avatar) { menuPlayerListed.playerHead.SetColor(val); break; } } } visuals.colorSet = true; } } public class SliderReinitializer : MonoBehaviour { public string elementName = ""; public MenuSlider menuSlider; public float startValue; public void Start() { ((Component)this).gameObject.GetComponent<MenuSlider>().elementName = elementName; ((TMP_Text)((Component)((Component)this).gameObject.transform.Find("Element Name")).GetComponent<TextMeshProUGUI>()).SetText(elementName, true); ((Object)((Component)this).gameObject).name = "Slider - " + elementName; menuSlider.SetBar(startValue); } } [HarmonyPatch(typeof(MenuPageColor), "Start")] private class MenuPageColor_Start_Patch { [HarmonyPostfix] public static void MenuPageColor_Start_Postfix(MenuPageColor __instance) { //IL_0030: 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_00e6: Unknown result type (might be due to invalid IL or missing references) //IL_0115: Unknown result type (might be due to invalid IL or missing references) //IL_011f: Unknown result type (might be due to invalid IL or missing references) //IL_014e: Unknown result type (might be due to invalid IL or missing references) //IL_0158: Unknown result type (might be due to invalid IL or missing references) ((Component)__instance).transform.Find("Color Button Holder"); ((Component)__instance).transform.Find("Menu Button - Confirm").localPosition = new Vector3(330f, 80f, 0f); foreach (MenuPages menuPage2 in MenuManager.instance.menuPages) { GameObject menuPage = menuPage2.menuPage; if (((Object)menuPage).name == "Menu Page Settings Audio") { Transform obj = menuPage.transform.Find("Menu Scroll Box"); Transform obj2 = ((obj != null) ? obj.Find("Mask") : null); Transform obj3 = ((obj2 != null) ? obj2.Find("Scroller") : null); Transform val = ((obj3 != null) ? obj3.Find("Slider - Master volume") : null); if ((Object)(object)val != (Object)null) { RedSlider = CreateColorSlider(((Component)val).gameObject, ((Component)__instance).transform, new Vector3(60f, 525f, 0f), "Color [RED]", Color.red, 753); GreenSlider = CreateColorSlider(((Component)val).gameObject, ((Component)__instance).transform, new Vector3(60f, 495f, 0f), "Color [GREEN]", Color.green, 754); BlueSlider = CreateColorSlider(((Component)val).gameObject, ((Component)__instance).transform, new Vector3(60f, 465f, 0f), "Color [BLUE]", Color.blue, 755); } } } } } [HarmonyPatch(typeof(MenuButtonColor), "Start")] private class MenuButtonColor_Start_Patch { [HarmonyPostfix] public static void MenuButtonColor_Start_Postfix(MenuButtonColor __instance) { //IL_002d: Unknown result type (might be due to invalid IL or missing references) //IL_0038: Unknown result type (might be due to invalid IL or missing references) //IL_004c: Unknown result type (might be due to invalid IL or missing references) //IL_0051: Unknown result type (might be due to invalid IL or missing references) if (DataDirector.instance.ColorGetBody() == __instance.colorID) { __instance.menuPageColor.menuColorSelected.SetColor(AssetManager.instance.playerColors[__instance.colorID], ((Component)__instance).transform.position - new Vector3(0f, 405f, 0f)); } } } [HarmonyPatch(typeof(PlayerAvatar), "PlayerAvatarSetColor")] private class PlayerAvatar_PlayerAvatarSetColor_Patch { [HarmonyPostfix] public static void PlayerAvatar_PlayerAvatarSetColor_Postfix(PlayerAvatar __instance, int colorIndex) { //IL_000d: Unknown result type (might be due to invalid IL or missing references) ModdedColorPlayerAvatar component = ((Component)__instance).GetComponent<ModdedColorPlayerAvatar>(); if (component != null) { _ = component.moddedColor; if (true) { ModdedColorPlayerAvatar.LocalPlayerAvatarSetColor(); } } } } [HarmonyPatch(typeof(PlayerAvatarVisuals), "MenuAvatarGetColorsFromRealAvatar")] private class PlayerAvatarVisuals_MenuAvatarGetColorsFromRealAvatar_Patch { public static Material bodyMaterial; [HarmonyPrefix] public static bool PlayerAvatarVisuals_MenuAvatarGetColorsFromRealAvatar_Prefix(PlayerAvatarVisuals __instance) { //IL_0044: Unknown result type (might be due to invalid IL or missing references) if (__instance.isMenuAvatar && !Object.op_Implicit((Object)(object)__instance.playerAvatar)) { __instance.playerAvatar = PlayerAvatar.instance; } bodyMaterial = ((Component)((Component)__instance).transform).GetComponentInParent<PlayerHealth>().bodyMaterial; bodyMaterial.SetColor(Shader.PropertyToID("_AlbedoColor"), ModdedColorPlayerAvatar.LocalColor); return false; } } [HarmonyPatch(typeof(MenuColorSelected), "SetColor")] private class MenuColorSelected_SetColor_Patch { [HarmonyPostfix] public static void MenuColorSelected_SetColor_Postfix(MenuColorSelected __instance, Color color, Vector3 position) { //IL_0012: Unknown result type (might be due to invalid IL or missing references) //IL_002f: Unknown result type (might be due to invalid IL or missing references) //IL_0057: 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_004c: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)RedSlider != (Object)null) { RedSlider.SetBar(color.r); } if ((Object)(object)GreenSlider != (Object)null) { GreenSlider.SetBar(color.g); } if ((Object)(object)BlueSlider != (Object)null) { BlueSlider.SetBar(color.b); } ModdedColorPlayerAvatar.LocalColor = color; } } [HarmonyPatch(typeof(MenuPageColor), "ConfirmButton")] private class MenuPageColor_ConfirmButton_Patch { [HarmonyPrefix] public static void MenuPageColor_ConfirmButton_Prefix(MenuPageColor __instance) { ModdedColorPlayerAvatar.LocalPlayerAvatarSetColor(); } } [HarmonyPatch(typeof(DataDirector), "SettingValueSet")] private class DataDirector_SettingValueSet_Patch { [HarmonyPrefix] public static bool DataDirector_SettingValueSet_Prefix(DataDirector __instance, Setting setting, int value) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Invalid comparison between Unknown and I4 //IL_001c: Unknown result type (might be due to invalid IL or missing references) //IL_0022: Invalid comparison between Unknown and I4 //IL_0038: Unknown result type (might be due to invalid IL or missing references) //IL_003e: Invalid comparison between Unknown and I4 if ((int)setting == 753) { ModdedColorPlayerAvatar.LocalColor.r = (float)value / 100f; return false; } if ((int)setting == 754) { ModdedColorPlayerAvatar.LocalColor.g = (float)value / 100f; return false; } if ((int)setting == 755) { ModdedColorPlayerAvatar.LocalColor.b = (float)value / 100f; return false; } return true; } } private const string modGUID = "x753.CustomColors"; private const string modName = "CustomColors"; private const string modVersion = "1.1.0"; private readonly Harmony harmony = new Harmony("x753.CustomColors"); private static CustomColorsMod Instance; public static MenuSlider RedSlider; public static MenuSlider GreenSlider; public static MenuSlider BlueSlider; private void Awake() { //IL_0042: Unknown result type (might be due to invalid IL or missing references) //IL_0048: Expected O, but got Unknown if ((Object)(object)Instance == (Object)null) { Instance = this; } harmony.PatchAll(); ((BaseUnityPlugin)this).Logger.LogInfo((object)"Plugin CustomColors is loaded!"); ES3Settings val = new ES3Settings("ModSettingsData.es3", new Enum[1] { (Enum)(object)(Location)0 }); if (ES3.KeyExists("PlayerBodyColorR", val)) { string s = ES3.Load<string>("PlayerBodyColorR", "0", val); string s2 = ES3.Load<string>("PlayerBodyColorG", "1", val); string s3 = ES3.Load<string>("PlayerBodyColorB", "0", val); ModdedColorPlayerAvatar.LocalColor.r = float.Parse(s); ModdedColorPlayerAvatar.LocalColor.g = float.Parse(s2); ModdedColorPlayerAvatar.LocalColor.b = float.Parse(s3); } } public static MenuSlider CreateColorSlider(GameObject sliderPrefab, Transform parentTransform, Vector3 position, string elementName, Color color, int settingNum) { //IL_000d: Unknown result type (might be due to invalid IL or missing references) //IL_0032: 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_00d3: Unknown result type (might be due to invalid IL or missing references) //IL_00f7: Unknown result type (might be due to invalid IL or missing references) //IL_011b: Unknown result type (might be due to invalid IL or missing references) //IL_011d: Unknown result type (might be due to invalid IL or missing references) //IL_013b: Unknown result type (might be due to invalid IL or missing references) //IL_013d: Unknown result type (might be due to invalid IL or missing references) //IL_015b: Unknown result type (might be due to invalid IL or missing references) //IL_015d: Unknown result type (might be due to invalid IL or missing references) GameObject obj = Object.Instantiate<GameObject>(sliderPrefab, parentTransform); obj.transform.position = position; ((Graphic)((Component)obj.transform.Find("SliderBG").Find("RawImage (1)")).GetComponent<RawImage>()).color = Color.black; ((Component)obj.transform.Find("SliderBG").Find("RawImage (2)")).gameObject.SetActive(false); ((Graphic)((Component)obj.transform.Find("SliderBG").Find("RawImage (3)")).GetComponent<RawImage>()).color = new Color(0.1f, 0.1f, 0.1f); ((Component)obj.transform.Find("MaskedText")).gameObject.SetActive(false); ((Graphic)((Component)obj.transform.Find("Bar").Find("RawImage")).GetComponent<RawImage>()).color = color; MenuSlider component = obj.GetComponent<MenuSlider>(); component.pointerSegmentJump = 1; component.buttonSegmentJump = 1; obj.GetComponent<MenuSetting>().setting = (Setting)settingNum; Object.Destroy((Object)(object)obj.GetComponent<MenuSettingElement>()); SliderReinitializer sliderReinitializer = obj.AddComponent<SliderReinitializer>(); sliderReinitializer.menuSlider = component; sliderReinitializer.elementName = elementName; if (color == Color.red) { sliderReinitializer.startValue = ModdedColorPlayerAvatar.LocalColor.r; } else if (color == Color.green) { sliderReinitializer.startValue = ModdedColorPlayerAvatar.LocalColor.g; } else if (color == Color.blue) { sliderReinitializer.startValue = ModdedColorPlayerAvatar.LocalColor.b; } return component; } } }
plugins/Xaru-JustRetryPlus/JustRetryPlus.dll
Decompiled 2 months agousing System; using System.Collections; using System.Collections.Generic; 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 BepInEx.Logging; using HarmonyLib; 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("JustRetryPlus")] [assembly: AssemblyConfiguration("Debug")] [assembly: AssemblyFileVersion("1.0.1.0")] [assembly: AssemblyInformationalVersion("1.0.1")] [assembly: AssemblyProduct("JustRetryPlus")] [assembly: AssemblyTitle("JustRetryPlus")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("1.0.1.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 JustRetryPlus { [BepInPlugin("JustRetryPlus", "JustRetryPlus", "1.0.1")] public class Plugin : BaseUnityPlugin { internal static ManualLogSource Logger; private static ConfigEntry<bool> _shouldResetLevel; private static ConfigEntry<bool> _shouldRestartWithFullHealth; private static bool _didFailLevel; private static ConfigEntry<bool> _isEnabled; private static ConfigEntry<int> _healthToHeal; public static bool ShouldResetLevel => _shouldResetLevel.Value; public static bool ShouldRestartWithFullHealth => _shouldRestartWithFullHealth.Value; public static bool DidFailLevel { get { return _didFailLevel; } set { _didFailLevel = value; } } public static bool IsEnabled => _isEnabled.Value; public static int HealthToHealValue => _healthToHeal.Value; private void Awake() { //IL_0021: Unknown result type (might be due to invalid IL or missing references) //IL_0027: Expected O, but got Unknown //IL_0060: Unknown result type (might be due to invalid IL or missing references) //IL_006a: Expected O, but got Unknown //IL_0091: Unknown result type (might be due to invalid IL or missing references) //IL_009b: Expected O, but got Unknown //IL_00c2: Unknown result type (might be due to invalid IL or missing references) //IL_00cc: Expected O, but got Unknown //IL_00f8: Unknown result type (might be due to invalid IL or missing references) //IL_0102: Expected O, but got Unknown Logger = ((BaseUnityPlugin)this).Logger; Logger.LogInfo((object)"Plugin JustRetryPlus is loaded!"); Harmony val = new Harmony("eu.xaru.justretryplus"); val.PatchAll(); Logger.LogInfo((object)"Harmony patches applied."); _isEnabled = ((BaseUnityPlugin)this).Config.Bind<bool>("Settings", "IsEnabled", true, new ConfigDescription("Toggle if the plugin should be enabled, if false the normal game death scene will take over", (AcceptableValueBase)(object)new AcceptableValueRange<bool>(false, true), Array.Empty<object>())); _shouldResetLevel = ((BaseUnityPlugin)this).Config.Bind<bool>("Settings", "ShouldResetLevel", false, new ConfigDescription("Toggle if the game should restart at level one & reset the map when failing a level", (AcceptableValueBase)(object)new AcceptableValueRange<bool>(false, true), Array.Empty<object>())); _shouldRestartWithFullHealth = ((BaseUnityPlugin)this).Config.Bind<bool>("Settings", "ShouldRestartWithFullHealth", true, new ConfigDescription("Toggle if the game should restart with full health when failing a level", (AcceptableValueBase)(object)new AcceptableValueRange<bool>(false, true), Array.Empty<object>())); _healthToHeal = ((BaseUnityPlugin)this).Config.Bind<int>("Settings", "HealthToHeal", 100, new ConfigDescription("The amount of health to heal when failing a level", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 200), Array.Empty<object>())); } private void Start() { Logger.LogInfo((object)"JustRetryPlus started!"); } } [HarmonyPatch(typeof(RunManager), "ChangeLevel")] public static class ChangeLevelPatch { [CompilerGenerated] private sealed class <DelayedAllHeal>d__2 : IEnumerator<object>, IEnumerator, IDisposable { private int <>1__state; private object <>2__current; object IEnumerator<object>.Current { [DebuggerHidden] get { return <>2__current; } } object IEnumerator.Current { [DebuggerHidden] get { return <>2__current; } } [DebuggerHidden] public <DelayedAllHeal>d__2(int <>1__state) { this.<>1__state = <>1__state; } [DebuggerHidden] void IDisposable.Dispose() { <>1__state = -2; } private bool MoveNext() { //IL_0034: Unknown result type (might be due to invalid IL or missing references) //IL_003e: Expected O, but got Unknown switch (<>1__state) { default: return false; case 0: <>1__state = -1; if (!Plugin.IsEnabled) { return false; } <>2__current = (object)new WaitForSeconds(5f); <>1__state = 1; return true; case 1: <>1__state = -1; Plugin.Logger.LogInfo((object)"Sending impulse to heal all players to full health after level failure"); GameDirector.instance.PlayerList.ForEach(delegate(PlayerAvatar player) { player.playerHealth.Heal(Plugin.HealthToHealValue, false); }); return false; } } bool IEnumerator.MoveNext() { //ILSpy generated this explicit interface implementation from .override directive in MoveNext return this.MoveNext(); } [DebuggerHidden] void IEnumerator.Reset() { throw new NotSupportedException(); } } private static void Prefix(RunManager __instance, ref bool _completedLevel, ref bool _levelFailed, ref ChangeLevelType _changeLevelType) { if (!Plugin.IsEnabled) { return; } Plugin.Logger.LogInfo((object)$"Level failed?: {_levelFailed}"); Plugin.DidFailLevel = _levelFailed; if (Plugin.DidFailLevel) { if (Plugin.ShouldResetLevel) { Plugin.Logger.LogInfo((object)"Restarting at level one"); __instance.ResetProgress(); __instance.SetRunLevel(); } Plugin.Logger.LogInfo((object)"Level failed, retrying..."); __instance.RestartScene(); Plugin.Logger.LogInfo((object)"Restarted scene"); } } private static void Postfix(RunManager __instance, bool _completedLevel, bool _levelFailed, ChangeLevelType _changeLevelType) { if (Plugin.IsEnabled && Plugin.ShouldRestartWithFullHealth && Plugin.DidFailLevel) { ((MonoBehaviour)__instance).StartCoroutine(DelayedAllHeal()); } } [IteratorStateMachine(typeof(<DelayedAllHeal>d__2))] private static IEnumerator DelayedAllHeal() { //yield-return decompiler failed: Unexpected instruction in Iterator.Dispose() return new <DelayedAllHeal>d__2(0); } } public static class MyPluginInfo { public const string PLUGIN_GUID = "JustRetryPlus"; public const string PLUGIN_NAME = "JustRetryPlus"; public const string PLUGIN_VERSION = "1.0.1"; } }
plugins/XiaohaiMod-XH_DamageShow_EnemyHealthBar/XH_DamageShow&EnemyHealthBar.dll
Decompiled 2 months agousing System; using System.Collections.Generic; using System.Diagnostics; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Versioning; using System.Security; using System.Security.Permissions; using BepInEx; using BepInEx.Logging; using HarmonyLib; using TMPro; using UnityEngine; using UnityEngine.UI; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)] [assembly: AssemblyTitle("REPO MOD")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("微软中国")] [assembly: AssemblyProduct("REPO MOD")] [assembly: AssemblyCopyright("Copyright © 微软中国 2025")] [assembly: AssemblyTrademark("")] [assembly: ComVisible(false)] [assembly: Guid("48060547-bfdb-47cd-aac0-71116dcfa012")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("1.0.0.0")] [module: UnverifiableCode] namespace REPO_MOD; [BepInPlugin("com.XhPlugin.Repo_Mod", "XH_REPO_DamageShow&EnemyHealthBar_Mod", "1.0.0")] public class Plugin : BaseUnityPlugin { public static ManualLogSource Logger; private readonly Harmony _harmony = new Harmony("com.XhPlugin.Repo_Mod"); private void Awake() { Logger = ((BaseUnityPlugin)this).Logger; _harmony.PatchAll(); Logger.LogInfo((object)"小海怪物血量MOD加载成功!Xiaohai DamageShow&EnemyHealthBar MOD loaded successfully!"); } } public class WorldSpaceUIDamageText : WorldSpaceUIChild { private TextMeshProUGUI textComponent; private float timer = 1.5f; private Vector3 baseWorldPosition; private float floatHeight; public void Awake() { textComponent = ((Component)this).GetComponent<TextMeshProUGUI>(); if ((Object)(object)textComponent == (Object)null) { textComponent = ((Component)this).gameObject.AddComponent<TextMeshProUGUI>(); } } public override void Start() { //IL_000e: 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_0042: Unknown result type (might be due to invalid IL or missing references) ((WorldSpaceUIChild)this).Start(); ((Graphic)textComponent).color = Color.red; ((TMP_Text)textComponent).fontSize = 40f; ((TMP_Text)textComponent).alignment = (TextAlignmentOptions)514; baseWorldPosition = base.worldPosition; } public override void Update() { //IL_0022: Unknown result type (might be due to invalid IL or missing references) //IL_0027: Unknown result type (might be due to invalid IL or missing references) //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_003c: Unknown result type (might be due to invalid IL or missing references) ((WorldSpaceUIChild)this).Update(); floatHeight += Time.deltaTime * 0.8f; base.worldPosition = baseWorldPosition + Vector3.up * floatHeight; timer -= Time.deltaTime; ((TMP_Text)textComponent).alpha = Mathf.Clamp01(timer * 2f); if (timer <= 0f) { Object.Destroy((Object)(object)((Component)this).gameObject); } } public void Initialize(int damage) { if ((Object)(object)textComponent == (Object)null) { textComponent = ((Component)this).GetComponent<TextMeshProUGUI>(); } ((TMP_Text)textComponent).text = $"-{damage}"; } } public class WorldSpaceUIHealthText : WorldSpaceUIChild { private TextMeshProUGUI textComponent; private float timer = 5f; private EnemyHealth targetEnemy; private static Dictionary<EnemyHealth, WorldSpaceUIHealthText> activeTexts = new Dictionary<EnemyHealth, WorldSpaceUIHealthText>(); protected void Awake() { //IL_0013: Unknown result type (might be due to invalid IL or missing references) textComponent = ((Component)this).GetComponent<TextMeshProUGUI>(); ((Graphic)textComponent).color = Color.red; ((TMP_Text)textComponent).fontSize = 15f; ((TMP_Text)textComponent).alignment = (TextAlignmentOptions)514; } public override void Update() { //IL_0036: 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_003e: Unknown result type (might be due to invalid IL or missing references) //IL_005b: 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_0066: Unknown result type (might be due to invalid IL or missing references) //IL_006b: Unknown result type (might be due to invalid IL or missing references) //IL_0070: Unknown result type (might be due to invalid IL or missing references) ((WorldSpaceUIChild)this).Update(); if ((Object)(object)targetEnemy != (Object)null) { Collider component = ((Component)targetEnemy).GetComponent<Collider>(); float num; if (!((Object)(object)component != (Object)null)) { num = 3f; } else { Bounds bounds = component.bounds; num = ((Bounds)(ref bounds)).size.y + 3f; } float num2 = num; base.worldPosition = ((Component)targetEnemy).transform.position + Vector3.up * num2; } timer -= Time.deltaTime; if (timer <= 0f) { Cleanup(); } if ((Object)(object)targetEnemy != (Object)null) { string text = targetEnemy.enemy.EnemyParent.enemyName; if (text == null) { text = "未知敌人"; } ((TMP_Text)textComponent).text = $"{text}\r\n{targetEnemy.healthCurrent}/{targetEnemy.health}"; } } public void Initialize(EnemyHealth enemy) { targetEnemy = enemy; ((TMP_Text)textComponent).text = $"{enemy.healthCurrent}/{enemy.health}"; if (activeTexts.ContainsKey(enemy)) { activeTexts[enemy].RefreshTimer(); Object.Destroy((Object)(object)((Component)this).gameObject); } else { activeTexts.Add(enemy, this); } } public void RefreshTimer() { timer = 5f; ((TMP_Text)textComponent).text = $"{targetEnemy.healthCurrent}/{targetEnemy.health}"; } private void Cleanup() { if ((Object)(object)targetEnemy != (Object)null) { activeTexts.Remove(targetEnemy); } Object.Destroy((Object)(object)((Component)this).gameObject); } public static void CreateOrUpdate(EnemyHealth enemy) { if (activeTexts.TryGetValue(enemy, out var value)) { value.RefreshTimer(); } else { CreateNewText(enemy); } } private static void CreateNewText(EnemyHealth enemy) { //IL_0044: Unknown result type (might be due to invalid IL or missing references) //IL_004a: Expected O, but got Unknown if (!((Object)(object)WorldSpaceUIParent.instance == (Object)null)) { GameObject val = new GameObject("HealthText", new Type[3] { typeof(RectTransform), typeof(TextMeshProUGUI), typeof(WorldSpaceUIHealthText) }); val.transform.SetParent(((Component)WorldSpaceUIParent.instance).transform); WorldSpaceUIHealthText component = val.GetComponent<WorldSpaceUIHealthText>(); component.Initialize(enemy); } } } public static class DamageTextManager { public static void CreateDamageText(Vector3 position, int damage) { //IL_0033: Unknown result type (might be due to invalid IL or missing references) //IL_0039: Expected O, but got Unknown //IL_005f: 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_0075: Unknown result type (might be due to invalid IL or missing references) GameObject val = new GameObject("DamageText", new Type[3] { typeof(RectTransform), typeof(TextMeshProUGUI), typeof(WorldSpaceUIDamageText) }); val.transform.SetParent(((Component)WorldSpaceUIParent.instance).transform); WorldSpaceUIDamageText component = val.GetComponent<WorldSpaceUIDamageText>(); component.Initialize(damage); ((WorldSpaceUIChild)component).worldPosition = position; Plugin.Logger.LogInfo((object)$"生成伤害文本:-{damage} 位置:{position}"); } } public class EnemyHealthBar : MonoBehaviour { public class Billboard : MonoBehaviour { public Vector3 offset; private Camera mainCamera; private void Start() { mainCamera = Camera.main; } private void LateUpdate() { //IL_0023: Unknown result type (might be due to invalid IL or missing references) //IL_0038: 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) //IL_0063: Unknown result type (might be due to invalid IL or missing references) //IL_0069: Unknown result type (might be due to invalid IL or missing references) //IL_006e: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)mainCamera != (Object)null) { ((Component)this).transform.rotation = Quaternion.Euler(((Component)mainCamera).transform.eulerAngles.x, ((Component)mainCamera).transform.eulerAngles.y, 0f); ((Component)this).transform.position = ((Component)this).transform.parent.position + offset; } } } private float _lastDamageTime; private bool _isActive = true; public Vector3 worldOffset = new Vector3(0f, 2.5f, 0f); public Vector2 size = new Vector2(20f, 2.5f); public Color backgroundColor = new Color(0.3f, 0.3f, 0.3f, 0.9f); public Color healthColor = Color.red; public Canvas canvas; private Image foreground; private Image background; private EnemyHealth enemyHealth; private TextMeshProUGUI healthText; private void Awake() { enemyHealth = ((Component)this).GetComponent<EnemyHealth>(); InitializeCanvas(); UpdateHealthDisplay(); ResetTimer(); Debug.Log((object)("血条初始化完成,敌人:" + ((Object)enemyHealth).name)); } public void ResetTimer() { _lastDamageTime = Time.time; if (!_isActive) { ReactivateHealthBar(); } } private void ReactivateHealthBar() { _isActive = true; ((Component)canvas).gameObject.SetActive(true); UpdateHealthDisplay(); UpdateCanvasVisibility(); } private void DestroyHealthBar() { _isActive = false; ((Component)canvas).gameObject.SetActive(false); } private void InitializeCanvas() { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_000c: Expected O, but got Unknown //IL_0048: 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_007c: Unknown result type (might be due to invalid IL or missing references) //IL_009c: Unknown result type (might be due to invalid IL or missing references) //IL_00be: Unknown result type (might be due to invalid IL or missing references) //IL_0102: Unknown result type (might be due to invalid IL or missing references) //IL_0107: Unknown result type (might be due to invalid IL or missing references) GameObject val = new GameObject("HealthCanvas"); canvas = val.AddComponent<Canvas>(); canvas.renderMode = (RenderMode)2; ((Component)canvas).transform.SetParent(((Component)this).transform); ((Component)canvas).transform.localPosition = worldOffset; RectTransform component = ((Component)canvas).GetComponent<RectTransform>(); component.sizeDelta = size; ((Transform)component).localScale = new Vector3(0.03f, 0.03f, 0.03f); val.AddComponent<GraphicRaycaster>(); background = CreateBarElement(((Component)canvas).transform, backgroundColor, "Background"); foreground = CreateBarElement(((Component)canvas).transform, healthColor, "Foreground"); foreground.type = (Type)3; foreground.fillMethod = (FillMethod)0; foreground.fillOrigin = 0; Billboard billboard = val.AddComponent<Billboard>(); billboard.offset = worldOffset; CreateHealthText(((Component)canvas).transform); } private void CreateHealthText(Transform parent) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_000c: Expected O, but got Unknown //IL_004e: 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_0095: Unknown result type (might be due to invalid IL or missing references) //IL_00ab: Unknown result type (might be due to invalid IL or missing references) //IL_00c1: Unknown result type (might be due to invalid IL or missing references) //IL_00d7: Unknown result type (might be due to invalid IL or missing references) GameObject val = new GameObject("HealthText"); val.transform.SetParent(parent, false); healthText = val.AddComponent<TextMeshProUGUI>(); ((TMP_Text)healthText).alignment = (TextAlignmentOptions)514; ((TMP_Text)healthText).fontSize = 10f; ((Graphic)healthText).color = Color.white; ((TMP_Text)healthText).margin = new Vector4(0f, 0f, 0f, 10f); RectTransform component = ((Component)healthText).GetComponent<RectTransform>(); component.anchorMin = new Vector2(0.5f, 1f); component.anchorMax = new Vector2(0.5f, 1f); component.pivot = new Vector2(0.5f, 0.5f); component.anchoredPosition = new Vector2(0f, 5f); } private void UpdateHealthText() { //IL_009c: Unknown result type (might be due to invalid IL or missing references) //IL_0087: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)healthText != (Object)null && (Object)(object)enemyHealth != (Object)null) { ((TMP_Text)healthText).text = $"{enemyHealth.healthCurrent}/{enemyHealth.health}"; if ((float)enemyHealth.healthCurrent / (float)enemyHealth.health < 0.3f) { ((Graphic)healthText).color = Color.yellow; } else { ((Graphic)healthText).color = Color.white; } } } private Image CreateBarElement(Transform parent, Color color, string name) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0008: Expected O, but got Unknown //IL_0018: Unknown result type (might be due to invalid IL or missing references) //IL_001e: Expected O, but got Unknown //IL_0021: 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_0055: Unknown result type (might be due to invalid IL or missing references) //IL_0066: 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_0081: 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_0099: Unknown result type (might be due to invalid IL or missing references) GameObject val = new GameObject(name); val.transform.SetParent(parent, false); Texture2D val2 = new Texture2D(1, 1); val2.SetPixel(0, 0, Color.white); val2.Apply(); Image val3 = val.AddComponent<Image>(); val3.sprite = Sprite.Create(val2, new Rect(0f, 0f, 1f, 1f), Vector2.zero); ((Graphic)val3).color = color; RectTransform component = val.GetComponent<RectTransform>(); component.anchorMin = Vector2.zero; component.anchorMax = Vector2.one; component.offsetMin = Vector2.zero; component.offsetMax = Vector2.zero; return val3; } private void Update() { //IL_0039: 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_004a: Unknown result type (might be due to invalid IL or missing references) //IL_004f: Unknown result type (might be due to invalid IL or missing references) //IL_0054: Unknown result type (might be due to invalid IL or missing references) if (_isActive) { if (Time.time - _lastDamageTime > 5f) { DestroyHealthBar(); return; } Debug.DrawLine(((Component)this).transform.position, ((Component)this).transform.position + worldOffset, Color.green); UpdateHealthDisplay(); UpdateCanvasVisibility(); } } private void UpdateCanvasVisibility() { //IL_000b: 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_005c: 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) float num = Vector3.Distance(((Component)Camera.main).transform.position, ((Component)this).transform.position); float num2 = Mathf.Clamp01(1f - num / 50f); ((Graphic)foreground).color = new Color(healthColor.r, healthColor.g, healthColor.b, num2); ((Graphic)background).color = new Color(backgroundColor.r, backgroundColor.g, backgroundColor.b, num2 * 0.8f); } public void UpdateHealthDisplay() { //IL_0093: 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) if (!((Object)(object)enemyHealth == (Object)null)) { float num = Mathf.Clamp01((float)enemyHealth.healthCurrent / (float)enemyHealth.health); foreground.fillAmount = Mathf.Lerp(foreground.fillAmount, num, Time.deltaTime * 10f); if (num < 0.3f) { float num2 = Mathf.PingPong(Time.time * 2f, 1f); ((Graphic)foreground).color = new Color(1f, num2, num2, ((Graphic)foreground).color.a); } UpdateHealthText(); } } private void OnDestroy() { if ((Object)(object)canvas != (Object)null) { Debug.Log((object)("销毁血条:" + ((Object)enemyHealth).name)); Object.Destroy((Object)(object)((Component)canvas).gameObject); } } } [HarmonyPatch] public static class Patch { [HarmonyPatch(typeof(BigMessageUI))] internal class BigMessageUIPatch { [HarmonyPatch("Update")] [HarmonyPrefix] private static bool UpdatePrefix(BigMessageUI __instance, ref float ___bigMessageTimer) { if (___bigMessageTimer > 0f) { ___bigMessageTimer -= Time.deltaTime * 0.5f; return false; } return true; } } [HarmonyPatch(typeof(EnemyHealth), "Hurt")] [HarmonyPostfix] private static void OnHurt(EnemyHealth __instance, int _damage) { //IL_0052: Unknown result type (might be due to invalid IL or missing references) //IL_0057: 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_0066: Unknown result type (might be due to invalid IL or missing references) //IL_006b: 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_007a: Unknown result type (might be due to invalid IL or missing references) //IL_007f: 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) if (_damage <= 0 || (Object)(object)__instance == (Object)null) { return; } try { EnemyHealthBar enemyHealthBar = ((Component)__instance).GetComponent<EnemyHealthBar>(); if ((Object)(object)enemyHealthBar == (Object)null) { enemyHealthBar = ((Component)__instance).gameObject.AddComponent<EnemyHealthBar>(); } else { enemyHealthBar.ResetTimer(); } enemyHealthBar.UpdateHealthDisplay(); Vector3 position = ((Component)__instance).transform.position + Vector3.up * 1.5f + Random.insideUnitSphere * 0.3f; DamageTextManager.CreateDamageText(position, _damage); } catch (Exception arg) { Plugin.Logger.LogError((object)$"处理伤害时出错: {arg}"); } } [HarmonyPostfix] [HarmonyPatch(typeof(EnemyHealth), "Death")] private static void OnDeath(EnemyHealth __instance) { EnemyHealthBar component = ((Component)__instance).GetComponent<EnemyHealthBar>(); if ((Object)(object)component != (Object)null) { Object.Destroy((Object)(object)component); } } [HarmonyPostfix] [HarmonyPatch(typeof(EnemyHealth), "Awake")] private static void PostStart(EnemyHealth __instance) { //IL_0030: 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) try { if ((Object)(object)((Component)__instance).GetComponent<EnemyHealthBar>() == (Object)null) { EnemyHealthBar enemyHealthBar = ((Component)__instance).gameObject.AddComponent<EnemyHealthBar>(); enemyHealthBar.worldOffset = new Vector3(0f, GetEnemyHeight(__instance), 0f); Plugin.Logger.LogInfo((object)("初始化血条:" + ((Object)__instance).name)); } } catch (Exception arg) { Debug.LogError((object)$"血条初始化失败:{arg}"); } } private static float GetEnemyHeight(EnemyHealth enemy) { //IL_0019: Unknown result type (might be due to invalid IL or missing references) //IL_001e: Unknown result type (might be due to invalid IL or missing references) //IL_0021: Unknown result type (might be due to invalid IL or missing references) Collider component = ((Component)enemy).GetComponent<Collider>(); float result; if (!((Object)(object)component != (Object)null)) { result = 2.5f; } else { Bounds bounds = component.bounds; result = ((Bounds)(ref bounds)).size.y + 0.5f; } return result; } } [HarmonyPatch(typeof(ExtractionPoint))] public static class ExtractionPoint_Patches { private static bool once; [HarmonyPrefix] [HarmonyPatch("StateActive")] private static void Postfix_MissionText() { //IL_0019: Unknown result type (might be due to invalid IL or missing references) //IL_0023: Unknown result type (might be due to invalid IL or missing references) if (!once) { once = true; SemiFunc.UIFocusText("欢迎使用由CO2赞助的怪物血量MOD by小海", Color.white, AssetManager.instance.colorYellow, 5f); } } }
plugins/YMC_MHZ-MoreHead/MoreHead/MoreHead.dll
Decompiled 2 months agousing System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using BepInEx; using BepInEx.Logging; using HarmonyLib; using MenuLib; using Microsoft.CodeAnalysis; using MoreHead; using Newtonsoft.Json; using Photon.Pun; using UnityEngine; using UnityEngine.UI; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)] [assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = "")] [assembly: AssemblyCompany("MoreHead")] [assembly: AssemblyConfiguration("Debug")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: AssemblyInformationalVersion("1.0.0")] [assembly: AssemblyProduct("MoreHead")] [assembly: AssemblyTitle("MoreHead")] [assembly: AssemblyVersion("1.0.0.0")] 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; } } } [BepInPlugin("Mhz.REPOMoreHead", "MoreHead", "1.2.2")] public class Morehead : BaseUnityPlugin { private const string PluginGuid = "Mhz.REPOMoreHead"; private const string PluginName = "MoreHead"; private const string PluginVersion = "1.2.2"; public static ManualLogSource? Logger; public static Morehead? Instance { get; private set; } private void Awake() { //IL_0019: Unknown result type (might be due to invalid IL or missing references) //IL_001f: Expected O, but got Unknown Instance = this; Logger = ((BaseUnityPlugin)this).Logger; try { Harmony val = new Harmony("Mhz.REPOMoreHead"); val.PatchAll(typeof(PlayerAvatarVisualsPatch)); val.PatchAll(typeof(PlayerUpdatePatch)); val.PatchAll(typeof(PlayerAvatarAwakePatch)); val.PatchAll(typeof(GameDirectorUpdatePatch)); val.PatchAll(typeof(PlayerRevivePatch)); string text = "\n\n ███▄ ▄███▓ ▒█████ ██▀███ ▓█████ ██░ ██ ▓█████ ▄▄▄ ▓█████▄ \n▓██▒▀█▀ ██▒▒██▒ ██▒▓██ ▒ ██▒▓█ ▀ ▓██░ ██▒▓█ ▀▒████▄ ▒██▀ ██▌\n▓██ ▓██░▒██░ ██▒▓██ ░▄█ ▒▒███ ▒██▀███░▒███ ▒██ ▀█▄ ░██ █▌\n▒██ ▒██ ▒██ ██░▒███▀█▄ ▒▓█ ▄ ░▓█ ░██ ▒▓█ ▄░██▄▄▄▄██ ░▓█▄ ▌\n▒██▒ ░██▒░ ████▓▒░░██▓ ▒██▒░▒████▒░▓█▒░██▓░▒████▒▓█ ▓██▒░▒████▓ v1.2.2\n░ ▒░ ░ ░░ ▒░▒░▒░ ░ ▒▓ ░▒▓░░░ ▒░ ░ ▒ ░░▒░▒░░ ▒░ ░▒▒ ▓▒█░ ▒▒▓ ▒ \n░ ░ ░ ░ ▒ ▒░ ░▒ ░ ▒░ ░ ░ ░ ▒ ░▒░ ░ ░ ░ ░ ▒ ▒▒ ░ ░ ▒ ▒ \n░ ░ ░ ░ ░ ▒ ░░ ░ ░ ░ ░░ ░ ░ ░ ▒ ░ ░ ░ \n ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ \n"; ManualLogSource? logger = Logger; if (logger != null) { logger.LogMessage((object)text); } HeadDecorationManager.Initialize(); ConfigManager.Initialize(); MoreHeadUI.Initialize(); } catch (Exception ex) { ManualLogSource? logger2 = Logger; if (logger2 != null) { logger2.LogError((object)("Harmony补丁应用失败: " + ex.Message)); } } } private void OnApplicationQuit() { ConfigManager.SaveConfig(); } public static bool GetDecorationState(string? name) { return HeadDecorationManager.GetDecorationState(name); } } [HarmonyPatch(typeof(PlayerAvatar))] [HarmonyPatch("Update")] internal class PlayerUpdatePatch { private static void Postfix(PlayerAvatar __instance) { if (__instance.photonView.IsMine && GameManager.Multiplayer() && PhotonNetwork.LocalPlayer != null) { } } public static void UpdatePlayerDecorations(PlayerAvatar playerAvatar) { try { if ((Object)(object)playerAvatar?.playerAvatarVisuals == (Object)null) { return; } Dictionary<string, Transform> decorationParentNodes = DecorationUtils.GetDecorationParentNodes(((Component)playerAvatar.playerAvatarVisuals).transform); if (decorationParentNodes.Count == 0) { ManualLogSource? logger = Morehead.Logger; if (logger != null) { logger.LogWarning((object)"找不到任何装饰物父级节点"); } return; } DecorationUtils.EnsureDecorationContainers(decorationParentNodes); foreach (DecorationInfo decoration in HeadDecorationManager.Decorations) { if (decorationParentNodes.TryGetValue(decoration.ParentTag ?? string.Empty, out var value)) { Transform val = value.Find("HeadDecorations"); if ((Object)(object)val != (Object)null) { DecorationUtils.UpdateDecoration(val, decoration.Name ?? string.Empty, decoration.IsVisible); } } else { ManualLogSource? logger2 = Morehead.Logger; if (logger2 != null) { logger2.LogWarning((object)("找不到装饰物 " + decoration.DisplayName + " 的父级节点: " + decoration.ParentTag)); } } } } catch (Exception ex) { ManualLogSource? logger3 = Morehead.Logger; if (logger3 != null) { logger3.LogError((object)("更新玩家装饰物时出错: " + ex.Message)); } } } public static void UpdateMenuPlayerDecorations() { try { PlayerAvatarVisuals val = FindMenuPlayerVisuals(); if ((Object)(object)val == (Object)null) { return; } Dictionary<string, Transform> decorationParentNodes = DecorationUtils.GetDecorationParentNodes(((Component)val).transform); if (decorationParentNodes.Count == 0) { ManualLogSource? logger = Morehead.Logger; if (logger != null) { logger.LogWarning((object)"找不到任何菜单角色装饰物父级节点"); } return; } DecorationUtils.EnsureDecorationContainers(decorationParentNodes); foreach (DecorationInfo decoration in HeadDecorationManager.Decorations) { if (decorationParentNodes.TryGetValue(decoration.ParentTag ?? string.Empty, out var value)) { Transform val2 = value.Find("HeadDecorations"); if ((Object)(object)val2 != (Object)null) { Transform val3 = val2.Find(decoration.Name); if ((Object)(object)val3 == (Object)null) { AddMenuDecoration(val2, decoration.Name); } else { DecorationUtils.UpdateDecoration(val2, decoration.Name ?? string.Empty, decoration.IsVisible); } } } else { ManualLogSource? logger2 = Morehead.Logger; if (logger2 != null) { logger2.LogWarning((object)("找不到菜单角色装饰物 " + decoration.DisplayName + " 的父级节点: " + decoration.ParentTag)); } } } } catch (Exception ex) { ManualLogSource? logger3 = Morehead.Logger; if (logger3 != null) { logger3.LogError((object)("更新菜单角色装饰物状态失败: " + ex.Message)); } } } private static PlayerAvatarVisuals? FindMenuPlayerVisuals() { if ((Object)(object)PlayerAvatarMenu.instance == (Object)null) { return null; } return ((Component)PlayerAvatarMenu.instance).GetComponentInChildren<PlayerAvatarVisuals>(); } public static void AddMenuDecoration(Transform parent, string? decorationName) { string decorationName2 = decorationName; try { Transform val = parent.Find(decorationName2); if ((Object)(object)val != (Object)null) { bool decorationState = Morehead.GetDecorationState(decorationName2); ((Component)val).gameObject.SetActive(decorationState); return; } DecorationInfo decorationInfo = HeadDecorationManager.Decorations.Find((DecorationInfo d) => d.Name != null && d.Name.Equals(decorationName2, StringComparison.OrdinalIgnoreCase)); if (decorationInfo != null && (Object)(object)decorationInfo.Prefab != (Object)null) { GameObject val2 = Object.Instantiate<GameObject>(decorationInfo.Prefab, parent); ((Object)val2).name = decorationName2; val2.SetActive(decorationInfo.IsVisible); return; } ManualLogSource? logger = Morehead.Logger; if (logger != null) { logger.LogWarning((object)("AddMenuDecoration: 找不到装饰物 " + decorationName2 + " 或其预制体为空")); } } catch (Exception ex) { ManualLogSource? logger2 = Morehead.Logger; if (logger2 != null) { logger2.LogError((object)("为菜单角色添加装饰物时出错: " + ex.Message)); } } } } [HarmonyPatch(typeof(PlayerAvatar))] [HarmonyPatch("Awake")] internal class PlayerAvatarAwakePatch { private static void Postfix(PlayerAvatar __instance) { ((Component)__instance).gameObject.AddComponent<HeadDecorationSync>(); } } public class HeadDecorationSync : MonoBehaviourPun { public void SyncAllDecorations() { try { string[] array = new string[HeadDecorationManager.Decorations.Count]; bool[] array2 = new bool[HeadDecorationManager.Decorations.Count]; string[] array3 = new string[HeadDecorationManager.Decorations.Count]; for (int i = 0; i < HeadDecorationManager.Decorations.Count; i++) { DecorationInfo decorationInfo = HeadDecorationManager.Decorations[i]; array[i] = decorationInfo.Name; array2[i] = decorationInfo.IsVisible; array3[i] = decorationInfo.ParentTag; } ((MonoBehaviourPun)this).photonView.RPC("UpdateAllDecorations", (RpcTarget)1, new object[3] { array, array2, array3 }); } catch (Exception ex) { ManualLogSource? logger = Morehead.Logger; if (logger != null) { logger.LogError((object)("同步所有装饰物状态失败: " + ex.Message)); } } } [PunRPC] private void UpdateAllDecorations(string[] names, bool[] states, string[] parentTags) { try { PlayerAvatar component = ((Component)this).GetComponent<PlayerAvatar>(); if ((Object)(object)component == (Object)null || (Object)(object)component.playerAvatarVisuals == (Object)null) { ManualLogSource? logger = Morehead.Logger; if (logger != null) { logger.LogWarning((object)"找不到PlayerAvatar或PlayerAvatarVisuals组件"); } return; } Dictionary<string, Transform> decorationParentNodes = DecorationUtils.GetDecorationParentNodes(((Component)component.playerAvatarVisuals).transform); if (decorationParentNodes.Count == 0) { ManualLogSource? logger2 = Morehead.Logger; if (logger2 != null) { logger2.LogWarning((object)"找不到任何装饰物父级节点"); } return; } DecorationUtils.EnsureDecorationContainers(decorationParentNodes); for (int i = 0; i < names.Length; i++) { string decorationName = names[i]; bool showDecoration = states[i]; string key = parentTags[i]; if (decorationParentNodes.TryGetValue(key, out var value)) { Transform val = value.Find("HeadDecorations"); if ((Object)(object)val != (Object)null) { DecorationUtils.UpdateDecoration(val, decorationName, showDecoration); } } } } catch (Exception ex) { ManualLogSource? logger3 = Morehead.Logger; if (logger3 != null) { logger3.LogError((object)("RPC更新所有装饰物状态失败: " + ex.Message)); } } } } [HarmonyPatch(typeof(PlayerAvatarVisuals))] [HarmonyPatch("Start")] internal class PlayerAvatarVisualsPatch { private static void Postfix(PlayerAvatarVisuals __instance) { try { Dictionary<string, Transform> decorationParentNodes = DecorationUtils.GetDecorationParentNodes(((Component)__instance).transform); if (decorationParentNodes.Count == 0) { ManualLogSource? logger = Morehead.Logger; if (logger != null) { logger.LogWarning((object)$"找不到任何装饰物父级节点 (isMenuAvatar: {__instance.isMenuAvatar})"); } return; } DecorationUtils.EnsureDecorationContainers(decorationParentNodes); if (__instance.isMenuAvatar) { foreach (KeyValuePair<string, Transform> item in decorationParentNodes) { string key = item.Key; Transform value = item.Value; Transform val = value.Find("HeadDecorations"); if ((Object)(object)val != (Object)null) { foreach (DecorationInfo decoration in HeadDecorationManager.Decorations) { if (decoration.ParentTag == key) { PlayerUpdatePatch.AddMenuDecoration(val, decoration.Name); } } } } return; } foreach (DecorationInfo decoration2 in HeadDecorationManager.Decorations) { if (decorationParentNodes.TryGetValue(decoration2.ParentTag ?? string.Empty, out var value2)) { Transform val2 = value2.Find("HeadDecorations"); if ((Object)(object)val2 != (Object)null) { AddNewDecoration(val2, decoration2, __instance); } } else { ManualLogSource? logger2 = Morehead.Logger; if (logger2 != null) { logger2.LogWarning((object)("初始化时找不到装饰物 " + decoration2.DisplayName + " 的父级节点: " + decoration2.ParentTag)); } } } if (!GameManager.Multiplayer() || !((Object)(object)__instance.playerAvatar != (Object)null) || !((Object)(object)__instance.playerAvatar.photonView != (Object)null) || !__instance.playerAvatar.photonView.IsMine) { return; } try { HeadDecorationSync component = ((Component)__instance.playerAvatar).GetComponent<HeadDecorationSync>(); if ((Object)(object)component != (Object)null) { component.SyncAllDecorations(); return; } ManualLogSource? logger3 = Morehead.Logger; if (logger3 != null) { logger3.LogWarning((object)"找不到HeadDecorationSync组件,无法同步初始状态"); } } catch (Exception ex) { ManualLogSource? logger4 = Morehead.Logger; if (logger4 != null) { logger4.LogError((object)("同步初始装饰物状态失败: " + ex.Message)); } } } catch (Exception ex2) { ManualLogSource? logger5 = Morehead.Logger; if (logger5 != null) { logger5.LogError((object)$"添加装饰物失败: {ex2.Message} (isMenuAvatar: {__instance.isMenuAvatar})"); } } } private static void AddNewDecoration(Transform parent, DecorationInfo decoration, PlayerAvatarVisuals __instance) { Transform val = parent.Find(decoration.Name); if ((Object)(object)val != (Object)null) { ((Component)val).gameObject.SetActive(decoration.IsVisible); return; } if ((Object)(object)decoration.Prefab != (Object)null) { try { GameObject val2 = Object.Instantiate<GameObject>(decoration.Prefab, parent); ((Object)val2).name = decoration.Name; val2.SetActive(decoration.IsVisible); return; } catch (Exception ex) { ManualLogSource? logger = Morehead.Logger; if (logger != null) { logger.LogError((object)("实例化预制体时出错: " + ex.Message)); } return; } } ManualLogSource? logger2 = Morehead.Logger; if (logger2 != null) { logger2.LogWarning((object)("AddNewDecoration: 装饰物 " + decoration.DisplayName + " 的预制体为空")); } } } [HarmonyPatch(typeof(GameDirector))] [HarmonyPatch("Update")] internal class GameDirectorUpdatePatch { private static gameState previousState; private static void Postfix(GameDirector __instance) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0008: Invalid comparison between Unknown and I4 //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0011: Invalid comparison between Unknown and I4 //IL_0023: Unknown result type (might be due to invalid IL or missing references) //IL_0028: Unknown result type (might be due to invalid IL or missing references) try { if ((int)previousState != 2 && (int)__instance.currentState == 2) { SyncAllPlayersDecorations(); } previousState = __instance.currentState; } catch (Exception ex) { ManualLogSource? logger = Morehead.Logger; if (logger != null) { logger.LogError((object)("监听游戏状态变化时出错: " + ex.Message)); } } } private static void SyncAllPlayersDecorations() { try { PlayerAvatar val = FindLocalPlayer(); if ((Object)(object)val != (Object)null) { PlayerUpdatePatch.UpdatePlayerDecorations(val); HeadDecorationSync component = ((Component)val).GetComponent<HeadDecorationSync>(); if ((Object)(object)component != (Object)null) { component.SyncAllDecorations(); } } } catch (Exception ex) { ManualLogSource? logger = Morehead.Logger; if (logger != null) { logger.LogError((object)("同步所有玩家装饰物状态时出错: " + ex.Message)); } } } private static PlayerAvatar? FindLocalPlayer() { try { PlayerAvatar[] array = Object.FindObjectsOfType<PlayerAvatar>(); PlayerAvatar[] array2 = array; foreach (PlayerAvatar val in array2) { if ((Object)(object)val?.photonView != (Object)null && val.photonView.IsMine) { return val; } } } catch (Exception ex) { ManualLogSource? logger = Morehead.Logger; if (logger != null) { logger.LogError((object)("查找本地玩家时出错: " + ex.Message)); } } return null; } } [HarmonyPatch(typeof(PlayerAvatar))] [HarmonyPatch("ReviveRPC")] internal class PlayerRevivePatch { private static void Postfix(PlayerAvatar __instance) { try { if (__instance.photonView.IsMine) { ((MonoBehaviour)__instance).StartCoroutine(DelayedSync(__instance)); } } catch (Exception ex) { ManualLogSource? logger = Morehead.Logger; if (logger != null) { logger.LogError((object)("玩家复活时同步装饰物状态失败: " + ex.Message)); } } } private static IEnumerator DelayedSync(PlayerAvatar playerAvatar) { yield return null; yield return (object)new WaitForSeconds(0.2f); try { PlayerUpdatePatch.UpdatePlayerDecorations(playerAvatar); } catch (Exception e2) { ManualLogSource? logger = Morehead.Logger; if (logger != null) { logger.LogError((object)("更新玩家装饰物状态失败: " + e2.Message)); } } yield return (object)new WaitForSeconds(0.1f); try { HeadDecorationSync syncComponent = ((Component)playerAvatar).GetComponent<HeadDecorationSync>(); if ((Object)(object)syncComponent != (Object)null) { syncComponent.SyncAllDecorations(); yield break; } ManualLogSource? logger2 = Morehead.Logger; if (logger2 != null) { logger2.LogWarning((object)"玩家复活后找不到HeadDecorationSync组件"); } } catch (Exception e) { ManualLogSource? logger3 = Morehead.Logger; if (logger3 != null) { logger3.LogError((object)("同步装饰物状态失败: " + e.Message)); } } } } namespace MoreHead { public static class ConfigManager { private const string MOD_DATA_FOLDER = "REPOModData"; private const string MOD_FOLDER = "MoreHead"; private const string CONFIG_FILENAME = "MoreHeadConfig.json"; private static Dictionary<string?, bool> _decorationStates = new Dictionary<string, bool>(); private static ManualLogSource? Logger => Morehead.Logger; private static string NewConfigFilePath => Path.Combine(Application.persistentDataPath, "REPOModData", "MoreHead", "MoreHeadConfig.json"); private static string BepInExConfigFilePath => Path.Combine(Paths.ConfigPath, "MoreHeadConfig.json"); private static string OldConfigFilePath { get { Morehead? instance = Morehead.Instance; return Path.Combine(Path.GetDirectoryName((instance != null) ? ((BaseUnityPlugin)instance).Info.Location : null) ?? string.Empty, "MoreHeadConfig.txt"); } } public static void Initialize() { try { EnsureModDataDirectoryExists(); LoadConfig(); ApplySavedStates(); } catch (Exception ex) { ManualLogSource? logger = Logger; if (logger != null) { logger.LogError((object)("初始化配置管理器时出错: " + ex.Message)); } } } private static void EnsureModDataDirectoryExists() { try { string text = Path.Combine(Application.persistentDataPath, "REPOModData"); if (!Directory.Exists(text)) { Directory.CreateDirectory(text); ManualLogSource? logger = Logger; if (logger != null) { logger.LogInfo((object)("已创建MOD数据总文件夹: " + text)); } } string text2 = Path.Combine(text, "MoreHead"); if (!Directory.Exists(text2)) { Directory.CreateDirectory(text2); ManualLogSource? logger2 = Logger; if (logger2 != null) { logger2.LogInfo((object)("已创建MOD特定文件夹: " + text2)); } } } catch (Exception ex) { ManualLogSource? logger3 = Logger; if (logger3 != null) { logger3.LogError((object)("创建MOD数据目录时出错: " + ex.Message)); } } } private static void LoadConfig() { try { _decorationStates.Clear(); if (File.Exists(NewConfigFilePath) && LoadJsonConfig(NewConfigFilePath)) { ManualLogSource? logger = Logger; if (logger != null) { logger.LogInfo((object)("已从Unity存档位置加载配置: " + NewConfigFilePath)); } return; } if (File.Exists(BepInExConfigFilePath) && LoadJsonConfig(BepInExConfigFilePath)) { ManualLogSource? logger2 = Logger; if (logger2 != null) { logger2.LogInfo((object)("已从BepInEx配置目录加载配置: " + BepInExConfigFilePath)); } SaveConfigWithoutUpdate(); ManualLogSource? logger3 = Logger; if (logger3 != null) { logger3.LogInfo((object)("已将配置从BepInEx目录迁移到Unity存档位置: " + NewConfigFilePath)); } try { File.Delete(BepInExConfigFilePath); ManualLogSource? logger4 = Logger; if (logger4 != null) { logger4.LogInfo((object)("已删除BepInEx配置文件: " + BepInExConfigFilePath)); } return; } catch (Exception ex) { ManualLogSource? logger5 = Logger; if (logger5 != null) { logger5.LogWarning((object)("删除BepInEx配置文件失败: " + ex.Message)); } return; } } if (!File.Exists(OldConfigFilePath)) { return; } try { string[] array = File.ReadAllLines(OldConfigFilePath); string[] array2 = array; foreach (string text in array2) { if (!string.IsNullOrWhiteSpace(text)) { string[] array3 = text.Split('='); if (array3.Length == 2) { string key = array3[0].Trim(); bool value = array3[1].Trim().Equals("1", StringComparison.OrdinalIgnoreCase); _decorationStates[key] = value; } } } if (_decorationStates.Count <= 0) { return; } ManualLogSource? logger6 = Logger; if (logger6 != null) { logger6.LogInfo((object)$"已从旧文本格式加载配置,包含 {_decorationStates.Count} 个装饰物状态"); } SaveConfigWithoutUpdate(); ManualLogSource? logger7 = Logger; if (logger7 != null) { logger7.LogInfo((object)("已将旧文本格式配置迁移到新的JSON格式: " + NewConfigFilePath)); } try { File.Delete(OldConfigFilePath); ManualLogSource? logger8 = Logger; if (logger8 != null) { logger8.LogInfo((object)("已删除旧文本配置文件: " + OldConfigFilePath)); } } catch (Exception ex2) { ManualLogSource? logger9 = Logger; if (logger9 != null) { logger9.LogWarning((object)("删除旧文本配置文件失败: " + ex2.Message)); } } } catch (Exception ex3) { ManualLogSource? logger10 = Logger; if (logger10 != null) { logger10.LogError((object)("从旧文本格式加载配置时出错: " + ex3.Message)); } } } catch (Exception ex4) { ManualLogSource? logger11 = Logger; if (logger11 != null) { logger11.LogError((object)("加载配置时出错: " + ex4.Message)); } _decorationStates.Clear(); } } private static bool LoadJsonConfig(string filePath) { //IL_0095: Expected O, but got Unknown try { string text = File.ReadAllText(filePath); Dictionary<string, bool> dictionary = JsonConvert.DeserializeObject<Dictionary<string, bool>>(text); if (dictionary != null) { foreach (KeyValuePair<string, bool> item in dictionary) { _decorationStates[item.Key] = item.Value; } ManualLogSource? logger = Logger; if (logger != null) { logger.LogInfo((object)$"已从JSON加载配置,包含 {_decorationStates.Count} 个装饰物状态"); } return true; } } catch (JsonException val) { JsonException val2 = val; ManualLogSource? logger2 = Logger; if (logger2 != null) { logger2.LogError((object)("解析JSON配置文件时出错: " + ((Exception)(object)val2).Message)); } } catch (Exception ex) { ManualLogSource? logger3 = Logger; if (logger3 != null) { logger3.LogError((object)("加载JSON配置文件时出错: " + ex.Message)); } } return false; } public static void SaveConfig() { try { UpdateConfigData(); SaveToFile(); } catch (Exception ex) { ManualLogSource? logger = Logger; if (logger != null) { logger.LogError((object)("保存配置时出错: " + ex.Message)); } } } private static void SaveConfigWithoutUpdate() { try { SaveToFile(); } catch (Exception ex) { ManualLogSource? logger = Logger; if (logger != null) { logger.LogError((object)("保存配置时出错: " + ex.Message)); } } } private static void SaveToFile() { try { EnsureModDataDirectoryExists(); string contents = JsonConvert.SerializeObject((object)_decorationStates, (Formatting)1); File.WriteAllText(NewConfigFilePath, contents); } catch (Exception ex) { ManualLogSource? logger = Logger; if (logger != null) { logger.LogError((object)("写入配置文件时出错: " + ex.Message)); } } } private static void UpdateConfigData() { _decorationStates.Clear(); foreach (DecorationInfo decoration in HeadDecorationManager.Decorations) { _decorationStates[decoration.Name] = decoration.IsVisible; } } private static void ApplySavedStates() { try { int num = 0; foreach (DecorationInfo decoration in HeadDecorationManager.Decorations) { if (_decorationStates.TryGetValue(decoration.Name, out var value)) { decoration.IsVisible = value; num++; } } if (num > 0) { ManualLogSource? logger = Logger; if (logger != null) { logger.LogInfo((object)$"已应用 {num} 个已保存的装饰物状态"); } } } catch (Exception ex) { ManualLogSource? logger2 = Logger; if (logger2 != null) { logger2.LogError((object)("应用已保存的装饰物状态时出错: " + ex.Message)); } } } } public static class DecorationUtils { private const string HEAD_NODE_PATH = "[RIG]/code_lean/code_tilt/ANIM BOT/_____________________________________/ANIM BODY BOT/_____________________________________/ANIM BODY TOP/code_body_top_up/code_body_top_side/_____________________________________/ANIM HEAD BOT/code_head_bot_up/code_head_bot_side/_____________________________________/ANIM HEAD TOP/code_head_top"; private const string NECK_NODE_PATH = "[RIG]/code_lean/code_tilt/ANIM BOT/_____________________________________/ANIM BODY BOT/_____________________________________/ANIM BODY TOP/code_body_top_up/code_body_top_side/_____________________________________/ANIM HEAD BOT/code_head_bot_up/code_head_bot_side"; private const string BODY_NODE_PATH = "[RIG]/code_lean/code_tilt/ANIM BOT/_____________________________________/ANIM BODY BOT/_____________________________________/ANIM BODY TOP/code_body_top_up/code_body_top_side"; public static Dictionary<string, Transform> GetDecorationParentNodes(Transform rootTransform) { //IL_00a0: Unknown result type (might be due to invalid IL or missing references) Dictionary<string, Transform> dictionary = new Dictionary<string, Transform>(); Transform val = rootTransform.Find("[RIG]/code_lean/code_tilt/ANIM BOT/_____________________________________/ANIM BODY BOT/_____________________________________/ANIM BODY TOP/code_body_top_up/code_body_top_side/_____________________________________/ANIM HEAD BOT/code_head_bot_up/code_head_bot_side/_____________________________________/ANIM HEAD TOP/code_head_top"); if ((Object)(object)val != (Object)null) { dictionary["head"] = val; } Transform val2 = rootTransform.Find("[RIG]/code_lean/code_tilt/ANIM BOT/_____________________________________/ANIM BODY BOT/_____________________________________/ANIM BODY TOP/code_body_top_up/code_body_top_side/_____________________________________/ANIM HEAD BOT/code_head_bot_up/code_head_bot_side"); if ((Object)(object)val2 != (Object)null) { dictionary["neck"] = val2; } Transform val3 = rootTransform.Find("[RIG]/code_lean/code_tilt/ANIM BOT/_____________________________________/ANIM BODY BOT/_____________________________________/ANIM BODY TOP/code_body_top_up/code_body_top_side"); if ((Object)(object)val3 != (Object)null) { dictionary["body"] = val3; } Transform val4 = rootTransform.Find("WorldSpaceNode"); if ((Object)(object)val4 == (Object)null) { val4 = new GameObject("WorldSpaceNode").transform; val4.SetParent(rootTransform, false); ((Component)val4).gameObject.AddComponent<WorldSpaceFollower>(); } if ((Object)(object)val4 != (Object)null) { dictionary["world"] = val4; } return dictionary; } public static void EnsureDecorationContainers(Dictionary<string, Transform> parentNodes) { //IL_003b: 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_005c: 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) foreach (KeyValuePair<string, Transform> parentNode in parentNodes) { Transform value = parentNode.Value; Transform val = value.Find("HeadDecorations"); if ((Object)(object)val == (Object)null) { val = new GameObject("HeadDecorations").transform; val.SetParent(value, false); val.localPosition = Vector3.zero; val.localRotation = Quaternion.identity; val.localScale = Vector3.one; } } } public static void UpdateDecoration(Transform parent, string decorationName, bool showDecoration) { Transform val = parent.Find(decorationName); if ((Object)(object)val != (Object)null && ((Component)val).gameObject.activeSelf != showDecoration) { ((Component)val).gameObject.SetActive(showDecoration); } } } public class WorldSpaceFollower : MonoBehaviour { private Transform? _rootTransform; private Vector3 _initialOffset; private void Start() { //IL_002a: 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_003a: Unknown result type (might be due to invalid IL or missing references) //IL_003f: Unknown result type (might be due to invalid IL or missing references) //IL_004a: Unknown result type (might be due to invalid IL or missing references) //IL_005b: Unknown result type (might be due to invalid IL or missing references) _rootTransform = ((Component)this).transform.parent; if ((Object)(object)_rootTransform != (Object)null) { _initialOffset = ((Component)this).transform.position - _rootTransform.position; ((Component)this).transform.rotation = Quaternion.identity; ((Component)this).transform.localScale = Vector3.one; } } private void LateUpdate() { //IL_001e: 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_0029: 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) //IL_0054: 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 ((Object)(object)_rootTransform != (Object)null) { ((Component)this).transform.position = _rootTransform.position + _initialOffset; ((Component)this).transform.rotation = Quaternion.Euler(0f, _rootTransform.eulerAngles.y, 0f); ((Component)this).transform.localScale = Vector3.one; } } } public class DecorationInfo { public string? Name { get; set; } public string? DisplayName { get; set; } public bool IsVisible { get; set; } public GameObject? Prefab { get; set; } public string? ParentTag { get; set; } public string? BundlePath { get; set; } } public static class HeadDecorationManager { private static Dictionary<string?, string> parentPathMap = new Dictionary<string, string> { { "head", "[RIG]/code_lean/code_tilt/ANIM BOT/_____________________________________/ANIM BODY BOT/_____________________________________/ANIM BODY TOP/code_body_top_up/code_body_top_side/_____________________________________/ANIM HEAD BOT/code_head_bot_up/code_head_bot_side/_____________________________________/ANIM HEAD TOP/code_head_top" }, { "neck", "[RIG]/code_lean/code_tilt/ANIM BOT/_____________________________________/ANIM BODY BOT/_____________________________________/ANIM BODY TOP/code_body_top_up/code_body_top_side/_____________________________________/ANIM HEAD BOT/code_head_bot_up/code_head_bot_side" }, { "body", "[RIG]/code_lean/code_tilt/ANIM BOT/_____________________________________/ANIM BODY BOT/_____________________________________/ANIM BODY TOP/code_body_top_up/code_body_top_side" }, { "world", "WorldSpaceNode" } }; private static ManualLogSource? Logger => Morehead.Logger; public static List<DecorationInfo> Decorations { get; private set; } = new List<DecorationInfo>(); public static void Initialize() { try { ManualLogSource? logger = Logger; if (logger != null) { logger.LogInfo((object)"正在初始化装饰物管理器..."); } Decorations.Clear(); LoadAllDecorations(); ManualLogSource? logger2 = Logger; if (logger2 != null) { logger2.LogInfo((object)$"装饰物管理器初始化完成,共加载了 {Decorations.Count} 个装饰物"); } } catch (Exception ex) { ManualLogSource? logger3 = Logger; if (logger3 != null) { logger3.LogError((object)("初始化装饰物管理器时出错: " + ex.Message)); } } } private static void LoadAllDecorations() { try { Morehead? instance = Morehead.Instance; string directoryName = Path.GetDirectoryName((instance != null) ? ((BaseUnityPlugin)instance).Info.Location : null); if (string.IsNullOrEmpty(directoryName)) { ManualLogSource? logger = Logger; if (logger != null) { logger.LogError((object)"无法获取MOD所在目录"); } return; } string text = Path.Combine(directoryName, "Decorations"); if (!Directory.Exists(text)) { Directory.CreateDirectory(text); ManualLogSource? logger2 = Logger; if (logger2 != null) { logger2.LogInfo((object)("已创建装饰物目录: " + text)); } } List<string> list = new List<string>(); string[] files = Directory.GetFiles(text, "*.hhh"); list.AddRange(files); try { string pluginPath = Paths.PluginPath; if (!string.IsNullOrEmpty(pluginPath) && Directory.Exists(pluginPath)) { string[] files2 = Directory.GetFiles(pluginPath, "*.hhh", SearchOption.AllDirectories); list.AddRange(files2); ManualLogSource? logger3 = Logger; if (logger3 != null) { logger3.LogInfo((object)$"在plugins目录中找到 {files2.Length} 个.hhh文件"); } } else { ManualLogSource? logger4 = Logger; if (logger4 != null) { logger4.LogWarning((object)"无法找到BepInEx/plugins目录,将只加载本地装饰物"); } } } catch (Exception ex) { ManualLogSource? logger5 = Logger; if (logger5 != null) { logger5.LogError((object)("搜索plugins目录时出错: " + ex.Message)); } } list = list.Distinct().ToList(); if (list.Count == 0) { ManualLogSource? logger6 = Logger; if (logger6 != null) { logger6.LogWarning((object)"未找到任何装饰物包文件,请确保.hhh文件已放置"); } } else { ManualLogSource? logger7 = Logger; if (logger7 != null) { logger7.LogInfo((object)$"找到 {list.Count} 个装饰物包文件"); } if (files.Length != 0) { ManualLogSource? logger8 = Logger; if (logger8 != null) { logger8.LogInfo((object)$"- Decorations目录: {files.Length} 个文件"); } } } foreach (string item in list) { LoadDecorationBundle(item); } } catch (Exception ex2) { ManualLogSource? logger9 = Logger; if (logger9 != null) { logger9.LogError((object)("加载装饰物时出错: " + ex2.Message)); } } } private static void LoadDecorationBundle(string bundlePath) { AssetBundle val = null; try { if (!File.Exists(bundlePath)) { ManualLogSource? logger = Logger; if (logger != null) { logger.LogWarning((object)("文件不存在: " + bundlePath)); } return; } FileInfo fileInfo = new FileInfo(bundlePath); if (fileInfo.Length < 1024) { ManualLogSource? logger2 = Logger; if (logger2 != null) { logger2.LogWarning((object)$"文件过小,可能不是有效的AssetBundle: {bundlePath}, 大小: {fileInfo.Length} 字节"); } return; } string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(bundlePath); string parentTag = "head"; string text = fileNameWithoutExtension; if (fileNameWithoutExtension.Contains("_")) { string[] array = fileNameWithoutExtension.Split('_'); if (array.Length >= 2) { string text2 = array[^1].ToLower(); if (parentPathMap.ContainsKey(text2)) { parentTag = text2; text = string.Join("_", array, 0, array.Length - 1); } } } string text3 = EnsureUniqueName(text); if (text3 != text) { ManualLogSource? logger3 = Logger; if (logger3 != null) { logger3.LogWarning((object)("检测到重名,将基础名称从 " + text + " 修改为 " + text3)); } text = text3; } try { val = AssetBundle.LoadFromFile(bundlePath); if ((Object)(object)val == (Object)null) { ManualLogSource? logger4 = Logger; if (logger4 != null) { logger4.LogError((object)("无法加载AssetBundle,文件可能已损坏或不是有效的AssetBundle: " + bundlePath)); } return; } } catch (Exception ex) { ManualLogSource? logger5 = Logger; if (logger5 != null) { logger5.LogError((object)("加载AssetBundle时出错,文件可能不是有效的AssetBundle: " + bundlePath + ", 错误: " + ex.Message)); } return; } try { string[] allAssetNames; try { allAssetNames = val.GetAllAssetNames(); } catch (Exception ex2) { ManualLogSource? logger6 = Logger; if (logger6 != null) { logger6.LogError((object)("获取AssetBundle资源名称时出错: " + bundlePath + ", 错误: " + ex2.Message)); } val.Unload(true); return; } if (allAssetNames.Length == 0) { ManualLogSource? logger7 = Logger; if (logger7 != null) { logger7.LogWarning((object)("AssetBundle不包含任何资源: " + bundlePath)); } val.Unload(true); return; } bool flag = false; GameObject val2 = null; string[] array2 = allAssetNames; foreach (string text4 in array2) { try { val2 = val.LoadAsset<GameObject>(text4); if ((Object)(object)val2 != (Object)null) { flag = true; break; } } catch (Exception ex3) { ManualLogSource? logger8 = Logger; if (logger8 != null) { logger8.LogWarning((object)("加载资源 " + text4 + " 时出错: " + ex3.Message)); } } } if (!flag || (Object)(object)val2 == (Object)null) { ManualLogSource? logger9 = Logger; if (logger9 != null) { logger9.LogWarning((object)("AssetBundle不包含有效的GameObject资源: " + bundlePath)); } val.Unload(true); return; } string text5 = ((Object)val2).name; string text6 = EnsureUniqueDisplayName(text5); if (text6 != text5) { ManualLogSource? logger10 = Logger; if (logger10 != null) { logger10.LogWarning((object)("检测到显示名称重复,将显示名称从 " + text5 + " 修改为 " + text6)); } text5 = text6; } DecorationInfo decorationInfo = new DecorationInfo { Name = text, DisplayName = text5, IsVisible = false, Prefab = val2, ParentTag = parentTag, BundlePath = bundlePath }; Decorations.Add(decorationInfo); ManualLogSource? logger11 = Logger; if (logger11 != null) { logger11.LogInfo((object)("成功加载装饰物: " + decorationInfo.DisplayName + ", 标签: " + decorationInfo.ParentTag)); } val.Unload(false); } catch (Exception ex4) { ManualLogSource? logger12 = Logger; if (logger12 != null) { logger12.LogError((object)("处理AssetBundle时出错: " + ex4.Message)); } if ((Object)(object)val != (Object)null) { val.Unload(true); } } } catch (Exception ex5) { ManualLogSource? logger13 = Logger; if (logger13 != null) { logger13.LogError((object)("加载装饰物包时出错: " + ex5.Message + ", 路径: " + bundlePath)); } if ((Object)(object)val != (Object)null) { val.Unload(true); } } } private static string EnsureUniqueName(string baseName) { string name = baseName; int num = 1; while (Decorations.Any((DecorationInfo d) => d.Name != null && d.Name.Equals(name, StringComparison.OrdinalIgnoreCase))) { name = $"{baseName}({num})"; num++; } return name; } private static string EnsureUniqueDisplayName(string baseDisplayName) { string displayName = baseDisplayName; int num = 1; while (Decorations.Any((DecorationInfo d) => d.DisplayName != null && d.DisplayName.Equals(displayName, StringComparison.OrdinalIgnoreCase))) { displayName = $"{baseDisplayName}({num})"; num++; } return displayName; } private static string? GetParentTagFromPrefab(GameObject prefab) { string text = ((Object)prefab).name.ToLower(); foreach (string key in parentPathMap.Keys) { if (key != null && text.Contains(key)) { return key; } } return null; } public static bool GetDecorationState(string? name) { string name2 = name; DecorationInfo decorationInfo = Decorations.FirstOrDefault((DecorationInfo d) => d.Name != null && d.Name.Equals(name2, StringComparison.OrdinalIgnoreCase)); if (decorationInfo == null) { ManualLogSource? logger = Logger; if (logger != null) { logger.LogWarning((object)("GetDecorationState: 找不到装饰物 " + name2)); } } return decorationInfo?.IsVisible ?? false; } public static void SetDecorationState(string name, bool isVisible) { string name2 = name; DecorationInfo decorationInfo = Decorations.FirstOrDefault((DecorationInfo d) => d.Name != null && d.Name.Equals(name2, StringComparison.OrdinalIgnoreCase)); if (decorationInfo != null) { decorationInfo.IsVisible = isVisible; ManualLogSource? logger = Logger; if (logger != null) { logger.LogInfo((object)$"设置装饰物 {decorationInfo.DisplayName} 显示状态为: {isVisible}"); } } else { ManualLogSource? logger2 = Logger; if (logger2 != null) { logger2.LogWarning((object)("SetDecorationState: 找不到装饰物 " + name2)); } } } public static bool ToggleDecorationState(string? name) { string name2 = name; DecorationInfo decorationInfo = Decorations.FirstOrDefault((DecorationInfo d) => d.Name != null && d.Name.Equals(name2, StringComparison.OrdinalIgnoreCase)); if (decorationInfo != null) { decorationInfo.IsVisible = !decorationInfo.IsVisible; return decorationInfo.IsVisible; } ManualLogSource? logger = Logger; if (logger != null) { logger.LogWarning((object)("ToggleDecorationState: 找不到装饰物 " + name2)); } return false; } public static string GetParentPath(string parentTag) { if (parentPathMap.TryGetValue(parentTag.ToLower(), out string value)) { return value; } return parentPathMap["head"]; } public static void DisableAllDecorations() { try { int num = 0; foreach (DecorationInfo decoration in Decorations) { if (decoration.IsVisible) { decoration.IsVisible = false; num++; } } } catch (Exception ex) { ManualLogSource? logger = Logger; if (logger != null) { logger.LogError((object)("关闭所有装饰物时出错: " + ex.Message)); } } } } public static class MoreHeadUI { private static REPOButton? menuButton; private static REPOPopupPage? decorationsPage; private static Dictionary<string?, REPOButton> decorationButtons = new Dictionary<string, REPOButton>(); private static string currentTagFilter = "ALL"; private static Dictionary<string, REPOButton> tagFilterButtons = new Dictionary<string, REPOButton>(); private static Dictionary<string, REPOPopupPage?> tagPageCache = new Dictionary<string, REPOPopupPage>(); private static Dictionary<string, Dictionary<string, REPOButton>> tagPageButtonCache = new Dictionary<string, Dictionary<string, REPOButton>>(); private const string BUTTON_NAME = "<color=#FF0000>M</color><color=#FF3300>O</color><color=#FF6600>R</color><color=#FF9900>E</color><color=#FFCC00>H</color><color=#FFDD00>E</color><color=#FFEE00>A</color><color=#FFFF00>D</color>"; private const string PAGE_TITLE = "Rotate robot: A/D"; private static readonly string[] ALL_TAGS = new string[5] { "ALL", "HEAD", "NECK", "BODY", "WORLD" }; private static ManualLogSource? Logger => Morehead.Logger; public static void Initialize() { //IL_0013: Unknown result type (might be due to invalid IL or missing references) //IL_001d: Expected O, but got Unknown //IL_002c: 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) //IL_0052: Expected O, but got Unknown try { menuButton = new REPOButton("<color=#FF0000>M</color><color=#FF3300>O</color><color=#FF6600>R</color><color=#FF9900>E</color><color=#FFCC00>H</color><color=#FFDD00>E</color><color=#FFEE00>A</color><color=#FFFF00>D</color>", (Action)OnMenuButtonClick); MenuAPI.AddElementToEscapeMenu((REPOElement)(object)menuButton, new Vector2(0f, 0f)); decorationsPage = new REPOPopupPage("Rotate robot: A/D", (Action<REPOPopupPage>)SetupPopupPage); PreCreateTagPages(); } catch (Exception ex) { ManualLogSource? logger = Logger; if (logger != null) { logger.LogError((object)("初始化UI时出错: " + ex.Message)); } } } private static void PreCreateTagPages() { //IL_002e: Unknown result type (might be due to invalid IL or missing references) //IL_0034: Expected O, but got Unknown try { tagPageCache.Clear(); string[] aLL_TAGS = ALL_TAGS; foreach (string text in aLL_TAGS) { REPOPopupPage val = new REPOPopupPage("Rotate robot: A/D", (Action<REPOPopupPage>)SetupPopupPage); string text2 = currentTagFilter; currentTagFilter = text; CreatePageContentForTag(val, text); tagPageCache[text] = val; currentTagFilter = text2; } } catch (Exception ex) { ManualLogSource? logger = Logger; if (logger != null) { logger.LogError((object)("预创建标签页面缓存时出错: " + ex.Message)); } } } private static void SetupPopupPage(REPOPopupPage page) { //IL_000d: 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) try { page.SetSize(new Vector2(300f, 350f)); page.SetBackgroundDimming(true); page.SetMaskPadding((Padding?)new Padding(10f, 50f, 20f, 10f)); AddAuthorCredit(page); } catch (Exception ex) { ManualLogSource? logger = Logger; if (logger != null) { logger.LogError((object)("设置弹出页面属性时出错: " + ex.Message)); } } } private static void AddAuthorCredit(REPOPopupPage page) { //IL_0026: Unknown result type (might be due to invalid IL or missing references) //IL_002c: Expected O, but got Unknown //IL_0038: Unknown result type (might be due to invalid IL or missing references) try { REPOButton val = new REPOButton("<size=10><color=#FFFFA0>Masaicker</color> and <color=#FFFFA0>Yuriscat</color> co-developed.\n由<color=#FFFFA0>马赛克了</color>和<color=#FFFFA0>尤里的猫</color>共同制作。</size>", (Action)delegate { }); ((REPOSimplePage)page).AddElementToPage((REPOElement)(object)val, new Vector2(300f, 345f)); try { MenuManager obj = Object.FindObjectOfType<MenuManager>(); if (obj != null) { ((MonoBehaviour)obj).StartCoroutine(DelayedStyleAuthorCredit(val)); } } catch (Exception ex) { ManualLogSource? logger = Logger; if (logger != null) { logger.LogWarning((object)("无法修改作者标记样式: " + ex.Message)); } } } catch (Exception ex2) { ManualLogSource? logger2 = Logger; if (logger2 != null) { logger2.LogError((object)("添加作者标记时出错: " + ex2.Message)); } } } private static IEnumerator DelayedStyleAuthorCredit(REPOButton button) { yield return null; try { GameObject buttonObj = null; Button[] allButtons = Object.FindObjectsOfType<Button>(); Button[] array = allButtons; foreach (Button btn in array) { if (((Object)btn).name.Contains("Masaicker") && ((Object)btn).name.Contains("Yuriscat")) { buttonObj = ((Component)btn).gameObject; break; } } if (!((Object)(object)buttonObj != (Object)null)) { yield break; } Button buttonComponent = buttonObj.GetComponent<Button>(); if (!((Object)(object)buttonComponent != (Object)null)) { yield break; } ((Selectable)buttonComponent).interactable = false; Image[] images = buttonObj.GetComponentsInChildren<Image>(); Image[] array2 = images; foreach (Image image in array2) { if ((Object)(object)((Component)image).gameObject != (Object)(object)((Component)buttonComponent).gameObject) { ((Behaviour)image).enabled = false; } } } catch (Exception e) { ManualLogSource? logger = Logger; if (logger != null) { logger.LogWarning((object)("修改作者标记样式失败: " + e.Message)); } } } private static void OnMenuButtonClick() { //IL_0033: Unknown result type (might be due to invalid IL or missing references) //IL_003d: Expected O, but got Unknown try { if (tagPageCache.TryGetValue(currentTagFilter, out REPOPopupPage value)) { decorationsPage = value; } else { decorationsPage = new REPOPopupPage("Rotate robot: A/D", (Action<REPOPopupPage>)SetupPopupPage); CreatePageContent(); } REPOPopupPage? obj = decorationsPage; if (obj != null) { ((REPOSimplePage)obj).OpenPage(false); } SetHeaderPosition(); MovePlayerAvatarToFront(); AdjustMenuScrollBoxPosition(); UpdateButtonStates(); } catch (Exception ex) { ManualLogSource? logger = Logger; if (logger != null) { logger.LogError((object)("打开设置页面时出错: " + ex.Message)); } } } private static void SetHeaderPosition() { try { MonoBehaviour obj = Object.FindObjectOfType<MonoBehaviour>(); if (obj != null) { obj.StartCoroutine(DelayedSetHeaderPosition()); } } catch (Exception ex) { ManualLogSource? logger = Logger; if (logger != null) { logger.LogError((object)("设置标题位置时出错: " + ex.Message)); } } } private static IEnumerator DelayedSetHeaderPosition() { yield return null; try { FieldInfo headerTransformField = typeof(REPOPopupPage).GetField("headerTransform", BindingFlags.Instance | BindingFlags.NonPublic); if (headerTransformField != null) { object? value = headerTransformField.GetValue(decorationsPage); RectTransform headerTransform = (RectTransform)((value is RectTransform) ? value : null); if ((Object)(object)headerTransform != (Object)null) { ((Transform)headerTransform).localPosition = new Vector3(185.5049f, 360f, 0f); yield break; } ManualLogSource? logger = Logger; if (logger != null) { logger.LogWarning((object)"headerTransform为空"); } } else { ManualLogSource? logger2 = Logger; if (logger2 != null) { logger2.LogWarning((object)"找不到headerTransform字段"); } } } catch (Exception e) { ManualLogSource? logger3 = Logger; if (logger3 != null) { logger3.LogError((object)("延迟设置标题位置时出错: " + e.Message)); } } } private static void CreatePageContent() { CreatePageContentForTag(decorationsPage, currentTagFilter); } private static void CreatePageContentForTag(REPOPopupPage? page, string tag) { //IL_0183: Unknown result type (might be due to invalid IL or missing references) //IL_0189: Expected O, but got Unknown //IL_019a: Unknown result type (might be due to invalid IL or missing references) //IL_01b6: Unknown result type (might be due to invalid IL or missing references) //IL_01bc: Expected O, but got Unknown //IL_00d2: Unknown result type (might be due to invalid IL or missing references) //IL_00d9: Expected O, but got Unknown //IL_01cd: Unknown result type (might be due to invalid IL or missing references) //IL_00f3: Unknown result type (might be due to invalid IL or missing references) try { int num = 0; decorationButtons.Clear(); if (!tagPageButtonCache.ContainsKey(tag)) { tagPageButtonCache[tag] = new Dictionary<string, REPOButton>(); } else { tagPageButtonCache[tag].Clear(); } for (int i = 0; i < HeadDecorationManager.Decorations.Count; i++) { DecorationInfo decoration = HeadDecorationManager.Decorations[i]; if (tag == "ALL" || decoration.ParentTag?.ToLower() == tag.ToLower()) { REPOButton val = new REPOButton(GetButtonText(decoration, decoration.IsVisible), (Action)delegate { OnDecorationButtonClick(decoration.Name); }); int num2 = -(60 + num * 20); if (page != null) { page.AddElementToScrollView((REPOElement)(object)val, new Vector2(0f, (float)num2)); } decorationButtons[decoration.Name ?? string.Empty] = val; tagPageButtonCache[tag][decoration.Name ?? string.Empty] = val; num++; } } CreateTagFilterButtons(page); REPOButton val2 = new REPOButton("<size=18><color=#FFFFFF>C</color><color=#E6E6E6>L</color><color=#CCCCCC>O</color><color=#B3B3B3>S</color><color=#999999>E</color></size>", (Action)OnCloseButtonClick); if (page != null) { ((REPOSimplePage)page).AddElementToPage((REPOElement)(object)val2, new Vector2(301f, 0f)); } REPOButton val3 = new REPOButton("<size=18><color=#FFAA00>CLEAR ALL</color></size>", (Action)OnDisableAllButtonClick); if (page != null) { ((REPOSimplePage)page).AddElementToPage((REPOElement)(object)val3, new Vector2(401f, 0f)); } } catch (Exception ex) { ManualLogSource? logger = Logger; if (logger != null) { logger.LogError((object)("创建页面内容时出错: " + ex.Message)); } } } private static void CreateTagFilterButtons(REPOPopupPage? page) { //IL_0130: Unknown result type (might be due to invalid IL or missing references) //IL_0137: Expected O, but got Unknown //IL_0150: Unknown result type (might be due to invalid IL or missing references) try { tagFilterButtons.Clear(); for (int i = 0; i < ALL_TAGS.Length; i++) { string text = ALL_TAGS[i]; string text2 = text.ToLower(); if (1 == 0) { } string text3 = text2 switch { "head" => "#00AAFF", "neck" => "#AA00FF", "body" => "#FFAA00", "world" => "#00FFAA", _ => "#FFFFFF", }; if (1 == 0) { } string text4 = text3; string text5 = ((text2 == currentTagFilter.ToLower()) ? ("<size=14><b><color=" + text4 + ">" + text + "</color></b></size>") : ("<size=14><color=" + text4 + "50>" + text + "</color></size>")); string tagForCallback = ((text2 == "all") ? "ALL" : text); REPOButton val = new REPOButton(text5, (Action)delegate { OnTagFilterButtonClick(tagForCallback); }); int num = 70 + i * 40; if (page != null) { ((REPOSimplePage)page).AddElementToPage((REPOElement)(object)val, new Vector2((float)num, 20f)); } tagFilterButtons[tagForCallback] = val; } } catch (Exception ex) { ManualLogSource? logger = Logger; if (logger != null) { logger.LogError((object)("创建标签筛选按钮时出错: " + ex.Message)); } } } private static void OnTagFilterButtonClick(string tag) { //IL_005c: Unknown result type (might be due to invalid IL or missing references) //IL_0066: Expected O, but got Unknown try { if (!(tag == currentTagFilter)) { currentTagFilter = tag; REPOPopupPage? obj = decorationsPage; if (obj != null) { ((REPOSimplePage)obj).ClosePage(true); } if (tagPageCache.TryGetValue(tag, out REPOPopupPage value)) { decorationsPage = value; } else { decorationsPage = new REPOPopupPage("Rotate robot: A/D", (Action<REPOPopupPage>)SetupPopupPage); CreatePageContent(); tagPageCache[tag] = decorationsPage; } REPOPopupPage? obj2 = decorationsPage; if (obj2 != null) { ((REPOSimplePage)obj2).OpenPage(false); } SetHeaderPosition(); MovePlayerAvatarToFront(); AdjustMenuScrollBoxPosition(); UpdateButtonStates(); } } catch (Exception ex) { ManualLogSource? logger = Logger; if (logger != null) { logger.LogError((object)("切换标签筛选时出错: " + ex.Message)); } } } private static void UpdateButtonStates() { try { if (decorationButtons.Count == 0) { return; } foreach (DecorationInfo decoration in HeadDecorationManager.Decorations) { if ((currentTagFilter == "ALL" || decoration.ParentTag?.ToLower() == currentTagFilter.ToLower()) && decorationButtons.TryGetValue(decoration.Name ?? string.Empty, out REPOButton value)) { value.SetText(GetButtonText(decoration, decoration.IsVisible)); } } UpdateTagButtonHighlights(); } catch (Exception ex) { ManualLogSource? logger = Logger; if (logger != null) { logger.LogError((object)("更新按钮状态时出错: " + ex.Message)); } } } private static void UpdateTagButtonHighlights() { try { string[] aLL_TAGS = ALL_TAGS; foreach (string text in aLL_TAGS) { string text2 = ((text == "ALL") ? "ALL" : text); if (tagFilterButtons.TryGetValue(text2, out REPOButton value)) { string text3 = text.ToLower(); if (1 == 0) { } string text4 = text3 switch { "head" => "#00AAFF", "neck" => "#AA00FF", "body" => "#FFAA00", "world" => "#00FFAA", _ => "#FFFFFF", }; if (1 == 0) { } string text5 = text4; string text6 = ((text2 == currentTagFilter) ? ("<size=14><b><color=" + text5 + ">" + text + "</color></b></size>") : ("<size=14><color=" + text5 + "50>" + text + "</color></size>")); value.SetText(text6); } } } catch (Exception ex) { ManualLogSource? logger = Logger; if (logger != null) { logger.LogError((object)("更新标签按钮高亮状态时出错: " + ex.Message)); } } } private static void OnDecorationButtonClick(string? decorationName) { string decorationName2 = decorationName; try { DecorationInfo decorationInfo = HeadDecorationManager.Decorations.FirstOrDefault((DecorationInfo d) => d.Name != null && d.Name.Equals(decorationName2, StringComparison.OrdinalIgnoreCase)); if (decorationInfo == null) { ManualLogSource? logger = Logger; if (logger != null) { logger.LogWarning((object)("OnDecorationButtonClick: 找不到装饰物: " + decorationName2)); } return; } bool isEnabled = HeadDecorationManager.ToggleDecorationState(decorationName2); foreach (KeyValuePair<string, Dictionary<string, REPOButton>> item in tagPageButtonCache) { string key = item.Key; Dictionary<string, REPOButton> value = item.Value; if ((key == "ALL" || decorationInfo.ParentTag?.ToLower() == key.ToLower()) && value.TryGetValue(decorationName2 ?? string.Empty, out var value2)) { value2.SetText(GetButtonText(decorationInfo, isEnabled)); } } UpdateDecorations(); ConfigManager.SaveConfig(); } catch (Exception ex) { ManualLogSource? logger2 = Logger; if (logger2 != null) { logger2.LogError((object)("切换装饰物 " + decorationName2 + " 状态时出错: " + ex.Message)); } } } private static string GetButtonText(DecorationInfo decoration, bool isEnabled) { string text = decoration.DisplayName?.ToUpper() ?? "UNKNOWN"; string text2 = decoration.ParentTag ?? "unknown"; string text3 = text2.ToLower(); if (1 == 0) { } string text4 = text3 switch { "head" => "#00AAFF", "neck" => "#AA00FF", "body" => "#FFAA00", "world" => "#00FFAA", _ => "#AAAAAA", }; if (1 == 0) { } string text5 = text4; return "<size=16>" + (isEnabled ? "<color=#00FF00>[+]</color>" : "<color=#FF0000>[-]</color>") + " <color=" + text5 + "><size=12>(" + text2 + ")</size></color> " + text + "</size>"; } private static void OnCloseButtonClick() { try { MenuManager.instance.PageCloseAll(); } catch (Exception ex) { ManualLogSource? logger = Logger; if (logger != null) { logger.LogError((object)("关闭页面时出错: " + ex.Message)); } } } private static void UpdateDecorations() { try { PlayerAvatar val = FindLocalPlayer(); if ((Object)(object)val != (Object)null) { PlayerUpdatePatch.UpdatePlayerDecorations(val); HeadDecorationSync component = ((Component)val).GetComponent<HeadDecorationSync>(); if ((Object)(object)component != (Object)null) { component.SyncAllDecorations(); } } PlayerUpdatePatch.UpdateMenuPlayerDecorations(); } catch (Exception ex) { ManualLogSource? logger = Logger; if (logger != null) { logger.LogError((object)("更新装饰物状态时出错: " + ex.Message)); } } } private static PlayerAvatar? FindLocalPlayer() { try { PlayerAvatar[] array = Object.FindObjectsOfType<PlayerAvatar>(); PlayerAvatar[] array2 = array; foreach (PlayerAvatar val in array2) { if ((Object)(object)val?.photonView != (Object)null && val.photonView.IsMine) { return val; } } } catch (Exception ex) { ManualLogSource? logger = Logger; if (logger != null) { logger.LogError((object)("查找本地玩家时出错: " + ex.Message)); } } return null; } private static void MovePlayerAvatarToFront() { try { MonoBehaviour obj = Object.FindObjectOfType<MonoBehaviour>(); if (obj != null) { obj.StartCoroutine(DelayedMovePlayerAvatarToFront()); } } catch (Exception ex) { ManualLogSource? logger = Logger; if (logger != null) { logger.LogError((object)("移动玩家模型时出错: " + ex.Message)); } } } private static IEnumerator DelayedMovePlayerAvatarToFront() { yield return null; try { PlayerAvatarMenuHover playerAvatarHover = Object.FindObjectOfType<PlayerAvatarMenuHover>(); GameObject playerAvatarObj = null; if ((Object)(object)playerAvatarHover != (Object)null) { playerAvatarObj = ((Component)((Component)playerAvatarHover).transform.parent).gameObject; if (((Object)playerAvatarObj).name != "Menu Element Player Avatar") { playerAvatarObj = null; } } if ((Object)(object)playerAvatarObj == (Object)null) { playerAvatarObj = GameObject.Find("Menu Element Player Avatar"); } if ((Object)(object)playerAvatarObj != (Object)null) { object? value = AccessTools.Field(typeof(REPOPopupPage), "menuPage").GetValue(decorationsPage); MenuPage menuPage = (MenuPage)((value is MenuPage) ? value : null); if ((Object)(object)menuPage != (Object)null) { playerAvatarObj.transform.SetParent(((Component)menuPage).transform, true); playerAvatarObj.transform.SetAsLastSibling(); playerAvatarObj.transform.localPosition = new Vector3(-76f, -30f, 0f); } } else { ManualLogSource? logger = Logger; if (logger != null) { logger.LogWarning((object)"找不到玩家模型对象"); } } } catch (Exception e) { ManualLogSource? logger2 = Logger; if (logger2 != null) { logger2.LogError((object)("延迟移动玩家模型时出错: " + e.Message)); } } } private static void AdjustMenuScrollBoxPosition() { try { MonoBehaviour obj = Object.FindObjectOfType<MonoBehaviour>(); if (obj != null) { obj.StartCoroutine(DelayedAdjustMenuScrollBoxPosition()); } } catch (Exception ex) { ManualLogSource? logger = Logger; if (logger != null) { logger.LogError((object)("调整MenuScrollBox位置时出错: " + ex.Message)); } } } private static IEnumerator DelayedAdjustMenuScrollBoxPosition() { yield return null; yield return null; try { object? value = AccessTools.Field(typeof(REPOPopupPage), "menuScrollBox").GetValue(decorationsPage); MenuScrollBox menuScrollBox = (MenuScrollBox)((value is MenuScrollBox) ? value : null); if ((Object)(object)menuScrollBox != (Object)null) { RectTransform rectTransform = ((Component)menuScrollBox).GetComponent<RectTransform>(); if ((Object)(object)rectTransform != (Object)null) { Vector3 currentPosition2 = ((Transform)rectTransform).localPosition; Vector3 newPosition2 = new Vector3(currentPosition2.x, currentPosition2.y + 20f, currentPosition2.z); ((Transform)rectTransform).localPosition = newPosition2; yield break; } ManualLogSource? logger = Logger; if (logger != null) { logger.LogWarning((object)"无法获取MenuScrollBox的RectTransform组件"); } yield break; } ManualLogSource? logger2 = Logger; if (logger2 != null) { logger2.LogWarning((object)"无法获取MenuScrollBox组件"); } object? value2 = AccessTools.Field(typeof(REPOPopupPage), "menuPage").GetValue(decorationsPage); MenuPage menuPage = (MenuPage)((value2 is MenuPage) ? value2 : null); if (!((Object)(object)menuPage != (Object)null)) { yield break; } ManualLogSource? logger3 = Logger; if (logger3 != null) { logger3.LogInfo((object)"成功获取MenuPage组件,尝试查找MenuScrollBox"); } foreach (Transform item in ((Component)menuPage).transform) { Transform child = item; ManualLogSource? logger4 = Logger; if (logger4 != null) { logger4.LogInfo((object)("找到子对象: " + ((Object)child).name)); } if (!((Object)child).name.Contains("ScrollBox") && !((Object)(object)((Component)child).GetComponent<MenuScrollBox>() != (Object)null)) { continue; } RectTransform scrollBoxTransform = (RectTransform)(object)((child is RectTransform) ? child : null); if ((Object)(object)scrollBoxTransform != (Object)null) { Vector3 currentPosition = ((Transform)scrollBoxTransform).localPosition; Vector3 newPosition = (((Transform)scrollBoxTransform).localPosition = new Vector3(currentPosition.x, currentPosition.y + 20f, currentPosition.z)); ManualLogSource? logger5 = Logger; if (logger5 != null) { logger5.LogInfo((object)$"通过替代方法调整MenuScrollBox位置: 从 {currentPosition} 到 {newPosition}"); } } break; } } catch (Exception e) { ManualLogSource? logger6 = Logger; if (logger6 != null) { logger6.LogError((object)("调整MenuScrollBox位置时出错: " + e.Message + "\n" + e.StackTrace)); } } } private static void OnDisableAllButtonClick() { try { HeadDecorationManager.DisableAllDecorations(); foreach (DecorationInfo decoration in HeadDecorationManager.Decorations) { foreach (KeyValuePair<string, Dictionary<string, REPOButton>> item in tagPageButtonCache) { string key = item.Key; Dictionary<string, REPOButton> value = item.Value; if ((key == "ALL" || decoration.ParentTag?.ToLower() == key.ToLower()) && value.TryGetValue(decoration.Name ?? string.Empty, out var value2)) { value2.SetText(GetButtonText(decoration, isEnabled: false)); } } } UpdateDecorations(); ConfigManager.SaveConfig(); } catch (Exception ex) { ManualLogSource? logger = Logger; if (logger != null) { logger.LogError((object)("关闭所有装饰物时出错: " + ex.Message)); } } } } }
plugins/Zehs-ExtractionPointConfirmButton/com.github.zehsteam.ExtractionPointConfirmButton.dll
Decompiled 2 months agousing System; using System.Collections.Generic; using System.Diagnostics; using System.IO; 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 Microsoft.CodeAnalysis; using Photon.Pun; using REPOLib.Modules; using UnityEngine; using com.github.zehsteam.ExtractionPointConfirmButton.MonoBehaviours; using com.github.zehsteam.ExtractionPointConfirmButton.Patches; [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("Zehs")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyCopyright("Copyright © 2025 Zehs")] [assembly: AssemblyFileVersion("1.0.1.0")] [assembly: AssemblyInformationalVersion("1.0.1+7c041e9f7e7907f331a7f407a227a8738137bf57")] [assembly: AssemblyProduct("ExtractionPointConfirmButton")] [assembly: AssemblyTitle("com.github.zehsteam.ExtractionPointConfirmButton")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("1.0.1.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 com.github.zehsteam.ExtractionPointConfirmButton { internal static class Assets { public static GameObject ConfirmButtonObjectPrefab { get; private set; } public static void Load() { LoadAssetsFromAssetBundle(); } private static void LoadAssetsFromAssetBundle() { AssetBundle val = LoadAssetBundle("extractionpointconfirmbutton_assets"); if (!((Object)(object)val == (Object)null)) { ConfirmButtonObjectPrefab = LoadAssetFromAssetBundle<GameObject>("ConfirmButtonObject", val); Plugin.Logger.LogInfo((object)"Successfully loaded assets from AssetBundle!"); } } private static AssetBundle LoadAssetBundle(string fileName) { try { string directoryName = Path.GetDirectoryName(((BaseUnityPlugin)Plugin.Instance).Info.Location); string text = Path.Combine(directoryName, fileName); return AssetBundle.LoadFromFile(text); } catch (Exception arg) { Plugin.Logger.LogError((object)$"Failed to load AssetBundle \"{fileName}\". {arg}"); } return null; } private static T LoadAssetFromAssetBundle<T>(string name, AssetBundle assetBundle) where T : Object { if (string.IsNullOrWhiteSpace(name)) { Plugin.Logger.LogError((object)("Failed to load asset of type \"" + typeof(T).Name + "\" from AssetBundle. Name is null or whitespace.")); return default(T); } if ((Object)(object)assetBundle == (Object)null) { Plugin.Logger.LogError((object)("Failed to load asset of type \"" + typeof(T).Name + "\" with name \"" + name + "\" from AssetBundle. AssetBundle is null.")); return default(T); } T val = assetBundle.LoadAsset<T>(name); if ((Object)(object)val == (Object)null) { Plugin.Logger.LogError((object)("Failed to load asset of type \"" + typeof(T).Name + "\" with name \"" + name + "\" from AssetBundle. No asset found with that type and name.")); return default(T); } return val; } } [BepInPlugin("com.github.zehsteam.ExtractionPointConfirmButton", "ExtractionPointConfirmButton", "1.0.1")] [BepInDependency(/*Could not decode attribute arguments.*/)] internal class Plugin : BaseUnityPlugin { private readonly Harmony _harmony = new Harmony("com.github.zehsteam.ExtractionPointConfirmButton"); internal static Plugin Instance { get; private set; } internal static ManualLogSource Logger { get; private set; } private void Awake() { if ((Object)(object)Instance == (Object)null) { Instance = this; } Logger = Logger.CreateLogSource("com.github.zehsteam.ExtractionPointConfirmButton"); Logger.LogInfo((object)"ExtractionPointConfirmButton has awoken!"); _harmony.PatchAll(typeof(RunManagerPatch)); _harmony.PatchAll(typeof(ExtractionPointPatch)); Assets.Load(); NetworkPrefabs.RegisterNetworkPrefab(Assets.ConfirmButtonObjectPrefab); } } public static class MyPluginInfo { public const string PLUGIN_GUID = "com.github.zehsteam.ExtractionPointConfirmButton"; public const string PLUGIN_NAME = "ExtractionPointConfirmButton"; public const string PLUGIN_VERSION = "1.0.1"; } } namespace com.github.zehsteam.ExtractionPointConfirmButton.Patches { [HarmonyPatch(typeof(ExtractionPoint))] internal static class ExtractionPointPatch { private static readonly Dictionary<ExtractionPoint, float> _timeSinceConfirms = new Dictionary<ExtractionPoint, float>(); public static Dictionary<ExtractionPoint, ConfirmButton> ConfirmButtons { get; private set; } = new Dictionary<ExtractionPoint, ConfirmButton>(); public static void Reset() { ConfirmButtons.Clear(); _timeSinceConfirms.Clear(); } public static void ConfirmExtractionPoint(ExtractionPoint extractionPoint) { if ((Object)(object)extractionPoint == (Object)null || extractionPoint.isShop) { return; } if (extractionPoint.haulGoal - extractionPoint.haulCurrent > 0) { if (extractionPoint.StateIs((State)2)) { extractionPoint.StateSet((State)5); } } else { _timeSinceConfirms[extractionPoint] = Time.realtimeSinceStartup; } } [HarmonyPatch("Start")] [HarmonyPostfix] private static void StartPatch(ref ExtractionPoint __instance) { SpawnConfirmButtonObject(__instance); UpdateConfirmButtonVisibility(__instance); } [HarmonyPatch("Update")] [HarmonyPostfix] private static void UpdatePatch(ref ExtractionPoint __instance) { UpdateSuccessDelay(__instance); } [HarmonyPatch("StateSetRPC")] [HarmonyPostfix] private static void StateSetRPCPatch(ref ExtractionPoint __instance) { UpdateConfirmButtonVisibility(__instance); } private static void SpawnConfirmButtonObject(ExtractionPoint extractionPoint) { //IL_004b: 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_0052: Unknown result type (might be due to invalid IL or missing references) //IL_0057: 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_0074: 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) //IL_0066: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)extractionPoint == (Object)null || extractionPoint.isShop || !SemiFunc.IsMasterClientOrSingleplayer()) { return; } Transform val = ((Component)extractionPoint).transform.Find("Scale"); if ((Object)(object)val == (Object)null) { Plugin.Logger.LogError((object)"Failed to spawn confirm button object. Target transform is null."); return; } GameObject confirmButtonObjectPrefab = Assets.ConfirmButtonObjectPrefab; Vector3 position = val.position; Quaternion rotation = val.rotation; GameObject val2 = ((!SemiFunc.IsMultiplayer()) ? Object.Instantiate<GameObject>(confirmButtonObjectPrefab, position, rotation) : PhotonNetwork.InstantiateRoomObject(((Object)confirmButtonObjectPrefab).name, position, rotation, (byte)0, (object[])null)); ConfirmButton component = val2.GetComponent<ConfirmButton>(); if (SemiFunc.IsMultiplayer()) { component.SetExtractionPointRPC(extractionPoint.photonView.ViewID); } else { component.SetExtractionPoint(extractionPoint); } ConfirmButtons.Add(extractionPoint, component); } private static void UpdateSuccessDelay(ExtractionPoint extractionPoint) { if (!((Object)(object)extractionPoint == (Object)null) && !extractionPoint.isShop && HasConfirmButton(extractionPoint)) { bool flag = true; if (_timeSinceConfirms.TryGetValue(extractionPoint, out var value) && Time.realtimeSinceStartup - value <= 2f) { flag = false; } if (flag) { extractionPoint.successDelay = 1.5f; } else { extractionPoint.successDelay = 0f; } } } private static bool HasConfirmButton(ExtractionPoint extractionPoint) { if ((Object)(object)extractionPoint == (Object)null || extractionPoint.isShop) { return false; } if (ConfirmButtons.TryGetValue(extractionPoint, out var value)) { if ((Object)(object)value == (Object)null) { return false; } return ((Component)value).gameObject.activeSelf; } return false; } private static void UpdateConfirmButtonVisibility(ExtractionPoint extractionPoint) { //IL_0032: Unknown result type (might be due to invalid IL or missing references) if (!((Object)(object)extractionPoint == (Object)null) && !extractionPoint.isShop && ConfirmButtons.TryGetValue(extractionPoint, out var value) && !((Object)(object)value == (Object)null)) { ((Component)value).gameObject.SetActive(ShowConfirmButton(extractionPoint.stateSetTo)); } } private static bool ShowConfirmButton(State state) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0002: Invalid comparison between Unknown and I4 //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_0008: Invalid comparison between Unknown and I4 //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_000f: Invalid comparison between Unknown and I4 //IL_0013: Unknown result type (might be due to invalid IL or missing references) //IL_0015: Invalid comparison between Unknown and I4 if ((int)state == 1) { return false; } if ((int)state == 6) { return false; } if ((int)state == 9) { return false; } if ((int)state == 7) { return false; } return true; } } [HarmonyPatch(typeof(RunManager))] internal static class RunManagerPatch { [HarmonyPatch("UpdateLevel")] [HarmonyPostfix] private static void UpdateLevelPatch() { ExtractionPointPatch.Reset(); } } } namespace com.github.zehsteam.ExtractionPointConfirmButton.MonoBehaviours { public class ConfirmButton : MonoBehaviour { public Transform ButtonVisualTransform; private bool _buttonAnimation; private float _buttonAnimationEval; private ExtractionPoint _extractionPoint; private void Update() { ButtonAnimation(); } public void OnClick() { OnClickRPC(); } [PunRPC] public void SetExtractionPointRPC(int viewID) { PhotonView photonView = PhotonNetwork.GetPhotonView(viewID); if ((Object)(object)photonView == (Object)null) { Plugin.Logger.LogError((object)"ConfirmButton: failed to set extraction point. PhotonView is null."); return; } ExtractionPoint extractionPoint = default(ExtractionPoint); if (!((Component)photonView).TryGetComponent<ExtractionPoint>(ref extractionPoint)) { Plugin.Logger.LogError((object)"ConfirmButton: failed to set extraction point. ExtractionPoint is null."); return; } _extractionPoint = extractionPoint; Plugin.Logger.LogInfo((object)$"ConfirmButton: set extraction point. (ViewID: {viewID})"); } public void SetExtractionPoint(ExtractionPoint extractionPoint) { _extractionPoint = extractionPoint; Plugin.Logger.LogInfo((object)"ConfirmButton: set extraction point."); } [PunRPC] private void OnClickRPC() { ButtonPushVisualsStart(); ExtractionPointPatch.ConfirmExtractionPoint(_extractionPoint); } private void ButtonPushVisualsStart() { //IL_002c: 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) if (!((Object)(object)_extractionPoint == (Object)null) && !_buttonAnimation) { ButtonVisualTransform.localScale = new Vector3(1f, 0.1f, 1f); _extractionPoint.soundButton.Play(ButtonVisualTransform.position, 1f, 1f, 1f, 1f); _buttonAnimationEval = 0f; _buttonAnimation = true; } } private void ButtonAnimation() { //IL_008a: 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_0091: Unknown result type (might be due to invalid IL or missing references) //IL_00bd: Unknown result type (might be due to invalid IL or missing references) if (!((Object)(object)_extractionPoint == (Object)null) && _buttonAnimation) { _buttonAnimationEval += Time.deltaTime * 2f; _buttonAnimationEval = Mathf.Clamp01(_buttonAnimationEval); float num = _extractionPoint.buttonPressAnimationCurve.Evaluate(_buttonAnimationEval); Color val = default(Color); ((Color)(ref val))..ctor(1f, 0.5f, 0f, 1f); ((Renderer)((Component)ButtonVisualTransform).GetComponent<MeshRenderer>()).material.SetColor("_EmissionColor", Color.Lerp(val, Color.white, num)); num = Mathf.Clamp(num, 0.5f, 1f); ButtonVisualTransform.localScale = new Vector3(1f, num, 1f); if (_buttonAnimationEval >= 1f) { _buttonAnimation = false; _buttonAnimationEval = 0f; } } } } } namespace System.Runtime.CompilerServices { [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)] internal sealed class IgnoresAccessChecksToAttribute : Attribute { public IgnoresAccessChecksToAttribute(string assemblyName) { } } }
plugins/Zehs-REPOLib/REPOLib.dll
Decompiled 2 months agousing System; using System.Collections.Generic; using System.Diagnostics; 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.Configuration; using BepInEx.Logging; using ExitGames.Client.Photon; using HarmonyLib; using Microsoft.CodeAnalysis; using Photon.Pun; using Photon.Realtime; using REPOLib.Commands; using REPOLib.Extensions; using REPOLib.Modules; using REPOLib.Objects; using REPOLib.Objects.Sdk; using REPOLib.Patches; using UnityEngine; using UnityEngine.Audio; [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("Zehs")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyCopyright("Copyright © 2025 Zehs")] [assembly: AssemblyDescription("Library for adding content to R.E.P.O.")] [assembly: AssemblyFileVersion("1.4.2.0")] [assembly: AssemblyInformationalVersion("1.4.2+7d7a998c3dc831f9571300a03417f71d46ff38d3")] [assembly: AssemblyProduct("REPOLib")] [assembly: AssemblyTitle("REPOLib")] [assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/ZehsTeam/REPOLib")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("1.4.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.Module, AllowMultiple = false, Inherited = false)] internal sealed class RefSafetyRulesAttribute : Attribute { public readonly int Version; public RefSafetyRulesAttribute(int P_0) { Version = P_0; } } } namespace REPOLib { public static class BundleLoader { public static void LoadAllBundles(string root, string withExtension) { string[] files = Directory.GetFiles(root, "*" + withExtension, SearchOption.AllDirectories); string[] array = files; foreach (string text in array) { string text2 = text.Replace(root, ""); try { LoadBundle(text, text2); } catch (Exception arg) { Logger.LogError($"Failed to load bundle at {text2}: {arg}"); } } } public static void LoadBundle(string path, string relativePath) { AssetBundle val = AssetBundle.LoadFromFile(path); Mod[] array = val.LoadAllAssets<Mod>(); int num = array.Length; if (num <= 1) { if (num == 0) { throw new Exception("Bundle contains no mods."); } Mod mod = array[0]; Logger.LogInfo("Loading content from bundle at " + relativePath + " (" + mod.Identifier + ")"); Content[] array2 = val.LoadAllAssets<Content>(); Content[] array3 = array2; foreach (Content content in array3) { try { content.Initialize(mod); } catch (Exception arg) { throw new Exception($"Failed to load {content.Name} ({((object)content).GetType().Name}): {arg}"); } } return; } throw new Exception("Bundle contains more than one mod."); } } internal static class ConfigManager { public static ConfigFile ConfigFile { get; private set; } public static ConfigEntry<bool> ExtendedLogging { get; private set; } public static ConfigEntry<bool> DeveloperMode { get; private set; } public static void Initialize(ConfigFile configFile) { ConfigFile = configFile; BindConfigs(); } private static void BindConfigs() { ExtendedLogging = ConfigFile.Bind<bool>("General", "ExtendedLogging", false, "Enable extended logging."); DeveloperMode = ConfigFile.Bind<bool>("General", "DeveloperMode", false, "Enable developer mode cheats for testing."); } } internal static class Logger { public static ManualLogSource ManualLogSource { get; private set; } public static void Initialize(ManualLogSource manualLogSource) { ManualLogSource = manualLogSource; } public static void LogInfo(object data, bool extended = false) { Log((LogLevel)16, data, extended); } public static void LogWarning(object data, bool extended = false) { Log((LogLevel)4, data, extended); } public static void LogError(object data, bool extended = false) { Log((LogLevel)2, data, extended); } public static void Log(LogLevel logLevel, object data, bool extended = false) { //IL_0015: Unknown result type (might be due to invalid IL or missing references) if (!extended || IsExtendedLoggingEnabled()) { ManualLogSource manualLogSource = ManualLogSource; if (manualLogSource != null) { manualLogSource.Log(logLevel, data); } } } private static bool IsExtendedLoggingEnabled() { if (ConfigManager.ExtendedLogging == null) { return false; } return ConfigManager.ExtendedLogging.Value; } } [BepInPlugin("REPOLib", "REPOLib", "1.4.2")] public class Plugin : BaseUnityPlugin { private readonly Harmony _harmony = new Harmony("REPOLib"); public static Plugin Instance { get; private set; } private void Awake() { Instance = this; Logger.Initialize(Logger.CreateLogSource("REPOLib")); Logger.LogInfo("REPOLib has awoken!"); _harmony.PatchAll(typeof(RunManagerPatch)); _harmony.PatchAll(typeof(EnemyDirectorPatch)); _harmony.PatchAll(typeof(StatsManagerPatch)); _harmony.PatchAll(typeof(SemiFuncPatch)); _harmony.PatchAll(typeof(AudioManagerPatch)); ConfigManager.Initialize(((BaseUnityPlugin)this).Config); if (ConfigManager.DeveloperMode.Value) { _harmony.PatchAll(typeof(SteamManagerPatch)); } BundleLoader.LoadAllBundles(Paths.PluginPath, ".repobundle"); } } public static class MyPluginInfo { public const string PLUGIN_GUID = "REPOLib"; public const string PLUGIN_NAME = "REPOLib"; public const string PLUGIN_VERSION = "1.4.2"; } } namespace REPOLib.Patches { [HarmonyPatch(typeof(AudioManager))] internal static class AudioManagerPatch { [HarmonyPatch("Start")] [HarmonyPostfix] private static void StartPatch() { Utilities.FixAudioMixerGroupsOnPrefabs(); } } [HarmonyPatch(typeof(EnemyDirector))] internal static class EnemyDirectorPatch { private static bool _alreadyRegistered; [HarmonyPatch("Awake")] [HarmonyPostfix] private static void AwakePatch() { if (_alreadyRegistered) { foreach (EnemySetup registeredEnemy in Enemies.RegisteredEnemies) { EnemyDirector.instance.AddEnemy(registeredEnemy); } return; } Enemies.RegisterEnemies(); _alreadyRegistered = true; } } [HarmonyPatch(typeof(RunManager))] internal static class RunManagerPatch { private static bool _patchedAwake; [HarmonyPatch("Awake")] [HarmonyPostfix] [HarmonyPriority(0)] private static void AwakePatch() { if (!_patchedAwake) { _patchedAwake = true; NetworkPrefabs.Initialize(); NetworkingEvents.Initialize(); Valuables.RegisterValuables(); CommandManager.Initialize(); } } } [HarmonyPatch(typeof(SemiFunc))] internal static class SemiFuncPatch { [HarmonyPatch("Command")] [HarmonyPrefix] private static bool CommandPatch(string _command) { if (_command.StartsWith("/")) { return Command(_command); } return true; } private static bool Command(string message) { string text = message.ToLower(); string text2 = text.Split(' ')[0].Substring(1); string text3 = ""; if (text.Length > text2.Length) { text3 = text.Substring(text2.Length + 1).Trim(); } CommandManager.CommandExecutionMethods.TryGetValue(text2, out var value); if (value != null) { CommandExecutionAttribute customAttribute = value.GetCustomAttribute<CommandExecutionAttribute>(); if (CommandManager.CommandsEnabled.TryGetValue(customAttribute.Name, out var value2) && !value2) { return false; } if (customAttribute != null && customAttribute.RequiresDeveloperMode && !SteamManager.instance.developerMode) { Logger.LogWarning("Command " + text2 + " requires developer mode to be enabled. Enable it in REPOLib.cfg"); return false; } try { ParameterInfo[] parameters = value.GetParameters(); if (parameters.Length == 0) { value.Invoke(null, null); } else { value.Invoke(null, new object[1] { text3 }); } } catch (Exception arg) { Logger.LogError($"Error executing command: {arg}"); } return false; } return true; } } [HarmonyPatch(typeof(StatsManager))] internal static class StatsManagerPatch { [HarmonyPatch("RunStartStats")] [HarmonyPostfix] private static void RunStartStatsPatch() { Items.RegisterItems(); } } [HarmonyPatch(typeof(SteamManager))] public static class SteamManagerPatch { [HarmonyPatch("Awake")] [HarmonyPostfix] public static void AwakePatch(SteamManager __instance) { Logger.LogInfo("Enabling developer mode in SteamManager"); __instance.developerMode = true; } } } namespace REPOLib.Objects { public class CustomPrefabPool : IPunPrefabPool { public readonly Dictionary<string, GameObject> Prefabs = new Dictionary<string, GameObject>(); private DefaultPool _defaultPool; private IPunPrefabPool _otherPool; public DefaultPool DefaultPool { get { //IL_0009: Unknown result type (might be due to invalid IL or missing references) //IL_0013: Expected O, but got Unknown if (_defaultPool == null) { _defaultPool = new DefaultPool(); } return _defaultPool; } set { if (value != null) { _defaultPool = value; } } } public IPunPrefabPool OtherPool { get { return _otherPool; } set { if (!(value is DefaultPool) && !(value is CustomPrefabPool)) { _otherPool = value; } } } public bool RegisterPrefab(string prefabId, GameObject prefab) { //IL_0064: 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 ((Object)(object)prefab == (Object)null) { throw new ArgumentException("CustomPrefabPool: failed to register network prefab. Prefab is null."); } if (string.IsNullOrWhiteSpace(prefabId)) { throw new ArgumentException("CustomPrefabPool: failed to register network prefab. PrefabId is invalid."); } if (ResourcesHelper.HasPrefab(prefabId)) { Logger.LogError("CustomPrefabPool: failed to register network prefab \"" + prefabId + "\". Prefab already exists in Resources with the same prefab id."); return false; } if (Prefabs.TryGetValue(prefabId, out var value)) { LogLevel logLevel = (LogLevel)(((Object)(object)value == (Object)(object)prefab) ? 4 : 2); Logger.Log(logLevel, "CustomPrefabPool: failed to register network prefab \"" + prefabId + "\". There is already a prefab registered with the same prefab id."); return false; } Prefabs[prefabId.ToLower()] = prefab; Logger.LogInfo("CustomPrefabPool: registered network prefab \"" + prefabId + "\"", extended: true); return true; } public GameObject Instantiate(string prefabId, Vector3 position, Quaternion rotation) { //IL_001c: Unknown result type (might be due to invalid IL or missing references) //IL_001d: 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_0059: Unknown result type (might be due to invalid IL or missing references) //IL_0070: 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_003c: 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) GameObject val; if (!Prefabs.TryGetValue(prefabId.ToLower(), out var value)) { val = DefaultPool.Instantiate(prefabId, position, rotation); if ((Object)(object)val == (Object)null && OtherPool != null) { val = OtherPool.Instantiate(prefabId, position, rotation); } return val; } bool activeSelf = value.activeSelf; if (activeSelf) { value.SetActive(false); } val = Object.Instantiate<GameObject>(value, position, rotation); if (activeSelf) { value.SetActive(true); } Logger.LogInfo($"CustomPrefabPool: spawned network prefab \"{prefabId}\" at position {position}, rotation {((Quaternion)(ref rotation)).eulerAngles}", extended: true); return val; } public void Destroy(GameObject gameObject) { Object.Destroy((Object)(object)gameObject); } } public class UnityObjectNameComparer<T> : IEqualityComparer<T> where T : Object { public StringComparison ComparisonType { get; private set; } public UnityObjectNameComparer(StringComparison comparisonType = StringComparison.OrdinalIgnoreCase) { ComparisonType = comparisonType; } public bool Equals(T x, T y) { if ((Object)(object)x == (Object)(object)y) { return true; } if ((Object)(object)x == (Object)null || (Object)(object)y == (Object)null) { return false; } return ((Object)x).name.Equals(((Object)y).name, ComparisonType); } public int GetHashCode(T obj) { if (!((Object)(object)obj != (Object)null)) { return 0; } return ((Object)obj).name.GetHashCode(); } } } namespace REPOLib.Objects.Sdk { public abstract class Content : ScriptableObject { public abstract string Name { get; } public abstract void Initialize(Mod mod); } [CreateAssetMenu(menuName = "REPOLib/Enemy", order = 3, fileName = "New Enemy")] public class EnemyContent : Content { [SerializeField] private EnemySetup _setup; public EnemySetup Setup => _setup; public override string Name => ((Object)Setup).name; public override void Initialize(Mod mod) { Enemies.RegisterEnemy(Setup); } } [CreateAssetMenu(menuName = "REPOLib/Item", order = 2, fileName = "New Item")] public class ItemContent : Content { [SerializeField] private ItemAttributes _prefab; public ItemAttributes Prefab => _prefab; public override string Name => ((Object)Prefab).name; public override void Initialize(Mod mod) { _prefab.item.prefab = ((Component)_prefab).gameObject; Items.RegisterItem(Prefab.item); } } [CreateAssetMenu(menuName = "REPOLib/Mod", order = 0, fileName = "New Mod")] public class Mod : ScriptableObject { [SerializeField] private string _name; [SerializeField] private string _author; [SerializeField] private string _version = "1.0.0"; [SerializeField] private string _description; [SerializeField] private string _websiteUrl; [SerializeField] private string[] _dependencies = new string[1] { "Zehs-REPOLib-1.4.2" }; [SerializeField] private Sprite _icon; [SerializeField] private TextAsset _readme; public string Name => _name; public string Author => _author; public string Version => _version; public string Description => _description; public string WebsiteUrl => _websiteUrl; public IReadOnlyList<string> Dependencies => _dependencies; public Sprite Icon => _icon; public TextAsset Readme => _readme; public string FullName => Author + "-" + Name; public string Identifier => Author + "-" + Name + "-" + Version; } [CreateAssetMenu(menuName = "REPOLib/Valuable", order = 1, fileName = "New Valuable")] public class ValuableContent : Content { [SerializeField] private ValuableObject _prefab; [SerializeField] private string[] _valuablePresets = new string[1] { Valuables.GenericValuablePresetName }; public ValuableObject Prefab => _prefab; public IReadOnlyList<string> ValuablePresets => _valuablePresets; public override string Name => ((Object)Prefab).name; public override void Initialize(Mod mod) { Valuables.RegisterValuable(((Component)Prefab).gameObject, ValuablePresets.ToList()); } } } namespace REPOLib.Modules { public static class Enemies { private static readonly List<EnemySetup> _enemiesToRegister = new List<EnemySetup>(); private static readonly List<EnemySetup> _enemiesRegistered = new List<EnemySetup>(); private static bool _canRegisterEnemies = true; public static IReadOnlyList<EnemySetup> RegisteredEnemies => _enemiesRegistered; internal static void RegisterEnemies() { if (!_canRegisterEnemies) { return; } EnemyParent val = default(EnemyParent); foreach (EnemySetup item in _enemiesToRegister) { if (!_enemiesRegistered.Contains(item) && item.spawnObjects[0].TryGetComponent<EnemyParent>(ref val)) { if (EnemyDirector.instance.AddEnemy(item)) { _enemiesRegistered.Add(item); Logger.LogInfo("Added enemy \"" + ((Object)item.spawnObjects[0]).name + "\" to difficulty " + ((object)(Difficulty)(ref val.difficulty)).ToString(), extended: true); } else { Logger.LogWarning("Failed to add enemy \"" + ((Object)item.spawnObjects[0]).name + "\" to difficulty " + ((object)(Difficulty)(ref val.difficulty)).ToString(), extended: true); } } } _enemiesToRegister.Clear(); _canRegisterEnemies = false; } public static void RegisterEnemy(EnemySetup enemySetup) { if ((Object)(object)enemySetup == (Object)null || enemySetup.spawnObjects == null || enemySetup.spawnObjects.Count == 0) { throw new ArgumentException("Failed to register enemy. EnemySetup or spawnObjects list is empty."); } EnemyParent enemyParent = enemySetup.GetEnemyParent(); if ((Object)(object)enemyParent == (Object)null) { Logger.LogError("Failed to register enemy \"" + ((Object)enemySetup).name + "\". No enemy prefab found in spawnObjects list."); return; } if (!_canRegisterEnemies) { Logger.LogError("Failed to register enemy \"" + enemyParent.enemyName + "\". You can only register enemies in awake!"); } if (ResourcesHelper.HasEnemyPrefab(enemySetup)) { Logger.LogError("Failed to register enemy \"" + enemyParent.enemyName + "\". Enemy prefab already exists in Resources with the same name."); return; } if (_enemiesToRegister.Contains(enemySetup)) { Logger.LogError("Failed to register enemy \"" + enemyParent.enemyName + "\". Enemy is already registered!"); return; } foreach (GameObject distinctSpawnObject in enemySetup.GetDistinctSpawnObjects()) { foreach (EnemySetup item in _enemiesToRegister) { if (item.AnySpawnObjectsNameEquals(((Object)distinctSpawnObject).name)) { Logger.LogError("Failed to register enemy \"" + enemyParent.enemyName + "\". Enemy \"" + ((Object)item).name + "\" already has a spawn object called \"" + ((Object)distinctSpawnObject).name + "\""); return; } } } foreach (GameObject distinctSpawnObject2 in enemySetup.GetDistinctSpawnObjects()) { string enemyPrefabPath = ResourcesHelper.GetEnemyPrefabPath(distinctSpawnObject2); NetworkPrefabs.RegisterNetworkPrefab(enemyPrefabPath, distinctSpawnObject2); Utilities.FixAudioMixerGroups(distinctSpawnObject2); } _enemiesToRegister.Add(enemySetup); } } public static class Items { private static readonly List<Item> _itemsToRegister = new List<Item>(); private static readonly List<Item> _itemsRegistered = new List<Item>(); private static bool _canRegisterItems = true; public static IReadOnlyList<Item> RegisteredItems => _itemsRegistered; internal static void RegisterItems() { if ((Object)(object)StatsManager.instance == (Object)null) { Logger.LogError("Failed to register items. StatsManager instance is null."); return; } Logger.LogInfo("Adding items."); foreach (Item item in _itemsToRegister) { if (StatsManager.instance.AddItem(item)) { if (!_itemsRegistered.Contains(item)) { _itemsRegistered.Add(item); } Logger.LogInfo("Added item \"" + item.itemName + "\"", extended: true); } else { Logger.LogWarning("Failed to add item \"" + item.itemName + "\"", extended: true); } } _canRegisterItems = false; } public static void RegisterItem(Item item) { if ((Object)(object)item == (Object)null) { throw new ArgumentException("Failed to register item. Item is null."); } if ((Object)(object)item.prefab == (Object)null) { Logger.LogError("Failed to register item \"" + item.itemName + "\". Item prefab is null."); return; } if (item.itemAssetName != ((Object)item.prefab).name) { Logger.LogError("Failed to register item \"" + item.itemName + "\". Item itemAssetName does not match the prefab name."); return; } if (!_canRegisterItems) { Logger.LogError("Failed to register item \"" + item.itemName + "\". You can only register items from your plugins awake!"); return; } if (ResourcesHelper.HasItemPrefab(item)) { Logger.LogError("Failed to register item \"" + item.itemName + "\". Item prefab already exists in Resources with the same name."); return; } if (_itemsToRegister.Any((Item x) => x.itemAssetName == item.itemAssetName)) { Logger.LogError("Failed to register item \"" + item.itemName + "\". Item prefab already exists with the same name."); return; } if (_itemsToRegister.Contains(item)) { Logger.LogError("Failed to register item \"" + item.itemName + "\". Item is already registered!"); return; } string itemPrefabPath = ResourcesHelper.GetItemPrefabPath(item); NetworkPrefabs.RegisterNetworkPrefab(itemPrefabPath, item.prefab); Utilities.FixAudioMixerGroups(item.prefab); _itemsToRegister.Add(item); } } public static class NetworkingEvents { public static readonly byte[] ReservedEventCodes = new byte[3] { 0, 1, 2 }; private static readonly List<NetworkedEvent> _customEvents = new List<NetworkedEvent>(); public static readonly RaiseEventOptions RaiseAll = new RaiseEventOptions { Receivers = (ReceiverGroup)1 }; public static readonly RaiseEventOptions RaiseOthers = new RaiseEventOptions { Receivers = (ReceiverGroup)0 }; public static readonly RaiseEventOptions RaiseMasterClient = new RaiseEventOptions { Receivers = (ReceiverGroup)2 }; public static IReadOnlyList<NetworkedEvent> CustomEvents => _customEvents; internal static void Initialize() { PhotonNetwork.NetworkingClient.EventReceived += OnEvent; Application.quitting += delegate { PhotonNetwork.NetworkingClient.EventReceived -= OnEvent; }; } internal static void AddCustomEvent(NetworkedEvent networkedEvent) { if (!_customEvents.Contains(networkedEvent)) { _customEvents.Add(networkedEvent); } } private static void OnEvent(EventData photonEvent) { _customEvents.FirstOrDefault((NetworkedEvent e) => e.EventCode == photonEvent.Code)?.EventAction?.Invoke(photonEvent); } internal static bool TryGetUniqueEventCode(out byte eventCode) { eventCode = 0; while (IsEventCodeTaken(eventCode) && eventCode < 200) { eventCode++; } if (eventCode > 200) { eventCode = 0; return false; } return true; } public static bool IsEventCodeTaken(byte eventCode) { if (ReservedEventCodes.Any((byte x) => x == eventCode)) { return true; } if (_customEvents.Any((NetworkedEvent x) => x.EventCode == eventCode)) { return true; } return false; } } public class NetworkedEvent { public string Name { get; private set; } public byte EventCode { get; private set; } public Action<EventData> EventAction { get; private set; } public NetworkedEvent(string name, Action<EventData> eventAction) { Name = name; EventAction = eventAction; if (NetworkingEvents.TryGetUniqueEventCode(out var eventCode)) { EventCode = eventCode; NetworkingEvents.AddCustomEvent(this); Logger.LogInfo($"Registered NetworkedEvent \"{Name}\" with event code: {EventCode}", extended: true); } else { Logger.LogError("Failed to register NetworkedEvent \"" + Name + "\". Could not get unique event code."); } } public void RaiseEvent(object eventContent, RaiseEventOptions raiseEventOptions, SendOptions sendOptions) { //IL_0018: 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 (SemiFunc.IsMultiplayer()) { PhotonNetwork.RaiseEvent(EventCode, eventContent, raiseEventOptions, sendOptions); } else if ((int)raiseEventOptions.Receivers != 0) { RaiseEventSingleplayer(eventContent); } } private void RaiseEventSingleplayer(object eventContent) { //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_000d: Unknown result type (might be due to invalid IL or missing references) //IL_001a: Expected O, but got Unknown if (!SemiFunc.IsMultiplayer()) { EventData val = new EventData { Code = EventCode }; val.Parameters[val.CustomDataKey] = eventContent; val.Parameters[val.SenderKey] = 1; EventAction?.Invoke(val); } } } public static class NetworkPrefabs { private static CustomPrefabPool _customPrefabPool; internal static CustomPrefabPool CustomPrefabPool { get { if (_customPrefabPool == null) { _customPrefabPool = new CustomPrefabPool(); } return _customPrefabPool; } private set { _customPrefabPool = value; } } internal static void Initialize() { if (PhotonNetwork.PrefabPool is CustomPrefabPool) { Logger.LogWarning("NetworkPrefabs failed to initialize. PhotonNetwork.PrefabPool is already a CustomPrefabPool."); return; } Logger.LogInfo("Initializing NetworkPrefabs."); Logger.LogInfo($"PhotonNetwork.PrefabPool = {((object)PhotonNetwork.PrefabPool).GetType()}", extended: true); IPunPrefabPool prefabPool = PhotonNetwork.PrefabPool; DefaultPool val = (DefaultPool)(object)((prefabPool is DefaultPool) ? prefabPool : null); if (val != null) { CustomPrefabPool.DefaultPool = val; } else { CustomPrefabPool.OtherPool = PhotonNetwork.PrefabPool; } PhotonNetwork.PrefabPool = (IPunPrefabPool)(object)CustomPrefabPool; Logger.LogInfo("Replaced PhotonNetwork.PrefabPool with CustomPrefabPool."); Logger.LogInfo($"PhotonNetwork.PrefabPool = {((object)PhotonNetwork.PrefabPool).GetType()}", extended: true); Logger.LogInfo("Finished initializing NetworkPrefabs."); } public static void RegisterNetworkPrefab(GameObject prefab) { RegisterNetworkPrefab((prefab != null) ? ((Object)prefab).name : null, prefab); } public static void RegisterNetworkPrefab(string prefabId, GameObject prefab) { CustomPrefabPool.RegisterPrefab(prefabId, prefab); } } public static class ResourcesHelper { public static string GetValuablesFolderPath(Type volumeType) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0022: Expected I4, but got Unknown return Path.Combine("Valuables/", (int)volumeType switch { 0 => "01 Tiny/", 1 => "02 Small/", 2 => "03 Medium/", 3 => "04 Big/", 4 => "05 Wide/", 5 => "06 Tall/", 6 => "07 Very Tall/", _ => string.Empty, }); } public static string GetItemsFolderPath() { return "Items/"; } public static string GetEnemiesFolderPath() { return "Enemies/"; } public static string GetValuablePrefabPath(ValuableObject valuableObject) { //IL_0010: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)valuableObject == (Object)null) { return string.Empty; } string valuablesFolderPath = GetValuablesFolderPath(valuableObject.volumeType); return Path.Combine(valuablesFolderPath, ((Object)((Component)valuableObject).gameObject).name); } public static string GetValuablePrefabPath(GameObject prefab) { if ((Object)(object)prefab == (Object)null) { return string.Empty; } ValuableObject valuableObject = default(ValuableObject); if (prefab.TryGetComponent<ValuableObject>(ref valuableObject)) { return GetValuablePrefabPath(valuableObject); } return string.Empty; } public static string GetItemPrefabPath(Item item) { if ((Object)(object)item == (Object)null) { return string.Empty; } return GetItemPrefabPath(item.prefab); } public static string GetItemPrefabPath(GameObject prefab) { if ((Object)(object)prefab == (Object)null) { return string.Empty; } string itemsFolderPath = GetItemsFolderPath(); return Path.Combine(itemsFolderPath, ((Object)prefab).name); } public static string GetEnemyPrefabPath(EnemySetup enemySetup) { if ((Object)(object)enemySetup == (Object)null || enemySetup.spawnObjects == null) { return string.Empty; } GameObject mainSpawnObject = enemySetup.GetMainSpawnObject(); if ((Object)(object)mainSpawnObject == (Object)null) { return string.Empty; } string enemiesFolderPath = GetEnemiesFolderPath(); return Path.Combine(enemiesFolderPath, ((Object)mainSpawnObject).name); } public static string GetEnemyPrefabPath(GameObject prefab) { if ((Object)(object)prefab == (Object)null) { return string.Empty; } string enemiesFolderPath = GetEnemiesFolderPath(); return Path.Combine(enemiesFolderPath, ((Object)prefab).name); } public static bool HasValuablePrefab(ValuableObject valuableObject) { if ((Object)(object)valuableObject == (Object)null) { return false; } string valuablePrefabPath = GetValuablePrefabPath(valuableObject); return (Object)(object)Resources.Load<GameObject>(valuablePrefabPath) != (Object)null; } public static bool HasItemPrefab(Item item) { if ((Object)(object)item == (Object)null) { return false; } string itemPrefabPath = GetItemPrefabPath(item); return (Object)(object)Resources.Load<GameObject>(itemPrefabPath) != (Object)null; } public static bool HasEnemyPrefab(EnemySetup enemySetup) { if ((Object)(object)enemySetup == (Object)null) { return false; } foreach (GameObject distinctSpawnObject in enemySetup.GetDistinctSpawnObjects()) { string enemyPrefabPath = GetEnemyPrefabPath(distinctSpawnObject); if ((Object)(object)Resources.Load<GameObject>(enemyPrefabPath) != (Object)null) { return true; } } return false; } public static bool HasPrefab(GameObject prefab) { return (Object)(object)Resources.Load<GameObject>((prefab != null) ? ((Object)prefab).name : null) != (Object)null; } public static bool HasPrefab(string prefabId) { return (Object)(object)Resources.Load<GameObject>(prefabId) != (Object)null; } } public static class Utilities { private static readonly List<GameObject> _prefabsToFix = new List<GameObject>(); private static readonly List<GameObject> _fixedPrefabs = new List<GameObject>(); internal static void FixAudioMixerGroupsOnPrefabs() { foreach (GameObject item in _prefabsToFix) { item.FixAudioMixerGroups(); _fixedPrefabs.Add(item); } _prefabsToFix.Clear(); } public static void FixAudioMixerGroups(GameObject prefab) { if (!((Object)(object)prefab == (Object)null) && !_prefabsToFix.Contains(prefab) && !_fixedPrefabs.Contains(prefab)) { if ((Object)(object)AudioManager.instance == (Object)null) { _prefabsToFix.Add(prefab); return; } prefab.FixAudioMixerGroups(); _fixedPrefabs.Add(prefab); } } } public static class Valuables { private static readonly Dictionary<string, LevelValuables> _valuablePresets = new Dictionary<string, LevelValuables>(); private static readonly Dictionary<GameObject, List<string>> _valuablesToRegister = new Dictionary<GameObject, List<string>>(); private static readonly List<GameObject> _valuablesRegistered = new List<GameObject>(); private static bool _canRegisterValuables = true; public static IReadOnlyList<GameObject> RegisteredValuables => _valuablesRegistered; public static IReadOnlyList<LevelValuables> ValuablePresets => _valuablePresets.Values.ToList(); public static string GenericValuablePresetName => "Valuables - Generic"; private static void CacheValuablePresets() { if ((Object)(object)RunManager.instance == (Object)null) { Logger.LogError("Failed to cache LevelValuables. RunManager instance is null."); return; } foreach (Level level in RunManager.instance.levels) { foreach (LevelValuables valuablePreset in level.ValuablePresets) { _valuablePresets.TryAdd(((Object)valuablePreset).name, valuablePreset); } } } internal static void RegisterValuables() { if (!_canRegisterValuables) { return; } CacheValuablePresets(); if (_valuablePresets.Count == 0) { Logger.LogError("Failed to register valuables. LevelValuables list is empty!"); return; } Logger.LogInfo("Adding valuables to valuable presets."); foreach (GameObject key in _valuablesToRegister.Keys) { if (_valuablesRegistered.Contains(key)) { continue; } List<string> list = _valuablesToRegister[key]; if (!list.Any((string x) => _valuablePresets.Keys.Any((string y) => x == y))) { Logger.LogError("Valuable \"" + ((Object)key).name + "\" does not have any valid valuable preset names set. Adding generic valuable preset name."); list.Add(GenericValuablePresetName); } foreach (string item in list) { if (item == null || !_valuablePresets.ContainsKey(item)) { Logger.LogError("Failed to add valuable \"" + ((Object)key).name + "\" to valuable preset \"" + item + "\". The valuable preset does not exist."); } else if (_valuablePresets[item].AddValuable(key)) { _valuablesRegistered.Add(key); Logger.LogInfo("Added valuable \"" + ((Object)key).name + "\" to valuable preset \"" + item + "\"", extended: true); } else { Logger.LogWarning("Failed to add valuable \"" + ((Object)key).name + "\" to valuable preset \"" + item + "\"", extended: true); } } } _valuablesToRegister.Clear(); _canRegisterValuables = false; } public static void RegisterValuable(GameObject prefab) { RegisterValuable(prefab, new List<string>()); } public static void RegisterValuable(GameObject prefab, List<LevelValuables> presets) { RegisterValuable(prefab, presets.Select((LevelValuables preset) => ((Object)preset).name).ToList()); } public static void RegisterValuable(GameObject prefab, List<string> presetNames) { ValuableObject valuableObject = default(ValuableObject); if ((Object)(object)prefab == (Object)null) { Logger.LogError("Failed to register valuable. Prefab is null."); } else if (!prefab.TryGetComponent<ValuableObject>(ref valuableObject)) { Logger.LogError("Failed to register valuable. Prefab does not have a ValuableObject component."); } else { RegisterValuable(valuableObject, presetNames); } } public static void RegisterValuable(ValuableObject valuableObject) { RegisterValuable(valuableObject, new List<string>()); } public static void RegisterValuable(ValuableObject valuableObject, List<LevelValuables> presets) { RegisterValuable(valuableObject, presets.Select((LevelValuables preset) => ((Object)preset).name).ToList()); } public static void RegisterValuable(ValuableObject valuableObject, List<string> presetNames) { if ((Object)(object)valuableObject == (Object)null) { Logger.LogError("Failed to register valuable. ValuableObject is null."); return; } GameObject prefab = ((Component)valuableObject).gameObject; if (presetNames == null || presetNames.Count == 0) { presetNames = new List<string>(1) { GenericValuablePresetName }; } if (!_canRegisterValuables) { Logger.LogError("Failed to register valuable \"" + ((Object)prefab).name + "\". You can only register valuables from your plugins awake!"); return; } if (ResourcesHelper.HasValuablePrefab(valuableObject)) { Logger.LogError("Failed to register valuable \"" + ((Object)prefab).name + "\". Valuable prefab already exists in Resources with the same name."); return; } if (_valuablesToRegister.Keys.Any((GameObject x) => ((Object)x).name.Equals(((Object)prefab).name, StringComparison.OrdinalIgnoreCase))) { Logger.LogError("Failed to register valuable \"" + ((Object)prefab).name + "\". Valuable prefab already exists with the same name."); return; } if (_valuablesToRegister.ContainsKey(prefab)) { Logger.LogWarning("Failed to register valuable \"" + ((Object)prefab).name + "\". Valuable is already registered!"); return; } string valuablePrefabPath = ResourcesHelper.GetValuablePrefabPath(valuableObject); NetworkPrefabs.RegisterNetworkPrefab(valuablePrefabPath, prefab); Utilities.FixAudioMixerGroups(prefab); _valuablesToRegister.Add(prefab, presetNames); } [Obsolete("prefabId is no longer supported", true)] public static void RegisterValuable(string prefabId, GameObject prefab) { RegisterValuable(prefab); } [Obsolete("prefabId is no longer supported", true)] public static void RegisterValuable(string prefabId, GameObject prefab, List<LevelValuables> presets) { RegisterValuable(prefab, presets); } [Obsolete("prefabId is no longer supported", true)] public static void RegisterValuable(string prefabId, GameObject prefab, List<string> presetNames) { RegisterValuable(prefab, presetNames); } } } namespace REPOLib.Extensions { public static class EnemyDirectorExtension { public static bool HasEnemy(this EnemyDirector enemyDirector, EnemySetup enemySetup) { //IL_003a: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)enemySetup == (Object)null || enemySetup.spawnObjects.Count == 0) { return false; } EnemyParent val = default(EnemyParent); foreach (GameObject spawnObject in enemySetup.spawnObjects) { if (spawnObject.TryGetComponent<EnemyParent>(ref val) && enemyDirector.TryGetList(val.difficulty, out var list)) { return list.Contains(enemySetup); } } return false; } public static bool AddEnemy(this EnemyDirector enemyDirector, EnemySetup enemySetup) { //IL_002d: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)enemySetup == (Object)null) { return false; } EnemyParent val = default(EnemyParent); foreach (GameObject spawnObject in enemySetup.spawnObjects) { if (spawnObject.TryGetComponent<EnemyParent>(ref val) && enemyDirector.TryGetList(val.difficulty, out var list) && !list.Contains(enemySetup)) { list.Add(enemySetup); return true; } } return false; } public static bool TryGetList(this EnemyDirector enemyDirector, Difficulty difficultyType, out List<EnemySetup> list) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0012: Expected I4, but got Unknown list = (int)difficultyType switch { 0 => enemyDirector.enemiesDifficulty1, 1 => enemyDirector.enemiesDifficulty2, 2 => enemyDirector.enemiesDifficulty3, _ => null, }; return list != null; } } internal static class EnemySetupExtension { public static List<GameObject> GetDistinctSpawnObjects(this EnemySetup enemySetup) { if ((Object)(object)enemySetup == (Object)null || enemySetup.spawnObjects == null) { return new List<GameObject>(); } return enemySetup.spawnObjects.Where((GameObject x) => (Object)(object)x != (Object)null).Distinct(new UnityObjectNameComparer<GameObject>()).ToList(); } public static GameObject GetMainSpawnObject(this EnemySetup enemySetup) { EnemyParent enemyParent = enemySetup.GetEnemyParent(); if (enemyParent == null) { return null; } return ((Component)enemyParent).gameObject; } public static EnemyParent GetEnemyParent(this EnemySetup enemySetup) { EnemyParent result = default(EnemyParent); foreach (GameObject distinctSpawnObject in enemySetup.GetDistinctSpawnObjects()) { if (distinctSpawnObject.TryGetComponent<EnemyParent>(ref result)) { return result; } } return null; } public static bool AnySpawnObjectsNameEquals(this EnemySetup enemySetup, string name, StringComparison comparisonType = StringComparison.OrdinalIgnoreCase) { if ((Object)(object)enemySetup == (Object)null) { return false; } return enemySetup.GetDistinctSpawnObjects().Any((GameObject x) => ((Object)x).name.Equals(name, comparisonType)); } } internal static class GameObjectExtension { public static void FixAudioMixerGroups(this GameObject gameObject) { if ((Object)(object)gameObject == (Object)null) { return; } if ((Object)(object)AudioManager.instance == (Object)null) { Logger.LogWarning("Failed to fix audio mixer groups on GameObject \"" + ((Object)gameObject).name + "\". AudioManager instance is null."); return; } AudioSource[] componentsInChildren = gameObject.GetComponentsInChildren<AudioSource>(); AudioSource[] array = componentsInChildren; foreach (AudioSource val in array) { if ((Object)(object)val.outputAudioMixerGroup == (Object)null) { Logger.LogWarning("Failed to fix audio mixer groups on GameObject \"" + ((Object)gameObject).name + "\". No audio mixer group is assigned."); continue; } AudioMixer val2 = (AudioMixer)(((Object)val.outputAudioMixerGroup.audioMixer).name switch { "Master" => AudioManager.instance.MasterMixer, "Music" => AudioManager.instance.MusicMasterGroup.audioMixer, "Sound" => AudioManager.instance.SoundMasterGroup.audioMixer, "Spectate" => AudioManager.instance.MicrophoneSpectateGroup.audioMixer, _ => AudioManager.instance.SoundMasterGroup.audioMixer, }); AudioMixerGroup[] array2 = val2.FindMatchingGroups(((Object)val.outputAudioMixerGroup).name); AudioMixerGroup val3; if (array2.Length >= 1) { val3 = array2[0]; } else { val3 = AudioManager.instance.SoundMasterGroup; Logger.LogWarning("Could not find matching audio mixer group for GameObject \"" + ((Object)gameObject).name + "\" -> AudioSource \"" + ((Object)val).name + "\". Using default audio mixer group \"" + ((Object)val3).name + "\"", extended: true); } val.outputAudioMixerGroup = val3; Logger.LogInfo("Fixed audio mixer group on GameObject \"" + ((Object)gameObject).name + "\" -> AudioSource \"" + ((Object)val).name + "\". AudioMixerGroup \"" + ((Object)val2).name + " > " + ((Object)val3).name + "\"", extended: true); } } } internal static class LevelValuablesExtension { public static bool HasValuable(this LevelValuables levelValuables, GameObject prefab) { //IL_000e: Unknown result type (might be due to invalid IL or missing references) ValuableObject val = default(ValuableObject); if (!prefab.TryGetComponent<ValuableObject>(ref val)) { return false; } if (!levelValuables.TryGetList(val.volumeType, out var list)) { return false; } return list.Contains(prefab); } public static bool AddValuable(this LevelValuables levelValuables, GameObject prefab) { //IL_000e: Unknown result type (might be due to invalid IL or missing references) ValuableObject val = default(ValuableObject); if (!prefab.TryGetComponent<ValuableObject>(ref val)) { return false; } if (!levelValuables.TryGetList(val.volumeType, out var list)) { return false; } if (list.Contains(prefab)) { return false; } list.Add(prefab); return true; } public static bool TryGetList(this LevelValuables levelValuables, Type volumeType, out List<GameObject> list) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0022: Expected I4, but got Unknown list = (int)volumeType switch { 0 => levelValuables.tiny, 1 => levelValuables.small, 2 => levelValuables.medium, 3 => levelValuables.big, 4 => levelValuables.wide, 5 => levelValuables.tall, 6 => levelValuables.veryTall, _ => null, }; return list != null; } public static bool TryGetCombinedList(this LevelValuables levelValuables, out List<GameObject> list) { List<List<GameObject>> source = new List<List<GameObject>> { levelValuables.tiny, levelValuables.small, levelValuables.medium, levelValuables.big, levelValuables.wide, levelValuables.tall, levelValuables.veryTall }; list = (from x in source.SelectMany((List<GameObject> volumeType) => volumeType) where (Object)(object)x != (Object)null select x).Distinct().ToList(); return list != null; } } internal static class StatsManagerExtension { public static bool HasItem(this StatsManager statsManager, Item item) { if ((Object)(object)item == (Object)null) { return false; } return statsManager.itemDictionary.ContainsKey(item.itemAssetName); } public static bool AddItem(this StatsManager statsManager, Item item) { if (!statsManager.itemDictionary.ContainsKey(item.itemAssetName)) { statsManager.itemDictionary.Add(item.itemAssetName, item); } foreach (Dictionary<string, int> item2 in statsManager.AllDictionariesWithPrefix("item")) { item2[item.itemAssetName] = 0; } return true; } } } namespace REPOLib.Commands { [AttributeUsage(AttributeTargets.Method, Inherited = false, AllowMultiple = false)] public class CommandExecutionAttribute : Attribute { public bool RequiresDeveloperMode { get; private set; } public bool EnabledByDefault { get; private set; } public string Name { get; private set; } public string Description { get; private set; } public CommandExecutionAttribute(string name = null, string description = null, bool enabledByDefault = true, bool requiresDeveloperMode = false) { RequiresDeveloperMode = requiresDeveloperMode; EnabledByDefault = enabledByDefault; Name = name ?? ""; Description = description ?? ""; } } [AttributeUsage(AttributeTargets.Method, Inherited = false, AllowMultiple = false)] public class CommandInitializerAttribute : Attribute { } [AttributeUsage(AttributeTargets.Method, Inherited = false, AllowMultiple = true)] public class CommandAliasAttribute : Attribute { public string Alias { get; private set; } public CommandAliasAttribute(string alias) { Alias = alias; } } public static class CommandManager { private static List<MethodInfo> commandExecutionMethodCache = new List<MethodInfo>(); public static Dictionary<string, MethodInfo> CommandExecutionMethods { get; private set; } = new Dictionary<string, MethodInfo>(); public static List<MethodInfo> CommandInitializerMethods { get; private set; } = new List<MethodInfo>(); public static Dictionary<string, bool> CommandsEnabled { get; private set; } = new Dictionary<string, bool>(); public static void Initialize() { Logger.LogInfo("CommandManager initializing.", extended: true); CommandInitializerMethods = (from method in AppDomain.CurrentDomain.GetAssemblies().SelectMany((Assembly assembly) => assembly.GetTypes()).SelectMany((Type type) => type.GetMethods()) where method.GetCustomAttribute<CommandInitializerAttribute>() != null select method).ToList(); foreach (MethodInfo commandInitializerMethod in CommandInitializerMethods) { try { Logger.LogInfo($"Initializing command initializer on method {commandInitializerMethod.DeclaringType}.{commandInitializerMethod.Name}", extended: true); if (!commandInitializerMethod.IsStatic) { Logger.LogWarning($"Command initializer {commandInitializerMethod.DeclaringType}.{commandInitializerMethod.Name} is not static!"); } commandInitializerMethod.Invoke(null, null); } catch (Exception arg) { Logger.LogError($"Failed to initialize command: {arg}"); } } FindAllCommandMethods(); foreach (KeyValuePair<string, MethodInfo> commandExecutionMethod in CommandExecutionMethods) { if (!commandExecutionMethod.Value.IsStatic) { Logger.LogWarning("Command execution method for command \"" + commandExecutionMethod.Key + "\" is not static!"); } } BindConfigs(); Logger.LogInfo("Finished initializing custom commands."); } public static void FindAllCommandMethods() { commandExecutionMethodCache = (from method in AppDomain.CurrentDomain.GetAssemblies().SelectMany((Assembly assembly) => assembly.GetTypes()).SelectMany((Type type) => type.GetMethods()) where method.GetCustomAttribute<CommandExecutionAttribute>() != null select method).ToList(); foreach (MethodInfo item in commandExecutionMethodCache) { ParameterInfo[] parameters = item.GetParameters(); if (parameters.Length > 1) { Logger.LogError("Command \"" + item.GetCustomAttribute<CommandExecutionAttribute>().Name + "\" execution method \"" + item.Name + "\" has too many parameters! Should only have 1 string parameter or none."); break; } if (parameters.Length == 1 && parameters[0].ParameterType != typeof(string)) { Logger.LogError("Command \"" + item.GetCustomAttribute<CommandExecutionAttribute>().Name + "\" execution method \"" + item.Name + "\" has parameter of the wrong type! Should be string."); break; } IEnumerable<CommandAliasAttribute> customAttributes = item.GetCustomAttributes<CommandAliasAttribute>(); bool flag = false; if (customAttributes == null || customAttributes.Count() == 0) { Logger.LogWarning("Command " + item.Name + " has no alias attributes!"); continue; } foreach (CommandAliasAttribute item2 in customAttributes) { if (CommandExecutionMethods.TryAdd(item2.Alias, item)) { Logger.LogInfo($"Registered command alias \"{item2.Alias}\" for method \"{item.DeclaringType}.{item.Name}\".", extended: true); flag = true; } } if (!flag) { Logger.LogWarning("Failed to add any command aliases for method \"" + item.Name + "\"."); } } } public static void BindConfigs() { foreach (MethodInfo item in commandExecutionMethodCache) { CommandExecutionAttribute customAttribute = item.GetCustomAttribute<CommandExecutionAttribute>(); BepInPlugin customAttribute2 = ((MemberInfo)(from type in item.Module.Assembly.GetTypes() where ((MemberInfo)type).GetCustomAttribute<BepInPlugin>() != null select type).ToList()[0]).GetCustomAttribute<BepInPlugin>(); string text = ((customAttribute2 != null) ? customAttribute2.GUID : null) ?? "Unknown"; string text2 = item.DeclaringType.ToString() ?? "Unknown"; List<string> list = new List<string>(); foreach (CommandAliasAttribute customAttribute3 in item.GetCustomAttributes<CommandAliasAttribute>()) { list.Add(customAttribute3.Alias); } string text3 = customAttribute.Name ?? "Unknown"; string text4 = "(Alias(es): [" + string.Join(", ", list) + "])\n\n" + (customAttribute.Description ?? "Unknown"); bool enabledByDefault = customAttribute.EnabledByDefault; CommandsEnabled[text3] = ConfigManager.ConfigFile.Bind<bool>("Commands." + text, text3, enabledByDefault, text4).Value; } } } public static class SpawnItemCommand { [CommandExecution("Spawn Item", "Spawn an instance of an item with the specified (case-insensitive) name. You can optionally leave out \"Item \" from the prefab name.", true, true)] [CommandAlias("spawnitem")] [CommandAlias("si")] public static void Execute(string args) { Logger.LogInfo("Running spawn command with args \"" + args + "\"", extended: true); if (args == null || args.Length == 0) { Logger.LogWarning("No args provided to spawn command."); } else if (!SemiFunc.IsMasterClientOrSingleplayer()) { Logger.LogError("Only the host can spawn items!"); } else if ((Object)(object)StatsManager.instance == (Object)null) { Logger.LogError("Failed spawn item command, StatsManager is not initialized."); } else if ((Object)(object)PlayerAvatar.instance == (Object)null) { Logger.LogWarning("Can't spawn anything, player avatar is not initialized."); } else { SpawnItemByName(args); } } private static void SpawnItemByName(string name) { //IL_000a: Unknown result type (might be due to invalid IL or missing references) //IL_0019: Unknown result type (might be due to invalid IL or missing references) //IL_0023: Unknown result type (might be due to invalid IL or missing references) //IL_0028: Unknown result type (might be due to invalid IL or missing references) //IL_002d: 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_00d2: Unknown result type (might be due to invalid IL or missing references) //IL_00e9: 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_00a5: Unknown result type (might be due to invalid IL or missing references) //IL_00b7: 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) Vector3 val = ((Component)PlayerAvatar.instance).transform.position + ((Component)PlayerAvatar.instance).transform.forward * 1f; Logger.LogInfo($"Trying to spawn item \"{name}\" at {val}...", extended: true); if (!TryGetItemByName(name, out var item)) { Logger.LogWarning("Could not find an item with the name \"" + name + "\" to spawn."); return; } try { if (SemiFunc.IsMultiplayer()) { string itemPrefabPath = ResourcesHelper.GetItemPrefabPath(item); if (itemPrefabPath == string.Empty) { Logger.LogError("Failed to get the path of item \"" + item.itemName + "\""); return; } Logger.LogInfo($"Network spawning \"{itemPrefabPath}\" at {val}."); PhotonNetwork.InstantiateRoomObject(itemPrefabPath, val, Quaternion.identity, (byte)0, (object[])null); } else { Logger.LogInfo($"Locally spawning \"{item.itemName}\" at {val}."); Object.Instantiate<GameObject>(item.prefab, val, Quaternion.identity); } } catch (Exception arg) { Logger.LogError($"Failed to spawn \"{item.itemName}\":\n{arg}"); } } private static bool TryGetItemByName(string name, out Item item) { if ((Object)(object)StatsManager.instance == (Object)null) { item = null; return false; } Item[] source = StatsManager.instance.itemDictionary.Values.ToArray(); item = ((IEnumerable<Item>)source).FirstOrDefault((Func<Item, bool>)((Item x) => x.itemAssetName.Equals(name, StringComparison.OrdinalIgnoreCase) || x.itemName.Equals(name, StringComparison.OrdinalIgnoreCase))); return (Object)(object)item != (Object)null; } } public static class SpawnValuableCommand { private static bool initialized = false; private static readonly Dictionary<string, GameObject> valuablePrefabs = new Dictionary<string, GameObject>(); [CommandInitializer] public static void Initialize() { Logger.LogInfo("Initializing spawn valuable command"); CacheValuables(); initialized = true; } public static void CacheValuables() { valuablePrefabs.Clear(); if ((Object)(object)RunManager.instance == (Object)null) { Logger.LogError("Failed to cache LevelValuables. RunManager instance is null."); return; } foreach (Level level in RunManager.instance.levels) { foreach (LevelValuables valuablePreset in level.ValuablePresets) { if (!valuablePreset.TryGetCombinedList(out var list)) { continue; } foreach (GameObject item in list) { valuablePrefabs.TryAdd(((Object)item).name.ToLower(), item); } } } } [CommandExecution("Spawn Valuable", "Spawn an instance of a valuable with the specified (case-insensitive) name. You can optionally leave out \"Valuable \" from the prefab name.", true, true)] [CommandAlias("spawnvaluable")] [CommandAlias("spawnval")] [CommandAlias("sv")] public static void Execute(string args) { Logger.LogInfo("Running spawn command with args \"" + args + "\"", extended: true); if (args == null || args.Length == 0) { Logger.LogWarning("No args provided to spawn command."); } else if (!initialized) { Logger.LogError("Spawn command not initialized!"); } else if (!SemiFunc.IsMasterClientOrSingleplayer()) { Logger.LogError("Only the host can spawn valuables!"); } else if ((Object)(object)PlayerAvatar.instance == (Object)null) { Logger.LogWarning("Can't spawn anything, player avatar is not initialized."); } else if ((Object)(object)ValuableDirector.instance == (Object)null) { Logger.LogError("ValuableDirector not initialized."); } else { SpawnValuableByName(args); } } private static void SpawnValuableByName(string name) { //IL_000a: Unknown result type (might be due to invalid IL or missing references) //IL_0019: Unknown result type (might be due to invalid IL or missing references) //IL_0023: Unknown result type (might be due to invalid IL or missing references) //IL_0028: Unknown result type (might be due to invalid IL or missing references) //IL_002d: 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_00d2: 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_00e5: 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_00b7: 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) Vector3 val = ((Component)PlayerAvatar.instance).transform.position + ((Component)PlayerAvatar.instance).transform.forward * 1f; Logger.LogInfo($"Trying to spawn \"{name}\" at {val}...", extended: true); if (!TryGetValuableByName(name, out var prefab)) { Logger.LogWarning("Spawn command failed. Unknown valuable with name \"" + name + "\""); return; } try { if (SemiFunc.IsMultiplayer()) { string valuablePrefabPath = ResourcesHelper.GetValuablePrefabPath(prefab); if (valuablePrefabPath == string.Empty) { Logger.LogError("Failed to get the path of valuable \"" + ((Object)prefab).name + "\""); return; } Logger.LogInfo($"Network spawning \"{valuablePrefabPath}\" at {val}."); PhotonNetwork.InstantiateRoomObject(valuablePrefabPath, val, Quaternion.identity, (byte)0, (object[])null); } else { Logger.LogInfo($"Locally spawning {((Object)prefab).name} at {val}."); Object.Instantiate<GameObject>(prefab, val, Quaternion.identity); } } catch (Exception arg) { Logger.LogError($"Failed to spawn \"{name}\":\n{arg}"); } } private static bool TryGetValuableByName(string name, out GameObject prefab) { if (valuablePrefabs.TryGetValue(name.ToLower(), out prefab)) { return true; } if (valuablePrefabs.TryGetValue("valuable " + name.ToLower(), out prefab)) { return true; } return false; } } } namespace System.Runtime.CompilerServices { [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)] internal sealed class IgnoresAccessChecksToAttribute : Attribute { public IgnoresAccessChecksToAttribute(string assemblyName) { } } }
plugins/zelofi-MorePlayers/MorePlayers/MovePlayers.dll
Decompiled 2 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 HarmonyLib; using Photon.Pun; using Photon.Realtime; using Steamworks; using Steamworks.Data; 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("AdjustMaxPlayers")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("AdjustMaxPlayers")] [assembly: AssemblyCopyright("Copyright © 2025")] [assembly: AssemblyTrademark("")] [assembly: ComVisible(false)] [assembly: Guid("332fb87a-6417-4a3c-b614-543d93450b34")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")] [assembly: AssemblyVersion("1.0.0.0")] namespace MorePlayers; [BepInPlugin("zelofi.MorePlayers", "MorePlayers", "1.0.1")] public class Plugin : BaseUnityPlugin { [HarmonyPatch(typeof(NetworkConnect), "TryJoiningRoom")] public class TryJoiningRoomPatch { private static bool Prefix(ref string ___RoomName) { //IL_0059: 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) //IL_0079: Expected O, but got Unknown if (string.IsNullOrEmpty(___RoomName)) { mls.LogError((object)"RoomName is null or empty, using previous method!"); return true; } if (configMaxPlayers.Value == 0) { mls.LogError((object)"The MaxPlayers config is null or empty, using previous method!"); return true; } if ((Object)(object)NetworkConnect.instance != (Object)null) { PhotonNetwork.JoinOrCreateRoom(___RoomName, new RoomOptions { MaxPlayers = configMaxPlayers.Value }, TypedLobby.Default, (string[])null); return false; } mls.LogError((object)"NetworkConnect instance is null, using previous method!"); return true; } } [HarmonyPatch(typeof(SteamManager), "HostLobby")] public class HostLobbyPatch { private static bool Prefix() { HostLobbyAsync(); return false; } private static async void HostLobbyAsync() { Debug.Log((object)"Steam: Hosting lobby..."); Lobby? lobby = await SteamMatchmaking.CreateLobbyAsync(configMaxPlayers.Value); if (!lobby.HasValue) { Debug.LogError((object)"Lobby created but not correctly instantiated."); return; } Lobby value = lobby.Value; ((Lobby)(ref value)).SetPublic(); value = lobby.Value; ((Lobby)(ref value)).SetJoinable(false); } } public const string modGUID = "zelofi.MorePlayers"; public const string modName = "MorePlayers"; public const string modVersion = "1.0.1"; private readonly Harmony harmony = new Harmony("zelofi.MorePlayers"); public static ConfigEntry<int> configMaxPlayers; public static ManualLogSource mls; private void Awake() { mls = Logger.CreateLogSource("zelofi.MorePlayers"); mls.LogInfo((object)"zelofi.MorePlayers is now awake!"); configMaxPlayers = ((BaseUnityPlugin)this).Config.Bind<int>("General", "MaxPlayers", 10, "The max amount of players allowed in a server"); harmony.PatchAll(typeof(TryJoiningRoomPatch)); harmony.PatchAll(typeof(HostLobbyPatch)); } }
plugins/zombieseatflesh7-ColoredNametags/ColoredNametags.dll
Decompiled 2 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 HarmonyLib; using Microsoft.CodeAnalysis; using Mono.Cecil.Cil; using MonoMod.Cil; using MonoMod.RuntimeDetour; using TMPro; 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("ColoredNametags")] [assembly: AssemblyConfiguration("Debug")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: AssemblyInformationalVersion("1.0.0")] [assembly: AssemblyProduct("ColoredNametags")] [assembly: AssemblyTitle("ColoredNametags")] [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 ColoredNametags { public static class MyPluginInfo { public const string PLUGIN_GUID = "ColoredNametags"; public const string PLUGIN_NAME = "ColoredNametags"; public const string PLUGIN_VERSION = "1.0.0"; } } namespace NameColorizer { [BepInPlugin("zombieseatflesh7.ColoredNametags", "Colored Nametags", "1.0.0")] public class ColoredNametagMod : BaseUnityPlugin { [CompilerGenerated] private static class <>O { public static Action<Action<WorldSpaceUIParent, PlayerAvatar>, WorldSpaceUIParent, PlayerAvatar> <0>__WorldSpaceUIParent_PlayerNameHook; public static Action<Action<PlayerAvatarVisuals, int, Color>, PlayerAvatarVisuals, int, Color> <1>__PlayerAvatarVisuals_SetColorHook; public static Manipulator <2>__SetPlayerNameTransparency; } public const string PLUGIN_GUID = "zombieseatflesh7.ColoredNametags"; public const string PLUGIN_NAME = "Colored Nametags"; public const string PLUGIN_VERSION = "1.0.0"; internal static readonly ManualLogSource logger = Logger.CreateLogSource("Colored Nametags"); private static string RGBToHex(Color color) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0013: 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) int num = Mathf.RoundToInt(color.r * 255f); int num2 = Mathf.RoundToInt(color.g * 255f); int num3 = Mathf.RoundToInt(color.b * 255f); return num.ToString("X2") + num2.ToString("X2") + num3.ToString("X2"); } private static void WorldSpaceUIParent_PlayerNameHook(Action<WorldSpaceUIParent, PlayerAvatar> orig, WorldSpaceUIParent self, PlayerAvatar player) { orig(self, player); UpdatePlayerNametagColor(player); } private static void PlayerAvatarVisuals_SetColorHook(Action<PlayerAvatarVisuals, int, Color> orig, PlayerAvatarVisuals self, int _colorIndex, Color _setColor) { //IL_0004: Unknown result type (might be due to invalid IL or missing references) orig(self, _colorIndex, _setColor); UpdatePlayerNametagColor(self.playerAvatar); } private static void UpdatePlayerNametagColor(PlayerAvatar player) { //IL_001c: Unknown result type (might be due to invalid IL or missing references) //IL_0021: Unknown result type (might be due to invalid IL or missing references) //IL_0052: 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_0069: 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) //IL_007f: Unknown result type (might be due to invalid IL or missing references) //IL_0084: Unknown result type (might be due to invalid IL or missing references) //IL_0085: Unknown result type (might be due to invalid IL or missing references) if (!((Object)(object)player.worldSpaceUIPlayerName == (Object)null)) { Color color = player.playerAvatarVisuals.color; color.r += 0.666f; color.g += 0.666f; color.b += 0.666f; color *= 1f / Mathf.Max(new float[3] { color.r, color.g, color.b }); string text = RGBToHex(color); ((TMP_Text)player.worldSpaceUIPlayerName.text).text = "<color=#" + text + ">" + player.playerName; } } private void Awake() { //IL_0032: Unknown result type (might be due to invalid IL or missing references) //IL_0069: Unknown result type (might be due to invalid IL or missing references) //IL_00a0: 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_009a: Unknown result type (might be due to invalid IL or missing references) //IL_00a0: Expected O, but got Unknown new Hook((MethodBase)AccessTools.Method(typeof(WorldSpaceUIParent), "PlayerName", (Type[])null, (Type[])null), (Delegate)new Action<Action<WorldSpaceUIParent, PlayerAvatar>, WorldSpaceUIParent, PlayerAvatar>(WorldSpaceUIParent_PlayerNameHook)); new Hook((MethodBase)AccessTools.Method(typeof(PlayerAvatarVisuals), "SetColor", (Type[])null, (Type[])null), (Delegate)new Action<Action<PlayerAvatarVisuals, int, Color>, PlayerAvatarVisuals, int, Color>(PlayerAvatarVisuals_SetColorHook)); MethodInfo? method = typeof(WorldSpaceUIPlayerName).GetMethod("Update", BindingFlags.Instance | BindingFlags.NonPublic); object obj = <>O.<2>__SetPlayerNameTransparency; if (obj == null) { Manipulator val = SetPlayerNameTransparency; <>O.<2>__SetPlayerNameTransparency = val; obj = (object)val; } new ILHook((MethodBase)method, (Manipulator)obj); } private static void SetPlayerNameTransparency(ILContext il) { //IL_0002: 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) ILCursor val = new ILCursor(il).Goto(0, (MoveType)0, false); if (val.TryGotoNext(new Func<Instruction, bool>[2] { (Instruction i) => ILPatternMatchingExt.MatchLdcR4(i, 0.5f), (Instruction i) => ILPatternMatchingExt.MatchNewobj<Color>(i) })) { val.Remove(); val.Emit(OpCodes.Ldc_R4, 0.75f); } } } }