using System; 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.Threading; using System.Threading.Tasks; using Archipelago.MultiClient.Net; using Archipelago.MultiClient.Net.BounceFeatures.DeathLink; using Archipelago.MultiClient.Net.Enums; using Archipelago.MultiClient.Net.Helpers; using Archipelago.MultiClient.Net.MessageLog.Messages; using Archipelago.MultiClient.Net.MessageLog.Parts; using Archipelago.MultiClient.Net.Models; using ArchipelagoRandomizer.Features; using ArchipelagoRandomizer.Items; using ArchipelagoRandomizer.Items.ItemImpls; using ArchipelagoRandomizer.Locations; using BepInEx; using BepInEx.Configuration; using BepInEx.Logging; using Com.LuisPedroFonseca.ProCamera2D; using Cysharp.Threading.Tasks; using Dialogue; using HarmonyLib; using I2.Loc; using InControl; using Microsoft.CodeAnalysis; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using NineSolsAPI; using RCGFSM.Animation; using RCGFSM.Items; using RCGFSM.Map; using RCGFSM.PlayerAbility; using RCGFSM.PlayerAction; using RCGFSM.Variable; using RCGMaker.AddressableAssets; using RCGMaker.Core; using RCGMaker.Runtime; using TMPro; using UnityEngine; using UnityEngine.Events; using UnityEngine.UI; using _3_Script._0_RedCandleGamesUtilities.UICanvas.ActivateChecker; [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("ArchipelagoRandomizer")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyDescription("A Nine Sols mod for the Archipelago multi-game randomizer system")] [assembly: AssemblyFileVersion("0.5.5.0")] [assembly: AssemblyInformationalVersion("0.5.5+d2cd01a4aaa6bf3746e337eccab56ab3719ccda8")] [assembly: AssemblyProduct("ArchipelagoRandomizer")] [assembly: AssemblyTitle("ArchipelagoRandomizer")] [assembly: AssemblyVersion("0.5.5.0")] [module: RefSafetyRules(11)] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Embedded] internal sealed class RequiresLocationAttribute : Attribute { } [CompilerGenerated] [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] [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] [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 Archipelago.MultiClient.Net { [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, Inherited = false, AllowMultiple = false)] internal sealed class DataStoragePropertyAttribute : Attribute { public string? SessionVariable { get; } public Scope Scope { get; } public string Key { get; } public DataStoragePropertyAttribute(string sessionVariable, Scope scope, string key) { //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) SessionVariable = sessionVariable; Scope = scope; Key = key; } public DataStoragePropertyAttribute(string sessionVariable, string key) : this(sessionVariable, (Scope)0, key) { } } } namespace ArchipelagoRandomizer { [BepInDependency(/*Could not decode attribute arguments.*/)] [BepInPlugin("ArchipelagoRandomizer", "ArchipelagoRandomizer", "0.5.5")] public class APRandomizer : BaseUnityPlugin { public ConfigEntry ForceTrueEigongSetting; public ConfigEntry BossScalingSetting; public ConfigEntry ScaleDownEarlyBossesSetting; public ConfigEntry ScaleUpLateBossesSetting; private ConfigEntry DeathLinkSetting; public ConfigEntry FlowerlessDeathLinkSetting; public ConfigEntry ShowAPMessagesSetting; public ConfigEntry FilterAPMessagesByPlayerSetting; public ConfigEntry BatchSimultaneousMessagesSetting; private Harmony harmony; public static APRandomizer Instance; public static string SaveSlotsPath => Application.persistentDataPath; private void Awake() { //IL_02c0: Unknown result type (might be due to invalid IL or missing references) //IL_02fd: Unknown result type (might be due to invalid IL or missing references) Log.Init(((BaseUnityPlugin)this).Logger); RCGLifeCycle.DontDestroyForever(((Component)this).gameObject); Instance = this; harmony = Harmony.CreateAndPatchAll(typeof(APRandomizer).Assembly, (string)null); ForceTrueEigongSetting = ((BaseUnityPlugin)this).Config.Bind("", "Force True Eigong", false, "Set the true ending flag when you first enter New Kunlun Control Hub, so you can fight all 3 phases of True Eigong without having to do all the usual sidequests first.\n\nIf you toggle this setting after unlocking the New Kunlun Control Hub node, then the true ending flag will be toggled immediately."); ForceTrueEigongSetting.SettingChanged += delegate { //IL_0061: Unknown result type (might be due to invalid IL or missing references) Log.Info($"ForceTrueEigongSetting changed to {ForceTrueEigongSetting.Value}"); if (TeleportPoints.IsNodeUnlocked(TeleportPoints.TeleportPoint.NewKunlunControlHub)) { InGameConsole.Add($"Changing the true ending flag to {ForceTrueEigongSetting.Value} because the 'Force True Eigong' setting was changed."); ((ScriptableDataBool)SingletonBehaviour.Instance.allFlags.FlagDict["e78958a13315eb9418325caf25da9d4dScriptableDataBool"]).CurrentValue = ForceTrueEigongSetting.Value; } }; BossScalingSetting = ((BaseUnityPlugin)this).Config.Bind("Boss Scaling", "Boss Scaling", true, "Edit the health and damage values of (non-Eigong) Battle Memories bosses so they scale with the actual order you end up fighting them in the randomizer, instead of the vanilla game's expected order.\n\nFor example: If you fight Ji first, he'll have lower stats than vanilla. If you fight Yanlao last, he'll have higher stats than vanilla. Exact adjustments will be shown when you encounter the boss.\n\nSince Battle Memories stats are used as a guide, this setting ignores all bosses not included in the Battle Memories mode."); ScaleDownEarlyBossesSetting = ((BaseUnityPlugin)this).Config.Bind("Boss Scaling", "Scale Down Early Bosses", true, "Lowers the health and damage values of (non-Eigong) Battle Memories bosses that you encounter earlier than the intended vanilla order.\n\nWhen lowering a boss' stats, the result is a simple fraction of their vanilla stats based on encounter order. For example: If you fight Lady E (boss #5) as your 2nd boss, she'll have 2/5th of her vanilla stats.\n\nHas no effect unless the main 'Boss Scaling' setting is enabled."); ScaleUpLateBossesSetting = ((BaseUnityPlugin)this).Config.Bind("Boss Scaling", "Scale Up Late Bosses", true, "Raises the health and damage values of (non-Eigong) Battle Memories bosses that you encounter later than the intended vanilla order.\n\nWhen raising a boss' stats, the result is somewhere between their vanilla and Battle Memories stats based on encounter order. For example: If you fight Goumang (boss #2) as your 5th boss, her stats will be exactly halfway between her vanilla and Battle Memories stats.\n\nHas no effect unless the main 'Boss Scaling' setting is enabled."); DeathLinkSetting = ((BaseUnityPlugin)this).Config.Bind("Death Link", "Death Link", false, "When you die, everyone who enabled death link dies. Of course, the reverse is true too."); Log.Info($"applying initial DeathLink setting of {DeathLinkSetting.Value}"); DeathLinkManager.ApplyModSetting(DeathLinkSetting.Value); DeathLinkSetting.SettingChanged += delegate { Log.Info($"DeathLink setting changed to {DeathLinkSetting.Value}"); DeathLinkManager.ApplyModSetting(DeathLinkSetting.Value); }; FlowerlessDeathLinkSetting = ((BaseUnityPlugin)this).Config.Bind("Death Link", "Flowerless Death Link", true, "When you die from receiving a death link, no Tianhuo flower will be produced, and no jin or experience will be taken away.\n\nHas no effect on regular deaths."); ShowAPMessagesSetting = ((BaseUnityPlugin)this).Config.Bind("Message Display", "Show AP Messages", true, "Display all messages the Archipelago server sends to clients in both the main game window and the pause console. Turn this off if you find the AP messages too spammy, especially if they appear to be destabilizing the game.\n\nDropped messages can still be read in the BepInEx console window, or in any AP text client you have connected to the same slot."); FilterAPMessagesByPlayerSetting = ((BaseUnityPlugin)this).Config.Bind("Message Display", "Filter By Player", false, "Only display 'Player1 found Player2's Item' messsages in the main game window and pause console if you are one of those players. In larger multiworlds, this should hide the vast majority of AP messages not relevant to you, without disabling them completely.\n\nDropped messages can still be read in the BepInEx console window, or in any AP text client you have connected to the same slot."); BatchSimultaneousMessagesSetting = ((BaseUnityPlugin)this).Config.Bind("Message Display", "Batch Simultaneous Messages", true, "When receiving several messages within a fraction of a second, display only a single 'Received N messages' summary in the main window to prevent flooding the screen and lagging the game. All of the individual messages will still be added to the pause console."); Log.Info("trying to load Archipelago item and location IDs"); try { Assembly assembly = typeof(APRandomizer).GetTypeInfo().Assembly; using (StreamReader streamReader = new StreamReader(assembly.GetManifestResourceStream("ArchipelagoRandomizer.items.jsonc"))) { ItemNames.LoadArchipelagoIds(streamReader.ReadToEnd()); } using (StreamReader streamReader2 = new StreamReader(assembly.GetManifestResourceStream("ArchipelagoRandomizer.locations.jsonc"))) { LocationNames.LoadArchipelagoIds(streamReader2.ReadToEnd()); } Log.Info("loaded Archipelago item and location IDs"); } catch (Exception ex) { Log.Warning("id loading threw: " + ex.Message + " with stack:\n" + ex.StackTrace); if (ex.InnerException != null) { Log.Warning("id loading threw inner: " + ex.InnerException.Message + " with stack:\n" + ex.InnerException.StackTrace); } } Action obj = delegate { DebugTools.ShowDebugToolsPopup = !DebugTools.ShowDebugToolsPopup; }; KeyCode[] array = new KeyCode[3]; RuntimeHelpers.InitializeArray(array, (RuntimeFieldHandle)/*OpCode not supported: LdMemberToken*/); KeybindManager.Add((MonoBehaviour)(object)this, obj, new KeyboardShortcut((KeyCode)100, (KeyCode[])(object)array)); Action obj2 = delegate { for (int i = 0; i < 30; i++) { Log.Warning("x"); } }; KeyCode[] array2 = new KeyCode[3]; RuntimeHelpers.InitializeArray(array2, (RuntimeFieldHandle)/*OpCode not supported: LdMemberToken*/); KeybindManager.Add((MonoBehaviour)(object)this, obj2, new KeyboardShortcut((KeyCode)120, (KeyCode[])(object)array2)); ((BaseUnityPlugin)this).Logger.LogInfo((object)"Plugin ArchipelagoRandomizer is loaded!"); } private void OnDestroy() { Log.Info("APRandomizer::OnDestroy() called. Cleaning up AP server connection and Harmony patches."); ConnectionAndPopups.CleanupExistingAPServerConnection(); harmony.UnpatchSelf(); } private void Update() { ConnectionAndPopups.Update(); DebugTools.Update(); APServerAndSaveData.Update(); DeathLinkManager.Update(); } private void OnGUI() { ConnectionAndPopups.OnGUI(); DebugTools.OnGUI(); InGameConsole.OnGUI(); } } [HarmonyPatch] internal class BossScaling { private static Dictionary BossToVanillaOrder = new Dictionary { { "StealthGameMonster_SpearHorseMan", 1 }, { "StealthGameMonster_GouMang Variant", 2 }, { "StealthGameMonster_BossZombieSpear", 2 }, { "StealthGameMonster_BossZombieHammer", 2 }, { "Monster_GiantMechClaw", 3 }, { "StealthGameMonster_Boss_JieChuan", 4 }, { "StealthGameMonster_Boss_ButterFly Variant", 5 }, { "StealthGameMonster_伏羲_新", 6 }, { "StealthGameMonster_新女媧 Variant", 6 }, { "StealthGameMonster_Boss_Jee", 7 } }; private static Dictionary BossToDisplayName = new Dictionary { { "StealthGameMonster_SpearHorseMan", "Yingzhao" }, { "StealthGameMonster_GouMang Variant", "Goumang" }, { "StealthGameMonster_BossZombieSpear", "Goumang's Small Jiangshi" }, { "StealthGameMonster_BossZombieHammer", "Goumang's Big Jiangshi" }, { "Monster_GiantMechClaw", "Sky Rending Claw" }, { "StealthGameMonster_Boss_JieChuan", "Jiequan" }, { "StealthGameMonster_Boss_ButterFly Variant", "Lady Ethereal" }, { "StealthGameMonster_伏羲_新", "Fuxi" }, { "StealthGameMonster_新女媧 Variant", "Nuwa" }, { "StealthGameMonster_Boss_Jee", "Ji" } }; private static string BossScaling_EncounteredBossesListName = "BossesEncounteredInGame"; private static Dictionary BossToSaveDataName = new Dictionary { { "StealthGameMonster_SpearHorseMan", "Yingzhao" }, { "StealthGameMonster_GouMang Variant", "Goumang" }, { "StealthGameMonster_BossZombieSpear", "Goumang" }, { "StealthGameMonster_BossZombieHammer", "Goumang" }, { "Monster_GiantMechClaw", "Yanlao" }, { "StealthGameMonster_Boss_JieChuan", "Jiequan" }, { "StealthGameMonster_Boss_ButterFly Variant", "Lady Ethereal" }, { "StealthGameMonster_伏羲_新", "Fengs" }, { "StealthGameMonster_新女媧 Variant", "Fengs" }, { "StealthGameMonster_Boss_Jee", "Ji" } }; private static List AlreadyScaledBosses = new List(); private static Dictionary BossToAlreadyKilledFlag = new Dictionary { { "StealthGameMonster_GouMang Variant", "f5b26e3311ce4e84a961dc36a05e19b7ScriptableDataBool" }, { "StealthGameMonster_Boss_JieChuan", "9758240a82bf8472a884fe3123cd6a2cScriptableDataBool" } }; private static FieldRef BaseAttackValueRef => AccessTools.FieldRefAccess("BaseAttackValue"); private static FieldRef BaseHealthValueRef => AccessTools.FieldRefAccess("BaseHealthValue"); [HarmonyPrefix] [HarmonyPatch(typeof(MonsterBase), "Awake")] private static void MonsterBase_Awake(MonsterBase __instance) { string name = ((Object)__instance).name; if (PlayerGamePlayData.Instance.memoryMode.CurrentValue) { Log.Debug("BossScaling ignoring " + name + " because this is Battle Memories mode"); return; } if (!BossToVanillaOrder.ContainsKey(name)) { Log.Debug("BossScaling ignoring " + name + " because it's not in our boss list"); return; } if (name == "StealthGameMonster_Boss_JieChuan" && ((Object)SingletonBehaviour.Instance.gameLevel).name == "A5_S1") { Log.Info("BossScaling ignoring " + name + " because this is the unwinnable Jiequan 1 fight, not the 'real' Jiequan"); return; } if (BossToAlreadyKilledFlag.ContainsKey(name)) { GameFlagBase obj = SingletonBehaviour.Instance.allFlags.FlagDict[BossToAlreadyKilledFlag[name]]; GameFlagBase obj2 = ((obj is ScriptableDataBool) ? obj : null); if (obj2 != null && ((ScriptableDataBool)obj2).CurrentValue) { Log.Info("BossScaling ignoring " + name + " because they've already been killed"); return; } } if (APSaveManager.CurrentAPSaveData == null) { Log.Error("BossScaling aborting because APSession is null. If you're the developer doing hot reloading, this is normal."); return; } APSaveManager.CurrentAPSaveData.persistentModStringLists.TryGetValue(BossScaling_EncounteredBossesListName, out List value); bool flag = false; if (value == null) { value = new List(); flag = true; } string item = BossToSaveDataName[name]; if (!value.Contains(item)) { value.Add(item); flag = true; } int num = value.IndexOf(item) + 1; if (flag) { APSaveManager.CurrentAPSaveData.persistentModStringLists[BossScaling_EncounteredBossesListName] = value; APSaveManager.ScheduleWriteToCurrentSaveFile(); } if (!APRandomizer.Instance.BossScalingSetting.Value) { Log.Debug("BossScaling doing nothing because the 'Boss Scaling' mod setting is off."); return; } int num2 = BossToVanillaOrder[name]; if (num == num2) { InGameConsole.Add($"{BossToDisplayName.GetValueOrDefault(name)}'s health and damage have been left unchanged, since you encountered them as boss #{num} just like vanilla."); return; } float num3; float num4; if (num > num2) { if (!APRandomizer.Instance.ScaleUpLateBossesSetting.Value) { Log.Debug("BossScaling doing nothing because the 'Scale Up Late Bosses' mod setting is off."); return; } (num3, num4) = ScaleBetweenVanillaAndBattleMemories(__instance, num); } else { if (!APRandomizer.Instance.ScaleDownEarlyBossesSetting.Value) { Log.Debug("BossScaling doing nothing because the 'Scale Down Early Bosses' mod setting is off."); return; } (num3, num4) = ScaleBetweenZeroAndVanilla(__instance, num); } MonsterStat monsterStat = __instance.monsterStat; float num5 = BaseAttackValueRef.Invoke(monsterStat); float num6 = BaseHealthValueRef.Invoke(monsterStat); if (AlreadyScaledBosses.Contains(name)) { Log.Info("BossScaling skipping " + name + " because we already scaled it this session"); } else { Log.Info("BossScaling actually applying scaled stats to " + name); BaseAttackValueRef.Invoke(monsterStat) = num3; BaseHealthValueRef.Invoke(monsterStat) = num4; AlreadyScaledBosses.Add(name); } InGameConsole.Add(BossToDisplayName.GetValueOrDefault(name) + "'s " + $"health and damage have been set to {num4 / num6 * 100f}% and {num3 / num5 * 100f}% of their vanilla values\n" + $"because you're encountering them as boss #{num} instead of #{num2}"); } private static (float, float) ScaleBetweenVanillaAndBattleMemories(MonsterBase __instance, int actualOrder) { string name = ((Object)__instance).name; int num = BossToVanillaOrder[name]; MonsterStat monsterStat = __instance.monsterStat; float num2 = BaseAttackValueRef.Invoke(monsterStat); float num3 = BaseHealthValueRef.Invoke(monsterStat); float num4 = monsterStat.BossMemoryAttackScale * num2; float num5 = monsterStat.BossMemoryHealthScale * num3; float num6 = (num4 - num2) / (float)(8 - num); float num7 = num2 - num6 * (float)num; float num8 = (num5 - num3) / (float)(8 - num); float num9 = num3 - num8 * (float)num; float item = num6 * (float)actualOrder + num7; float item2 = num8 * (float)actualOrder + num9; return (item, item2); } private static (float, float) ScaleBetweenZeroAndVanilla(MonsterBase __instance, int actualOrder) { string name = ((Object)__instance).name; int num = BossToVanillaOrder[name]; MonsterStat monsterStat = __instance.monsterStat; float num2 = BaseAttackValueRef.Invoke(monsterStat); float num3 = BaseHealthValueRef.Invoke(monsterStat); float num4 = num2 / (float)num; float num5 = num3 / (float)num; float item = num4 * (float)actualOrder; float item2 = num5 * (float)actualOrder; return (item, item2); } } [HarmonyPatch] public class DeathLinkManager { [Serializable] [CompilerGenerated] private sealed class <>c { public static readonly <>c <>9 = new <>c(); public static DeathLinkReceivedHandler <>9__8_0; internal void b__8_0(DeathLink deathLinkObject) { lastDeathLinkObjectReceived = deathLinkObject; } } public static bool DeathLinkSettingValue = false; private static DeathLinkService? service = null; private static bool manualDeathInProgress = false; private static DeathLink? lastDeathLinkObjectReceived = null; private static List deathMessages = new List { " became one with the Tao.", " wasn't smoking enough.", " could not parry death." }; private static Random prng = new Random(); public static void ApplyModSetting(bool enabled) { DeathLinkSettingValue = enabled; ConnectionAndPopups.OnSessionOpened -= CreateDLServiceForSession; if (ConnectionAndPopups.APSession == null) { ConnectionAndPopups.OnSessionOpened += CreateDLServiceForSession; } else { CreateDLServiceForSession(ConnectionAndPopups.APSession); } } private static void CreateDLServiceForSession(ArchipelagoSession _) { if (service == null) { CreateDeathLinkService(); } else { ApplyModSettingToService(service); } } private static void ApplyModSettingToService(DeathLinkService deathLinkService) { if (DeathLinkSettingValue) { deathLinkService.EnableDeathLink(); } else { deathLinkService.DisableDeathLink(); } } public static void CleanupExistingDeathLinkService() { service = null; } private static void CreateDeathLinkService() { //IL_0042: Unknown result type (might be due to invalid IL or missing references) //IL_0047: Unknown result type (might be due to invalid IL or missing references) //IL_004d: Expected O, but got Unknown if (service != null) { return; } if (ConnectionAndPopups.APSession == null) { Log.Error("EnableDeathLinkImplHelper unable to create death link service because APSession is null"); return; } service = DeathLinkProvider.CreateDeathLinkService(ConnectionAndPopups.APSession); DeathLinkService? obj = service; object obj2 = <>c.<>9__8_0; if (obj2 == null) { DeathLinkReceivedHandler val = delegate(DeathLink deathLinkObject) { lastDeathLinkObjectReceived = deathLinkObject; }; <>c.<>9__8_0 = val; obj2 = (object)val; } obj.OnDeathLinkReceived += (DeathLinkReceivedHandler)obj2; ApplyModSettingToService(service); } public static void Update() { if (lastDeathLinkObjectReceived != (DeathLink)null) { DeathLink? deathLinkObject = lastDeathLinkObjectReceived; lastDeathLinkObjectReceived = null; OnDeathLinkReceived(deathLinkObject); } } public static void OnDeathLinkReceived(DeathLink deathLinkObject) { Log.Info($"OnDeathLinkReceived() Timestamp={deathLinkObject.Timestamp}, Source={deathLinkObject.Source}, Cause={deathLinkObject.Cause}"); GameObject obj = GameObject.Find("GameCore(Clone)/RCG LifeCycle/UIManager/GameplayUICamera/Always Canvas/DialoguePlayer(KeepThisEnable)"); DialoguePlayer val = ((obj != null) ? obj.GetComponent() : null); if ((Object)(object)val != (Object)null && (Object)(object)AccessTools.FieldRefAccess("playingDialogueGraph").Invoke(val) != (Object)null) { InGameConsole.Add("Ignoring death link (" + deathLinkObject.Cause + ") because dying mid-dialogue can softlock."); return; } InGameConsole.Add(deathLinkObject.Cause); ActuallyKillThePlayer(); } private static void ActuallyKillThePlayer() { manualDeathInProgress = true; Player.i.health.ReceiveDOT_Damage(9999f); manualDeathInProgress = false; } [HarmonyPostfix] [HarmonyPatch(/*Could not decode attribute arguments.*/)] private static void Player_get_NeedDeathPenalty(Player __instance, ref bool __result) { if (manualDeathInProgress && __result && APRandomizer.Instance.FlowerlessDeathLinkSetting.Value) { Log.Info("Player_get_NeedDeathPenalty preventing the usual death penalty because the Flowerless setting is on"); __result = false; } } [HarmonyPrefix] [HarmonyPatch(typeof(GameLevel), "HandlePlayerKilled")] public static void GameLevel_HandlePlayerKilled(GameLevel __instance) { //IL_00ba: Unknown result type (might be due to invalid IL or missing references) //IL_00c4: Expected O, but got Unknown Log.Info("GameLevel.HandlePlayerKilled called in " + ((Object)__instance).name); if (manualDeathInProgress) { Log.Info("GameLevel.HandlePlayerKilled patch ignoring death because this is a death we received from another player"); return; } if (!DeathLinkSettingValue) { Log.Info("GameLevel.HandlePlayerKilled patch ignoring death since death_link is off"); return; } if (service == null) { Log.Error("Unable to send death to AP server because death link service is null"); return; } if (APSaveManager.CurrentAPSaveData == null) { Log.Error("Unable to send death to AP server because we don't have an established AP connection"); return; } Log.Info("GameLevel.HandlePlayerKilled detected a death, sending to AP server"); string slotName = APSaveManager.CurrentAPSaveData.apConnectionData.slotName; string text = slotName + deathMessages[prng.Next(0, deathMessages.Count)]; InGameConsole.Add("Because death link is enabled, sending this death to other players with the message: \"" + text + "\""); service.SendDeathLink(new DeathLink(slotName, text)); } } internal class DebugTools { public static bool ShowDebugToolsPopup = false; private static string DebugPopup_Item = ""; private static string DebugPopup_Count = ""; public static void Update() { if (ShowDebugToolsPopup) { Cursor.visible = true; } } public static void OnGUI() { ConnectionAndPopups.UpdateStyles(); if (ShowDebugToolsPopup) { DrawDebugToolsPopup(); } } private static void DrawDebugToolsPopup() { //IL_003f: 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_008e: Unknown result type (might be due to invalid IL or missing references) //IL_0098: Expected O, but got Unknown //IL_00aa: 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_00c6: Expected O, but got Unknown //IL_00c1: Unknown result type (might be due to invalid IL or missing references) float num = (float)Screen.width * 0.6f; float num2 = (float)Screen.height * 0.75f; Rect windowRect = new Rect(((float)Screen.width - num) / 2f, ((float)Screen.height - num2) / 2f, num, num2); GUILayout.Width(((Rect)(ref windowRect)).width * 0.6f); GUIStyle windowStyle = ConnectionAndPopups.windowStyle; GUIStyle labelStyle = ConnectionAndPopups.labelStyle; GUIStyle textFieldStyle = ConnectionAndPopups.textFieldStyle; GUIStyle buttonStyle = ConnectionAndPopups.buttonStyle; GUIStyle centeredLabelStyle = new GUIStyle(labelStyle); centeredLabelStyle.alignment = (TextAnchor)1; GUI.Window(11261728, windowRect, (WindowFunction)delegate { //IL_016d: Unknown result type (might be due to invalid IL or missing references) //IL_0177: Expected O, but got Unknown //IL_023d: Unknown result type (might be due to invalid IL or missing references) //IL_0242: Unknown result type (might be due to invalid IL or missing references) //IL_0248: Expected O, but got Unknown //IL_0282: Unknown result type (might be due to invalid IL or missing references) //IL_0289: Expected O, but got Unknown //IL_0385: Unknown result type (might be due to invalid IL or missing references) //IL_038b: Expected O, but got Unknown //IL_039c: Unknown result type (might be due to invalid IL or missing references) //IL_03a2: Expected O, but got Unknown //IL_06b6: Unknown result type (might be due to invalid IL or missing references) //IL_06bc: Expected O, but got Unknown GUILayout.Label("", centeredLabelStyle, Array.Empty()); GUILayout.Label("NPCs & Events", centeredLabelStyle, Array.Empty()); GUILayout.BeginHorizontal(Array.Empty()); if (GUILayout.Button("Unlock Jiequan 1 Fight", buttonStyle, Array.Empty())) { ToastManager.Toast((object)"unlocking Jiequan 1 Fight"); Jiequan1Fight.ActuallyTriggerJiequan1Fight(); } if (GUILayout.Button("Unlock Lady E Soulscape", buttonStyle, Array.Empty())) { ToastManager.Toast((object)"unlocking Lady E Soulscape"); LadyESoulscapeEntrance.ActuallyTriggerLadyESoulscape(); } GUILayout.EndHorizontal(); GUILayout.BeginHorizontal(Array.Empty()); if (GUILayout.Button("Move Chiyou into FSP", buttonStyle, Array.Empty())) { ShopUnlocks.ActuallyMoveChiyouToFSP(); } if (GUILayout.Button("Move Kuafu into FSP", buttonStyle, Array.Empty())) { ShopUnlocks.ActuallyMoveKuafuToFSP(); } if (GUILayout.Button("Unlock Kuafu's Extra Inventory", buttonStyle, Array.Empty())) { ShopUnlocks.ActuallyUnlockKuafuExtraInventory(); } GUILayout.EndHorizontal(); GUILayout.Label("", centeredLabelStyle, Array.Empty()); GUILayout.Label("Miscellaneous", centeredLabelStyle, Array.Empty()); GUILayout.BeginHorizontal(Array.Empty()); if (GUILayout.Button("Unlock Most Teleports", buttonStyle, Array.Empty())) { ToastManager.Toast((object)"unlocking most teleport points"); TeleportPoints.UnlockAllNonPrisonTeleportPoints(); } if (GUILayout.Button("Test Death Link", buttonStyle, Array.Empty())) { ToastManager.Toast((object)"triggering test death link"); DeathLinkManager.OnDeathLinkReceived(new DeathLink("death link test player", "death link test cause")); } if (GUILayout.Button("Give 99999 Jin", buttonStyle, Array.Empty())) { ToastManager.Toast((object)"giving 99999 jin"); SingletonBehaviour.Instance.playerGameData.AddGold(99999, (GoldSourceTag)4); } if (GUILayout.Button("Check 1 Unchecked Location", buttonStyle, Array.Empty())) { ToastManager.Toast((object)"triggering random unchecked location check"); long key = ConnectionAndPopups.APSession.Locations.AllMissingLocations[0]; LocationTriggers.CheckLocation(LocationNames.archipelagoIdToLocation[key]); } GUILayout.EndHorizontal(); GUILayout.BeginHorizontal(Array.Empty()); if (GUILayout.Button("Enable Weakened Prison State", buttonStyle, Array.Empty())) { ToastManager.Toast((object)"enabling weakened prison state"); PlayerAbilityScenarioModifyPack val = (PlayerAbilityScenarioModifyPack)SingletonBehaviour.Instance.allFlags.FlagDict["df6a9a9f7748f4baba6207afdf10ea31PlayerAbilityScenarioModifyPack"]; val.ApplyOverriding((IStatModifierOwner)val); } if (GUILayout.Button("Disable Weakened Prison State", buttonStyle, Array.Empty())) { ToastManager.Toast((object)"disabling weakened prison state"); PlayerAbilityScenarioModifyPack val2 = (PlayerAbilityScenarioModifyPack)SingletonBehaviour.Instance.allFlags.FlagDict["df6a9a9f7748f4baba6207afdf10ea31PlayerAbilityScenarioModifyPack"]; val2.RevertApply((IStatModifierOwner)(object)val2); GameObject obj = GameObject.Find("A5_S2/[能力包] Player Ability Buff Debuff Override Pack FSM Variant/General FSM Object/--[States]/FSM/[State] Apply/[Action] PlayerAbilityModifyPackApplyAction"); PlayerAbilityModifyPackApplyAction val3 = ((obj != null) ? obj.GetComponent() : null); if ((Object)(object)val3 != (Object)null) { val2.RevertApply((IStatModifierOwner)(object)val3); } } if (GUILayout.Button("Toggle Hat", buttonStyle, Array.Empty())) { ToastManager.Toast((object)"toggling hat"); Player i = Player.i; if (Object.op_Implicit((Object)(object)i)) { bool flag = AccessTools.FieldRefAccess("_hasHat").Invoke(i); i.SetHasHat(!flag); } } if (GUILayout.Button("Toggle Story Walk", buttonStyle, Array.Empty())) { ToastManager.Toast((object)"toggling story walk"); Player i2 = Player.i; if (i2 != null) { i2.SetStoryWalk(!i2.IsStoryWalk, 1f); } } GUILayout.EndHorizontal(); GUILayout.Label("", centeredLabelStyle, Array.Empty()); GUILayout.Label("Core Progression Items", centeredLabelStyle, Array.Empty()); GUIStyle val4 = new GUIStyle(labelStyle); val4.fixedWidth = 200f; GUIStyle val5 = new GUIStyle(buttonStyle); val5.fixedWidth = 50f; GUILayout.BeginHorizontal(Array.Empty()); GUILayout.Label("MysticNymphScoutMode", val4, Array.Empty()); if (GUILayout.Button("On", val5, Array.Empty())) { InMemoryInventory.UpdateItemCount(Item.MysticNymphScoutMode, 1); } if (GUILayout.Button("Off", val5, Array.Empty())) { InMemoryInventory.UpdateItemCount(Item.MysticNymphScoutMode, 0); } GUILayout.Label("TaiChiKick", val4, Array.Empty()); if (GUILayout.Button("On", val5, Array.Empty())) { InMemoryInventory.UpdateItemCount(Item.TaiChiKick, 1); } if (GUILayout.Button("Off", val5, Array.Empty())) { InMemoryInventory.UpdateItemCount(Item.TaiChiKick, 0); } GUILayout.EndHorizontal(); GUILayout.BeginHorizontal(Array.Empty()); GUILayout.Label("ChargedStrike", val4, Array.Empty()); if (GUILayout.Button("On", val5, Array.Empty())) { InMemoryInventory.UpdateItemCount(Item.ChargedStrike, 1); } if (GUILayout.Button("Off", val5, Array.Empty())) { InMemoryInventory.UpdateItemCount(Item.ChargedStrike, 0); } GUILayout.Label("AirDash", val4, Array.Empty()); if (GUILayout.Button("On", val5, Array.Empty())) { InMemoryInventory.UpdateItemCount(Item.AirDash, 1); } if (GUILayout.Button("Off", val5, Array.Empty())) { InMemoryInventory.UpdateItemCount(Item.AirDash, 0); } GUILayout.EndHorizontal(); GUILayout.BeginHorizontal(Array.Empty()); GUILayout.Label("UnboundedCounter", val4, Array.Empty()); if (GUILayout.Button("On", val5, Array.Empty())) { InMemoryInventory.UpdateItemCount(Item.UnboundedCounter, 1); } if (GUILayout.Button("Off", val5, Array.Empty())) { InMemoryInventory.UpdateItemCount(Item.UnboundedCounter, 0); } GUILayout.Label("CloudLeap", val4, Array.Empty()); if (GUILayout.Button("On", val5, Array.Empty())) { InMemoryInventory.UpdateItemCount(Item.CloudLeap, 1); } if (GUILayout.Button("Off", val5, Array.Empty())) { InMemoryInventory.UpdateItemCount(Item.CloudLeap, 0); } GUILayout.EndHorizontal(); GUILayout.BeginHorizontal(Array.Empty()); GUILayout.Label("SuperMutantBuster", val4, Array.Empty()); if (GUILayout.Button("On", val5, Array.Empty())) { InMemoryInventory.UpdateItemCount(Item.SuperMutantBuster, 1); } if (GUILayout.Button("Off", val5, Array.Empty())) { InMemoryInventory.UpdateItemCount(Item.SuperMutantBuster, 0); } GUILayout.Label("Wall Climb", val4, Array.Empty()); if (GUILayout.Button("On", val5, Array.Empty())) { InMemoryInventory.UpdateItemCount(Item.WallClimb, 1); } if (GUILayout.Button("Off", val5, Array.Empty())) { InMemoryInventory.UpdateItemCount(Item.WallClimb, 0); } GUILayout.EndHorizontal(); GUILayout.BeginHorizontal(Array.Empty()); GUILayout.Label("Grapple", val4, Array.Empty()); if (GUILayout.Button("On", val5, Array.Empty())) { InMemoryInventory.UpdateItemCount(Item.Grapple, 1); } if (GUILayout.Button("Off", val5, Array.Empty())) { InMemoryInventory.UpdateItemCount(Item.Grapple, 0); } GUILayout.Label("Ledge Grab", val4, Array.Empty()); if (GUILayout.Button("On", val5, Array.Empty())) { InMemoryInventory.UpdateItemCount(Item.LedgeGrab, 1); } if (GUILayout.Button("Off", val5, Array.Empty())) { InMemoryInventory.UpdateItemCount(Item.LedgeGrab, 0); } GUILayout.EndHorizontal(); GUIStyle val6 = new GUIStyle(buttonStyle); val6.fixedWidth = 80f; GUILayout.Label("", centeredLabelStyle, Array.Empty()); GUILayout.Label("Arbitrary Item Update (using the mod's Item enum, not the AP names)", centeredLabelStyle, Array.Empty()); GUILayout.BeginHorizontal(Array.Empty()); DebugPopup_Item = GUILayout.TextField(DebugPopup_Item, textFieldStyle, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(((Rect)(ref windowRect)).width * 0.3f) }); DebugPopup_Count = GUILayout.TextField(DebugPopup_Count, textFieldStyle, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(((Rect)(ref windowRect)).width * 0.1f) }); if (GUILayout.Button("Update", val6, Array.Empty())) { InMemoryInventory.UpdateItemCount(Enum.Parse(DebugPopup_Item), int.Parse(DebugPopup_Count)); } GUILayout.EndHorizontal(); }, "Archipelago Randomizer Debug Tools (Ctrl+Alt+Shift+D to show/hide)", windowStyle); } } [HarmonyPatch] internal class ForcedPurchases { private static long LogicDifficulty = 1L; private static List DarkSteelPurchases = new List(6) { Location.SHOP_KUAFU_DARK_STEEL_1, Location.SHOP_KUAFU_DARK_STEEL_2, Location.SHOP_KUAFU_DARK_STEEL_3, Location.SHOP_KUAFU_EXTRA_DARK_STEEL_1, Location.SHOP_KUAFU_EXTRA_DARK_STEEL_2, Location.SHOP_KUAFU_EXTRA_DARK_STEEL_3 }; private static List HerbCatalystPurchases = new List(8) { Location.SHOP_KUAFU_HERB_CATALYST_1, Location.SHOP_KUAFU_HERB_CATALYST_2, Location.SHOP_KUAFU_HERB_CATALYST_3, Location.SHOP_KUAFU_HERB_CATALYST_4, Location.SHOP_KUAFU_HERB_CATALYST_5, Location.SHOP_KUAFU_HERB_CATALYST_6, Location.SHOP_KUAFU_HERB_CATALYST_7, Location.SHOP_KUAFU_HERB_CATALYST_8 }; public static void ApplySlotData(long? logicDifficulty) { LogicDifficulty = logicDifficulty.GetValueOrDefault(); } private static bool ShouldBlock_ShopRandoOff(MerchandiseData __instance) { //IL_0089: Unknown result type (might be due to invalid IL or missing references) //IL_008f: Expected O, but got Unknown if (LogicDifficulty == 0L) { return false; } List requireMaterialEntriesToBuy = __instance.requireMaterialEntriesToBuy; if (requireMaterialEntriesToBuy.Count != 1) { return false; } MaterialRequirementEntry val = requireMaterialEntriesToBuy[0]; if (((val != null) ? val.item.Title : null) != "Dark Steel") { return false; } bool isAcquired = ((GameFlagDescriptable)Player.i.mainAbilities.ChargedAttackAbility).IsAcquired; if (isAcquired) { return false; } if (((Object)__instance).name == "Merchandise_2_1_貫穿箭LV2") { return false; } PlayerWeaponData val2 = (PlayerWeaponData)SingletonBehaviour.Instance.allFlags.FlagDict["2f7009a00edd57c4fa4332ffcd15396aPlayerWeaponData"]; if (((GameFlagDescriptable)val2).IsAcquired) { return false; } int remainingDarkSteelCount = GetRemainingDarkSteelCount(); if (remainingDarkSteelCount > 1) { return false; } Log.Info($"ShouldBlock_ShopRandoOff: LogicDifficulty={LogicDifficulty}, entry.item.Title={val.item.Title}, csAcquired={isAcquired}, __instance.name={((Object)__instance).name}, cloudPiercerS.IsAcquired={((GameFlagDescriptable)val2).IsAcquired}, darkSteelCount={remainingDarkSteelCount}"); return true; } public static bool IsDarkSteelPurchase(MerchandiseData __instance) { List requireMaterialEntriesToBuy = __instance.requireMaterialEntriesToBuy; if (requireMaterialEntriesToBuy.Count != 1) { return false; } MaterialRequirementEntry obj = requireMaterialEntriesToBuy[0]; return ((obj != null) ? obj.item.Title : null) == "Dark Steel"; } public static bool IsHerbCatalystPurchase(MerchandiseData __instance) { List requireMaterialEntriesToBuy = __instance.requireMaterialEntriesToBuy; if (requireMaterialEntriesToBuy.Count != 1) { return false; } MaterialRequirementEntry obj = requireMaterialEntriesToBuy[0]; return ((obj != null) ? obj.item.Title : null) == "Herb Catalyst"; } public static int GetRemainingDarkSteelCount() { //IL_001c: Unknown result type (might be due to invalid IL or missing references) return ((FlagField)(object)((ItemData)((AbstractGameFlagCollection)SingletonBehaviour.Instance.allItemCollections[2]).rawCollection[13]).ownNum).CurrentValue; } public static int GetRemainingHerbCatalystCount() { //IL_001c: Unknown result type (might be due to invalid IL or missing references) return ((FlagField)(object)((ItemData)((AbstractGameFlagCollection)SingletonBehaviour.Instance.allItemCollections[2]).rawCollection[14]).ownNum).CurrentValue; } private static SerializableItemInfo[]? GetScoutsForDarkSteelPurchases() { Dictionary scouts = APSaveManager.CurrentAPSaveData?.scoutedLocations; if (scouts == null) { return null; } return DarkSteelPurchases.Select((Location location) => scouts[location]).ToArray(); } private static SerializableItemInfo[]? GetScoutsForHerbCatalystPurchases() { Dictionary scouts = APSaveManager.CurrentAPSaveData?.scoutedLocations; if (scouts == null) { return null; } return HerbCatalystPurchases.Select((Location location) => scouts[location]).ToArray(); } public static string[]? ShouldBlock_ShopRandoOn(MerchandiseData __instance) { //IL_0123: Unknown result type (might be due to invalid IL or missing references) if (!ShopRando.merchDataNameToLocation.TryGetValue(((Object)__instance).name, out var thisLocation)) { return null; } bool flag = IsDarkSteelPurchase(__instance); bool flag2 = IsHerbCatalystPurchase(__instance); if (!flag && !flag2) { return null; } int valueOrDefault = InMemoryInventory.ApInventory.GetValueOrDefault(flag ? Item.DarkSteel : Item.HerbCatalyst, 0); IEnumerable source = from scout in (flag ? GetScoutsForDarkSteelPurchases() : GetScoutsForHerbCatalystPurchases()).Take(valueOrDefault).Where(delegate(SerializableItemInfo scout) { Location location = LocationNames.archipelagoIdToLocation[((MinimalSerializableItemInfo)scout).LocationId]; return APSaveManager.CurrentAPSaveData?.locationsChecked?.GetValueOrDefault(location.ToString(), defaultValue: false) != true; }) where ((Enum)((MinimalSerializableItemInfo)scout).Flags).HasFlag((Enum)(object)(ItemFlags)1) select scout; int num = source.Count(); if (num == 0) { return null; } int num2 = (flag ? GetRemainingDarkSteelCount() : GetRemainingHerbCatalystCount()); if (num < num2) { return null; } SerializableItemInfo value = default(SerializableItemInfo); if (APSaveManager.CurrentAPSaveData?.scoutedLocations?.TryGetValue(thisLocation, out value) == true) { bool flag3 = ((Enum)((MinimalSerializableItemInfo)value).Flags).HasFlag((Enum)(object)(ItemFlags)1); int num3 = (flag ? DarkSteelPurchases : HerbCatalystPurchases).FindIndex((Location loc) => loc == thisLocation); Log.Info($"ShouldBlock_ShopRandoOn: thisLocation={thisLocation}, thisIndex={num3}, thisIsProgression={flag3}, apReceivedCount={valueOrDefault}, unboughtProgInLogicCount={num}, remainingMaterialCount={num2}"); string[] result = source.Select((SerializableItemInfo scout) => ShopRando.scoutInfoToShopTitle(scout)).ToArray(); if (!flag3) { return result; } if (num3 >= valueOrDefault) { return result; } } return null; } [HarmonyPostfix] [HarmonyPatch(typeof(MerchandiseData), "HasEnoughMaterial")] public static void MerchandiseData_HasEnoughMaterial(MerchandiseData __instance, ref bool __result) { if (ShopRando.RandomizeShops) { if (ShouldBlock_ShopRandoOn(__instance) != null) { Log.Info("MerchandiseData_HasEnoughMaterial patch blocking purchase of '" + ((Object)__instance).name + "' until more DS/HC items have been received"); __result = false; } } else if (ShouldBlock_ShopRandoOff(__instance)) { Log.Info("MerchandiseData_HasEnoughMaterial patch blocking purchase of '" + ((GameFlagDescriptable)__instance).Title + "' until Cloud Piercer S has been purchased"); __result = false; } } [HarmonyPostfix] [HarmonyPatch(/*Could not decode attribute arguments.*/)] private static void MerchandiseData_get_Description(MerchandiseData __instance, ref string __result) { if (!ShopRando.RandomizeShops && ShouldBlock_ShopRandoOff(__instance)) { __result = LoadingScreenTips.apRainbow + ": \nBecause you're playing on medium or higher logic difficulty, you don't have Charged Strike yet, and you only have one Dark Steel available right now, you must spend your last Dark Steel on Cloud Piercer S. \n\n" + __result; } } } [HarmonyPatch] internal class InGameConsole { public static List consoleMessages = new List(); private static readonly int backlogLimit = 1000; private static bool truncatingBacklog = false; private const int SHORT_DELAY_MS = 100; private const int LONG_DELAY_MS = 1000; private static int currentDelayTime = 100; private const int MAX_TOASTS_BEFORE_HIDING = 5; private static Task? displayToastsTask = null; public static ConcurrentStack pendingToasts = new ConcurrentStack(); public static GUIStyle? windowStyle = null; public static GUIStyle? labelStyle = null; public static GUIStyle? textFieldStyle = null; public static GUIStyle? buttonStyle = null; public static GUIStyle? backlogStyle = null; public static Texture2D? grayBgColorTex = null; public static Texture2D? blackBgColorTex = null; public static bool drewConsoleInLastOnGUICall = false; private static string ConsoleInput = ""; private static Vector2? scrollPos = null; public static void Add(string message, bool forceImmediateToast = false) { consoleMessages.Add(message); while (consoleMessages.Count > backlogLimit) { consoleMessages.RemoveAt(0); truncatingBacklog = true; } if (forceImmediateToast) { ToastManager.Toast((object)message); } else { ScheduleToast(message); } } private static void ScheduleToast(string message) { pendingToasts.Push(message); if (displayToastsTask == null) { StartNewToastTask(); } } private static void StartNewToastTask() { displayToastsTask = Task.Delay(currentDelayTime).ContinueWith(delegate { DisplayToasts(); }, TaskScheduler.Default); } private static void DisplayToasts() { if (pendingToasts.Count > 5) { if (APRandomizer.Instance.BatchSimultaneousMessagesSetting.Value) { int count = pendingToasts.Count; pendingToasts.Clear(); ToastManager.Toast((object)string.Format("Received {0} messages within {1}. Pause to read them.", count, (currentDelayTime == 100) ? "100 ms" : "1 second")); } else { string result; while (pendingToasts.TryPop(out result)) { ToastManager.Toast((object)result); } } currentDelayTime = 1000; StartNewToastTask(); } else { string result2; while (pendingToasts.TryPop(out result2)) { ToastManager.Toast((object)result2); } currentDelayTime = 100; displayToastsTask = null; } } public static void UpdateStyles() { //IL_0030: Unknown result type (might be due to invalid IL or missing references) //IL_003a: Expected O, but got Unknown //IL_003f: Unknown result type (might be due to invalid IL or missing references) //IL_0049: Expected O, but got Unknown //IL_0064: 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_00f0: Expected O, but got Unknown //IL_00fa: Unknown result type (might be due to invalid IL or missing references) //IL_0104: Expected O, but got Unknown //IL_010e: Unknown result type (might be due to invalid IL or missing references) //IL_0118: Expected O, but got Unknown //IL_0122: Unknown result type (might be due to invalid IL or missing references) //IL_012c: Expected O, but got Unknown //IL_0131: Unknown result type (might be due to invalid IL or missing references) //IL_013b: Expected O, but got Unknown //IL_0156: Unknown result type (might be due to invalid IL or missing references) if (windowStyle == null || labelStyle == null || textFieldStyle == null || buttonStyle == null || backlogStyle == null) { windowStyle = new GUIStyle(GUI.skin.window); grayBgColorTex = new Texture2D(1, 1, (TextureFormat)20, false); grayBgColorTex.SetPixel(0, 0, new Color(0.3f, 0.3f, 0.3f, 1f)); grayBgColorTex.Apply(); windowStyle.normal.background = grayBgColorTex; windowStyle.onActive.background = grayBgColorTex; windowStyle.onFocused.background = grayBgColorTex; windowStyle.onHover.background = grayBgColorTex; windowStyle.onNormal.background = grayBgColorTex; labelStyle = new GUIStyle(GUI.skin.label); textFieldStyle = new GUIStyle(GUI.skin.textField); buttonStyle = new GUIStyle(GUI.skin.button); backlogStyle = new GUIStyle(GUI.skin.scrollView); blackBgColorTex = new Texture2D(1, 1, (TextureFormat)20, false); blackBgColorTex.SetPixel(0, 0, new Color(0f, 0f, 0f, 1f)); blackBgColorTex.Apply(); backlogStyle.normal.background = blackBgColorTex; backlogStyle.onActive.background = blackBgColorTex; backlogStyle.onFocused.background = blackBgColorTex; backlogStyle.onHover.background = blackBgColorTex; backlogStyle.onNormal.background = blackBgColorTex; } float num = Mathf.Min((float)Screen.width / 1920f, (float)Screen.height / 1080f); int fontSize = Mathf.RoundToInt(24f * num); windowStyle.fontSize = fontSize; labelStyle.fontSize = fontSize; textFieldStyle.fontSize = fontSize; buttonStyle.fontSize = fontSize; } public static void OnGUI() { //IL_002e: 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_003b: Unknown result type (might be due to invalid IL or missing references) //IL_003d: Invalid comparison between Unknown and I4 //IL_003f: Unknown result type (might be due to invalid IL or missing references) //IL_0041: Invalid comparison between Unknown and I4 if (SingletonBehaviour.IsAvailable()) { UIRootPanel pausePanelUI = SingletonBehaviour.Instance.PausePanelUI; GameObject gameObject = ((Component)((Component)pausePanelUI).gameObject.transform.Find("Pause Menu")).gameObject; UIPanelState state = ((RCGUIPanel)pausePanelUI).state; if (gameObject.activeSelf && ((int)state == 3 || (int)state == 1)) { DrawInGameConsole(!drewConsoleInLastOnGUICall); drewConsoleInLastOnGUICall = true; } else { drewConsoleInLastOnGUICall = false; } } } private static void DrawInGameConsole(bool resetScrollPosition) { //IL_0044: 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_0080: 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) //IL_00c9: Unknown result type (might be due to invalid IL or missing references) //IL_00d9: Expected O, but got Unknown //IL_00d4: Unknown result type (might be due to invalid IL or missing references) UpdateStyles(); float num = (float)Screen.width * 0.5f; float num2 = (float)Screen.height * 0.63f; Rect windowRect = new Rect(((float)Screen.width - num) * 0.95f, ((float)Screen.height - num2) * 0.6f, num, num2); float scrollPanelHeight = ((Rect)(ref windowRect)).height * 0.87f; if (!scrollPos.HasValue || resetScrollPosition) { scrollPos = new Vector2(0f, float.MaxValue); } string text = "Archipelago Console"; if (truncatingBacklog) { text += $" (last {backlogLimit} messages)"; } GUI.Window(11261729, windowRect, (WindowFunction)delegate { //IL_001e: 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_0098: Unknown result type (might be due to invalid IL or missing references) //IL_009e: Invalid comparison between Unknown and I4 //IL_00a5: Unknown result type (might be due to invalid IL or missing references) //IL_00af: Invalid comparison between Unknown and I4 //IL_00b6: Unknown result type (might be due to invalid IL or missing references) //IL_00bd: Invalid comparison between Unknown and I4 GUILayout.BeginVertical((GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Height(scrollPanelHeight) }); scrollPos = GUILayout.BeginScrollView(scrollPos.Value, backlogStyle); foreach (string consoleMessage in consoleMessages) { GUILayout.Label(consoleMessage, Array.Empty()); } GUILayout.EndScrollView(); GUILayout.EndVertical(); GUILayout.BeginHorizontal(Array.Empty()); if (GUI.GetNameOfFocusedControl() == "APCommandEntry" && (int)Event.current.type == 4 && ((int)Event.current.keyCode == 271 || (int)Event.current.keyCode == 13)) { ExecuteAPCommand(); } GUI.SetNextControlName("APCommandEntry"); ConsoleInput = GUILayout.TextField(ConsoleInput, textFieldStyle, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(((Rect)(ref windowRect)).width * 0.97f) }); GUILayout.EndHorizontal(); }, text, windowStyle); } private static void ExecuteAPCommand() { string text = ConsoleInput; if (text == "") { return; } if (ConnectionAndPopups.APSession == null) { Add("Cannot send AP message '" + text + "' without a connection to the AP server"); return; } Task.Run(delegate { if (!Task.Run(delegate { ConnectionAndPopups.APSession.Say(text); }).Wait(TimeSpan.FromSeconds(2.0))) { Add("AP server timed out when we tried to send the message '" + text + "'. Did the connection go down?"); } ConsoleInput = ""; }); } } [HarmonyPatch] internal class JadeCosts { public static Dictionary JadeEnglishTitleToSaveFlag = new Dictionary { { "Immovable Jade", "b8fd8e42229824b788bc222b837382f2JadeData" }, { "Harness Force Jade", "a0a2cb6d037ee4d80a74fd447a21682eJadeData" }, { "Focus Jade", "36eb7e7b95e91467191b8f24dbbb5a3eJadeData" }, { "Swift Descent Jade", "1e635338961c24feb93798c36c07f128JadeData" }, { "Medical Jade", "8417398823dca444b924aa9e49e82385JadeData" }, { "Quick Dose Jade", "316728bf6fa814c8085a4ce094c6cabbJadeData" }, { "Steely Jade", "28837290da6d24917ad6c99213d99d3dJadeData" }, { "Stasis Jade", "1e983ace0eb874a3a883c5f1f50e2926JadeData" }, { "Mob Quell Jade - Yin", "45a17198c6bff4c42989f3e2d9cb583bJadeData" }, { "Mob Quell Jade - Yang", "8ff52186b5d2849f6930bd5bf5d86b8aJadeData" }, { "Bearing Jade", "fce2186e0ae684bde9548905d5ed5533JadeData" }, { "Divine Hand Jade", "ef792d1867d1a4a9c8ec6cd721ee5cb3JadeData" }, { "Iron Skin Jade", "ff5f58b8404514c11b7ec4166b294349JadeData" }, { "Pauper Jade", "562375e7a68ec42b28f3bdd5f45d7b72JadeData" }, { "Swift Blade Jade", "b4c7da472cfba425ba5d0b0309dc4f17JadeData" }, { "Last Stand Jade", "3411e0d523aec41f9be4e24ff81b6293JadeData" }, { "Recovery Jade", "e6f162e19282346db96145ee80b5ccc1JadeData" }, { "Breather Jade", "3ddbef7a7a579497b82fe3712177c089JadeData" }, { "Hedgehog Jade", "3c8fd0425b80a405a8fb9623094fcafcJadeData" }, { "Ricochet Jade", "dbda764ac569f4d6b871fb6c82f11adeJadeData" }, { "Revival Jade", "987349e8a21844d28a86853bb0e5de09JadeData" }, { "Soul Reaper Jade", "468a3373787c2443794e57f101b5f794JadeData" }, { "Health Thief Jade", "1796f5882076b4c7c859bc4b0747d8bbJadeData" }, { "Qi Blade Jade", "dfa6bbf26dfef4032a5287a7d9b27881JadeData" }, { "Qi Swipe Jade", "111a1eb49b6d0476488eba696f991e19JadeData" }, { "Reciprocation Jade", "589b90f2463944b95aeb6821385b3be6JadeData" }, { "Cultivation Jade", "cfcd9f0d330344e628e7d8742955c172JadeData" }, { "Avarice Jade", "88263fdff21bc8b4da3977c47ab02f03JadeData" }, { "Qi Thief Jade", null }, { "Killing Blow Jade", null } }; private static Dictionary JadeSaveFlagToVanillaCost = new Dictionary(); public static Dictionary JadeSaveFlagToSlotDataCost = new Dictionary(); public static void ApplySlotData(object? jadeCosts) { JadeSaveFlagToSlotDataCost = new Dictionary(); if (jadeCosts is string && (string)jadeCosts == "vanilla") { return; } JObject val = (JObject)((jadeCosts is JObject) ? jadeCosts : null); if (val == null) { Log.Error("JadeCosts::ApplySlotData aborting because jadeCosts was neither 'vanilla' nor a JObject"); return; } foreach (var (text2, val3) in val) { if (JadeEnglishTitleToSaveFlag.ContainsKey(text2)) { string text3 = JadeEnglishTitleToSaveFlag[text2]; if (text3 != null) { JadeSaveFlagToSlotDataCost[text3] = (long)(val3 ?? JToken.op_Implicit(0)); } } else { Log.Error("Unrecognized jade in slot data: " + text2); } } } [HarmonyPrefix] [HarmonyPatch(typeof(GameLevel), "Awake")] private static void GameLevel_Awake(GameLevel __instance) { try { bool flag = JadeSaveFlagToSlotDataCost.Count == 0; if (PlayerGamePlayData.Instance.memoryMode.CurrentValue) { flag = true; } JadeDataCollection jadeDataColleciton = Player.i.mainAbilities.jadeDataColleciton; List gameFlagDataList = ((GameFlagBaseCollection)(object)jadeDataColleciton).gameFlagDataList; if (JadeSaveFlagToVanillaCost.Count == 0) { foreach (JadeData item in gameFlagDataList) { JadeSaveFlagToVanillaCost[((GameFlagBase)item).FinalSaveID] = item.Cost; } } int num = 0; foreach (JadeData item2 in gameFlagDataList) { string finalSaveID = ((GameFlagBase)item2).FinalSaveID; if (!JadeSaveFlagToVanillaCost.ContainsKey(finalSaveID)) { Log.Error("jade cost application failed for " + ((GameFlagDescriptable)item2).Title + " / " + finalSaveID + ", somehow it was missing from JadeSaveFlagToVanillaCost"); } else if (!flag && !JadeSaveFlagToSlotDataCost.ContainsKey(finalSaveID)) { Log.Error("jade cost application failed for " + ((GameFlagDescriptable)item2).Title + " / " + finalSaveID + ", somehow it was missing from JadeSaveFlagToSlotDataCost"); } else { int num2 = (int)(flag ? JadeSaveFlagToVanillaCost[finalSaveID] : JadeSaveFlagToSlotDataCost[finalSaveID]); if (item2.Cost != num2) { item2.Cost = num2; AccessTools.FieldRefAccess>("EquipEffectModifierEntries").Invoke(item2)[0].value = num2; num++; } } } float value = ((AbstractStatData)jadeDataColleciton.PlayerCurrentJadePowerStat).Value; AccessTools.Method(typeof(JadeDataCollection), "InitCalculateCurrentJadePowerUsage", Array.Empty(), (Type[])null).Invoke(jadeDataColleciton, Array.Empty()); float value2 = ((AbstractStatData)jadeDataColleciton.PlayerCurrentJadePowerStat).Value; if (num == 0) { if (flag) { Log.Info("JadeCosts::GameLevel_Awake did nothing because all jades were already set to their vanilla costs"); } else { Log.Info("JadeCosts::GameLevel_Awake did nothing because all jades were already set to this slot's custom jade costs"); } } else if (flag) { Log.Info($"JadeCosts::GameLevel_Awake reset {num} jades to their vanilla costs; cost in use changed from {value} to {value2}"); } else { Log.Info($"JadeCosts::GameLevel_Awake applied {num} custom jade costs; cost in use changed from {value} to {value2}"); } } catch (Exception ex) { Log.Error("JadeCosts::GameLevel_Awake threw: " + ex.Message + "\nwith stack:\n" + ex.StackTrace + "\nand InnerException: " + ex.InnerException?.Message + "\nwith stack:\n" + ex.InnerException?.StackTrace); } } } [HarmonyPatch] internal class LoadingScreenTips { public static string apRainbow = "ARCHIPELAGO RANDOMIZER"; private static List randomizerTips = new List(13) { "Press F1 to access settings for all your Nine Sols mods, including this randomizer.", "Reaching Eigong requires only Sol Seal items. There's no need to visit Tianhuo Research Institute.", "This randomizer depends on the TeleportFromAnywhere mod because an important item may end up randomly placed in a \"dead end\" you can only escape by teleporting.", "Shennong will become sick only after you acquire your first poison item.", "The randomizer's \"logic\" assumes:\n- Jiequan requires Charged Strike\n- Lady Ethereal requires Air Dash\n- Ji requires Tai-Chi Kick\n- Eigong requires Air Dash or Cloud Leap", "There are 5 mutants who drop an item when permanently killed with Super Mutant Buster.\n2 in ED (Living Area), 2 in ED (Sanctum), and 1 in TRC.", "The Peach Blossom Village rescue can be done as soon as you find the Abandoned Mines Access Token. It's no longer tied to escaping Prison and being rescued by Chiyou.", "Since talking to Ji at Daybreak Tower is a location, this randomizer makes Ji one of the few NPCs who can talk to you after his own death.", "Fighting Jiequan for real at the top of the Factory Zone can be done either before or after the Prison sequence. This makes Jiequan the only NPC who can kill you after he dies.", "All \"Limitless Realm\" segments are disabled and skipped in this randomizer.", "If Apeman Facility (Monitoring) was not your first root node, then that node will be automatically unlocked when you enter AF(M), because the upper part of AF(M) is unreachable without it.", "The large spike ball in Grotto (East) will never land in Grotto (Entry) in this randomizer, since it would block critical paths if we let it.", "This randomizer doesn't touch the items that are only reachable after the \"Point of no Return\", or after giving Shennong all poisons. You're free to replay that content or ignore it." }; [HarmonyPostfix] [HarmonyPatch(/*Could not decode attribute arguments.*/)] private static void LoadingScreenTipDataCollection_get_FetchAcquiredTips(LoadingScreenTipDataCollection __instance, List __result) { if (__result == null) { Log.Error("LoadingScreenTipDataCollection_get_FetchAcquiredTips aborting because this tip collection is null"); return; } if (__result.Count <= 0) { Log.Error("LoadingScreenTipDataCollection_get_FetchAcquiredTips aborting because this tip collection is empty"); return; } LoadingScreenTipData item = __result[0]; __result.Clear(); foreach (string randomizerTip in randomizerTips) { _ = randomizerTip; __result.Add(item); } } [HarmonyPostfix] [HarmonyPatch(typeof(LoadingScreenPanel), "UpdateView")] private static void LoadingScreenPanel_UpdateView(LoadingScreenPanel __instance) { TextMeshProUGUI component = GameObject.Find("ApplicationCore(Clone) (RCGLifeCycle)/4 UIGroupManager/ApplicationUICam/[Canvas]LoadingScreenPanel/LoadingScreenPanel/TipPanel/PanelMask/DialoguePanel/Background/Outline/TitleText").GetComponent(); if (((TMP_Text)component).text != apRainbow) { ((TMP_Text)component).text = apRainbow; ((TMP_Text)component).enableWordWrapping = false; } if (!((OneAxisInputControl)__instance.nextActionData.Action).WasPressed && !((OneAxisInputControl)__instance.previousActionData.Action).WasPressed) { AccessTools.FieldRefAccess("currentIndex").Invoke(__instance) = Random.Range(0, randomizerTips.Count); } int num = AccessTools.FieldRefAccess("currentIndex").Invoke(__instance); AccessTools.FieldRefAccess("step").Invoke(__instance).text = $"{num + 1}/{randomizerTips.Count}"; AccessTools.FieldRefAccess("tipText").Invoke(__instance).text = randomizerTips[num]; } } [HarmonyPatch] internal class PreventWeakenedPrisonState { private static bool ShouldPrevent; public static void ApplySlotData(long? rawPreventValue) { if (!rawPreventValue.HasValue) { ShouldPrevent = false; } else { ShouldPrevent = rawPreventValue == 1; } } [HarmonyPrefix] [HarmonyPatch(typeof(PlayerAbilityModifyPackApplyAction), "OnStateEnterImplement")] private static bool PlayerAbilityModifyPackApplyAction_OnStateEnterImplement(PlayerAbilityModifyPackApplyAction __instance) { if (!ShouldPrevent) { return true; } if (((Object)__instance.Pack).name == "A5 Jail Debuff Pack 虛弱監獄" && LocationTriggers.GetFullDisambiguatedPath(((Component)__instance).gameObject) == "A5_S2/[能力包] Player Ability Buff Debuff Override Pack FSM Variant/General FSM Object/--[States]/FSM/[State] Apply/[Action] PlayerAbilityModifyPackApplyAction") { Log.Info("PreventWeakenedPrisonState patch preventing Prison's PlayerAbilityModifyPackApplyAction from running"); InGameConsole.Add("Prevented weakened Prison state from being applied to Yi, since this slot was generated with prevent_weakened_prison_state: true"); return false; } return true; } } [HarmonyPatch] internal class ShopUnlocks { private enum ShopUnlockMethod { VanillaLikeLocations, SolSeals, UnlockItems } private static ShopUnlockMethod unlockMethod = ShopUnlockMethod.VanillaLikeLocations; private static long kuafuSeals = 0L; private static long chiyouSeals = 0L; private static long kuafuExtraSeals = 0L; private static string kuafuInFSPFlag = "e2ccc29dc8f187b45be6ce50e7f4174aScriptableDataBool"; private static string chiyouInFSPFlag = "bf49eb7e251013c4cb62eca6e586b465ScriptableDataBool"; public static string KuafuExtraInventory_ModSaveFlag = "UnlockedKuafuFSPShopExtraInventory"; private static GameObject? kuafuShopPanel = null; public static void ApplySlotData(Dictionary slotData) { if (!slotData.ContainsKey("shop_unlocks")) { unlockMethod = ShopUnlockMethod.VanillaLikeLocations; return; } long num = (long)slotData["shop_unlocks"]; switch (num) { case 0L: unlockMethod = ShopUnlockMethod.VanillaLikeLocations; break; case 1L: unlockMethod = ShopUnlockMethod.SolSeals; kuafuSeals = (long)slotData["kuafu_shop_unlock_sol_seals"]; chiyouSeals = (long)slotData["chiyou_shop_unlock_sol_seals"]; kuafuExtraSeals = (long)slotData["kuafu_extra_inventory_unlock_sol_seals"]; break; case 2L: unlockMethod = ShopUnlockMethod.UnlockItems; break; default: Log.Error($"ShopUnlocks::ApplySlotData aborting because shop_unlocks was {num}"); unlockMethod = ShopUnlockMethod.VanillaLikeLocations; break; } } [HarmonyPrefix] [HarmonyPatch(typeof(GameLevel), "Awake")] private static void GameLevel_Awake(GameLevel __instance) { try { if (unlockMethod == ShopUnlockMethod.SolSeals && (kuafuSeals <= 0 || chiyouSeals <= 0 || kuafuExtraSeals <= 0) && InMemoryInventory.GetSolSealsCount() <= 0) { Log.Info("ShopUnlocks::GameLevel_Awake handling zero seal unlocks"); if (kuafuSeals == 0L) { ActuallyMoveKuafuToFSP(); } if (chiyouSeals == 0L) { ActuallyMoveChiyouToFSP(); } if (kuafuExtraSeals == 0L) { ActuallyUnlockKuafuExtraInventory(); } } } catch (Exception ex) { Log.Error("ShopUnlocks::GameLevel_Awake threw: " + ex.Message + "\nwith stack:\n" + ex.StackTrace + "\nand InnerException: " + ex.InnerException?.Message + "\nwith stack:\n" + ex.InnerException?.StackTrace); } } public static void OnItemUpdate(Item item) { if (unlockMethod == ShopUnlockMethod.VanillaLikeLocations) { return; } if (unlockMethod == ShopUnlockMethod.SolSeals) { int solSealsCount = InMemoryInventory.GetSolSealsCount(); if (solSealsCount >= kuafuSeals) { ActuallyMoveKuafuToFSP(); } if (solSealsCount >= chiyouSeals) { ActuallyMoveChiyouToFSP(); } if (solSealsCount >= kuafuExtraSeals) { ActuallyUnlockKuafuExtraInventory(); } } else if (unlockMethod == ShopUnlockMethod.UnlockItems) { int num = (InMemoryInventory.ApInventory.ContainsKey(Item.ProgressiveShopUnlock) ? InMemoryInventory.ApInventory[Item.ProgressiveShopUnlock] : 0); if (num >= 1) { ActuallyMoveKuafuToFSP(); } if (num >= 2) { ActuallyMoveChiyouToFSP(); } if (num >= 3) { ActuallyUnlockKuafuExtraInventory(); } } } public static void OnLocationCheck(Location location) { if (unlockMethod == ShopUnlockMethod.VanillaLikeLocations) { switch (location) { case Location.RP_KUAFU_SANCTUM: ActuallyMoveKuafuToFSP(); break; case Location.FGH_CHIYOU_BRIDGE: ActuallyMoveChiyouToFSP(); ActuallyUnlockKuafuExtraInventory(); break; } } } public static void ActuallyMoveKuafuToFSP() { //IL_0019: Unknown result type (might be due to invalid IL or missing references) //IL_001f: Expected O, but got Unknown ScriptableDataBool val = (ScriptableDataBool)SingletonBehaviour.Instance.allFlags.FlagDict[kuafuInFSPFlag]; if (!val.CurrentValue) { InGameConsole.Add("Moving Kuafu into FSP and unlocking his shop"); val.CurrentValue = true; ShopRando.EnsureShopsScouted(); } } public static void ActuallyMoveChiyouToFSP() { //IL_0019: Unknown result type (might be due to invalid IL or missing references) //IL_001f: Expected O, but got Unknown ScriptableDataBool val = (ScriptableDataBool)SingletonBehaviour.Instance.allFlags.FlagDict[chiyouInFSPFlag]; if (!val.CurrentValue) { InGameConsole.Add("Moving Chiyou into FSP and unlocking his shop"); val.CurrentValue = true; ShopRando.EnsureShopsScouted(); } } public static void ActuallyUnlockKuafuExtraInventory() { if (APSaveManager.CurrentAPSaveData == null) { Log.Error("ShopUnlocks::ActuallyUnlockKuafuExtraInventory() aborting because there's no AP connection/save file to write to"); return; } APSaveManager.CurrentAPSaveData.otherPersistentModFlags.TryGetValue(KuafuExtraInventory_ModSaveFlag, out var value); if (!value) { InGameConsole.Add("Unlocking the extra inventory of Kuafu's FSP shop"); APSaveManager.CurrentAPSaveData.otherPersistentModFlags[KuafuExtraInventory_ModSaveFlag] = true; ShopRando.EnsureShopsScouted(); } } [HarmonyPrefix] [HarmonyPatch(/*Could not decode attribute arguments.*/)] private static bool FlagFieldBoolEntry_get_isValid(FlagFieldBoolEntry __instance, ref bool __result) { if (((Object)((FlagFieldEntry)(object)__instance).flagBase).name != "A6_S1_蚩尤救回羿") { return true; } if ((Object)(object)kuafuShopPanel == (Object)null) { kuafuShopPanel = GameObject.Find("AG_S2/Room/NPCs/議會演出相關Binding/NPC_KuaFoo_Base/NPC_KuaFoo_BaseFSM/FSM Animator/LogicRoot/NPC_KuaFoo/General FSM Object/Animator(FSM)/LogicRoot/NPC_Talking_Controller/Config/[Set] 中間層選項/Canvas/[中間層] UI Interact Options Root Panel/ConfirmProvider/UpgradeTable"); } GameObject? obj = kuafuShopPanel; if (obj != null && obj.activeSelf) { bool value = default(bool); if (APSaveManager.CurrentAPSaveData != null && APSaveManager.CurrentAPSaveData.otherPersistentModFlags.TryGetValue(KuafuExtraInventory_ModSaveFlag, out value) && value) { __result = true; return true; } __result = false; return false; } return true; } [HarmonyPrefix] [HarmonyPatch(typeof(SetVariableBoolAction), "OnStateEnterImplement")] private static bool SetVariableBoolAction_OnStateEnterImplement(SetVariableBoolAction __instance) { VariableBool targetFlag = __instance.targetFlag; object obj; if (targetFlag == null) { obj = null; } else { ScriptableDataBool boolFlag = targetFlag.boolFlag; obj = ((boolFlag != null) ? ((GameFlagBase)boolFlag).FinalSaveID : null); } if ((string?)obj == kuafuInFSPFlag) { string fullDisambiguatedPath = LocationTriggers.GetFullDisambiguatedPath(((Component)__instance).gameObject); if (fullDisambiguatedPath == "A2_S5_ BossHorseman_GameLevel/Room/Sleeppod FSM/[CutScene]BackFromSleeppod/--[States]/FSM/[State] PlayCutScene/[Action] Get_BossKey = true" || fullDisambiguatedPath == "VR_Kuafu/VR_Kuafu_Skin/BG_DREAM/VRMemory FSM/PlayerSensor FSM Prototype/--[States]/FSM/[State] Play End 表演結束/[Action] GetBossKey") { Log.Info("ShopUnlocks::SetVariableBoolAction_OnStateEnterImplement preventing Kuafu from being moved into FSP by " + fullDisambiguatedPath); return false; } } return true; } [HarmonyPostfix] [HarmonyPatch(/*Could not decode attribute arguments.*/)] private static void AbstractConditionComp_get_FinalResult(AbstractConditionComp __instance, ref bool __result) { if (unlockMethod == ShopUnlockMethod.VanillaLikeLocations) { return; } Dictionary dictionary = APSaveManager.CurrentAPSaveData?.locationsChecked; string key = Location.RP_KUAFU_SANCTUM.ToString(); bool flag = dictionary != null && dictionary.ContainsKey(key) && dictionary[key]; if (((Object)__instance).name == "[Condition] GetBossKeyAuthority") { if (__result == flag) { return; } string fullDisambiguatedPath = LocationTriggers.GetFullDisambiguatedPath(((Component)__instance).gameObject); if (fullDisambiguatedPath == "A2_S5_ BossHorseman_GameLevel/Room/Simple Binding Tool/Boss_SpearHorse_Logic/[Mech]BossDoorx6_FSM Variant/--[States]/FSM/[State] Init/[Action] HasGotBossAuthority Transition/[Condition] GetBossKeyAuthority" || fullDisambiguatedPath == "A2_S5_ BossHorseman_GameLevel/Room/Simple Binding Tool/Boss_SpearHorse_Logic/[Mech]BossDoorx6_FSM Variant/--[States]/FSM/[State] Closed/[Action] HasGotBossAuthority Transition/[Condition] GetBossKeyAuthority") { __result = flag; } if (fullDisambiguatedPath == "A2_S5_ BossHorseman_GameLevel/Room/Simple Binding Tool/Boss_SpearHorse_Logic/[Mech]BossDoorx6_FSM Variant (1)/--[States]/FSM/[State] Init/[Action] HasGotBossAuthority Transition/[Condition] GetBossKeyAuthority" || fullDisambiguatedPath == "A2_S5_ BossHorseman_GameLevel/Room/Simple Binding Tool/Boss_SpearHorse_Logic/[Mech]BossDoorx6_FSM Variant (1)/--[States]/FSM/[State] Closed/[Action] HasGotBossAuthority Transition/[Condition] GetBossKeyAuthority") { __result = flag; } } if (((Object)__instance).name == "[Condition] GetBossKeyAuthority == false") { if (__result == !flag) { return; } string fullDisambiguatedPath2 = LocationTriggers.GetFullDisambiguatedPath(((Component)__instance).gameObject); if (fullDisambiguatedPath2 == "A2_S5_ BossHorseman_GameLevel/Room/Simple Binding Tool/Boss_SpearHorse_Logic/[Mech]BossDoorx6_FSM Variant (1)/--[States]/FSM/[State] HoloOpened/[Action] Bosskilled But No Authority -> ClosedDoor/[Condition] GetBossKeyAuthority == false") { __result = !flag; } if (fullDisambiguatedPath2 == "A2_S5_ BossHorseman_GameLevel/Room/Simple Binding Tool/Boss_SpearHorse_Logic/[Mech]BossDoorx6_FSM Variant/--[States]/FSM/[State] HoloOpened/[Action] Bosskilled But No Authority -> ClosedDoor/[Condition] GetBossKeyAuthority == false") { __result = !flag; } } if (((Object)__instance).name == "[Condition] FlagBoolCondition" && __result != flag && LocationTriggers.GetFullDisambiguatedPath(((Component)__instance).gameObject) == "A2_S5_ BossHorseman_GameLevel/Room/Sleeppod FSM/EnterSleeppodFSM/--[States]/FSM/[State] Init/[Action] Entered Transition/[Condition] FlagBoolCondition") { Log.Info($"AbstractConditionComp_get_FinalResult changing the 'should Kuafu's vital sanctum be open' check, since the AP sanctum location ({flag}) doesn't match the Kuafu-in-FSP flag ({__result})"); __result = flag; } } } [HarmonyPatch] internal class SkillTree { private static long LogicDifficulty; public static void ApplySlotData(long? logicDifficulty) { LogicDifficulty = logicDifficulty.GetValueOrDefault(); } [HarmonyPrefix] [HarmonyPatch(typeof(GameLevel), "Awake")] private static void GameLevel_Awake(GameLevel __instance) { //IL_0022: Unknown result type (might be due to invalid IL or missing references) //IL_0028: Expected O, but got Unknown try { if (LogicDifficulty > 0) { SkillNodeData val = (SkillNodeData)SingletonBehaviour.Instance.allFlags.FlagDict["ae3f7be7afb294d2eba0f6f4d129c6d0SkillNodeData"]; if (!((GameFlagDescriptable)val).IsAcquired) { Log.Info($"SkillTree::GameLevel_Awake auto-unlocking Swift Runner since LogicDifficulty is {LogicDifficulty}"); ((GameFlagDescriptable)val).PlayerPicked(); InGameConsole.Add("The Swift Runner skill has been automatically unlocked\nbecause this slot was generated with a logic_difficulty of medium or higher"); } } } catch (Exception ex) { Log.Error("SkillTree::GameLevel_Awake threw: " + ex.Message + "\nwith stack:\n" + ex.StackTrace + "\nand InnerException: " + ex.InnerException?.Message + "\nwith stack:\n" + ex.InnerException?.StackTrace); } } } [HarmonyPatch] internal class TrackerMapPage { private static Dictionary GameLevelToTrackerPage = new Dictionary { { "A6_S3", "abandoned_mines" }, { "A3_S5_BossGouMang_GameLevel", "agrarian_hall" }, { "A10S5", "ancient_stone_pillar" }, { "A1_S3_GameLevel", "apeman_facility_depths" }, { "A1_S2_GameLevel", "apeman_facility_elevator" }, { "A1_S1_GameLevel", "apeman_facility_monitoring" }, { "A4_S3", "boundless_repository" }, { "AG_S1", "central_hall" }, { "A2_S6", "central_transport_hub" }, { "A7_S1", "cortex_center" }, { "A9_S2", "empyrean_district_living_area" }, { "A9_S1", "empyrean_district_passages" }, { "A9_S3", "empyrean_district_sanctum" }, { "A5_S1", "factory_great_hall" }, { "A5_S3", "factory_machine_room" }, { "A5_S4", "factory_production_area" }, { "A6_S1", "factory_underground" }, { "AG_S2", "four_seasons_pavilion" }, { "GameLevel", "galactic_dock_and_village" }, { "A3_S2", "greenhouse" }, { "A10_S3", "grotto_of_scriptures_east" }, { "A10_S1", "grotto_of_scriptures_entry" }, { "A10_S4", "grotto_of_scriptures_west" }, { "A4_S2", "inner_warehouse" }, { "A3_S1", "lake_yaochi_ruins" }, { "P2_R22_Savepoint_GameLevel", "nobility_hall" }, { "A4_S1", "outer_warehouse" }, { "A2_S1", "power_reservoir_central" }, { "A2_S2", "power_reservoir_east" }, { "A2_S3", "power_reservoir_west" }, { "A5_S2", "prison" }, { "A2_S5_ BossHorseman_GameLevel", "radiant_pagoda" }, { "A5_S5", "shengwu_hall" }, { "A9_S4", "sky_tower" }, { "A11_S1", "tiandao_research_center" }, { "A11_S2", "tianhuo_research_institute" }, { "A0_S7", "underground_cave" }, { "A3_S3", "water_and_oxygen_synthesis" }, { "A0_S6", "yangu_hall" }, { "A3_S7", "yinglong_canal" } }; [HarmonyPrefix] [HarmonyPatch(typeof(GameLevel), "Awake")] private static void GameLevel_Awake(GameLevel __instance) { try { string name = ((Object)__instance).name; string value; if (ConnectionAndPopups.APSession == null) { Log.Error("TrackerMapPage::GameLevel_Awake aborting because APSession is null"); } else if (GameLevelToTrackerPage.TryGetValue(name, out value)) { ArchipelagoSession aPSession = ConnectionAndPopups.APSession; string text = $"{aPSession.ConnectionInfo.Slot}_{aPSession.ConnectionInfo.Team}_nine_sols_area"; Log.Info("TrackerMapPage::GameLevel_Awake setting DataStorage key \"" + text + "\" to value \"" + value + "\""); aPSession.DataStorage[text] = DataStorageElement.op_Implicit(value); } else { Log.Info("TrackerMapPage::GameLevel_Awake called with unknown levelName = " + name); } } catch (Exception ex) { Log.Error("TrackerMapPage::GameLevel_Awake threw: " + ex.Message + "\nwith stack:\n" + ex.StackTrace + "\nand InnerException: " + ex.InnerException?.Message + "\nwith stack:\n" + ex.InnerException?.StackTrace); } } } [HarmonyPatch] internal class Goal { [HarmonyPrefix] [HarmonyPatch(typeof(SetVariableBoolAction), "OnStateEnterImplement")] private static void SetVariableBoolAction_OnStateEnterImplement(SetVariableBoolAction __instance) { VariableBool targetFlag = __instance.targetFlag; object obj; if (targetFlag == null) { obj = null; } else { ScriptableDataBool boolFlag = targetFlag.boolFlag; obj = ((boolFlag != null) ? ((GameFlagBase)boolFlag).FinalSaveID : null); } string text = (string)obj; if (text == null) { return; } bool flag = false; if (text == "85d361b9-7c43-4a1d-91c2-fd19e4bbb0b1_6b037c39982d34953a066792ab66783aScriptableDataBool") { flag = true; } else if (text == "e965aab1c014b4273b928b17fbcff379ScriptableDataBool") { flag = true; } if (!flag) { return; } if (PlayerGamePlayData.Instance.memoryMode.CurrentValue) { Log.Info("Goal code ignoring Eigong kill because this is Battle Memories mode"); return; } Log.Info($"Eigong flag: id={text}, TargetValue={__instance.TargetValue}"); InGameConsole.Add("Eigong defeat detected by SetVariableBoolAction_OnStateEnterImplement. Congratulations!", forceImmediateToast: true); InGameConsole.Add("Telling the AP server that you've achieved your goal.", forceImmediateToast: true); Task.Run(delegate { try { if (!Task.Run(delegate { ConnectionAndPopups.APSession.SetGoalAchieved(); }).Wait(TimeSpan.FromSeconds(2.0))) { string text2 = "AP server timed out when we tried to tell it that you've achieved your goal. Did the connection go down?"; Log.Warning(text2); InGameConsole.Add("" + text2 + ""); } } catch (Exception ex) { Log.Error("Caught error in SetGoalAchieved's timeout callback: '" + ex.Message + "'\n" + ex.StackTrace); } }); } } internal static class Log { private static ManualLogSource? logSource; internal static void Init(ManualLogSource logSource) { Log.logSource = logSource; } internal static void Debug(object data) { ManualLogSource? obj = logSource; if (obj != null) { obj.LogDebug(data); } } internal static void Error(object data) { ManualLogSource? obj = logSource; if (obj != null) { obj.LogError(data); } } internal static void Fatal(object data) { ManualLogSource? obj = logSource; if (obj != null) { obj.LogFatal(data); } } internal static void Info(object data) { ManualLogSource? obj = logSource; if (obj != null) { obj.LogInfo(data); } } internal static void Message(object data) { ManualLogSource? obj = logSource; if (obj != null) { obj.LogMessage(data); } } internal static void Warning(object data) { ManualLogSource? obj = logSource; if (obj != null) { obj.LogWarning(data); } } } public class APConnectionData { public string hostname = ""; public int port; public string slotName = ""; public string password = ""; public string? roomId; } public class APRandomizerSaveData { public APConnectionData apConnectionData = new APConnectionData(); public Dictionary locationsChecked = new Dictionary(); public Dictionary itemsAcquired = new Dictionary(); public Dictionary otherPersistentModFlags = new Dictionary(); public Dictionary> persistentModStringLists = new Dictionary>(); public Dictionary scoutedLocations = new Dictionary(); } [HarmonyPatch] internal class APSaveManager { public static APRandomizerSaveData?[] apSaveSlots = new APRandomizerSaveData[4]; public static int selectedSlotIndex = -1; public static bool apSavesLoaded = false; public static Task? scheduledSaveFileWriteTCS = null; public static APRandomizerSaveData? CurrentAPSaveData { get { if (selectedSlotIndex < 0) { return null; } return apSaveSlots[selectedSlotIndex]; } } [HarmonyPrefix] [HarmonyPatch(typeof(StartMenuLogic), "Start")] public static void StartMenuLogic_Start_Prefix(StartMenuLogic __instance) { apSavesLoaded = false; Log.Info("StartMenuLogic_Start_Prefix making sure any active AP session gets cleaned up"); ConnectionAndPopups.CleanupExistingAPServerConnection(); } [HarmonyPostfix] [HarmonyPatch(typeof(SaveSlotUIButton), "UpdateUI")] public static async void SaveSlotUIButton_UpdateUI_Postfix(SaveSlotUIButton __instance) { if (!apSavesLoaded) { await LoadAPSaves(); apSavesLoaded = true; } if (!__instance.SaveExist) { ((Behaviour)__instance).enabled = true; return; } APRandomizerSaveData aPRandomizerSaveData = apSaveSlots[__instance.index]; if (aPRandomizerSaveData != null) { ((Behaviour)__instance).enabled = true; APConnectionData apConnectionData = aPRandomizerSaveData.apConnectionData; TMP_Text lastSceneText = __instance.lastSceneText; lastSceneText.text = lastSceneText.text + "\n" + apConnectionData.hostname + ":" + apConnectionData.port + " - " + apConnectionData.slotName; } else { ((Behaviour)__instance).enabled = false; TMP_Text lastSceneText2 = __instance.lastSceneText; lastSceneText2.text += "\n[Vanilla Save]"; } } private static string APSaveDataPathForSlot(int i) { string saveSlotsPath = APRandomizer.SaveSlotsPath; string text = SaveManager.GetSlotDirPath(i) + "_Ixrec_ArchipelagoRandomizer.json"; return saveSlotsPath + "/" + text; } private static async Task LoadAPSaves() { Log.Info("Loading Archipelago save data"); GameObject saveSlotButtonsGO = GameObject.Find("MenuLogic/MainMenuLogic/Providers/StartGame SaveSlotPanel/SlotGroup/SlotGroup H"); for (int i = 0; i <= 3; i++) { UniTask val = SingletonBehaviour.Instance.CheckSaveExist(i); string saveSlotVanillaFolderName = SaveManager.GetSlotDirPath(i); string saveSlotAPModFilePath = APSaveDataPathForSlot(i); bool apSaveFileExists = File.Exists(saveSlotAPModFilePath); Transform buttonsForThisSlotT = saveSlotButtonsGO.transform.GetChild(i * 2); if (!(await val)) { apSaveSlots[i] = null; SetChangeButtonVisible(visible: false, buttonsForThisSlotT, i); continue; } if (apSaveFileExists) { Log.Info(saveSlotVanillaFolderName + " has AP save data"); try { APRandomizerSaveData aPRandomizerSaveData = JsonConvert.DeserializeObject(File.ReadAllText(saveSlotAPModFilePath)); if (aPRandomizerSaveData == null) { aPRandomizerSaveData = new APRandomizerSaveData(); } if (aPRandomizerSaveData.persistentModStringLists == null) { aPRandomizerSaveData.persistentModStringLists = new Dictionary>(); } apSaveSlots[i] = aPRandomizerSaveData; } catch (Exception ex) { Log.Error("failed to deserialize randomizer save data in " + saveSlotAPModFilePath + "\nMessage: " + ex.Message + "\nStackTrace: " + ex.StackTrace); } SetChangeButtonVisible(visible: true, buttonsForThisSlotT, i); continue; } Log.Info(saveSlotVanillaFolderName + " is a vanilla save"); Transform child = buttonsForThisSlotT.GetChild(0); ((Behaviour)((Component)child).GetComponent