From bfcd48950d9c416b03c93f04d98af0529403355c Mon Sep 17 00:00:00 2001 From: Tom Bohar Date: Tue, 20 Oct 2026 21:28:18 -0400 Subject: [PATCH] Snapshot for release 2026.10.20.1 (internal 7116fab) --- .../Aelrynth}/AelrynthBoards.cs | 26 +- .../Aelrynth/AelrynthFeature.cs | 106 +++ .../Aelrynth/AelrynthPages.cs | 252 +++++ .../Aelrynth}/VaultFeed.cs | 73 +- .../AelrynthPlugin.cs | 127 +++ .../RynthCore.Plugin.RynthAelrynth.csproj | 15 +- .../ServerData.cs | 3 +- .../Combat/BuffManager.cs | 23 +- .../Combat/CombatManager.cs | 279 +++--- .../Combat/DebuffTimers.cs | 103 +++ .../Combat/SpellDatabase.cs | 9 + .../Combat/WorldObjectCache.cs | 13 + .../CorpseOpenController.cs | 2 + Plugins/RynthCore.Plugin.RynthAi/GameInput.cs | 272 ++++++ .../RynthCore.Plugin.RynthAi/HubInterface.cs | 20 +- .../RynthCore.Plugin.RynthAi/Huds/HudState.cs | 3 +- .../Huds/MiniRemoteHud.cs | 122 ++- .../Huds/MovedTabs.cs | 4 +- .../Huds/SectionsManifest.cs | 92 +- Plugins/RynthCore.Plugin.RynthAi/Jumper.cs | 68 +- .../LegacyUi/LegacyAdvancedSettingsUi.cs | 14 +- .../LegacyUi/LegacyDashboardRenderer.cs | 37 +- .../LegacyUi/LegacyUiSettings.cs | 47 +- .../Loot/InventoryManager.cs | 2 +- .../Loot/T11ItemSupport.cs | 27 +- .../MagToolsCommands.Extra.cs | 506 ++++++++++ .../MagToolsCommands.cs | 52 +- .../ManaStoneManager.cs | 27 +- .../Meta/ExpressionEngine.UbCompat.cs | 373 ++++++++ .../Meta/ExpressionEngine.cs | 26 +- .../Meta/ExpressionReference.txt | 20 +- .../Meta/MetaManager.cs | 231 ++++- .../MiniRemote/Crafting/TinkerCatalog.cs | 14 +- .../MiniRemote/Crafting/TinkerRunner.cs | 2 +- .../MiniRemote/IltClient.cs | 203 ---- .../MiniRemote/MiniRemoteContext.cs | 17 +- .../MiniRemote/MiniRemoteController.cs | 85 +- .../MiniRemote/MiniRemoteInventory.cs | 43 +- .../MiniRemote/MiniRemoteState.cs | 14 +- .../MiniRemote/PetsTab.cs | 420 ++------- .../MiniRemote/ServerHubClient.cs | 303 ++++++ .../NavigationEngine.cs | 15 + .../RynthCore.Plugin.RynthAi/PlayerCompass.cs | 23 + .../RynthCore.Plugin.RynthAi/PluginExports.cs | 28 - .../RynthAiCommands.cs | 41 +- .../RynthAiPlugin.LocalFeatures.cs | 70 +- .../RynthCore.Plugin.RynthAi/RynthAiPlugin.cs | 56 +- .../RynthAiServerCommand.cs | 13 +- .../RynthAiT11Command.cs | 133 --- .../RynthCore.Plugin.RynthAi.csproj | 2 - .../UtilityBeltCommands.cs | 13 + .../UtilityBeltCompatCommands.cs | 362 ++++++++ .../UtilityBeltExtraCommands.cs | 13 +- .../Vendor/AutoVendorManager.cs | 138 ++- .../Vendor/AutoVendorPlanner.cs | 64 +- .../Conquest/ConquestData.cs} | 16 +- .../Conquest/ConquestFeature.cs | 143 +++ .../Conquest/ConquestPages.cs | 417 +++++++++ .../Conquest}/CustomQuests.cs | 26 +- .../ConquestPlugin.cs | 118 +++ .../Resources/customquests.csv | 0 .../RynthCore.Plugin.RynthConquest.csproj | 26 +- .../ServerData.cs | 1 + .../THIRD_PARTY_NOTICES.md | 42 + .../DataInterface.cs | 31 +- .../Hub/IltFeatureCatalog.cs | 89 ++ .../Hub/IltGuardian.cs | 86 ++ .../Hub/IltHubController.cs | 135 ++- .../Hub/IltHubState.cs | 74 +- .../Hub/IltHubStore.cs | 5 + .../RynthCore.Plugin.RynthILT/Hub/IltHubUi.cs | 48 +- .../Hub/IltMigration.cs | 97 +- .../Hub/IltPetAutomation.cs | 394 ++++++++ .../Hub/IltPetCaptureRules.cs} | 14 +- .../Hub/IltPetLogs.cs | 5 +- .../Hub/IltQuestBonus.cs | 6 + .../Hub/IltRingEvade.cs | 121 +++ .../Hub/IltSalvage.cs | 9 + .../Hub/IltSections.cs | 2 +- .../Hub/IltSessionRates.cs | 18 + .../Hub/IltSettings.cs | 2 + .../RynthCore.Plugin.RynthILT/Hub/IltT11.cs | 213 +++++ .../Hub/IltVaultedDungeons.cs | 13 +- .../Hub/RynthAiClient.cs | 57 +- .../RynthCore.Plugin.RynthILT/HubInterface.cs | 85 +- .../IltSectionsManifest.cs | 129 +++ .../IltSettingsView/IltSettingsUi.cs | 45 +- .../PluginExports.cs | 29 +- .../ProfileInterface.cs | 3 + .../RynthCore.Plugin.RynthILT.csproj | 22 +- .../RynthILTPlugin.cs | 114 ++- .../ServerInterface.cs | 81 ++ .../Data/BankRoster.cs | 78 ++ .../Data/ExternalStorage.cs | 48 + .../InventoryContext.cs | 7 + .../PluginExports.cs | 21 +- .../RynthCore.Plugin.RynthInventory.csproj | 6 +- .../RynthInventoryPlugin.cs | 141 ++- .../Views/BankingTab.cs | 237 +++++ .../Views/InventoryView.cs | 36 +- .../RynthCore.Plugin.RynthNav/AutoRunGate.cs | 76 ++ .../RynthNavPlugin.PortalAim.cs | 2 +- .../RynthNavPlugin.Settle.cs | 4 +- .../RynthNavPlugin.TownNet.cs | 6 +- .../RynthNavPlugin.Travel.cs | 4 +- .../RynthNavPlugin.Turn.cs | 6 +- .../RynthNavPlugin.cs | 17 +- .../Data/ChatRequest.cs | 24 - .../Data/DynamicStamps.cs | 170 ++++ .../Data/IltServerProfile.cs | 232 +++++ .../Data/Legendary.cs | 135 +++ .../Data/NavTargets.cs | 86 ++ .../Data/QuestFlags.cs | 61 +- .../Data/ServerIdentity.cs | 22 +- .../Data/VoidTracker.cs | 2 +- .../OracleContext.cs | 67 +- .../OracleSettings.cs | 33 +- .../PluginExports.cs | 2 +- .../Resources/dynstamps.csv | 244 +++++ .../Resources/legendary.csv | 41 + .../RynthCore.Plugin.RynthOracle.csproj | 11 +- .../RynthOraclePlugin.cs | 298 ++++-- .../THIRD_PARTY_NOTICES.md | 10 +- .../Views/AboutTab.cs | 74 +- .../Views/BoardsTab.cs | 152 --- .../Views/CharacterTab.cs | 96 +- .../Views/ConquestTab.cs | 204 ---- .../Views/DynamicStampsTab.cs | 214 +++++ .../Views/LegendaryTab.cs | 18 + .../Views/MarkersTab.cs | 56 +- .../Views/OracleView.cs | 30 +- .../Views/PetBreedingTab.cs | 202 ++++ .../Views/QuestsTab.cs | 781 ++++++++++++++-- .../Views/RefreshBar.cs | 92 +- Plugins/Shared/EngineServerState.cs | 74 ++ Plugins/Shared/PetCaptureLines.cs | 8 +- Plugins/Shared/RynthAiHubApi.cs | 52 +- Plugins/Shared/RynthAiSessionClient.cs | 3 + Plugins/Shared/RynthIltDataApi.cs | 152 ++- Plugins/Shared/RynthIltHubApi.cs | 116 ++- Plugins/Shared/RynthIltServerApi.cs | 74 ++ Plugins/Shared/RynthServerProfileApi.cs | 5 +- .../Shared/ServerPack/ServerChatRequest.cs | 23 + .../Shared/ServerPack/ServerPackExports.cs | 21 +- Plugins/Shared/ServerPack/ServerPackInfo.cs | 7 + .../Shared/ServerPack/ServerPackInterface.cs | 13 +- Plugins/Shared/ServerPack/ServerPackModel.cs | 22 +- Plugins/Shared/ServerPack/ServerPackPages.cs | 86 ++ Plugins/Shared/ServerPack/ServerPackPlugin.cs | 137 ++- .../Shared/ServerPack/ServerPackProfile.cs | 111 ++- .../Shared/ServerPack/ServerPackRefresh.cs | 88 ++ .../Shared/ServerPack/ServerPackSettings.cs | 158 ++++ Plugins/Shared/ServerPack/ServerPackUi.cs | 31 +- Plugins/Shared/ServerPack/ServerPlugin.props | 8 +- Plugins/Shared/StorageFeed.cs | 153 +++ Shared/RynthCore.LootSdk/T11/T11PlayerAugs.cs | 6 + Tools/RynthCore.AutoVendorTests/Program.cs | 44 + .../Fakes/FakeHost.cs | 116 +++ .../Fakes/FakeServerHub.cs | 168 ++++ Tools/RynthCore.RynthAiHostTests/Program.cs | 10 +- .../Tests/BackAwayTests.cs | 111 +++ .../Tests/DebuffRenewTests.cs | 94 ++ .../Tests/DoorTests.cs | 29 + .../Tests/ExpressionTests.cs | 73 +- .../Tests/GiveTests.cs | 137 +++ .../Tests/IltClientLookupTests.cs | 39 - .../Tests/ManaStoneChoiceTests.cs | 32 +- .../Tests/MetaAuditTests.cs | 258 ++++++ .../Tests/MetaSampleCompatTests.cs | 146 +++ .../Tests/MetaTests.cs | 85 ++ .../Tests/MiniRemoteMoveTests.cs | 151 ++- .../Tests/NavEngineTests.cs | 21 + .../Tests/RingEvadeTests.cs | 97 -- .../Tests/SectionsTests.cs | 76 +- .../Tests/ServerHubClientLookupTests.cs | 40 + .../Tests/ServerPluginForwardTests.cs | 76 ++ .../Tests/T11LootTests.cs | 19 +- .../Tests/TinkerTests.cs | 16 +- .../Tests/UbCompatTests.cs | 158 ++++ .../Tests/UbMtSafetyTests.cs | 340 +++++++ .../Tests/VitalsTests.cs | 56 ++ Tools/RynthCore.RynthAiTests/Program.cs | 1 - .../RynthCore.RynthAiTests.csproj | 1 - Tools/RynthILT.Tests/BreedingTests.cs | 13 +- Tools/RynthILT.Tests/DataApiTests.cs | 47 +- Tools/RynthILT.Tests/FakeAiHub.cs | 76 ++ Tools/RynthILT.Tests/FeatureCatalogTests.cs | 74 ++ Tools/RynthILT.Tests/MoveTests.cs | 75 +- Tools/RynthILT.Tests/PetAutomationTests.cs | 189 ++++ .../PetCaptureRulesTests.cs | 5 +- Tools/RynthILT.Tests/ProfileTests.cs | 11 + Tools/RynthILT.Tests/Program.cs | 6 + Tools/RynthILT.Tests/RemoteTabTests.cs | 94 ++ Tools/RynthILT.Tests/RingEvadeTests.cs | 134 +++ Tools/RynthILT.Tests/RynthILT.Tests.csproj | 10 + Tools/RynthILT.Tests/T11Tests.cs | 113 +++ Tools/RynthILT.Tests/VaultedSwitchTests.cs | 64 ++ Tools/RynthInventory.Tests/Program.cs | 101 +- .../RynthInventory.Tests.csproj | 4 +- .../RynthInventory.Tests/StorageFeedTests.cs | 79 ++ Tools/RynthInventory.Tests/VaultFeedTests.cs | 157 ---- Tools/RynthNav.RouteTests/AutoRunGateTests.cs | 177 ++++ Tools/RynthNav.RouteTests/Program.cs | 1 + .../RynthNav.RouteTests.csproj | 2 + Tools/RynthOracle.Tests/MergedQuestsTests.cs | 872 ++++++++++++++++++ Tools/RynthOracle.Tests/Program.cs | 233 ++--- .../RynthOracle.Tests.csproj | 5 +- Tools/RynthOracle.Tests/ServerMoveTests.cs | 112 +++ Tools/RynthServerPack.Tests/AelrynthTests.cs | 119 +++ Tools/RynthServerPack.Tests/ConquestTests.cs | 216 +++++ Tools/RynthServerPack.Tests/Program.cs | 4 + .../RynthServerPack.Tests.csproj | 20 + .../ServerPackHooksTests.cs | 210 +++++ .../ServerProjectsTests.cs | 30 + Tools/RynthServerPack.Tests/VaultTests.cs | 229 +++++ 215 files changed, 16197 insertions(+), 2835 deletions(-) rename Plugins/{RynthCore.Plugin.RynthOracle/Data => RynthCore.Plugin.RynthAelrynth/Aelrynth}/AelrynthBoards.cs (92%) create mode 100644 Plugins/RynthCore.Plugin.RynthAelrynth/Aelrynth/AelrynthFeature.cs create mode 100644 Plugins/RynthCore.Plugin.RynthAelrynth/Aelrynth/AelrynthPages.cs rename Plugins/{RynthCore.Plugin.RynthInventory/Scanning => RynthCore.Plugin.RynthAelrynth/Aelrynth}/VaultFeed.cs (79%) create mode 100644 Plugins/RynthCore.Plugin.RynthAelrynth/AelrynthPlugin.cs create mode 100644 Plugins/RynthCore.Plugin.RynthAi/Combat/DebuffTimers.cs create mode 100644 Plugins/RynthCore.Plugin.RynthAi/GameInput.cs create mode 100644 Plugins/RynthCore.Plugin.RynthAi/MagToolsCommands.Extra.cs create mode 100644 Plugins/RynthCore.Plugin.RynthAi/Meta/ExpressionEngine.UbCompat.cs delete mode 100644 Plugins/RynthCore.Plugin.RynthAi/MiniRemote/IltClient.cs create mode 100644 Plugins/RynthCore.Plugin.RynthAi/MiniRemote/ServerHubClient.cs create mode 100644 Plugins/RynthCore.Plugin.RynthAi/PlayerCompass.cs delete mode 100644 Plugins/RynthCore.Plugin.RynthAi/RynthAiT11Command.cs create mode 100644 Plugins/RynthCore.Plugin.RynthAi/UtilityBeltCompatCommands.cs rename Plugins/{RynthCore.Plugin.RynthOracle/Data/Conquest.cs => RynthCore.Plugin.RynthConquest/Conquest/ConquestData.cs} (96%) create mode 100644 Plugins/RynthCore.Plugin.RynthConquest/Conquest/ConquestFeature.cs create mode 100644 Plugins/RynthCore.Plugin.RynthConquest/Conquest/ConquestPages.cs rename Plugins/{RynthCore.Plugin.RynthOracle/Data => RynthCore.Plugin.RynthConquest/Conquest}/CustomQuests.cs (60%) create mode 100644 Plugins/RynthCore.Plugin.RynthConquest/ConquestPlugin.cs rename Plugins/{RynthCore.Plugin.RynthOracle => RynthCore.Plugin.RynthConquest}/Resources/customquests.csv (100%) create mode 100644 Plugins/RynthCore.Plugin.RynthConquest/THIRD_PARTY_NOTICES.md create mode 100644 Plugins/RynthCore.Plugin.RynthILT/Hub/IltPetAutomation.cs rename Plugins/{RynthCore.Plugin.RynthAi/MiniRemote/PetCaptureRules.cs => RynthCore.Plugin.RynthILT/Hub/IltPetCaptureRules.cs} (93%) create mode 100644 Plugins/RynthCore.Plugin.RynthILT/Hub/IltRingEvade.cs create mode 100644 Plugins/RynthCore.Plugin.RynthILT/Hub/IltT11.cs create mode 100644 Plugins/RynthCore.Plugin.RynthILT/IltSectionsManifest.cs create mode 100644 Plugins/RynthCore.Plugin.RynthILT/ServerInterface.cs create mode 100644 Plugins/RynthCore.Plugin.RynthInventory/Data/BankRoster.cs create mode 100644 Plugins/RynthCore.Plugin.RynthInventory/Data/ExternalStorage.cs create mode 100644 Plugins/RynthCore.Plugin.RynthInventory/Views/BankingTab.cs create mode 100644 Plugins/RynthCore.Plugin.RynthNav/AutoRunGate.cs delete mode 100644 Plugins/RynthCore.Plugin.RynthOracle/Data/ChatRequest.cs create mode 100644 Plugins/RynthCore.Plugin.RynthOracle/Data/DynamicStamps.cs create mode 100644 Plugins/RynthCore.Plugin.RynthOracle/Data/IltServerProfile.cs create mode 100644 Plugins/RynthCore.Plugin.RynthOracle/Data/Legendary.cs create mode 100644 Plugins/RynthCore.Plugin.RynthOracle/Data/NavTargets.cs create mode 100644 Plugins/RynthCore.Plugin.RynthOracle/Resources/dynstamps.csv create mode 100644 Plugins/RynthCore.Plugin.RynthOracle/Resources/legendary.csv delete mode 100644 Plugins/RynthCore.Plugin.RynthOracle/Views/BoardsTab.cs delete mode 100644 Plugins/RynthCore.Plugin.RynthOracle/Views/ConquestTab.cs create mode 100644 Plugins/RynthCore.Plugin.RynthOracle/Views/DynamicStampsTab.cs create mode 100644 Plugins/RynthCore.Plugin.RynthOracle/Views/LegendaryTab.cs create mode 100644 Plugins/RynthCore.Plugin.RynthOracle/Views/PetBreedingTab.cs create mode 100644 Plugins/Shared/RynthIltServerApi.cs create mode 100644 Plugins/Shared/ServerPack/ServerChatRequest.cs create mode 100644 Plugins/Shared/ServerPack/ServerPackPages.cs create mode 100644 Plugins/Shared/ServerPack/ServerPackRefresh.cs create mode 100644 Plugins/Shared/ServerPack/ServerPackSettings.cs create mode 100644 Plugins/Shared/StorageFeed.cs create mode 100644 Tools/RynthCore.RynthAiHostTests/Fakes/FakeServerHub.cs create mode 100644 Tools/RynthCore.RynthAiHostTests/Tests/BackAwayTests.cs create mode 100644 Tools/RynthCore.RynthAiHostTests/Tests/DebuffRenewTests.cs delete mode 100644 Tools/RynthCore.RynthAiHostTests/Tests/IltClientLookupTests.cs create mode 100644 Tools/RynthCore.RynthAiHostTests/Tests/MetaAuditTests.cs create mode 100644 Tools/RynthCore.RynthAiHostTests/Tests/MetaSampleCompatTests.cs delete mode 100644 Tools/RynthCore.RynthAiHostTests/Tests/RingEvadeTests.cs create mode 100644 Tools/RynthCore.RynthAiHostTests/Tests/ServerHubClientLookupTests.cs create mode 100644 Tools/RynthCore.RynthAiHostTests/Tests/ServerPluginForwardTests.cs create mode 100644 Tools/RynthCore.RynthAiHostTests/Tests/UbCompatTests.cs create mode 100644 Tools/RynthCore.RynthAiHostTests/Tests/UbMtSafetyTests.cs create mode 100644 Tools/RynthILT.Tests/FakeAiHub.cs create mode 100644 Tools/RynthILT.Tests/PetAutomationTests.cs rename Tools/{RynthCore.RynthAiTests/Tests => RynthILT.Tests}/PetCaptureRulesTests.cs (96%) create mode 100644 Tools/RynthILT.Tests/RemoteTabTests.cs create mode 100644 Tools/RynthILT.Tests/RingEvadeTests.cs create mode 100644 Tools/RynthILT.Tests/T11Tests.cs create mode 100644 Tools/RynthILT.Tests/VaultedSwitchTests.cs create mode 100644 Tools/RynthInventory.Tests/StorageFeedTests.cs delete mode 100644 Tools/RynthInventory.Tests/VaultFeedTests.cs create mode 100644 Tools/RynthNav.RouteTests/AutoRunGateTests.cs create mode 100644 Tools/RynthOracle.Tests/MergedQuestsTests.cs create mode 100644 Tools/RynthOracle.Tests/ServerMoveTests.cs create mode 100644 Tools/RynthServerPack.Tests/AelrynthTests.cs create mode 100644 Tools/RynthServerPack.Tests/ConquestTests.cs create mode 100644 Tools/RynthServerPack.Tests/ServerPackHooksTests.cs create mode 100644 Tools/RynthServerPack.Tests/VaultTests.cs diff --git a/Plugins/RynthCore.Plugin.RynthOracle/Data/AelrynthBoards.cs b/Plugins/RynthCore.Plugin.RynthAelrynth/Aelrynth/AelrynthBoards.cs similarity index 92% rename from Plugins/RynthCore.Plugin.RynthOracle/Data/AelrynthBoards.cs rename to Plugins/RynthCore.Plugin.RynthAelrynth/Aelrynth/AelrynthBoards.cs index 58a1c45..a007686 100644 --- a/Plugins/RynthCore.Plugin.RynthOracle/Data/AelrynthBoards.cs +++ b/Plugins/RynthCore.Plugin.RynthAelrynth/Aelrynth/AelrynthBoards.cs @@ -1,8 +1,20 @@ +// Moved here from RynthOracle (Data/AelrynthBoards.cs) on 2026-10-20: Aelrynth-only features live in RynthAelrynth. using System; using System.Collections.Generic; using System.Text.RegularExpressions; +using RynthCore.Plugin.ServerPack; -namespace RynthCore.Plugin.RynthOracle.Data; +namespace RynthCore.Plugin.RynthAelrynth; + +/// A row of a leaderboard. +internal sealed class BoardRow +{ + public int Rank; + public string Name = ""; + public string Value = ""; + public string Extra = ""; + public bool IsYou; +} /// A board in Aelrynth's /top overview. internal sealed class AelrynthBoardSummary @@ -26,7 +38,7 @@ internal sealed class TrialDungeon } /// -/// Aelrynth's leaderboards (tag Aelrynth), read from the replies of the server's own commands +/// Aelrynth's leaderboards, read from the replies of the server's own commands /// (ACEPublic Mods: Aeshnidae.Leaderboard /top, Aeshnidae.Trials /trial; one Broadcast line /// each, numbers with thousands separators). Formats (Commands.cs): /// /top "Leaderboards - N characters, refreshed X. /top <board> ..." @@ -38,8 +50,8 @@ internal sealed class TrialDungeon /// /trial <dungeon> "Dungeon (LLLL) - top 10, best per character, any tier:" /// then " r. m:ss Name (tier T, K kills, d MMM)" and " records per tier/you/this week" lines /// Entry lines only count right after their header (within a few seconds), so ordinary chat -/// can't add rows. The two commands share /top with ConquestAC's very different reply, which is -/// why each parser only runs on its own server. +/// can't add rows. Conquest answers /top in a very different shape (RynthConquest's parser), which is +/// why each server plugin reads only its own server's replies. /// internal sealed class AelrynthBoards { @@ -81,7 +93,7 @@ internal sealed class AelrynthBoards private Block _block; private long _blockMs; - private readonly ChatRequest _topReq = new(), _trialReq = new(); + private readonly ServerChatRequest _topReq = new(), _trialReq = new(); public void Clear() { @@ -110,7 +122,7 @@ internal sealed class AelrynthBoards private void Start(Block b, long now) { _block = b; _blockMs = now; } - /// A chat line: true when it was a leaderboard reply; = it answers RynthOracle's request. + /// A chat line: true when it was a leaderboard reply; = it answers RynthAelrynth's request. public bool OnChatLine(string text, long now, out bool ours) { ours = false; @@ -255,7 +267,7 @@ internal sealed class AelrynthBoards return false; } - private bool Mine(ChatRequest req, long now, out bool ours) + private bool Mine(ServerChatRequest req, long now, out bool ours) { ours = req.Awaiting(now); req.Extend(now); diff --git a/Plugins/RynthCore.Plugin.RynthAelrynth/Aelrynth/AelrynthFeature.cs b/Plugins/RynthCore.Plugin.RynthAelrynth/Aelrynth/AelrynthFeature.cs new file mode 100644 index 0000000..bc236dd --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAelrynth/Aelrynth/AelrynthFeature.cs @@ -0,0 +1,106 @@ +// AelrynthFeature.cs - What RynthAelrynth does on Aelrynth, without the host (AelrynthPlugin.cs wires it +// to the engine, AelrynthPages.cs draws it). Moved out of RynthOracle on 2026-10-20 so that only players +// who installed RynthAelrynth carry Aelrynth's features: +// * reads the replies of Aelrynth's own commands (AelrynthBoards: /top, /top me, /trial) and hides +// the replies to its own requests when HideOwnReplies is on; +// * reads the account vault (VaultFeed: /mule-data, moved here from RynthInventory, which asked every +// server for it) a few seconds after login and every ten minutes, and hands it to RynthInventory +// through the generic storage feed (Plugins/Shared/StorageFeed.cs), so it shows in Global Inventory. +// Settings: rynthaelrynth.json (ServerPackSettings); "hide own replies" is taken over once from +// rynthoracle.json (it was RynthOracle's hideOwnQuestReplies). +// Threads: everything here runs under Gate (chat and tick from the pump, the pages on the render thread). +// Pure: RynthServerPack.Tests covers it. +using System; +using RynthCore.Plugin.ServerPack; +using RynthCore.Plugin.Shared; + +namespace RynthCore.Plugin.RynthAelrynth; + +internal sealed class AelrynthFeature +{ + public const string SettingHideOwnReplies = "hideOwnReplies"; + /// Set once rynthoracle.json's setting was taken over (it's never read again). + public const string MigrationMarker = "migratedFromRynthOracle"; + + /// RynthAelrynth's pages (AelrynthPages draws them): id, label, tooltip. + public static readonly (string Id, string Label, string Tooltip)[] PageList = + { + ("boards", "Leaderboards", "Aelrynth's /top leaderboards and /trial dungeon records (RynthAelrynth)."), + }; + + /// Held for everything below (pump and render thread). + public readonly object Gate = new(); + public readonly AelrynthBoards Boards = new(); + + /// Hide the replies to RynthAelrynth's own requests (a command typed by hand always shows). + public bool HideOwnReplies = true; + + /// Sends a chat command as if typed (the vault's /mule-data); the plugin sets it (AelrynthPlugin). + public Func SendCommand = _ => false; + + /// The account vault reader. + public readonly VaultFeed Vault; + private long _nextVaultAskMs; + + /// What happened to the last vault read on its way to RynthInventory ("" before one). + public string VaultHandOff = string.Empty; + + public AelrynthFeature() => Vault = new VaultFeed(cmd => SendCommand(cmd)); + + /// Takes over RynthOracle's reply-hiding choice once (default: hidden, as it was there). + public static bool Migrate(ServerPackSettings settings, string oraclePath) => settings.MigrateOnce(MigrationMarker, s => + { + if (ServerPackSettings.ReadBoolFrom(oraclePath, "hideOwnQuestReplies") is bool hide) s.SetBool(SettingHideOwnReplies, hide); + }); + + public void LoadSettings(ServerPackSettings s) => HideOwnReplies = s.GetBool(SettingHideOwnReplies, true); + + public void SaveSettings(ServerPackSettings s) + { + if (s.SetBool(SettingHideOwnReplies, HideOwnReplies)) s.Save(); + } + + /// Login and logout: the boards and the vault are read fresh. + public void Reset() + { + Boards.Clear(); + Vault.Reset(); + _nextVaultAskMs = 0; + VaultHandOff = string.Empty; + } + + /// + /// An incoming chat line on Aelrynth: true when it should be hidden. The vault's data lines (and + /// the unknown-command reply to our own probe) always are; a leaderboard reply to our own request + /// is when HideOwnReplies is on. + /// + public bool OnChatLine(string text, int chatType, long nowMs) + { + if (Vault.ShouldEat(text, chatType)) return true; + return Boards.OnChatLine(text.TrimEnd('\r', '\n'), nowMs, out bool ours) && ours && HideOwnReplies; + } + + /// + /// The vault's timing (plugin tick, on Aelrynth): the first read + /// after login, then every unless the server has no vault. + /// Returns the record to hand to RynthInventory when a read just finished, else null. + /// + public StorageFeedRecord? VaultTick(long nowMs, string account) + { + if (_nextVaultAskMs == 0) _nextVaultAskMs = nowMs + VaultFeed.FirstAskMs; + else if (nowMs >= _nextVaultAskMs && Vault.Status != VaultFeed.State.Unsupported) + { + _nextVaultAskMs = nowMs + VaultFeed.RefreshMs; + Vault.Ask(nowMs); + } + Vault.Tick(nowMs, account); + return Vault.TakeChanged() ? Vault.Record : null; + } + + /// "/rserver vault": a read now (even on a server that said it has none); the next timed one in ten minutes. + public bool VaultAskNow(long nowMs) + { + _nextVaultAskMs = nowMs + VaultFeed.RefreshMs; + return Vault.Ask(nowMs, force: true); + } +} diff --git a/Plugins/RynthCore.Plugin.RynthAelrynth/Aelrynth/AelrynthPages.cs b/Plugins/RynthCore.Plugin.RynthAelrynth/Aelrynth/AelrynthPages.cs new file mode 100644 index 0000000..7745c0c --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAelrynth/Aelrynth/AelrynthPages.cs @@ -0,0 +1,252 @@ +// RynthOracle's Leaderboards tab, Aelrynth's half (Views/BoardsTab.cs), moved here on 2026-10-20 and +// redrawn with ImGui as RynthAelrynth's Leaderboards page: a sub-tab of the Mini Remote's Server +// section while on Aelrynth, and a tab of the /rserver window. +using System; +using System.Numerics; +using ImGuiNET; +using RynthCore.Plugin.ServerPack; +using RynthCore.Plugin.Shared; + +namespace RynthCore.Plugin.RynthAelrynth; + +/// +/// Aelrynth's /top boards (every board's leader, one board's top 10, your own standings) and the +/// /trial dungeon records. Render thread: draws holding the feature's lock, and queues what it sends. +/// +internal sealed class AelrynthPages +{ + private static readonly Vector4 Gold = new(1.00f, 0.84f, 0.30f, 1f); + private static readonly Vector4 Red = new(0.95f, 0.45f, 0.40f, 1f); + private static readonly Vector4 Selected = new(0.26f, 0.45f, 0.70f, 1f); + + private readonly AelrynthFeature _f; + private readonly Func _active; + private readonly Action _runOnTick; + private readonly Func _send; + private readonly Action _print; + private readonly Action _saveSettings; + private readonly ServerRefreshRow _refresh = new(); + + private int _view; // 0 boards, 1 me, 2 trials + private string _boardArg = ""; + private string _trialArg = ""; + + public AelrynthPages(AelrynthFeature feature, Func active, Action runOnTick, Func send, + Action print, Action saveSettings) + { + _f = feature; + _active = active; + _runOnTick = runOnTick; + _send = send; + _print = print; + _saveSettings = saveSettings; + } + + public ServerPage[] Pages() + { + var list = AelrynthFeature.PageList; + return new[] { new ServerPage(list[0].Id, list[0].Label, list[0].Tooltip, DrawBoards) }; + } + + /// Logout: the next character's status lines start empty. + public void Reset() => _refresh.Reset(); + + private void DrawBoards() + { + if (!_active()) + { + SafeImGui.TextWrapped("This page is for Aelrynth. RynthCore doesn't see this world as Aelrynth " + + "(check RynthCore Options > Diagnostics, or /rserver info)."); + return; + } + lock (_f.Gate) + { + AelrynthBoards a = _f.Boards; + if (Toggle("Boards##ab_v0", _view == 0)) _view = 0; + ImGui.SameLine(); + if (Toggle("Me##ab_v1", _view == 1)) _view = 1; + ImGui.SameLine(); + if (Toggle("Trials##ab_v2", _view == 2)) _view = 2; + _refresh.Draw("ab" + _view, BoardsHelp(), RefreshBoards); + ImGui.Separator(); + if (a.LastError.Length > 0) SafeImGui.TextColored(Red, a.LastError); + + if (_view == 1) DrawMe(a); + else if (_view == 2) DrawTrials(a); + else DrawOverview(a); + + ImGui.Spacing(); + bool hide = _f.HideOwnReplies; + if (ImGui.Checkbox("Hide the replies to RynthAelrynth's own requests##ab_hide", ref hide)) + { + _f.HideOwnReplies = hide; + _runOnTick(_saveSettings); + } + if (ImGui.IsItemHovered()) SafeImGui.SetTooltip("/top and /trial when RynthAelrynth sends them. A command you type yourself always shows its reply."); + } + } + + private void DrawMe(AelrynthBoards a) + { + if (ImGui.BeginChild("##ab_me", new Vector2(0f, 300f), ImGuiChildFlags.Borders)) + { + foreach (AelrynthStanding s in a.Standings) + { + SafeImGui.Text(Cut(s.Title, 34)); + ImGui.SameLine(260f); + SafeImGui.Text(s.Rank > 0 ? $"#{s.Rank} of {s.Of}" : "-"); + if (s.Value.Length > 0) { ImGui.SameLine(380f); SafeImGui.Text(s.Value); } + } + if (a.Standings.Count == 0) ImGui.TextDisabled("Nothing read yet. Press Refresh."); + } + ImGui.EndChild(); + } + + private void DrawTrials(AelrynthBoards a) + { + ImGui.SetNextItemWidth(220f); + ImGui.InputText("Dungeon##ab_trialarg", ref _trialArg, 48); + ImGui.SameLine(); + if (ImGui.SmallButton("Top 10##ab_trialtop") && _trialArg.Trim().Length > 0) Ask(a, isTrial: true, _trialArg); + if (ImGui.BeginChild("##ab_trials", new Vector2(0f, 300f), ImGuiChildFlags.Borders)) + { + int i = 0; + foreach (TrialDungeon d in a.Trials) + { + TrialDungeon row = d; + if (ImGui.Selectable($"{d.Name} ({d.Landblock})##ab_t{i++}")) + { + _trialArg = row.Name; + Ask(a, isTrial: true, row.Name); + } + if (ImGui.IsItemHovered()) SafeImGui.SetTooltip("Click for this dungeon's top 10."); + ImGui.TextDisabled(" record:"); ImGui.SameLine(90f); SafeImGui.TextWrapped(d.Record); + ImGui.TextDisabled(" you:"); ImGui.SameLine(90f); SafeImGui.Text(d.You); + ImGui.TextDisabled(" this week:"); ImGui.SameLine(90f); SafeImGui.Text(d.Week); + } + foreach (string line in a.TrialLines) if (!line.StartsWith("Trials - ", StringComparison.Ordinal)) SafeImGui.TextWrapped(line); + if (a.TrialBoardTitle.Length > 0) + { + ImGui.SeparatorText(a.TrialBoardTitle); + foreach (BoardRow r in a.TrialRows) + { + SafeImGui.Text($"{r.Rank,2}. {r.Value}"); + ImGui.SameLine(90f); + SafeImGui.Text(Cut(r.Name, 28)); + ImGui.SameLine(300f); + SafeImGui.TextDisabled(Cut(r.Extra, 40)); + } + foreach (string n in a.TrialNotes) SafeImGui.TextWrapped(n); + } + if (a.Trials.Count == 0 && a.TrialBoardTitle.Length == 0) ImGui.TextDisabled("Nothing read yet. Press Refresh."); + } + ImGui.EndChild(); + } + + private void DrawOverview(AelrynthBoards a) + { + if (ImGui.SmallButton("All boards##ab_all")) Ask(a, isTrial: false, ""); + if (ImGui.IsItemHovered()) SafeImGui.SetTooltip("Sends /top: every board's leader."); + ImGui.SameLine(); + ImGui.SetNextItemWidth(160f); + ImGui.InputText("Board##ab_arg", ref _boardArg, 32); + ImGui.SameLine(); + if (ImGui.SmallButton("Top 10##ab_board") && _boardArg.Trim().Length > 0) Ask(a, isTrial: false, _boardArg); + if (a.OverviewNote.Length > 0) SafeImGui.TextDisabled(a.OverviewNote); + + if (a.BoardTitle.Length > 0) + { + ImGui.SeparatorText($"{a.BoardTitle} ({a.BoardNote})"); + if (a.BoardYou.Length > 0) SafeImGui.TextColored(Gold, a.BoardYou); + if (ImGui.BeginChild("##ab_rows", new Vector2(0f, 300f), ImGuiChildFlags.Borders)) + { + ImGui.TextDisabled("Rank"); ImGui.SameLine(60f); ImGui.TextDisabled("Name"); ImGui.SameLine(280f); ImGui.TextDisabled("Value"); + foreach (BoardRow r in a.BoardRows) + { + SafeImGui.Text(r.Rank.ToString()); + ImGui.SameLine(60f); + if (r.IsYou) SafeImGui.TextColored(Gold, Cut(r.Name, 30)); + else SafeImGui.Text(Cut(r.Name, 30)); + ImGui.SameLine(280f); + SafeImGui.Text(r.Value); + if (r.Extra.Length > 0) { ImGui.SameLine(420f); SafeImGui.TextDisabled(Cut(r.Extra, 40)); } + } + if (a.BoardRows.Count == 0) ImGui.TextDisabled("Nothing read yet. Press Refresh."); + } + ImGui.EndChild(); + return; + } + if (ImGui.BeginChild("##ab_overview", new Vector2(0f, 300f), ImGuiChildFlags.Borders)) + { + int i = 0; + foreach (AelrynthBoardSummary s in a.Overview) + { + AelrynthBoardSummary row = s; + if (ImGui.Selectable(Cut(s.Title, 30) + "##ab_o" + i++, false, ImGuiSelectableFlags.None, new Vector2(230f, 0f))) + { + _boardArg = row.Key; + Ask(a, isTrial: false, row.Key); + } + if (ImGui.IsItemHovered()) SafeImGui.SetTooltip($"/top {s.Key}"); + ImGui.SameLine(240f); + SafeImGui.Text(Cut(s.Leader, 24)); + if (s.Value.Length > 0) { ImGui.SameLine(430f); SafeImGui.Text(s.Value); } + } + if (a.Overview.Count == 0) ImGui.TextDisabled("Nothing read yet. Press All boards."); + } + ImGui.EndChild(); + } + + // ── Refresh (RynthOracle's RefreshBar, Aelrynth's part) ───────────── + + private ServerRefreshResult RefreshBoards() + { + AelrynthBoards a = _f.Boards; + string key = _view switch { 1 => "top me", 2 => "trial", _ => "top " + _boardArg }; + if (_refresh.CoolingDown(key, Environment.TickCount64)) return new ServerRefreshResult(ServerRefreshRow.TooSoon); + int before = a.Revision; + string cmd = _view switch + { + 1 => Ask(a, isTrial: false, "me"), + 2 => Ask(a, isTrial: true, ""), + _ => Ask(a, isTrial: false, a.BoardTitle.Length > 0 ? _boardArg : ""), + }; + return new ServerRefreshResult($"Sent {cmd}.", () => a.Revision != before); + } + + private string BoardsHelp() => _view switch + { + 1 => "Sends /top me and reads the reply.", + 2 => "Sends /trial and reads the dungeon list.", + _ => "Sends /top (every board's leader), or asks again for the board that is open.", + }; + + /// + /// "/top [arg]" or "/trial [arg]" on the next tick, marked as RynthAelrynth's own (its reply can + /// be hidden); returns the command. + /// + private string Ask(AelrynthBoards a, bool isTrial, string arg) + { + string cmd = string.IsNullOrWhiteSpace(arg) ? (isTrial ? "/trial" : "/top") : (isTrial ? "/trial " : "/top ") + arg.Trim(); + _runOnTick(() => + { + lock (_f.Gate) + { + if (isTrial) a.RequestTrial(arg, Environment.TickCount64); + else a.RequestTop(arg, Environment.TickCount64); + } + if (!_send(cmd)) _print($"Couldn't send {cmd} (not in the world)."); + }); + return cmd; + } + + private static bool Toggle(string label, bool selected) + { + if (selected) ImGui.PushStyleColor(ImGuiCol.Button, Selected); + bool clicked = ImGui.SmallButton(label); + if (selected) ImGui.PopStyleColor(); + return clicked; + } + + private static string Cut(string s, int max) => s.Length <= max ? s : s.Substring(0, Math.Max(0, max - 3)) + "..."; +} diff --git a/Plugins/RynthCore.Plugin.RynthInventory/Scanning/VaultFeed.cs b/Plugins/RynthCore.Plugin.RynthAelrynth/Aelrynth/VaultFeed.cs similarity index 79% rename from Plugins/RynthCore.Plugin.RynthInventory/Scanning/VaultFeed.cs rename to Plugins/RynthCore.Plugin.RynthAelrynth/Aelrynth/VaultFeed.cs index 8eb7c07..ea3732e 100644 --- a/Plugins/RynthCore.Plugin.RynthInventory/Scanning/VaultFeed.cs +++ b/Plugins/RynthCore.Plugin.RynthAelrynth/Aelrynth/VaultFeed.cs @@ -1,31 +1,34 @@ +// Moved here from RynthInventory (Scanning/VaultFeed.cs) on 2026-10-20: RynthInventory asked every server +// for an Aelrynth vault; now only RynthAelrynth asks, on Aelrynth, and hands the vault to RynthInventory +// through the generic storage feed (Plugins/Shared/StorageFeed.cs). using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Globalization; using System.Text.Json; -using RynthCore.Plugin.RynthInventory.Data; using RynthCore.Plugin.Shared; -namespace RynthCore.Plugin.RynthInventory.Scanning; +namespace RynthCore.Plugin.RynthAelrynth; /// /// The Aelrynth account vault (the Aeshnidae.Mule mod): item storage the retail client is never -/// shown, so the only way to see inside is to ask. The plugin types /mule-data, exactly as a +/// shown, so the only way to see inside is to ask. RynthAelrynth types /mule-data, exactly as a /// player could, and the server answers one chat line a page: /// /// ~ael1 {"t":"mule","ready":true,"page":1,"pages":3,"count":57,"max":1000,"items":[{...}]} /// /// (the same "~ael1" lines the Aelrynth Companion reads; only lines whose "t" is "mule" are ours). -/// The pages are collected into one StorageRecord and kept with the character's storage, so the -/// vault is searched, shown with icons and merged across characters like any other storage; the -/// newest copy wins, and a vault belongs to the account, so every character sees the same one. +/// The pages are collected into one StorageFeedRecord, which RynthAelrynth sends to RynthInventory +/// (StorageFeed): it is kept with the character's storage, so the vault is searched, shown with +/// icons and merged across characters like any other storage; the newest copy wins, and a vault +/// belongs to the account, so every character sees the same one. /// -/// A server without the command is asked once after login; its "Unknown command" reply is eaten -/// and the plugin stays quiet. A vault the server says is not ready yet is asked again a few -/// times, and is never recorded as empty. +/// A server without the command (Aelrynth without the mod, or a world wrongly taken for Aelrynth) +/// is asked once after login; its "Unknown command" reply is eaten and the feed stays quiet. A +/// vault the server says is not ready yet is asked again a few times, and is never recorded as empty. /// -/// Threads: may run on AC's thread (it only queues); everything else runs -/// on the plugin tick. +/// Threads: only queues; everything else runs on the plugin tick. +/// Pure: RynthServerPack.Tests covers it. /// internal sealed class VaultFeed { @@ -33,6 +36,8 @@ internal sealed class VaultFeed public const string Prefix = "~ael1 "; public const string Label = "Account vault"; public const string VaultName = "Aelrynth vault"; + /// After login, before the first /mule-data; then every . + public const long FirstAskMs = 8_000, RefreshMs = 10 * 60_000; public enum State { Idle, Asking, Unsupported, Waiting } @@ -47,17 +52,17 @@ internal sealed class VaultFeed private volatile bool _expecting; private int _readyTries; private long _retryAtMs; - private readonly List _pages = new(); + private readonly List _pages = new(); private bool _changed; public VaultFeed(Func send) => _send = send; public State Status { get; private set; } = State.Idle; /// The vault once a full read finished (null until then). - public StorageRecord? Record { get; private set; } + public StorageFeedRecord? Record { get; private set; } public int Max { get; private set; } - /// For /ginv status. + /// For /rserver info. public string Describe() => Status switch { State.Unsupported => "no vault on this server", @@ -69,12 +74,16 @@ internal sealed class VaultFeed /// True once after was replaced. public bool TakeChanged() { bool c = _changed; _changed = false; return c; } + /// Login and logout: a fresh read (the record from before is forgotten). public void Reset() { Status = State.Idle; _expecting = false; _pages.Clear(); _readyTries = 0; + Record = null; + _changed = false; + Max = 0; while (_lines.TryDequeue(out _)) { } } @@ -142,7 +151,7 @@ internal sealed class VaultFeed if (Status == State.Waiting && nowMs >= _retryAtMs) SendPage(nowMs, 1); else if (Status == State.Asking && nowMs - _sentAtMs > AnswerWindowMs) { - // Nothing came back: a server without the mod, or a lost line. The next /ginv vault retries. + // Nothing came back: a server without the mod, or a lost line. The next refresh retries. _expecting = false; Status = State.Idle; _pages.Clear(); @@ -190,15 +199,7 @@ internal sealed class VaultFeed { Status = State.Waiting; _retryAtMs = nowMs + RetryReadyMs; _pages.Clear(); return; } - Record = new StorageRecord - { - Id = VaultId(account), - Name = VaultName, - Label = Label, - Cell = 0, - SeenUtc = DateTime.UtcNow, - Items = new List(_pages), - }; + Record = new StorageFeedRecord(VaultId(account), VaultName, Label, new List(_pages)); _pages.Clear(); _changed = true; Status = State.Idle; @@ -210,29 +211,15 @@ internal sealed class VaultFeed } } - private static ItemRecord Item(JsonElement e) - { - var it = new ItemRecord - { - Id = UInt(e, "o"), - Wcid = UInt(e, "w"), - Name = Str(e, "n"), - Icon = UInt(e, "i"), - Underlay = UInt(e, "u"), - Overlay = UInt(e, "v"), - Stack = Math.Max(1, Int(e, "s", 1)), - MaxStack = Int(e, "m", 0), - ItemType = UInt(e, "y"), - Place = ItemPlace.Storage, - }; - it.Category = ItemCategory.FromItemType(it.ItemType); - return it; - } + private static StorageFeedItem Item(JsonElement e) => new( + UInt(e, "o"), UInt(e, "w"), Str(e, "n"), UInt(e, "i"), UInt(e, "u"), UInt(e, "v"), + Math.Max(1, Int(e, "s", 1)), Int(e, "m", 0), UInt(e, "y")); /// /// A stand-in container id for the account's vault. Storage is merged by (server, id) with the /// newest copy winning, so the same id on every character of the account shows ONE vault. It is - /// in the top of the id space, where no object the client has seen lives. + /// in the top of the id space, where no object the client has seen lives (StorageFeed.IsStandInId). + /// The same formula as RynthInventory used, so vaults saved before the move are replaced, not doubled. /// public static uint VaultId(string account) { diff --git a/Plugins/RynthCore.Plugin.RynthAelrynth/AelrynthPlugin.cs b/Plugins/RynthCore.Plugin.RynthAelrynth/AelrynthPlugin.cs new file mode 100644 index 0000000..6f8447c --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAelrynth/AelrynthPlugin.cs @@ -0,0 +1,127 @@ +// AelrynthPlugin.cs - RynthAelrynth's own features, through the shared server plugin's hooks +// (Plugins/Shared/ServerPack/ServerPackPlugin.cs). Aelrynth-specific code that RynthOracle and +// RynthInventory used to carry lives here since 2026-10-20 (Aelrynth/AelrynthFeature.cs says what), +// so a player without RynthAelrynth gets none of it, and no other server is asked for a vault. +using System; +using System.IO; +using RynthCore.Plugin.RynthAelrynth; +using RynthCore.Plugin.Shared; + +namespace RynthCore.Plugin.ServerPack; + +public sealed partial class ServerPackPlugin +{ + private readonly AelrynthFeature _aelrynth = new(); + private AelrynthPages? _aelrynthPages; + // The last vault read, until RynthInventory took it (it may load after the read). + private StorageFeedRecord? _vaultToHandOff; + private long _nextVaultHandOffMs; + private const long VaultHandOffRetryMs = 30_000; + + /// Where RynthOracle kept the reply-hiding choice before it moved here (read once). + internal static string OracleSettingsPath => Path.Combine( + Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "RynthCore", "rynthoracle.json"); + + partial void ServerPages(System.Collections.Generic.List pages) + { + _aelrynthPages = new AelrynthPages(_aelrynth, () => Active, RunOnTick, Send, + text => ChatLine($"[{RynthPluginInfo.Name}] {text}"), SaveAelrynthSettings); + pages.AddRange(_aelrynthPages.Pages()); + } + + partial void ServerCommandVerbs(System.Collections.Generic.List verbs) => verbs.Add("vault"); + + partial void ServerInitialize() + { + _aelrynth.SendCommand = Send; + if (AelrynthFeature.Migrate(Settings, OracleSettingsPath)) + LogTagged("Took over RynthOracle's reply-hiding choice from rynthoracle.json."); + lock (_aelrynth.Gate) _aelrynth.LoadSettings(Settings); + } + + private void SaveAelrynthSettings() + { + lock (_aelrynth.Gate) _aelrynth.SaveSettings(Settings); + } + + partial void ServerLoginComplete() + { + lock (_aelrynth.Gate) _aelrynth.Reset(); + _vaultToHandOff = null; + _aelrynthPages?.Reset(); + } + + partial void ServerLogout() + { + lock (_aelrynth.Gate) _aelrynth.Reset(); + _vaultToHandOff = null; + _aelrynthPages?.Reset(); + } + + partial void ServerShutdown() => SaveAelrynthSettings(); + + partial void ServerChatText(string text, int chatType, ref bool eat) + { + if (!Active) return; + bool hide; + lock (_aelrynth.Gate) hide = _aelrynth.OnChatLine(text, chatType, Environment.TickCount64); + if (hide) eat = true; + } + + partial void ServerTick(bool active) + { + if (!active || !Host.HasInvokeChatParser) return; + long now = Environment.TickCount64; + uint player = Host.HasGetPlayerId ? Host.GetPlayerId() : 0; + if (player == 0) return; // the vault belongs to the account; wait for the character + string account = Host.TryGetAccountName(out string a) && a.Trim().Length > 0 ? a.Trim() : "unknown"; + StorageFeedRecord? read; + lock (_aelrynth.Gate) read = _aelrynth.VaultTick(now, account); + if (read != null) { _vaultToHandOff = read; _nextVaultHandOffMs = 0; } + if (_vaultToHandOff != null && now >= _nextVaultHandOffMs) HandOffVault(now); + } + + /// + /// The vault to RynthInventory (StorageFeed), which files it with the character's storage. Kept and + /// offered again now and then while RynthInventory isn't there to take it. + /// + private void HandOffVault(long now) + { + StorageFeedRecord? vault = _vaultToHandOff; + if (vault == null) return; + bool taken = Host.HasSendPluginCommand + && Host.SendPluginCommand(StorageFeed.TargetPlugin, StorageFeed.Action, StorageFeed.ToJson(vault)); + string note = taken + ? $"{vault.Items.Count} item(s) handed to RynthInventory at {DateTime.Now:HH:mm}" + : "RynthInventory isn't loaded (or is too old), so the vault isn't in Global Inventory"; + lock (_aelrynth.Gate) _aelrynth.VaultHandOff = note; + if (taken) _vaultToHandOff = null; + else _nextVaultHandOffMs = now + VaultHandOffRetryMs; + } + + partial void ServerChatCommand(string[] parts, ref bool handled) + { + if (parts.Length < 2 || !parts[1].Equals("vault", StringComparison.OrdinalIgnoreCase)) return; + handled = true; + string tag = $"[{RynthPluginInfo.Name}] "; + if (!Active) { ChatLine(tag + "The account vault is Aelrynth's; RynthCore doesn't see this world as Aelrynth."); return; } + bool asked; + string state; + lock (_aelrynth.Gate) + { + asked = _aelrynth.VaultAskNow(Environment.TickCount64); + state = _aelrynth.Vault.Describe(); + } + ChatLine(tag + (asked ? "Reading the account vault (/mule-data)..." : "The vault is already being read: " + state)); + } + + partial void ServerInfoLines(Action line) + { + lock (_aelrynth.Gate) + { + string handOff = _aelrynth.VaultHandOff.Length > 0 ? "; " + _aelrynth.VaultHandOff : ""; + line("Account vault: " + _aelrynth.Vault.Describe() + handOff + " (/rserver vault reads it now)."); + line("Own replies (/top, /trial) " + (_aelrynth.HideOwnReplies ? "hidden" : "shown") + "."); + } + } +} diff --git a/Plugins/RynthCore.Plugin.RynthAelrynth/RynthCore.Plugin.RynthAelrynth.csproj b/Plugins/RynthCore.Plugin.RynthAelrynth/RynthCore.Plugin.RynthAelrynth.csproj index 630a200..389e70b 100644 --- a/Plugins/RynthCore.Plugin.RynthAelrynth/RynthCore.Plugin.RynthAelrynth.csproj +++ b/Plugins/RynthCore.Plugin.RynthAelrynth/RynthCore.Plugin.RynthAelrynth.csproj @@ -2,17 +2,26 @@ + The build is shared (..\Shared\ServerPack\ServerPlugin.props); ServerData.cs holds what is known. + Aelrynth's own features (AelrynthPlugin.cs, Aelrynth\) came from RynthOracle and RynthInventory on + 2026-10-20: the /top leaderboards and /trial records (a page of the Mini Remote's Server section), + and the account vault (/mule-data), handed to RynthInventory's Global Inventory. --> RynthCore.Plugin.RynthAelrynth - 0.1.0 + 0.2.0 aelrynth Aelrynth aelrynth.com Aelrynth*|Aeshnidae* - Aelrynth only: the server card (its mods, links, account setup) in the Mini Remote. + Aelrynth only: the server card (its mods, links, account setup), Aelrynth's leaderboards and Trials records in the Mini Remote, and the account vault in Global Inventory. + + + + + + diff --git a/Plugins/RynthCore.Plugin.RynthAelrynth/ServerData.cs b/Plugins/RynthCore.Plugin.RynthAelrynth/ServerData.cs index ae444f2..ceda2cc 100644 --- a/Plugins/RynthCore.Plugin.RynthAelrynth/ServerData.cs +++ b/Plugins/RynthCore.Plugin.RynthAelrynth/ServerData.cs @@ -16,8 +16,9 @@ internal static class ServerData { "Bank mod: Radiance and Luminance banking (RynthCore reads its totals).", "Skill Mastery mod (RynthCore shows mastery progress).", - "Account vault for mules (RynthCore reads its contents).", + "Account vault for mules (RynthCore reads its contents; RynthAelrynth puts it in Global Inventory, /rserver vault).", "RynthOracle has an Aelrynth quest pack (quests.aelrynth.csv).", + "RynthAelrynth's Leaderboards page (Server section, or /rserver): the /top boards and /trial dungeon records.", "The world was named Aeshnidae before; both names count.", }, Website = "https://aelrynth.com", diff --git a/Plugins/RynthCore.Plugin.RynthAi/Combat/BuffManager.cs b/Plugins/RynthCore.Plugin.RynthAi/Combat/BuffManager.cs index c86f1c4..22d65b6 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Combat/BuffManager.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Combat/BuffManager.cs @@ -1987,10 +1987,15 @@ public partial class BuffManager : IDisposable // for the wand and back (slow, and the 10-06 stalls began at those switches), so a stamina // potion listed in Consumables goes before it. A potion drunk under 2.5 s ago: no Revitalize // on top of it. In Magic stance (a caster) Revitalize stays first. + int sentBefore = _vitalActionsSent; if (curStamPct < stamThreshold && AttemptStaminaChain()) { _isRechargingStamina = true; - if (_restamRun) _restamRunCasts++; + // Only a cast, kit or potion actually sent counts toward the run's cap. The chain also + // answers "handled" while it waits for the last cast to finish, and counting those ticks + // ended every run after one Robustification (2.3 s of waiting = the 4-cast cap): Re-stam To + // 90 stopped near 60 (Drakkon, 2026-10-20). + if (_restamRun && _vitalActionsSent != sentBefore) _restamRunCasts++; return true; } @@ -2077,11 +2082,21 @@ public partial class BuffManager : IDisposable private bool _restamRun; private int _restamRunCasts; internal const int RestamRunMaxCasts = 4; + // Vital casts, kits and potions actually sent (a wait for the last one isn't one). + private int _vitalActionsSent; /// The stamina % to recharge under now (see the fields above). internal static int StaminaLine(bool inCombat, int stamPct, LegacyUiSettings s, ref bool run, ref int casts) { - if (!inCombat) { run = false; return s.TopOffStam; } + if (!inCombat) + { + // A recharge started in the fight finishes to Re-stam To when the fight ends, instead of + // dropping to the top-off line (Top Stam can be lower than Re-stam To). + if (run && s.RestamTo > s.RestamAt && stamPct < s.RestamTo && casts < RestamRunMaxCasts) + return Math.Max(s.RestamTo, s.TopOffStam); + run = false; + return s.TopOffStam; + } if (s.RestamTo <= s.RestamAt) { run = false; return s.RestamAt; } if (stamPct < s.RestamAt) { @@ -2272,6 +2287,7 @@ public partial class BuffManager : IDisposable return VitalNo($"the client refused the cast (spell {spellId})"); } sent = true; + _vitalActionsSent++; _lastVitalCastAt = DateTime.Now; if (IsRecoveryVital(what)) NoteRecoveryAttempt(); NoteCastIssued(spellId); @@ -2329,6 +2345,7 @@ public partial class BuffManager : IDisposable _host.Log($"[RynthAi] Vitals: drinking {rule.Name} ({rule.Type})" + (potion.Id != rule.Id ? " from a new stack." : ".")); _host.UseFor(unchecked((uint)potion.Id), "Buff", $"vitals: drink {rule.Name} ({rule.Type}) from the Items list"); _lastPotionAt = DateTime.Now; + _vitalActionsSent++; _lastCastAttempt = DateTime.Now; if (IsHealthPotionType(types)) NoteHealSent(rule.Name); return true; @@ -2345,6 +2362,7 @@ public partial class BuffManager : IDisposable _host.Log($"[RynthAi] Vitals: using {wo.Name} from the pack ({kind})."); _host.UseFor(unchecked((uint)wo.Id), "Buff", $"vitals: {kind} potion from the pack"); _lastPotionAt = DateTime.Now; + _vitalActionsSent++; _lastCastAttempt = DateTime.Now; if (IsHealthPotionType(types)) NoteHealSent(wo.Name ?? "health potion"); return true; @@ -2528,6 +2546,7 @@ public partial class BuffManager : IDisposable if (HeldCastBlocksItemUse(out _)) return false; _host.Log($"[RynthAi] Vitals: using {kit.Name} from the pack."); _host.UseOnFor(unchecked((uint)kit.Id), playerId, "Buff", "vitals: stamina kit on yourself"); + _vitalActionsSent++; _lastCastAttempt = DateTime.Now; MarkKitUsed(stamina: true); return true; diff --git a/Plugins/RynthCore.Plugin.RynthAi/Combat/CombatManager.cs b/Plugins/RynthCore.Plugin.RynthAi/Combat/CombatManager.cs index 0fe8f80..27adb2b 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Combat/CombatManager.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Combat/CombatManager.cs @@ -1147,6 +1147,7 @@ public partial class CombatManager : IDisposable _waitingForDebuffResult = false; _pendingDebuffTargetId = 0; } + _debuffs.Forget(id); } public void SetPlayerId(uint playerId) { @@ -1181,14 +1182,13 @@ public partial class CombatManager : IDisposable private uint _playerId; private MonsterMatchEvaluator? _monsterMatchEval; - private readonly HashSet _confirmedDebuffs = new(); - // Failed tries (fizzle/resist/refusal) per "{target}_{debuff}", cleared with _confirmedDebuffs. - private readonly Dictionary _debuffFailures = new(); - private const int DebuffMaxFailures = 3; + // The rule's debuffs per target: landed ones renewed before they wear off, failed tries counted. + private readonly DebuffTimers _debuffs = new(); private int _lastDebuffTargetId = 0; private string? _pendingDebuffKey = null; private int _pendingDebuffTargetId = 0; + private int _pendingDebuffSpellId = 0; private int _pendingDebuffTier = 0; private bool _waitingForDebuffResult = false; private DateTime _pendingDebuffCastTime = DateTime.MinValue; @@ -1749,8 +1749,7 @@ public partial class CombatManager : IDisposable // "ou cast …". IndexOf matches both "You cast" and "ou cast". if (text.IndexOf("ou cast ", StringComparison.OrdinalIgnoreCase) >= 0) { - string key = $"{_pendingDebuffTargetId}_{_pendingDebuffKey}"; - _confirmedDebuffs.Add(key); + NoteDebuffLanded(); _waitingForDebuffResult = false; _lastSpellCast = DateTime.Now; return; @@ -1780,19 +1779,15 @@ public partial class CombatManager : IDisposable /// /// A debuff didn't land (fizzle, resist, refusal). Recast it, but only up to - /// DebuffMaxFailures times per target: a mob the character's Creature Magic can't land + /// DebuffTimers.MaxFailures times per target: a mob the character's Creature Magic can't land /// on used to get the same debuff forever, and the bot never reached its attack spells /// (debuffs don't feed the no-damage blacklist either). /// private void NoteDebuffFailed(string what) { - string key = $"{_pendingDebuffTargetId}_{_pendingDebuffKey}"; - _debuffFailures.TryGetValue(key, out int n); - _debuffFailures[key] = ++n; - if (n >= DebuffMaxFailures) + if (_debuffs.Failed(_pendingDebuffTargetId, _pendingDebuffKey ?? "")) // skip it for this target { - _confirmedDebuffs.Add(key); // skip it for this target - _host.WriteToChat($"[RynthAi] {what}: {_pendingDebuffKey} — {n} tries on this target, skipping it", 2); + _host.WriteToChat($"[RynthAi] {what}: {_pendingDebuffKey} — {DebuffTimers.MaxFailures} tries on this target, skipping it", 2); } else { @@ -1802,6 +1797,20 @@ public partial class CombatManager : IDisposable _lastSpellCast = DateTime.Now; } + /// + /// The pending debuff landed (or its result never came, taken as landed): timed by the + /// spell's duration so it is cast again just before it wears off; a spell with no duration + /// is cast once per target, as all of them were before 2026-10-20. Archmage's Endurance + /// isn't counted, so with it a renewal comes early rather than late. + /// + private void NoteDebuffLanded() + { + int seconds = SpellDatabase.DurationSeconds(_pendingDebuffSpellId); + _debuffs.Landed(_pendingDebuffTargetId, _pendingDebuffKey ?? "", seconds, DateTime.Now); + if (seconds > 0) + _host.Log($"[CombatCast] debuff {_pendingDebuffKey} on 0x{(uint)_pendingDebuffTargetId:X8}: lasts {seconds} s, renewed in {seconds - DebuffTimers.Lead(seconds):0} s"); + } + // ── Position re-sync after casts that land nothing (2026-10-12) ────────────────────────── // Flight 63260: after a stray stop burst rode with a cast, every projectile cast (Corruption // VII, Nether Arc VII) was answered - components burned, UseDone - and nothing landed, until a @@ -1885,104 +1894,80 @@ public partial class CombatManager : IDisposable /// Test seam: one judged magic cast with no damage. internal void MagicMissForTest(int tid) => NoteMagicMissForResync(tid); - // ── Empyrean Handler lethal-ring evade (chat-triggered back-jump) ───────── - // ACECustom Handler emote: "The handler briefly channels infused Empyrean hatred - // to release a lethal ring." The ring can't be melee-evaded — if the character is - // inside its cast radius they die. On that line, when still in range of a Handler, - // cancel the current swing/cast and back-jump away, then resume combat (target kept). - private const string HandlerRingChannelHint = "channels infused Empyrean hatred to release a lethal ring"; - private const string HandlerRingChannelStart = "The handler briefly channels"; - private const string HandlerNameHint = "Empyrean Handler"; - /// Yards: Handler lethal ring is treated as at least this wide (RingRange when larger). - internal const double HandlerRingDangerYards = 12.0; - /// Back-jump charge (ms) — run-back + jump must clear ~ring radius. - private const int HandlerRingJumpHoldMs = 750; - private const double HandlerRingEvadeCooldownMs = 4_000; + // ── Back away from a danger point (RynthAi.Hub BackAwayFrom) ────────────── + // A generic "get out of this radius now", asked for by a server plugin that knows its server's + // dangers: face the object, run-back jump away from it (Jumper "xs"; facing away and jumping back + // would leap into it), hold attacks until the jump settles, then re-engage the same target. + // RynthILT asks for it when Infinite Leaftide's Empyrean Handler channels its lethal ring (the + // detection and its setting moved there 2026-10-20; Silentkelpie's PR 12). Only while the macro is + // running with combat on: an idle character, or one driven by hand or by a meta, never has the + // keyboard taken. - private DateTime _handlerRingEvadeAt = DateTime.MinValue; - private DateTime _handlerRingEvadeUntil = DateTime.MinValue; - private int _handlerRingEvadeId; - private bool _handlerRingJumpStarted; + /// BackAwayFrom results (RynthAi.Hub BackAwayFrom passes them on as they are). + internal const int BackAwayStarted = 1, BackAwayNotNow = 0, BackAwayOutside = 2, BackAwayUnknownObject = 3, BackAwayJumpRefused = -1; + + /// The jump charge range a caller may ask for (ms). + internal const int BackAwayMinHoldMs = 100, BackAwayMaxHoldMs = 3000; + + /// After the jump: turn, land and one re-engage tick before attacks resume (ms). + private const int BackAwaySettleMs = 2_200; + + private DateTime _backAwayUntil = DateTime.MinValue; + private bool _backAwayJumpStarted; /// - /// Plugin wires this to Jumper.Start("xs", faceHeading, ms) — face the Handler - /// then run-back jump (x+s) so the body moves away. Returns false if the jumper refused. + /// Plugin wires this to Jumper.Start("xs", faceHeading, ms) — face the danger, then + /// run-back jump (x+s) so the body moves away. Returns false if the jumper refused. /// public Func? RequestBackJump { get; set; } /// True while the wired jumper is mid-turn / charge / settle. public Func? JumpBusy { get; set; } - /// True while a Handler-ring evade is holding combat (jump or settle). - public bool RingEvadeActive => - _handlerRingEvadeUntil != DateTime.MinValue && DateTime.Now < _handlerRingEvadeUntil; + /// True while a back-away is holding combat (jump or settle). + public bool BackAwayActive => + _backAwayUntil != DateTime.MinValue && DateTime.Now < _backAwayUntil; /// - /// Chat line from RynthAiPlugin.OnChatWindowText. Starts a back-jump evade when the - /// Handler channels its lethal ring and the character is still inside ring range. + /// Backs the character away from when it is within the danger radius: + /// , or Ring Range when that is larger (anything a ring reaches). + /// is the jump's charge (clamped to 100-3000 ms). Cancels the swing or + /// cast in progress, keeps the target. is only for the log. Returns a + /// BackAway* result: started, not now (macro stopped, combat off, already backing away), outside + /// the radius, unknown object (no position), or the jump didn't start. Pump thread. /// - public void HandleChatForRingEvade(string? text, int chatType = -1) + public int BackAwayFrom(int objectId, double radiusYards, int holdMs, string reason) { - if (string.IsNullOrEmpty(text)) return; - // Gate: only while the macro is running with combat on, and only if the setting allows it. - // Otherwise a Handler line heard while the character is idle or being driven by hand (or by a - // meta) would take over the keyboard for a back-jump. - if (!_settings.HandlerRingEvade || !_settings.IsMacroRunning || !_settings.EnableCombat) return; - // Handler channel is an Emote (0x0C). ChatSource.IsPlayerAuthored treats Emote as - // player speech, which would skip every real Handler line — anchor on the unique - // phrase starting the line instead (player copies are "Name says, \"...\"). - bool anchored = - RynthCore.Plugin.Shared.ChatSource.StartsWithMarker(text, HandlerRingChannelStart, StringComparison.OrdinalIgnoreCase) - || (RynthCore.Plugin.Shared.ChatSource.StartsWithMarker(text, "The handler", StringComparison.OrdinalIgnoreCase) - && text.IndexOf(HandlerRingChannelHint, StringComparison.OrdinalIgnoreCase) >= 0); - if (!anchored) + string why = string.IsNullOrWhiteSpace(reason) ? "a server plugin's request" : reason.Trim(); + if (!_settings.IsMacroRunning || !_settings.EnableCombat) return BackAwayNotNow; + if (BackAwayActive) return BackAwayNotNow; + uint me = _host.GetPlayerId(); + if (me == 0 || objectId == 0) return BackAwayUnknownObject; + double dist = _worldFilter.Distance(unchecked((int)me), objectId); + if (dist < 0 || dist == double.MaxValue || double.IsNaN(dist)) { - // Mid-line only when the type is clearly not player speech (some clients strip "The "). - if (chatType is RynthCore.Plugin.Shared.ChatSource.Speech - or RynthCore.Plugin.Shared.ChatSource.Tell - or RynthCore.Plugin.Shared.ChatSource.OutgoingTell - or RynthCore.Plugin.Shared.ChatSource.Channel - or RynthCore.Plugin.Shared.ChatSource.ChannelSend - or RynthCore.Plugin.Shared.ChatSource.Allegiance - or RynthCore.Plugin.Shared.ChatSource.Fellowship) - return; - if (text.IndexOf(HandlerRingChannelHint, StringComparison.OrdinalIgnoreCase) < 0) return; - if (text.IndexOf(" says,", StringComparison.OrdinalIgnoreCase) >= 0 - || text.IndexOf(" tells you,", StringComparison.OrdinalIgnoreCase) >= 0) - return; + _host.Log($"[CombatEvade] Back away ({why}): 0x{objectId:X8} has no position - no jump."); + return BackAwayUnknownObject; } - - DateTime now = DateTime.Now; - if (_handlerRingEvadeAt != DateTime.MinValue - && (now - _handlerRingEvadeAt).TotalMilliseconds < HandlerRingEvadeCooldownMs) - return; - - if (!TryFindHandlerForRingEvade(out int handlerId, out double dist, out string name)) - { - _host.Log("[CombatEvade] Handler lethal-ring channel heard, but no Empyrean Handler is nearby — no jump."); - return; - } - - double danger = Math.Max(HandlerRingDangerYards, Math.Max(1, _settings.RingRange)); + string name = _worldFilter[objectId]?.Name ?? $"0x{objectId:X8}"; + double danger = Math.Max(double.IsNaN(radiusYards) ? 0 : radiusYards, Math.Max(1, _settings.RingRange)); if (dist > danger) { - _host.Log($"[CombatEvade] Handler lethal-ring channel; '{name}' at {dist:0.0} m (outside {danger:0.#} m) — staying put."); - return; + _host.Log($"[CombatEvade] Back away ({why}): '{name}' at {dist:0.0} m (outside {danger:0.#} m) - staying put."); + return BackAwayOutside; } - // Face the Handler, then Jumper "xs" (back + run) moves the body away from it. - // Facing away + back-jump would leap into the ring. - float faceHandler = 0f; - if (TryGetHeadingTo(handlerId, out double toHandler, out _)) - faceHandler = (float)(toHandler % 360.0); - else if (_host.TryGetPlayerHeading(out float curr)) - faceHandler = curr; + // Face the danger, then Jumper "xs" (back + run) moves the body away from it. + float face = 0f; + if (TryGetHeadingTo(objectId, out double toIt, out _)) + face = (float)(toIt % 360.0); + else if (PlayerCompass.TryGet(_host, out float curr)) + face = curr; - _handlerRingEvadeAt = now; - _handlerRingEvadeId = handlerId; - _handlerRingJumpStarted = false; + int hold = Math.Clamp(holdMs, BackAwayMinHoldMs, BackAwayMaxHoldMs); + _backAwayJumpStarted = false; // Hold combat long enough for turn + charge + land + one re-engage tick. - _handlerRingEvadeUntil = now.AddMilliseconds(HandlerRingJumpHoldMs + 2_200); + _backAwayUntil = DateTime.Now.AddMilliseconds(hold + BackAwaySettleMs); // Stop the bound melee/missile attack so the jump isn't eaten by the swing servo. try @@ -1992,100 +1977,50 @@ public partial class CombatManager : IDisposable } catch { } - bool started = RequestBackJump?.Invoke(faceHandler, HandlerRingJumpHoldMs) == true; - if (started) + if (RequestBackJump?.Invoke(face, hold) == true) { - _handlerRingJumpStarted = true; - _host.Log($"[CombatEvade] Empyrean Handler lethal ring — back-jump away from '{name}' " + - $"at {dist:0.0} m (danger {danger:0.#} m), face {faceHandler:0}° then xs."); - } - else - { - _handlerRingEvadeUntil = DateTime.MinValue; - _handlerRingEvadeId = 0; - _host.Log("[CombatEvade] Empyrean Handler lethal ring heard in range, but the back-jump did not start."); + _backAwayJumpStarted = true; + _host.Log($"[CombatEvade] Back away ({why}): back-jump away from '{name}' " + + $"at {dist:0.0} m (danger {danger:0.#} m), face {face:0} then xs."); + return BackAwayStarted; } + _backAwayUntil = DateTime.MinValue; + _host.Log($"[CombatEvade] Back away ({why}): '{name}' in range, but the back-jump did not start."); + return BackAwayJumpRefused; } /// - /// Holds Think from attacking while the Handler-ring back-jump runs. Keeps the target - /// so combat re-engages as soon as the jumper settles. + /// Holds Think from attacking while a back-away jump runs. Keeps the target so combat + /// re-engages as soon as the jumper settles. /// - private bool TickRingEvade() + private bool TickBackAway() { - if (_handlerRingEvadeUntil == DateTime.MinValue) return false; + if (_backAwayUntil == DateTime.MinValue) return false; DateTime now = DateTime.Now; bool jumperBusy = JumpBusy?.Invoke() == true; // Jump never started / failed: clear early. - if (_handlerRingJumpStarted && !jumperBusy && now >= _handlerRingEvadeUntil) + if (_backAwayJumpStarted && !jumperBusy && now >= _backAwayUntil) { - _handlerRingEvadeUntil = DateTime.MinValue; - _handlerRingEvadeId = 0; - _handlerRingJumpStarted = false; - _host.Log("[CombatEvade] Handler ring evade done — re-engaging."); + _backAwayUntil = DateTime.MinValue; + _backAwayJumpStarted = false; + _host.Log("[CombatEvade] Back away done - re-engaging."); return false; } - if (jumperBusy || now < _handlerRingEvadeUntil) + if (jumperBusy || now < _backAwayUntil) { - LastCombatSkipReason = "handler-ring-evade"; + LastCombatSkipReason = "back-away"; _tickWait = CombatLatencyTracker.Wait.Other; return true; } - _handlerRingEvadeUntil = DateTime.MinValue; - _handlerRingEvadeId = 0; - _handlerRingJumpStarted = false; - _host.Log("[CombatEvade] Handler ring evade done — re-engaging."); + _backAwayUntil = DateTime.MinValue; + _backAwayJumpStarted = false; + _host.Log("[CombatEvade] Back away done - re-engaging."); return false; } - /// Nearest Empyrean Handler (active target preferred when it is one). - private bool TryFindHandlerForRingEvade(out int handlerId, out double dist, out string name) - { - handlerId = 0; dist = double.MaxValue; name = ""; - int me = _host.GetPlayerId() == 0 ? 0 : (int)_host.GetPlayerId(); - if (me == 0) return false; - - int bestId = 0; - double bestDist = double.MaxValue; - string bestName = ""; - - void Consider(int id, string? nm) - { - if (id == 0 || string.IsNullOrEmpty(nm)) return; - if (nm.IndexOf(HandlerNameHint, StringComparison.OrdinalIgnoreCase) < 0) return; - double d = _worldFilter.Distance(me, id); - if (d < 0 || d >= bestDist) return; - bestDist = d; bestId = id; bestName = nm; - } - - if (activeTargetId != 0) - Consider(activeTargetId, _worldFilter[activeTargetId]?.Name); - - foreach (var s in _scannedTargets) - Consider(s.Id, s.Name); - - // Landscape fallback when the scan hasn't listed it yet (channel can land mid-approach). - if (bestId == 0) - { - try - { - foreach (WorldObject wo in _worldFilter.GetLandscape()) - { - if ((int)wo.ObjectClass != (int)AcObjectClass.Monster) continue; - Consider(wo.Id, wo.Name); - } - } - catch { } - } - - if (bestId == 0) return false; - handlerId = bestId; dist = bestDist; name = bestName; - return true; - } - public void ReportDamageOnTarget(int targetId) { _magicMissesSinceHit = 0; // something we cast landed: the server's position is fine @@ -3098,9 +3033,9 @@ public partial class CombatManager : IDisposable return true; } - // Empyrean Handler lethal-ring back-jump: hold casts/swings until the jump settles, - // then fall through and re-engage the same target. - if (TickRingEvade()) + // A back-away (a server plugin's danger, e.g. RynthILT's Empyrean Handler ring): hold + // casts/swings until the jump settles, then fall through and re-engage the same target. + if (TickBackAway()) return true; double acDistanceLimit = _settings.MonsterRange; @@ -6522,7 +6457,7 @@ public partial class CombatManager : IDisposable { if ((DateTime.Now - _pendingDebuffCastTime).TotalMilliseconds > DEBUFF_RESULT_TIMEOUT_MS) { - _confirmedDebuffs.Add($"{_pendingDebuffTargetId}_{_pendingDebuffKey}"); + NoteDebuffLanded(); _waitingForDebuffResult = false; } else @@ -6534,8 +6469,7 @@ public partial class CombatManager : IDisposable if (activeTargetId != _lastDebuffTargetId) { - _confirmedDebuffs.Clear(); - _debuffFailures.Clear(); + _debuffs.NewTarget(DateTime.Now); _lastDebuffTargetId = activeTargetId; } @@ -6545,10 +6479,11 @@ public partial class CombatManager : IDisposable if (rule != null) { var pendingDebuffs = BuildDebuffList(rule, element); + DateTime now = DateTime.Now; foreach (var debuffKey in pendingDebuffs) { - string key = $"{activeTargetId}_{debuffKey}"; - if (_confirmedDebuffs.Contains(key)) continue; + if (_debuffs.IsOn(activeTargetId, debuffKey, now)) continue; + bool renewal = _debuffs.RenewAt(activeTargetId, debuffKey) != null; int spellId = 0; int castTier = 0; @@ -6571,10 +6506,11 @@ public partial class CombatManager : IDisposable _lastCastWasRing = false; _pendingDebuffKey = debuffKey; _pendingDebuffTargetId = activeTargetId; + _pendingDebuffSpellId = spellId; _pendingDebuffTier = castTier; _waitingForDebuffResult = true; _pendingDebuffCastTime = DateTime.Now; - _host.WriteToChat($"[RynthAi] Casting: {debuffKey} (T{castTier}) on {target.Name}", 5); + _host.WriteToChat($"[RynthAi] {(renewal ? "Renewing" : "Casting")}: {debuffKey} (T{castTier}) on {target.Name}", 5); } catch { } return; @@ -6768,8 +6704,9 @@ public partial class CombatManager : IDisposable private bool HasPendingDebuffs(MonsterRule rule, string element) { if (rule == null) return false; + DateTime now = DateTime.Now; foreach (var debuffKey in BuildDebuffList(rule, element)) - if (!_confirmedDebuffs.Contains($"{activeTargetId}_{debuffKey}")) return true; + if (!_debuffs.IsOn(activeTargetId, debuffKey, now)) return true; return false; } diff --git a/Plugins/RynthCore.Plugin.RynthAi/Combat/DebuffTimers.cs b/Plugins/RynthCore.Plugin.RynthAi/Combat/DebuffTimers.cs new file mode 100644 index 0000000..7a7cc1d --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAi/Combat/DebuffTimers.cs @@ -0,0 +1,103 @@ +using System; +using System.Collections.Generic; + +namespace RynthCore.Plugin.RynthAi; + +/// +/// Which of a monster rule's debuffs (Imperil, the vulns, Fester, Yield, Broadside, Gravity +/// Well, custom ones) are on which target, and when each is due again. A landed debuff with a +/// known duration is renewed a little before it wears off (2026-10-20: they were cast once +/// per target, so a long fight with a high-HP monster lost them after 4-5 minutes). One with +/// no known duration, or given up on after fizzles or resists, is +/// not cast at that target again until the fight moves to another one. +/// Timers live across target switches (a monster fought again keeps them) and go when they +/// fall due or the monster does. CombatManager's thread only; no host calls. +/// +internal sealed class DebuffTimers +{ + public const int MaxFailures = 3; + /// Renew this long before the end, at most (a fifth of a short debuff's length). + public const double MaxLeadSeconds = 5.0; + private const int MaxTimers = 256; + + private readonly Dictionary<(int Target, string Key), DateTime> _renewAt = new(); + private readonly HashSet<(int Target, string Key)> _done = new(); + private readonly Dictionary<(int Target, string Key), int> _failures = new(); + + /// On the target and not due yet, or not to be cast at it again. + public bool IsOn(int target, string key, DateTime now) => + _done.Contains((target, key)) || (_renewAt.TryGetValue((target, key), out DateTime at) && now < at); + + /// When a landed debuff is due again; null when it has no timer. + public DateTime? RenewAt(int target, string key) => + _renewAt.TryGetValue((target, key), out DateTime at) ? at : null; + + /// + /// It landed (or no result line came back in time, taken as landed). With a duration it is + /// due again before it wears off; without one, never on this target. + /// + public void Landed(int target, string key, double durationSeconds, DateTime now) + { + _failures.Remove((target, key)); // a renewal gets its own tries + if (durationSeconds <= 0) + { + _done.Add((target, key)); + return; + } + if (_renewAt.Count >= MaxTimers && !_renewAt.ContainsKey((target, key))) Prune(now); + _renewAt[(target, key)] = now.AddSeconds(durationSeconds - Lead(durationSeconds)); + } + + /// How long before a debuff of this length runs out it is cast again. + public static double Lead(double durationSeconds) => Math.Min(MaxLeadSeconds, durationSeconds * 0.2); + + /// A fizzle, resist or refusal. True when that was the last try (given up on this target). + public bool Failed(int target, string key) + { + _failures.TryGetValue((target, key), out int n); + _failures[(target, key)] = ++n; + if (n < MaxFailures) return false; + _done.Add((target, key)); + return true; + } + + public int Failures(int target, string key) => _failures.TryGetValue((target, key), out int n) ? n : 0; + + /// The fight moved to another target: the once-only and given-up marks start over, timers stay. + public void NewTarget(DateTime now) + { + _done.Clear(); + _failures.Clear(); + Prune(now); + } + + /// The monster is gone (dead or out of view): its timers too. + public void Forget(int target) + { + if (_renewAt.Count == 0) return; + List<(int, string)>? drop = null; + foreach (var k in _renewAt.Keys) + if (k.Target == target) (drop ??= new()).Add(k); + if (drop != null) foreach (var k in drop) _renewAt.Remove(k); + } + + public int TimerCount => _renewAt.Count; + + private void Prune(DateTime now) + { + if (_renewAt.Count == 0) return; + List<(int, string)>? drop = null; + foreach (var kv in _renewAt) + if (kv.Value <= now) (drop ??= new()).Add(kv.Key); + if (drop != null) foreach (var k in drop) _renewAt.Remove(k); + // Still full of live timers (hundreds of monsters debuffed at once): drop the soonest due. + while (_renewAt.Count >= MaxTimers) + { + (int, string) soonest = default; + DateTime best = DateTime.MaxValue; + foreach (var kv in _renewAt) + if (kv.Value < best) { best = kv.Value; soonest = kv.Key; } + _renewAt.Remove(soonest); + } + } +} diff --git a/Plugins/RynthCore.Plugin.RynthAi/Combat/SpellDatabase.cs b/Plugins/RynthCore.Plugin.RynthAi/Combat/SpellDatabase.cs index 94eb121..bad5a23 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Combat/SpellDatabase.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Combat/SpellDatabase.cs @@ -13,6 +13,9 @@ public static class SpellDatabase // names ("Slithering Flames"), so a wall is found by its category and ranked by its power. private static readonly Dictionary _spellMeta = new(); private static readonly Dictionary> _idsByCategory = new(); + // How long an enchantment lasts, in seconds before Archmage's Endurance (column 6): the + // debuff renewal times landed debuffs by it (2026-10-20). Absent or 0: no timer. + private static readonly Dictionary _durations = new(); private static bool _loaded = false; private static readonly Dictionary _builtinSpells = new Dictionary @@ -45,6 +48,7 @@ public static class SpellDatabase _spellNames.Clear(); _spellMeta.Clear(); _idsByCategory.Clear(); + _durations.Clear(); _loaded = false; try @@ -76,6 +80,8 @@ public static class SpellDatabase _idsByCategory[category] = ids = new List(); ids.Add(spellId); } + if (columns.Length >= 6 && int.TryParse(columns[5].Trim(), out int seconds) && seconds > 0) + _durations[spellId] = seconds; } } @@ -137,6 +143,9 @@ public static class SpellDatabase return false; } + /// How long the spell's enchantment lasts in seconds (before Archmage's Endurance), 0 when it has none. + public static int DurationSeconds(int spellId) => _durations.TryGetValue(spellId, out int s) ? s : 0; + /// Every spell id of a category (ACE SpellCategory), in data order. public static IReadOnlyList IdsInCategory(int category) => _idsByCategory.TryGetValue(category, out List? ids) ? ids : Array.Empty(); diff --git a/Plugins/RynthCore.Plugin.RynthAi/Combat/WorldObjectCache.cs b/Plugins/RynthCore.Plugin.RynthAi/Combat/WorldObjectCache.cs index ab14f54..7a68d5f 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Combat/WorldObjectCache.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Combat/WorldObjectCache.cs @@ -616,6 +616,19 @@ public class WorldObjectCache _inventory.Remove(id); _landscape.Add(id); } + else if (uid < 0x80000000u) + { + // A static id is a world object (a door, a sign, a lever), never something carried. + // One created before its position was readable - a dungeon's objects arrive while the + // character is still in portal space - was filed as inventory here for good, so the + // door scans (which walk the landscape) never saw the door: "Open Doors" on, a closed + // door in the way, no door use at all (Dargoth Hera, Infested Mine, 2026-10-19). It is + // Unknown landscape, as when its position is known; the scans read the position then. + _creatures.Remove(id); + _inventory.Remove(id); + _landscape.Add(id); + cls = AcObjectClass.Unknown; + } else { _inventory.Add(id); diff --git a/Plugins/RynthCore.Plugin.RynthAi/CorpseOpenController.cs b/Plugins/RynthCore.Plugin.RynthAi/CorpseOpenController.cs index 3b424b8..a05f2c8 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/CorpseOpenController.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/CorpseOpenController.cs @@ -577,6 +577,8 @@ public sealed partial class RynthAiPlugin public override void OnVendorClose(uint vendorId) { _metaManager?.OnVendorClose(vendorId); + // /mt vendor addbuy / addsell lists belong to the vendor that was open. + ClearMtVendorLists(); var autoVendor = _autoVendor; if (autoVendor != null) diff --git a/Plugins/RynthCore.Plugin.RynthAi/GameInput.cs b/Plugins/RynthCore.Plugin.RynthAi/GameInput.cs new file mode 100644 index 0000000..17ce2a5 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAi/GameInput.cs @@ -0,0 +1,272 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Runtime.InteropServices; + +namespace RynthCore.Plugin.RynthAi; + +/// +/// Key and mouse input posted to AC's own window, for the Mag-Tools /mt verbs that drive the +/// client directly: send, click, movement, strafe, get xy, +/// client. A port of Mag-Tools' PostMessageTools (Mag-Plugins\Shared\PostMessageTools.cs): +/// the same virtual keys, scan codes (lParam) and click spots, so metas written for Mag-Tools +/// behave the same. +/// +/// The window is the one in this process with AC's class ("Turbine Device Class"), found once. +/// PostMessage is safe from any thread. A key held for a time is released from +/// (the plugin tick), not from a timer: nothing here may outlive the plugin's Shutdown. +/// +/// Nothing in this class decides whether input is allowed. Every caller goes through +/// RynthAiPlugin.KeystrokesAllowed (the setting "Allow metas to send keystrokes", off by +/// default) first; counts every post so a test can prove that. +/// +internal static class GameInput +{ + private const uint WM_KEYDOWN = 0x0100, WM_KEYUP = 0x0101, WM_MOUSEMOVE = 0x0200, + WM_LBUTTONDOWN = 0x0201, WM_LBUTTONUP = 0x0202; + private const byte VK_RETURN = 0x0D, VK_SHIFT = 0x10, VK_CONTROL = 0x11, VK_PAUSE = 0x13, + VK_SPACE = 0x20, VK_DELETE = 0x2E, VK_F4 = 0x73, VK_F12 = 0x7B; + private const int SW_MINIMIZE = 6, SW_RESTORE = 9; + + // A key held longer than this is a mistake (a meta typed 1500000 for 1500). + public const int MaxHoldMs = 10_000; + // The longest line /mt send msg types. + public const int MaxMessageChars = 200; + + private static IntPtr _hwnd; + // Pending key releases, run by Pump when due (or at once by Shutdown). + private static readonly System.Collections.Generic.List<(long DueMs, Action Release)> Pending = new(); + + /// Every message this class tried to post (counted before the window is looked up). + public static int PostAttempts { get; private set; } + + /// Tests only: receives (message, wParam, lParam) instead of a window, which then counts as found. + internal static Action? TestSink; + + /// AC's game window in this process, or IntPtr.Zero. + public static IntPtr GameWindow + { + get + { + if (TestSink != null) return (IntPtr)1; + if (_hwnd != IntPtr.Zero && IsWindow(_hwnd)) return _hwnd; + // Every top-level AC window on the desktop, keeping this process's (several clients run). + // FindWindowEx rather than EnumWindows: no callback delegate to marshal under NativeAOT. + uint pid = (uint)Environment.ProcessId; + IntPtr found = IntPtr.Zero, h = IntPtr.Zero; + for (int i = 0; i < 64; i++) + { + h = FindWindowEx(IntPtr.Zero, h, "Turbine Device Class", null); + if (h == IntPtr.Zero) break; + GetWindowThreadProcessId(h, out uint p); + if (p == pid) { found = h; break; } + } + _hwnd = found; + return found; + } + } + + public static bool Available => GameWindow != IntPtr.Zero; + + // ── Keys (Mag-Tools PostMessageTools) ────────────────────────────────────── + + public static void SendEnter() => Key(VK_RETURN, 0x001C0001, 0xC01C0001); + public static void SendPause() => Key(VK_PAUSE, 0x00450001, 0xC0450001); + public static void SendDel() => Key(VK_DELETE, 0x01530001, 0x01530001); + /// F4: opens / closes the fellowship panel. + public static void SendF4() => Key(VK_F4, 0x003E0001, 0xC03E0001); + /// F12: opens / closes the main pack. + public static void SendF12() => Key(VK_F12, 0x00580001, 0xC0580001); + + /// Ctrl + a letter. + public static void SendCntrl(char ch) + { + Post(WM_KEYDOWN, VK_CONTROL, 0x001D0001); + Post(WM_KEYDOWN, CharCode(ch), 0x00100001); + Post(WM_KEYUP, CharCode(ch), 0xC0100001); + Post(WM_KEYUP, VK_CONTROL, 0xC01D0001); + } + + /// Types key by key (letters, space and "/"; as Mag-Tools). + public static void SendMsg(string msg) + { + if (msg.Length > MaxMessageChars) msg = msg[..MaxMessageChars]; + foreach (char ch in msg) + { + uint lparam = (uint)((ScanCode(ch) << 16) | 1); + Post(WM_KEYDOWN, CharCode(ch), lparam); + Post(WM_KEYUP, CharCode(ch), 0xC0000000 | lparam); + } + } + + /// Space (a jump), held ms, with the shift / w z x c keys + /// pressed as it is released (Mag-Tools /mt jump). + public static void SendSpace(int msToHoldDown = 0, bool shift = false, bool w = false, bool z = false, bool x = false, bool c = false) + { + Post(WM_KEYDOWN, VK_SPACE, 0x00390001); + void Release() + { + if (shift) Post(WM_KEYDOWN, VK_SHIFT, 0x002A0001); + if (w) Post(WM_KEYDOWN, CharCode('w'), 0x00110001); + if (z) Post(WM_KEYDOWN, CharCode('z'), 0x002C0001); + if (x) Post(WM_KEYDOWN, CharCode('x'), 0x002D0001); + if (c) Post(WM_KEYDOWN, CharCode('c'), 0x002E0001); + Post(WM_KEYUP, VK_SPACE, 0xC0390001); + if (w) Post(WM_KEYUP, CharCode('w'), 0xC0110001); + if (z) Post(WM_KEYUP, CharCode('z'), 0xC02C0001); + if (x) Post(WM_KEYUP, CharCode('x'), 0xC02D0001); + if (c) Post(WM_KEYUP, CharCode('c'), 0xC02E0001); + if (shift) Post(WM_KEYUP, VK_SHIFT, 0xC02A0001); + } + After(msToHoldDown, Release); + } + + /// A movement key (a letter of AC's keymap) held ms. + public static void SendMovement(char ch, int msToHoldDown = 0) + { + uint scan = (uint)ScanCode(ch) * 0x10000; + Post(WM_KEYDOWN, CharCode(ch), 0x00000001 + scan); + After(msToHoldDown, () => Post(WM_KEYUP, CharCode(ch), 0xC0000001 + scan)); + } + + // ── Mouse ───────────────────────────────────────────────────────────────── + + /// A left click at window coordinates (, ). + public static void SendMouseClick(int x, int y) + { + uint loc = (uint)((y << 16) | (x & 0xFFFF)); + Post(WM_MOUSEMOVE, 0, loc); + Post(WM_LBUTTONDOWN, 1, loc); + Post(WM_LBUTTONUP, 0, loc); + } + + // AC's confirmation box buttons, relative to the window's centre. Three heights each, as Mag-Tools: + // windowed and windowless clients put the box a few pixels apart. + public static void ClickOK() => ClickCentre(0); + public static void ClickYes() => ClickCentre(-80); + public static void ClickNo() => ClickCentre(80); + + private static void ClickCentre(int dx) + { + RECT r; + if (TestSink != null) r = new RECT { Right = 800, Bottom = 600 }; + else if (!GetWindowRect(GameWindow, out r)) return; + int w = r.Right - r.Left, h = r.Bottom - r.Top; + foreach (int dy in new[] { 18, 25, 31 }) + SendMouseClick(w / 2 + dx, h / 2 + dy); + } + + /// The cursor relative to the game window's top-left (Mag-Tools /mt get xy), or false. + public static bool TryCursorInWindow(out int x, out int y) + { + x = y = 0; + if (!GetCursorPos(out POINT p) || !GetWindowRect(GameWindow, out RECT r)) return false; + x = p.X - r.Left; + y = p.Y - r.Top; + return true; + } + + // ── Window ─────────────────────────────────────────────────────────────── + + public static bool Minimize() => TestSink != null ? Sink(0xFFF0, SW_MINIMIZE) : ShowWindow(GameWindow, SW_MINIMIZE); + public static bool Restore() => TestSink != null ? Sink(0xFFF0, SW_RESTORE) : ShowWindow(GameWindow, SW_RESTORE); + + private static bool Sink(uint msg, uint wParam) + { + PostAttempts++; + TestSink!(msg, wParam, 0); + return true; + } + + // ── Internals ──────────────────────────────────────────────────────────── + + private static void Key(byte vk, uint down, uint up) + { + Post(WM_KEYDOWN, vk, down); + Post(WM_KEYUP, vk, up); + } + + private static void Post(uint msg, uint wParam, uint lParam) + { + PostAttempts++; + if (TestSink != null) { TestSink(msg, wParam, lParam); return; } + IntPtr h = GameWindow; + if (h != IntPtr.Zero) PostMessage(h, msg, (IntPtr)wParam, (IntPtr)unchecked((int)lParam)); + } + + /// Runs now, or from after . + private static void After(int ms, Action action) + { + if (ms <= 0) { action(); return; } + ms = Math.Min(ms, MaxHoldMs); + lock (Pending) Pending.Add((Environment.TickCount64 + ms, action)); + } + + /// Releases the keys whose hold time is up. Called every plugin tick. + public static void Pump() + { + if (Pending.Count == 0) return; + List? due = null; + long now = Environment.TickCount64; + lock (Pending) + { + for (int i = Pending.Count - 1; i >= 0; i--) + { + if (Pending[i].DueMs > now) continue; + (due ??= new()).Insert(0, Pending[i].Release); + Pending.RemoveAt(i); + } + } + if (due == null) return; + foreach (var release in due) + { + try { release(); } + catch (Exception ex) { Debug.WriteLine("GameInput release failed: " + ex.Message); } + } + } + + /// Plugin shutdown: releases every key still held, then forgets the window. + public static void Shutdown() + { + List all; + lock (Pending) + { + all = new List(Pending.Count); + foreach (var p in Pending) all.Add(p.Release); + Pending.Clear(); + } + foreach (var release in all) + { + try { release(); } + catch (Exception ex) { Debug.WriteLine("GameInput release failed: " + ex.Message); } + } + _hwnd = IntPtr.Zero; + } + + private static byte ScanCode(char ch) => char.ToLowerInvariant(ch) switch + { + 'a' => 0x1E, 'b' => 0x30, 'c' => 0x2E, 'd' => 0x20, 'e' => 0x12, 'f' => 0x21, 'g' => 0x22, 'h' => 0x23, + 'i' => 0x17, 'j' => 0x24, 'k' => 0x25, 'l' => 0x26, 'm' => 0x32, 'n' => 0x31, 'o' => 0x18, 'p' => 0x19, + 'q' => 0x10, 'r' => 0x13, 's' => 0x1F, 't' => 0x14, 'u' => 0x16, 'v' => 0x2F, 'w' => 0x11, 'x' => 0x2D, + 'y' => 0x15, 'z' => 0x2C, '/' => 0x35, ' ' => 0x39, + _ => 0, + }; + + private static byte CharCode(char ch) + { + char c = char.ToLowerInvariant(ch); + if (c >= 'a' && c <= 'z') return (byte)(0x41 + (c - 'a')); + return c == '/' ? (byte)0xBF : (byte)0x20; + } + + [StructLayout(LayoutKind.Sequential)] private struct RECT { public int Left, Top, Right, Bottom; } + [StructLayout(LayoutKind.Sequential)] private struct POINT { public int X, Y; } + [DllImport("user32.dll")] private static extern bool PostMessage(IntPtr hWnd, uint msg, IntPtr wParam, IntPtr lParam); + [DllImport("user32.dll", CharSet = CharSet.Unicode)] + private static extern IntPtr FindWindowEx(IntPtr parent, IntPtr after, string className, string? title); + [DllImport("user32.dll")] private static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint pid); + [DllImport("user32.dll")] private static extern bool IsWindow(IntPtr hWnd); + [DllImport("user32.dll")] private static extern bool GetWindowRect(IntPtr hWnd, out RECT rect); + [DllImport("user32.dll")] private static extern bool GetCursorPos(out POINT p); + [DllImport("user32.dll")] private static extern bool ShowWindow(IntPtr hWnd, int cmd); +} diff --git a/Plugins/RynthCore.Plugin.RynthAi/HubInterface.cs b/Plugins/RynthCore.Plugin.RynthAi/HubInterface.cs index 9d9165a..1db271d 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/HubInterface.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/HubInterface.cs @@ -45,6 +45,8 @@ internal static unsafe class HubInterface t->SessionReset = &SessionReset; t->SessionStatsMore = &SessionStatsMore; t->VaultedDungeonsEnabled = &VaultedDungeonsEnabled; + t->BackAwayFrom = &BackAwayFrom; + t->SetPlayerCounter = &SetPlayerCounter; t->Version = RynthAiHubApiV1.InterfaceVersion; _table = t; } @@ -251,7 +253,7 @@ internal static unsafe class HubInterface catch { return 0; } } - /// RynthAi's Vaulted Dungeons setting: RynthILT's keeper runs only while it is on (off by default). + /// Obsolete slot: the profile's old Vaulted Dungeons value (RynthILT's own setting since 2026-10-20; an older RynthILT reads this). [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] private static int VaultedDungeonsEnabled() { @@ -259,6 +261,22 @@ internal static unsafe class HubInterface catch { return 0; } } + /// A server plugin's back-away (RynthILT: the Empyrean Handler's ring); BackAway* results, 0 before login. + [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] + private static int BackAwayFrom(uint objectId, float radiusYards, int holdMs) + { + try { return Plugin?.BackAwayForServer(objectId, radiusYards, holdMs) ?? RynthAiHub.BackAwayNotNow; } + catch { return RynthAiHub.BackAwayNotNow; } + } + + /// A wield counter from the server plugin (T11 "Can Wield"); 0 for an id that is no counter, or after shutdown. + [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] + private static int SetPlayerCounter(uint propertyId, long value) + { + try { return !_released && T11ItemSupport.SetCounter(propertyId, value) ? 1 : 0; } + catch { return 0; } + } + [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] private static void SessionReset() { diff --git a/Plugins/RynthCore.Plugin.RynthAi/Huds/HudState.cs b/Plugins/RynthCore.Plugin.RynthAi/Huds/HudState.cs index 5d4618f..c5486f5 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Huds/HudState.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Huds/HudState.cs @@ -40,11 +40,12 @@ public sealed class HudState public bool MiniShowPet = true; public bool MiniShowGems = true; public bool MiniShowToggles = true; + /// Obsolete since 2026-10-20 (kept so huds.json loads): the Bank section's switch is RynthILT's (copied once). public bool MiniShowBank = true; public bool MiniShowRebuff = true; /// Chat translator row: on/off, receive / send language swap. public bool MiniShowTranslate = true; - /// Temple guardian row: the last riddle answer with a Give button (only while one is recent). + /// Obsolete since 2026-10-20 (kept so huds.json loads): the Guardian line's switch is RynthILT's (copied once). public bool MiniShowGuardian = true; /// Gem grid slots, row-major from the top-left (empty Name = unassigned). public List MiniRemoteSlots = new(); diff --git a/Plugins/RynthCore.Plugin.RynthAi/Huds/MiniRemoteHud.cs b/Plugins/RynthCore.Plugin.RynthAi/Huds/MiniRemoteHud.cs index 0bc27e4..bf7aa3b 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Huds/MiniRemoteHud.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Huds/MiniRemoteHud.cs @@ -1,13 +1,11 @@ // MiniRemoteHud.cs — The Mini Remote (UtilityBelt-style) for RynthAi. Render thread only. // // One window with tabs: Remote (the sections below), the universal tabs Pets and Crafting (every -// world, MiniRemote/; the Quests tab moved to RynthOracle 2026-10-13), and on Infinite Leaftide -// the RynthILT plugin's ILT tabs (Banking, Gear, Charms, Games; its Character tab moved to -// RynthOracle's Character tab 2026-10-13: RynthILT.Hub GetTabs / RenderTab through IltClient; an ILT tab -// shows once the server reports its feature on, and never without RynthILT). The tab bar's -// selection is saved (HudState.MiniRemoteTab) and "/ra hub open
" or RynthCore's -// dashboard switch it (RequestTab). The Guardian and Bounties are RynthILT's RynthCore ILT -// panels (the bar's ILT button). +// world, MiniRemote/; the Quests tab moved to RynthOracle 2026-10-13), then whatever tabs the active +// server plugin offers (its hub: GetTabs / RenderTab through ServerHubClient; RynthILT's Banking, Gear, +// Charms, Games and Vaulted Dungeons on Infinite Leaftide). Nothing server-specific is drawn here +// without one. The tab bar's selection is saved (HudState.MiniRemoteTab) and "/ra hub open +//
" or RynthCore's dashboard switch it (RequestTab). // Right-click on the remote: "Character" (Spells, Pets, Crafting, RynthOracle's Character, Quests, // Quest Timers and Fellowship, Skills, Inventory, Item Count, Inventory HUDs: windows every server // has), then "Server: ", i.e. the installed server plugins' windows for the world you're on, @@ -18,19 +16,20 @@ // The V/H button stacks the sections (vertical) or lays them out in three columns (horizontal). // // Remote sections (each can be hidden from the Options menu): -// Stats session time and per-hour XP / luminance / kills, plus coins / pyreals (RynthILT's rates on ILT) +// Stats session time and per-hour XP / luminance / kills, then the server plugin's own rate lines +// (section "remote-stats": RynthILT's coins / pyreals per hour) // Target the creature combat is attacking: name, health bar, distance -// Pet the summon that is out (health bar, time left), else the next combat essence and -// whether it is ready +// Pet the summon that is out (health bar, time left), else (while a server plugin is active) +// the next combat essence and whether it is ready // Slots 5 × 6 quick-use item grid; click uses the item (an empty slot takes the selected // pack item), right-click assigns / clears, and items dragged from the game's // inventory or the RynthCore Inventory window drop straight into a slot. Ctrl+wheel // over the grid (or Options > Slot size) grows / shrinks the boxes. // Toggles macro and subsystem switches (same as the dashboard buttons; not in the drawer) -// Bank ILT bank balances (pyreals, luminance, keys, coins; drawn by RynthILT) // Rebuff force rebuff / cancel rebuff // Translate chat translator on/off and the receive <-> send language swap -// Guardian the last Temple guardian answer with a Give button (only while it is recent; RynthILT) +// + the server plugin's Remote sections around them (RynthILT: Bank, Guardian answer; their +// switches are its own, drawn in the Options popup through section "remote-options") // All game actions are posted to the pump thread. // // RenderEmbedded draws the same sections and Options menu inside the engine's RynthAi dashboard @@ -85,11 +84,14 @@ internal sealed class MiniRemoteHud private bool _openOptions; // The header's Options button was right-clicked this frame: its popup opens, not the remote's menu. private bool _headerRightClick; - /// One tab after Remote: a universal one (drawn here) or RynthILT's. - private readonly record struct TabEntry(string Id, string Label, Vector2 Size, bool Ilt); + /// One tab after Remote: a universal one (drawn here) or the server plugin's. + private readonly record struct TabEntry(string Id, string Label, Vector2 Size, bool FromServer); // The tabs offered this frame (reused, so a frame doesn't allocate). private readonly List _tabs = new(); + // The server plugin drew one of its Remote sections (Bank, Guardian) in the last frame: the + // horizontal layout keeps their column for it. + private bool _serverEconomyDrawn; public MiniRemoteHud(HudController hud) => _hud = hud; @@ -127,7 +129,7 @@ internal sealed class MiniRemoteHud RenderBody(s, _hud.Remote(), allowTabs: true); // Right-click on the remote opens the Character / server menu, unless a slot's own menu is - // open (the ILT tabs have their own right-click menus). + // open (a server plugin's tabs have their own right-click menus). if (_onRemoteTab && _slotMenuIndex < 0 && !_headerRightClick && ImGui.IsWindowHovered(ImGuiHoveredFlags.ChildWindows) && ImGui.IsMouseReleased(ImGuiMouseButton.Right)) ImGui.OpenPopup(MenuPopup); RenderOptions(s, embedded: false); @@ -175,8 +177,8 @@ internal sealed class MiniRemoteHud // ── Tabs ──────────────────────────────────────────────────────────────── /// - /// The tab bar (when : the universal tabs on every world, RynthILT's - /// tabs on Infinite Leaftide) and the selected tab: the remote, or a tab's body in a child of its + /// The tab bar (when : the universal tabs on every world, then the + /// server plugin's tabs on its server) and the selected tab: the remote, or a tab's body in a child of its /// fixed size. Returns the width the content wants (never narrower than the tab bar's labels). /// private float RenderBody(HudState s, MiniRemoteController? remote, bool allowTabs) @@ -187,9 +189,9 @@ internal sealed class MiniRemoteHud if (allowTabs && remote != null) { foreach (string id in MiniRemoteTabs.Universal) - _tabs.Add(new TabEntry(id, MiniRemoteTabs.Label(id), MiniRemoteTabs.Size(id), Ilt: false)); - foreach (IltTabInfo t in remote.Ilt.Tabs()) - if (t.Shown) _tabs.Add(new TabEntry(t.Id, t.Label, new Vector2(t.Width, t.Height), Ilt: true)); + _tabs.Add(new TabEntry(id, MiniRemoteTabs.Label(id), MiniRemoteTabs.Size(id), FromServer: false)); + foreach (ServerTabInfo t in remote.ServerHub.Tabs()) + if (t.Shown) _tabs.Add(new TabEntry(t.Id, t.Label, new Vector2(t.Width, t.Height), FromServer: true)); } if (_tabs.Count == 0) { @@ -221,8 +223,8 @@ internal sealed class MiniRemoteHud s.MiniRemoteTab = tab.Id; // The tab draws into a child of its own size; tables in it scroll inside it. ImGui.BeginChild(TabBodyId(tab.Id), tab.Size, ImGuiChildFlags.None, ImGuiWindowFlags.None); - bool drawn = tab.Ilt ? remote!.Ilt.RenderTab(tab.Id) : remote!.RenderTab(tab.Id); - if (!drawn) SafeImGui.TextDisabled(tab.Ilt ? "RynthILT isn't drawing this tab (not loaded, or not ready yet)." : "Not ready."); + bool drawn = tab.FromServer ? remote!.ServerHub.RenderTab(tab.Id) : remote!.RenderTab(tab.Id); + if (!drawn) SafeImGui.TextDisabled(tab.FromServer ? "The server plugin isn't drawing this tab (not loaded, or not ready yet)." : "Not ready."); ImGui.EndChild(); width = Math.Max(width, tab.Size.X); ImGui.EndTabItem(); @@ -233,7 +235,7 @@ internal sealed class MiniRemoteHud } // Tab labels as NUL-terminated UTF-8 and the tab body child ids, built once per tab so the tab - // bar doesn't allocate per frame (RynthILT's tabs arrive by id at run time). + // bar doesn't allocate per frame (a server plugin's tabs arrive by id at run time). private static readonly byte[] RemoteTabLabel = Utf8Z("Remote##mrtab"); private readonly Dictionary _tabLabels = new(StringComparer.Ordinal); private readonly Dictionary _tabBodyIds = new(StringComparer.Ordinal); @@ -308,7 +310,7 @@ internal sealed class MiniRemoteHud int cols = 0; if (s.MiniShowStats || s.MiniShowTarget || s.MiniShowPet) cols++; if (s.MiniShowGems || ShowToggles(s)) cols++; - if (s.MiniShowBank || s.MiniShowRebuff || s.MiniShowTranslate || s.MiniShowGuardian) cols++; + if (s.MiniShowRebuff || s.MiniShowTranslate || _serverEconomyDrawn) cols++; cols = Math.Max(1, cols); return cols * colW + (cols - 1) * ImGui.GetStyle().ItemSpacing.X; } @@ -394,7 +396,7 @@ internal sealed class MiniRemoteHud RenderActionSections(s); ImGui.EndChild(); } - if (s.MiniShowBank || s.MiniShowRebuff || s.MiniShowTranslate || s.MiniShowGuardian) + if (s.MiniShowRebuff || s.MiniShowTranslate || _serverEconomyDrawn) { BeginColumn("##mrcoleconomy", colW); RenderEconomySections(s, remote); @@ -449,17 +451,19 @@ internal sealed class MiniRemoteHud private void RenderEconomySections(HudState s, MiniRemoteController? remote) { - // Bank and Guardian are RynthILT's (nothing is drawn off ILT or without it). - if (s.MiniShowBank) remote?.Ilt.RenderSection(RynthIltHub.SectionRemoteBank); + // The server plugin's Remote sections (RynthILT: Bank, Guardian answer) decide themselves whether + // they show (their switches are the plugin's); nothing is drawn without one. + bool drawn = remote?.ServerHub.RenderSection(RynthIltHub.SectionRemoteBank) == true; if (s.MiniShowRebuff) RenderRebuff(); if (s.MiniShowTranslate && _hud.Translate is { } translate) translate.RenderHubSection(); - if (s.MiniShowGuardian) remote?.Ilt.RenderSection(RynthIltHub.SectionRemoteGuardian); + drawn |= remote?.ServerHub.RenderSection(RynthIltHub.SectionRemoteGuardian) == true; + _serverEconomyDrawn = drawn; } // ── Sections ──────────────────────────────────────────────────────────── - /// An Infinite Leaftide world, as RynthILT sees it (false without RynthILT). - private static bool IltActive(MiniRemoteController? remote) => remote != null && remote.Ilt.IsIltWorld; + /// A server plugin is active for this world (RynthILT on Infinite Leaftide); false without one. + private static bool ServerActive(MiniRemoteController? remote) => remote != null && remote.ServerHub.ServerActive; private static void Stat(string label, string value) { @@ -470,7 +474,7 @@ internal sealed class MiniRemoteHud /// /// Session stats on every world: the shared SessionStats (RynthTracker's code, so these match the - /// Tracker panel), plus ILT coins and pyreals (RynthILT's rates). + /// Tracker panel), plus the server plugin's own rate lines (RynthILT's coins and pyreals). /// private void RenderStats(MiniRemoteController? remote) { @@ -486,9 +490,7 @@ internal sealed class MiniRemoteHud if (ImGui.IsItemHovered()) SafeImGui.SetTooltip($"{v.LumPassUp:N0} this session.\n{PassUpTooltip}"); } Stat("Kills:", HudDraw.Compact(v.KillsPerHour) + "/h"); - if (remote == null || !remote.Ilt.TryGetRates(out double coins, out double pyreals)) return; - Stat("Coins:", HudDraw.Compact(coins) + "/h"); - Stat("Pyr:", HudDraw.Compact(pyreals) + "/h"); + remote?.ServerHub.RenderSection(RynthIltHub.SectionRemoteStats); } /// @@ -561,7 +563,7 @@ internal sealed class MiniRemoteHud HealthBar("##mrtargethp", c.TargetHealth); } - /// The live summon when one is out, else the Pets tab's next-essence line (ILT worlds). + /// The live summon when one is out, else (with a server plugin active) the Pets tab's next-essence line. private static void RenderPet(MiniRemoteController? remote, CombatHudSnapshot c) { if (c.PetId != 0) @@ -569,7 +571,7 @@ internal sealed class MiniRemoteHud RenderSummon(remote, c); return; } - if (!IltActive(remote)) { ImGui.TextDisabled("Summon: none"); return; } + if (!ServerActive(remote)) { ImGui.TextDisabled("Summon: none"); return; } string name = remote!.Pets.HudPetName; string status = remote.Pets.HudPetStatus; if (name.Length == 0) { ImGui.TextDisabled("No combat pet set"); return; } @@ -583,7 +585,7 @@ internal sealed class MiniRemoteHud ImGui.TextColored(ColLabel, "Summon:"); ImGui.SameLine(); ImGui.TextUnformatted(c.PetName); - if (IltActive(remote) && remote!.Pets.HudPetStatus == "Healing") + if (ServerActive(remote) && remote!.Pets.HudPetStatus == "Healing") { ImGui.SameLine(); ImGui.TextColored(ColBusy, "Healing"); @@ -641,13 +643,9 @@ internal sealed class MiniRemoteHud { float w = (ImGui.GetContentRegionAvail().X - ImGui.GetStyle().ItemSpacing.X) * 0.5f; w = Math.Max(w, 70f); - if (ImGui.Button("Reset XP", new Vector2(w, 0))) - _hud.Post(() => - { - _hud.SessionStats?.RequestReset(); - _hud.Remote()?.Ilt.Command("rates reset"); // RynthILT's coin / pyreal session too - }); - if (ImGui.IsItemHovered()) ImGui.SetTooltip("Start the session stats over (RynthTracker, RynthOracle and RynthILT follow this session)."); + // A server plugin's own rates follow this session (RynthILT restarts its coins when it restarts). + if (ImGui.Button("Reset XP", new Vector2(w, 0))) _hud.Post(() => _hud.SessionStats?.RequestReset()); + if (ImGui.IsItemHovered()) ImGui.SetTooltip("Start the session stats over (RynthTracker, RynthOracle and a server plugin's rates follow this session)."); ImGui.SameLine(); if (ImGui.Button("Report", new Vector2(w, 0))) _hud.Post(ReportToChat); if (ImGui.IsItemHovered()) ImGui.SetTooltip("Print the session rates in your chat window (local only)."); @@ -662,8 +660,7 @@ internal sealed class MiniRemoteHud + $"({HudDraw.Compact(v.LumLast5Min)} last 5m)"; if (v.PassUpTracked) line += $", Pass-up {HudDraw.Compact(v.PassUpPerHour)}/h"; line += $", Kills {HudDraw.Compact(v.KillsPerHour)}/h ({v.Kills:N0})"; - if (_hud.Remote()?.Ilt.TryGetRates(out double coins, out double pyreals) == true) - line += $", Coins {HudDraw.Compact(coins)}/h, Pyr {HudDraw.Compact(pyreals)}/h"; + line += _hud.Remote()?.ServerHub.Text(RynthIltHub.TextSessionReport) ?? string.Empty; // the server plugin's rates _hud.Chat(line); } @@ -832,10 +829,10 @@ internal sealed class MiniRemoteHud Flag("Item slots", ref s.MiniShowGems); // The drawer's dashboard has these switches already; the setting is for the windows. if (!InDrawer) Flag("Toggles", ref s.MiniShowToggles); - Flag("Bank", ref s.MiniShowBank); Flag("Rebuff", ref s.MiniShowRebuff); Flag("Translate", ref s.MiniShowTranslate); - Flag("Guardian answer", ref s.MiniShowGuardian); + // The server plugin's Remote sections (RynthILT: Bank, Guardian answer): its own switches. + _hud.Remote()?.ServerHub.RenderSection(RynthIltHub.SectionRemoteOptions); ImGui.Separator(); Flag("Horizontal layout", ref s.MiniRemoteHorizontal); RenderSlotSizeSlider(s); @@ -875,9 +872,6 @@ internal sealed class MiniRemoteHud // ── Right-click menu: Character, then this server's plugin windows ───────── - /// RynthCore's server id for Infinite Leaftide (UI/ServerMenus.cs), the one RynthILT has tabs for. - private const string IltServerId = "ilt"; - /// /// The right-click menu. Top, "Character": windows every server has. Bottom: the server /// section, i.e. the installed server plugins' windows for the world you're on (RynthCore @@ -915,8 +909,8 @@ internal sealed class MiniRemoteHud if (_hud.Host.HasInvokeChatParser) { // RynthOracle's commands (it toggles its own windows; without RynthOracle nothing answers "/ro"). - // The character overview and its session are RynthOracle's Character tab (2026-10-13); - // Infinite Leaftide's charms and bank stay RynthILT's tabs (the server section below). + // The character overview and its session are RynthOracle's Character tab (2026-10-13); a + // server's own screens are its plugin's (the server section below). if (ImGui.MenuItem("Character##mrcharacter", MovedTabs.OracleCharacter)) _hud.RunEngineCommand(MovedTabs.OracleCharacter); if (ImGui.IsItemHovered()) ImGui.SetTooltip("RynthOracle's Character tab: the character and this session."); if (ImGui.MenuItem("Quests##mrquests", "/ro")) _hud.RunEngineCommand("/ro"); @@ -933,25 +927,28 @@ internal sealed class MiniRemoteHud } /// - /// The server section. Each section RynthCore marks active is listed, and so is Infinite - /// Leaftide while this character's "Treat this world as ILT" is on (RynthILT's override). - /// Without RynthCore's list it falls back to RynthILT's own ILT entries. + /// The server section. Each section RynthCore marks active is listed, and so is the server + /// plugin's own server while this character forces it (the plugin's override, e.g. RynthILT's + /// "Treat this world as ILT"). Without RynthCore's list it falls back to the server plugin's own + /// menu entries (its "server-menu" section). /// private void RenderServerMenu(MiniRemoteController? remote) { ServerMenuGroup[]? groups = ServerMenuModel.Groups; if (groups == null) { - remote?.Ilt.RenderSection(RynthIltHub.SectionServerMenu); + remote?.ServerHub.RenderSection(RynthIltHub.SectionServerMenu); return; } if (groups.Length == 0) return; // no server plugin installed + // The server the active server plugin's tabs and status belong to (RynthILT: "ilt"); "" without one. + string pluginServer = remote?.ServerHub.Text(RynthIltHub.TextServerId) ?? string.Empty; bool any = false; foreach (ServerMenuGroup g in groups) { - bool ilt = g.Id.Equals(IltServerId, StringComparison.OrdinalIgnoreCase); - bool forcedHere = ilt && remote?.Ilt.ForceIlt == true; + bool ours = pluginServer.Length > 0 && g.Id.Equals(pluginServer, StringComparison.OrdinalIgnoreCase); + bool forcedHere = ours && remote?.ServerHub.ServerForced == true; if (!g.Active && !forcedHere) continue; any = true; ImGui.Separator(); @@ -971,7 +968,8 @@ internal sealed class MiniRemoteHud if (item.Tooltip.Length > 0 && ImGui.IsItemHovered(ImGuiHoveredFlags.AllowWhenDisabled)) SafeImGui.SetTooltip(enabled ? item.Tooltip : item.Tooltip + "\nShows once the server reports this feature on."); } - if (ilt) remote?.Ilt.RenderSection(RynthIltHub.SectionIltStatus); + // The plugin's status under its server (RynthILT: why no ILT feature is on, Refresh). + if (ours) remote?.ServerHub.RenderSection(RynthIltHub.SectionIltStatus); } if (any) return; @@ -992,11 +990,11 @@ internal sealed class MiniRemoteHud else if (item.Command.Length > 0) _hud.RunEngineCommand(item.Command); } - /// RynthILT reports that ILT tab's feature on (false without RynthILT). + /// The server plugin reports that tab's feature on (false without one). private static bool TabAvailable(MiniRemoteController? remote, string tab) { if (remote == null) return false; - foreach (IltTabInfo t in remote.Ilt.Tabs()) + foreach (ServerTabInfo t in remote.ServerHub.Tabs()) if (string.Equals(t.Id, tab, StringComparison.OrdinalIgnoreCase)) return t.Available; return false; } diff --git a/Plugins/RynthCore.Plugin.RynthAi/Huds/MovedTabs.cs b/Plugins/RynthCore.Plugin.RynthAi/Huds/MovedTabs.cs index c4cde5b..4a40ab5 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Huds/MovedTabs.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Huds/MovedTabs.cs @@ -4,8 +4,8 @@ // RynthOracle's Character tab ("/ro character"), its ILT session rates to RynthCore's Mini Remote // "Session Stats" section (RynthILT's own "section:ilt-rates"), and the force-server override to // RynthCore Options > Diagnostics ("/rc diagnostics"). Infinite Leaftide's own screens stay -// RynthILT's: Charms and Banking are still Mini Remote ILT tabs (SectionsManifest places them on -// the rail), drawn by RynthILT. +// RynthILT's: Charms and Banking are still Mini Remote ILT tabs (RynthILT's own manifest places +// them on the rail since 2026-10-20), drawn by RynthILT. // Old saved tab ids, links and "/ra hub open|tab " land on the new home through CommandFor. // // Pure: the host tests check the mapping offline. diff --git a/Plugins/RynthCore.Plugin.RynthAi/Huds/SectionsManifest.cs b/Plugins/RynthCore.Plugin.RynthAi/Huds/SectionsManifest.cs index efc2a13..69217b5 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Huds/SectionsManifest.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Huds/SectionsManifest.cs @@ -4,22 +4,15 @@ // Stats - id "char" -, Map, Skills, Combat, Nav, Inventory, Crafting, Spells, Chat, Friends, // Fellowship, Pets) and any a plugin adds. It reads each plugin's optional // RynthPluginGetSectionsJson export every couple of seconds (schema: UI/Sections/SectionManifest.cs -// in RynthCore). RynthAi fills: -// every world Session Stats (the one session: RynthTracker, RynthOracle and RynthILT read the -// same numbers, and RynthCore drops its own overview for it), Pets, Crafting, -// Spells and Fellowship (the views of those core sections) -// Infinite RynthILT's tabs, hosted here as they are in RynthAi's own Mini Remote (RynthILT.Hub, -// Leaftide MiniRemote/IltClient.cs): Gear, Charms and Banking in Inventory, and a Games -// section of RynthAi's own -// Quests are RynthOracle's (since 2026-10-13), and RynthILT draws its ILT session extras, /fship -// and /qb views itself (its own manifest), so neither is listed here. RynthILT's Character tab -// moved out on 2026-10-13 (MovedTabs.cs): RynthOracle's Character tab and the ILT session rates in -// Session Stats. Charms and Banking stay RynthILT's tabs (Infinite Leaftide's own screens), so the -// engine's "/rc miniremote tab charms|banking" finds them here as "section:charms|banking". -// Each view is a surface "section:" RynthCore draws through RynthPluginRenderEmbed. An ILT -// view whose feature the server hasn't reported is listed but not enabled, with a note. +// in RynthCore). RynthAi fills, on every world: Session Stats (the one session: RynthTracker, +// RynthOracle and RynthILT read the same numbers, and RynthCore drops its own overview for it), +// Pets, Crafting, Spells and Fellowship (the views of those core sections). +// Nothing server-specific is listed here: a server plugin lists its own views (since 2026-10-20 +// RynthILT lists its Mini Remote tabs, Gear / Charms / Banking / Games / Vaulted Dungeons, and its +// Games section itself; RynthAi hosted them until then). Quests are RynthOracle's (since 2026-10-13). +// Each view is a surface "section:" RynthCore draws through RynthPluginRenderEmbed. // -// Pure: RynthILT's tabs come in as a list, so the host tests build it offline. +// Pure, so the host tests build it offline. using System; using System.Collections.Generic; using System.IO; @@ -42,12 +35,6 @@ internal static class SectionsManifest /// The session stats (RynthCore's Session Stats section, "char"). public const string SessionSurface = SurfacePrefix + "session"; - /// RynthCore's id for Infinite Leaftide. - public const string IltServer = "ilt"; - - /// Longest tab id taken from RynthILT (its ids are short ASCII words). - public const int MaxTabIdLength = 32; - /// One view RynthAi puts in a section. internal sealed record View(string Section, string Server, string Label, string Surface, bool Primary, Vector2 Size, bool Enabled, string Note, string Tooltip, int Order); @@ -55,37 +42,14 @@ internal static class SectionsManifest /// A section of RynthAi's own (beyond RynthCore's core twelve). internal sealed record Section(string Id, string Label, int Order); - /// RynthAi's own sections: Games (ILT) after Pets. - public static readonly Section[] OwnSections = - { - new("games", "Games", 1150), - }; + /// RynthAi's own sections beyond the core ones: none (Games went with RynthILT's tabs, 2026-10-20). + public static readonly Section[] OwnSections = Array.Empty
(); - private const string NotReportedNote = "Shows once the server reports this ILT feature on (RynthILT's ILT settings can ask again)."; - - /// Where each of RynthILT's tabs goes: section, label, order, tooltip. Unknown ids aren't listed. - private static readonly Dictionary IltPlacement = - new(StringComparer.OrdinalIgnoreCase) - { - ["gear"] = ("inventory", "Gear", 210, "ILT gear tools (RynthILT)."), - ["charms"] = ("inventory", "Charms", 220, "ILT charms and Guardian Hands: acquired, status, tier, toggles (RynthILT)."), - ["banking"] = ("inventory", "Banking", 230, "Your ILT bank: balances, deposits, withdrawals and transfers (RynthILT)."), - ["games"] = ("games", "Games", 100, "ILT games (RynthILT)."), - // Listed only while RynthILT shows the tab: the Vaulted Dungeons master switch (RynthAi - // Settings > Navigation) is on, on an ILT world. - ["vaulted"] = ("nav", "Vaulted Dungeons", 220, - "Keep the character in one Vaulted Dungeon (RynthILT; Settings > Navigation > Vaulted Dungeons)."), - }; - - /// The surface name of a tab's view ("section:gear"). + /// The surface name of a tab's view ("section:pets"). public static string SurfaceOf(string tabId) => SurfacePrefix + tabId; - /// - /// Every view, from what is available now: RynthAi's own (every world) and - /// (RynthILT's tabs with their sizes and whether the server has - /// each feature on; empty without RynthILT or off ILT). - /// - public static List Views(IReadOnlyList iltTabs) + /// Every view RynthAi offers (the same on every world). + public static List Views() { var views = new List { @@ -95,21 +59,12 @@ internal static class SectionsManifest new("pets", string.Empty, "Pets", PetsSurface, true, MiniRemoteTabs.Size(MiniRemoteTabs.Pets), true, string.Empty, "Combat pets: the summon out, essences, and the pet picker (RynthAi).", 100), new("crafting", string.Empty, "Crafting", CraftingSurface, true, MiniRemoteTabs.Size(MiniRemoteTabs.Crafting), true, string.Empty, - "Tinkering benches, chunking / clap and split arrows (RynthAi).", 100), + "Tinkering benches: retail tinks, your own rows and the server plugin's salvage (RynthAi).", 100), new("spells", string.Empty, "Spells", SpellsSurface, true, new Vector2(900, 560), true, string.Empty, "The spell catalog and buff profiles (RynthAi).", 100), new("fellowship", string.Empty, "Fellowship", FellowshipSurface, true, new Vector2(380, 360), true, string.Empty, "Your fellowship: members, leader, XP sharing (RynthAi; also RynthOracle's Fellowship tab).", 100), }; - - // Infinite Leaftide: RynthILT's tabs that it shows on this world. - foreach (IltTabInfo tab in iltTabs) - { - if (!tab.Shown || !IsTabId(tab.Id) || !IltPlacement.TryGetValue(tab.Id, out var place)) continue; - var size = new Vector2(MathF.Max(0f, tab.Width), MathF.Max(0f, tab.Height)); - views.Add(new View(place.Section, IltServer, place.Label, SurfaceOf(tab.Id.ToLowerInvariant()), true, size, - tab.Available, tab.Available ? string.Empty : NotReportedNote, place.Tooltip, place.Order)); - } return views; } @@ -166,23 +121,4 @@ internal static class SectionsManifest return tabId.Length > 0; } - /// The RynthILT tab a "section:<tab>" surface draws, if it names one we place. - public static bool TryIltTabOf(string surface, out string tabId) - { - tabId = string.Empty; - if (!surface.StartsWith(SurfacePrefix, StringComparison.Ordinal)) return false; - string id = surface.Substring(SurfacePrefix.Length); - if (!IsTabId(id) || !IltPlacement.ContainsKey(id)) return false; - tabId = id; - return true; - } - - /// A short lowercase-ASCII id (letters, digits, '-'): nothing else is spliced into a surface name. - private static bool IsTabId(string? id) - { - if (string.IsNullOrEmpty(id) || id.Length > MaxTabIdLength) return false; - foreach (char c in id) - if (!(c is >= 'a' and <= 'z' or >= 'A' and <= 'Z' or >= '0' and <= '9' or '-')) return false; - return true; - } } diff --git a/Plugins/RynthCore.Plugin.RynthAi/Jumper.cs b/Plugins/RynthCore.Plugin.RynthAi/Jumper.cs index 3e6a1e8..7414842 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Jumper.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Jumper.cs @@ -34,8 +34,59 @@ internal sealed class Jumper private bool _pausedNav; private bool _prevEnableNavigation; + // Face only (/mt face, /ub face; ub-IT's DoFace): navigation is held while turning, the turn + // is sent again every 100 ms until the heading is within 1 degree, and given up after 5 s. + private bool _faceOnly; + private DateTime _lastFaceTurnAt; + private const double FaceToleranceDeg = 1.0; + private static readonly TimeSpan FaceRetry = TimeSpan.FromMilliseconds(100); + private static readonly TimeSpan FaceTimeout = TimeSpan.FromSeconds(5); + public bool IsBusy => _isTurning || _needToJump || _charging || _waitingForJump; + /// Turns to (any degrees; normalized to 0-360), holding nav meanwhile. + public bool Face(double heading) + { + if (IsBusy && !_faceOnly) + { + _chat("[RynthAi] You are jumping. Try again later."); + return false; + } + if (!_host.HasTurnToHeading) + { + _chat("[RynthAi] TurnToHeading not available."); + return false; + } + _targetHeading = (float)(((heading % 360) + 360) % 360); + if (!_faceOnly) PauseNav(); + _faceOnly = true; + _isTurning = true; + _turningStartedAt = _lastFaceTurnAt = DateTime.UtcNow; + _host.TurnToHeadingBy("Face", _targetHeading); + RynthLog.Write(LogCat.Jumper, $"[Jumper] Face -> {_targetHeading:F1}"); + return true; + } + + /// The face turn: done within , else turn again; nav back when done. + private void TickFace() + { + DateTime now = DateTime.UtcNow; + if (now - _lastFaceTurnAt < FaceRetry) return; + _lastFaceTurnAt = now; + bool read = PlayerCompass.TryGet(_host, out float current); + double off = read ? Math.Abs(((current - _targetHeading) % 360 + 540) % 360 - 180) : 0; + if (read && off >= FaceToleranceDeg && now - _turningStartedAt < FaceTimeout) + { + _host.TurnToHeadingBy("Face", _targetHeading); + return; + } + _isTurning = _faceOnly = false; + RestoreNav(); + RynthLog.Write(LogCat.Jumper, read && off >= FaceToleranceDeg + ? $"[Jumper] Face {_targetHeading:F1}: still {off:F1} deg off after {FaceTimeout.TotalSeconds:0} s, gave up" + : $"[Jumper] Face {_targetHeading:F1} done (heading {(read ? current.ToString("F1") : "?")})"); + } + public Jumper(RynthCoreHost host, LegacyUiSettings settings, Action chat) { _host = host; @@ -45,6 +96,12 @@ internal sealed class Jumper public bool Start(string directionLetters, float? faceHeading, int msToHoldDown) { + // A face still turning (a meta's "/mt face 90" then "/ub jumpw 90") gives way to the jump. + if (_faceOnly) + { + _faceOnly = _isTurning = false; + RestoreNav(); + } if (IsBusy) { _chat("[RynthAi] You are already jumping. Try again later."); @@ -77,7 +134,7 @@ internal sealed class Jumper } else { - _targetHeading = _host.TryGetPlayerHeading(out float curr) ? curr : 0f; + _targetHeading = PlayerCompass.TryGet(_host, out float curr) ? curr : 0f; } PauseNav(); @@ -101,7 +158,7 @@ internal sealed class Jumper public void Cancel() { RestoreNav(); - _isTurning = _needToJump = _charging = _waitingForJump = false; + _isTurning = _needToJump = _charging = _waitingForJump = _faceOnly = false; _addW = _addX = _addZ = _addC = _addShift = false; } @@ -111,13 +168,18 @@ internal sealed class Jumper try { + if (_faceOnly) + { + TickFace(); + return; + } // TurnToHeading is an instant quaternion snap; the heading read // doesn't always reflect it immediately, so just wait a short // settle window rather than polling for a match. if (_isTurning && DateTime.UtcNow - _turningStartedAt >= TimeSpan.FromMilliseconds(150)) { _isTurning = false; - if (_host.TryGetPlayerHeading(out float current)) + if (PlayerCompass.TryGet(_host, out float current)) RynthLog.Write(LogCat.Jumper, $"[Jumper] Turn done heading={current:F1}"); } diff --git a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyAdvancedSettingsUi.cs b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyAdvancedSettingsUi.cs index 5964149..cd0202f 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyAdvancedSettingsUi.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyAdvancedSettingsUi.cs @@ -463,6 +463,17 @@ internal sealed class LegacyAdvancedSettingsUi ImGui.SliderInt("Give Interval (ms)", ref _settings.GiveQueueIntervalMs, 0, 2000); if (ImGui.IsItemHovered()) ImGui.SetTooltip("Minimum gap between two gives sent by /ra givea commands.\n0 = send the next give the moment the server answers the last (fastest).\nThe queue always waits for the server's answer first."); + + ImGui.Separator(); + ImGui.Spacing(); + ImGui.Text("Meta Compatibility"); + ImGui.Checkbox("Allow metas to send keystrokes (/mt send)", ref _settings.AllowMetaKeystrokes); + if (ImGui.IsItemHovered()) + ImGui.SetTooltip("Mag-Tools metas press keys and click inside the game window with /mt send, /mt click,\n" + + "/mt movement, /mt strafe, /mt client minimize|restore and the key form of /mt jump.\n" + + "Off (the default): those verbs log once and do nothing. Turn it on only for a meta you trust:\n" + + "the keys go to the game window as if you pressed them. /mt send /command (a chat command)\n" + + "is not a key press and works either way."); break; case "Recharge": @@ -741,9 +752,6 @@ internal sealed class LegacyAdvancedSettingsUi ImGui.SetTooltip("Drop a locked target only past this distance (hysteresis).\n0 or <= Monster Range = auto (Monster Range + 3)."); ImGui.SetNextItemWidth(120); ImGui.InputInt("Ring Range", ref _settings.RingRange); - ImGui.Checkbox("Evade Handler Ring", ref _settings.HandlerRingEvade); - if (ImGui.IsItemHovered()) - ImGui.SetTooltip("Empyrean Handler: when it channels its lethal ring and you are within 12 yards (or Ring Range if larger),\nback-jump away and re-engage. Acts only while the macro is running with combat on."); ImGui.SetNextItemWidth(120); ImGui.InputInt("Approach Range", ref _settings.ApproachRange); diff --git a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyDashboardRenderer.cs b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyDashboardRenderer.cs index 662b0f3..19f04a2 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyDashboardRenderer.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyDashboardRenderer.cs @@ -1100,6 +1100,20 @@ internal sealed partial class LegacyDashboardRenderer // ── Settings bridge (engine-side Avalonia SettingsPanel) ───────────────── + /// + /// The active server plugin's mirrored settings (RynthILT.Hub GetSetting / SetSetting, through the + /// Mini Remote's server client): the value, or -1 when none is offered. Set by RynthAiPlugin. + /// + public Func? ServerSettingGet { get; set; } + public Action? ServerSettingSet { get; set; } + + /// A mirrored server setting as a nullable bool (null = not offered: the engine row hides). + private bool? ServerSettingBool(string key) + { + int v = ServerSettingGet?.Invoke(key) ?? -1; + return v < 0 ? null : v != 0; + } + public string BuildSettingsJson() { try @@ -1139,7 +1153,6 @@ internal sealed partial class LegacyDashboardRenderer BlacklistCastSettleMs = s.BlacklistCastSettleMs, TargetNoProgressTimeoutSec = s.TargetNoProgressTimeoutSec, GiveQueueIntervalMs = s.GiveQueueIntervalMs, - T11ItemAugsOverride = s.T11ItemAugsOverride, // Recharge HealAt = s.HealAt, UsePotions = s.UsePotions, @@ -1197,6 +1210,10 @@ internal sealed partial class LegacyDashboardRenderer SpellCastIntervalMs = s.SpellCastIntervalMs, AttackSpellIntervalMs = s.AttackSpellIntervalMs, CastDispelSelf = s.CastDispelSelf, + UseDispelItems = s.UseDispelItems, + AutoFellowMgmt = s.AutoFellowMgmt, + MChargesWhenOff = s.MChargesWhenOff, + CustomPetRange = s.CustomPetRange, MinRingTargets = s.MinRingTargets, BlastRange = s.BlastRange, MinBlastTargets = s.MinBlastTargets, @@ -1221,7 +1238,7 @@ internal sealed partial class LegacyDashboardRenderer CorpseApproachRangeMin = s.CorpseApproachRangeMin, // Navigation BoostNavPriority = s.BoostNavPriority, - EnableVaultedDungeons = s.EnableVaultedDungeons, + EnableVaultedDungeons = ServerSettingBool(RynthCore.Plugin.Shared.RynthIltHub.SettingVaultedDungeons), // RynthILT's (null: the row hides) FollowNavMin = s.FollowNavMin, NavRingThickness = s.NavRingThickness, NavLineThickness = s.NavLineThickness, @@ -1393,7 +1410,6 @@ internal sealed partial class LegacyDashboardRenderer if (p.BlacklistCastSettleMs > 0) s.BlacklistCastSettleMs = p.BlacklistCastSettleMs; s.TargetNoProgressTimeoutSec = p.TargetNoProgressTimeoutSec; s.GiveQueueIntervalMs = p.GiveQueueIntervalMs; - s.T11ItemAugsOverride = p.T11ItemAugsOverride ?? -1; // Recharge s.HealAt = p.HealAt; s.UsePotions = p.UsePotions; @@ -1453,6 +1469,11 @@ internal sealed partial class LegacyDashboardRenderer s.SpellCastIntervalMs = p.SpellCastIntervalMs; if (p.AttackSpellIntervalMs is int attackDelay) s.AttackSpellIntervalMs = attackDelay; // absent = unchanged s.CastDispelSelf = p.CastDispelSelf; + // Absent (an engine without them) = unchanged. + if (p.UseDispelItems is bool useDispelItems) s.UseDispelItems = useDispelItems; + if (p.AutoFellowMgmt is bool autoFellow) s.AutoFellowMgmt = autoFellow; + if (p.MChargesWhenOff is bool mCharges) s.MChargesWhenOff = mCharges; + if (p.CustomPetRange is int petRange) s.CustomPetRange = Math.Clamp(petRange, 1, 50); s.MinRingTargets = p.MinRingTargets; s.BlastRange = p.BlastRange; s.MinBlastTargets = p.MinBlastTargets; @@ -1477,7 +1498,8 @@ internal sealed partial class LegacyDashboardRenderer s.CorpseApproachRangeMin = p.CorpseApproachRangeMin; // Navigation s.BoostNavPriority = p.BoostNavPriority; - if (p.EnableVaultedDungeons is bool vaulted) s.EnableVaultedDungeons = vaulted; // absent = unchanged + if (p.EnableVaultedDungeons is bool vaulted) // absent = unchanged + ServerSettingSet?.Invoke(RynthCore.Plugin.Shared.RynthIltHub.SettingVaultedDungeons, vaulted ? 1 : 0); // RynthILT's switch s.FollowNavMin = p.FollowNavMin; s.NavRingThickness = p.NavRingThickness; s.NavLineThickness = p.NavLineThickness; @@ -1966,7 +1988,7 @@ internal sealed partial class LegacyDashboardRenderer dst.TargetSelection = Math.Clamp(tmp.TargetSelection, 0, 3); dst.TargetLock = tmp.TargetLock; dst.RingRange = tmp.RingRange; - dst.HandlerRingEvade = tmp.HandlerRingEvade; // a profile saved before this setting loads it as on + dst.HandlerRingEvade = tmp.HandlerRingEvade; // obsolete (RynthILT's now): carried so the profile keeps it for RynthILT's one-time import dst.ApproachRange = tmp.ApproachRange; dst.MinRingTargets = tmp.MinRingTargets; dst.BlastRange = tmp.BlastRange; @@ -1989,7 +2011,7 @@ internal sealed partial class LegacyDashboardRenderer dst.CorpseApproachRangeMax = NormalizeCorpseRangeYards(tmp.CorpseApproachRangeMax, 10.0); dst.CorpseApproachRangeMin = NormalizeCorpseRangeYards(tmp.CorpseApproachRangeMin, 2.0); dst.BoostNavPriority = tmp.BoostNavPriority; - dst.EnableVaultedDungeons = tmp.EnableVaultedDungeons; + dst.EnableVaultedDungeons = tmp.EnableVaultedDungeons; // obsolete (RynthILT's now): carried for its one-time import dst.BoostLootPriority = tmp.BoostLootPriority; dst.OpenDoors = tmp.OpenDoors; dst.OpenDoorRange = tmp.OpenDoorRange; @@ -2118,6 +2140,7 @@ internal sealed partial class LegacyDashboardRenderer dst.AutoTradeAutoAccept = tmp.AutoTradeAutoAccept; dst.AutoTradeAutoAcceptChars = tmp.AutoTradeAutoAcceptChars ?? new(); dst.MetaDebug = tmp.MetaDebug; + dst.AllowMetaKeystrokes = tmp.AllowMetaKeystrokes; dst.StartMacroOnLogin = tmp.StartMacroOnLogin; dst.PatrolOnLogin = tmp.PatrolOnLogin; dst.YieldToVTank = tmp.YieldToVTank; @@ -2127,7 +2150,7 @@ internal sealed partial class LegacyDashboardRenderer dst.NavLabelMode = NavLabelModes.Clamp(tmp.NavLabelMode); dst.NavGuideLine = tmp.NavGuideLine; dst.GiveQueueIntervalMs = tmp.GiveQueueIntervalMs; - dst.T11ItemAugsOverride = tmp.T11ItemAugsOverride; + dst.T11ItemAugsOverride = tmp.T11ItemAugsOverride; // obsolete (RynthILT's now): carried for its one-time import dst.SpellCastIntervalMs = tmp.SpellCastIntervalMs; dst.StuckCastBreakMs = tmp.StuckCastBreakMs; dst.RecoveryRetryMs = tmp.RecoveryRetryMs; diff --git a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyUiSettings.cs b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyUiSettings.cs index bdf6572..cbf63a3 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyUiSettings.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyUiSettings.cs @@ -38,6 +38,15 @@ public sealed class LegacyUiSettings public bool EnableRaycasting = true; public bool MetaDebug; + /// + /// "Allow metas to send keystrokes (/mt send)". Off by default (2026-10-19). Mag-Tools' /mt send, + /// click, movement, strafe, client minimize|restore and the key fallback of /mt jump post raw + /// key and mouse messages to the game window; with this off they log once and do nothing. + /// Deliberately not in the expression settings map, /mt opt or the phone's settings: a meta + /// must not be able to switch it on for itself. + /// + public bool AllowMetaKeystrokes; + public int MovementMode; public float NavStopTurnAngle = 20f; public float NavResumeTurnAngle = 10f; @@ -207,9 +216,10 @@ public sealed class LegacyUiSettings // setting loads it as on. public bool TargetLock = true; public int RingRange = 5; - // Empyrean Handler lethal ring (CombatManager.HandleChatForRingEvade): when the Handler channels the - // ring and the character is inside its danger radius, back-jump away and re-engage. Only acts while - // the macro is running with combat on. On by default because it is gated that way. + // Obsolete since 2026-10-20 (unused here, kept so profiles still load and carry it): the Empyrean + // Handler lethal-ring evade is Infinite Leaftide's and lives in RynthILT now (its ILT settings, + // "/ilt settings"), which copied this value once. RynthAi keeps only the generic back-away it + // asks for (CombatManager.BackAwayFrom, RynthAi.Hub BackAwayFrom). public bool HandlerRingEvade = true; public int ApproachRange = 4; public int MinRingTargets = 4; @@ -257,10 +267,10 @@ public sealed class LegacyUiSettings public bool BoostNavPriority; /// - /// Options > Navigation > Vaulted Dungeons: the MASTER switch of RynthILT's Vaulted Dungeons - /// keeper (Infinite Leaftide / ACECustom only). Off by default. RynthILT reads it through - /// "RynthAi.Hub" VaultedDungeonsEnabled; while it is off the keeper does nothing (no recalls, - /// no /rc quit, no tab). This is the one place the switch lives. + /// Obsolete since 2026-10-20 (kept so profiles still load and carry it): the Vaulted Dungeons + /// keeper's master switch is RynthILT's own setting now, copied from here once. RynthAi only + /// mirrors RynthILT's value into the engine's Settings > Navigation row (ServerSettingGet / Set) + /// and answers this old value through RynthAi.Hub VaultedDungeonsEnabled for an older RynthILT. /// public bool EnableVaultedDungeons; public bool BoostLootPriority; @@ -414,9 +424,9 @@ public sealed class LegacyUiSettings public int GiveQueueIntervalMs = 0; /// - /// Item augmentation count used for T11 wield gates in loot rules ("T11: Can Wield"). - /// -1 = automatic (read from the server's "/aug" reply). ACECustom doesn't send the count - /// at login, so this is the fallback when "/aug" is unavailable. Set with /ra t11 augs. + /// Obsolete since 2026-10-20 (kept so profiles still load and carry it): the item augmentation + /// count override for the T11 "Can Wield" loot key is RynthILT's now ("/ilt t11 augs", copied from + /// here once), and RynthILT reports the counters it reads from "/aug" (RynthAi.Hub SetPlayerCounter). /// public int T11ItemAugsOverride = -1; @@ -608,7 +618,9 @@ public sealed class LegacyUiSettings public int BuffMinSkillLevelTier7 = 335; public int BuffMinSkillLevelTier8 = 435; - public bool EnableManaTapping = false; + // On for a new character (2026-10-20): with it off only stones already charged refill worn gear, and + // nothing charges them, so suits ran dry for players who never found the switch. A saved profile keeps its choice. + public bool EnableManaTapping = true; public int ManaTapMinMana = 2500; public int ManaStoneKeepCount = 5; @@ -951,7 +963,7 @@ public sealed class ItemsBridgePayload { public List Weapons { get; set; } = new(); public List Consumables { get; set; } = new(); - public bool EnableManaTapping { get; set; } + public bool EnableManaTapping { get; set; } = true; // absent from an old profile = the new default public int ManaTapMinMana { get; set; } public int ManaStoneKeepCount { get; set; } public string CurrentTargetName { get; set; } = string.Empty; @@ -1138,6 +1150,12 @@ public sealed class SettingsBridgePayload // Nullable since 0 became a real value (2026-10-08): a file without it keeps the default. public int? AttackSpellIntervalMs { get; set; } public bool CastDispelSelf { get; set; } + // VTank's options page (the engine's Classic dashboard, Main tab; 2026-10-19). Nullable: an engine + // without them sends none, and the saved values stay. + public bool? UseDispelItems { get; set; } + public bool? AutoFellowMgmt { get; set; } + public bool? MChargesWhenOff { get; set; } + public int? CustomPetRange { get; set; } public int MinRingTargets { get; set; } public int BlastRange { get; set; } public int MinBlastTargets { get; set; } = 3; // absent from an older engine: keep the default @@ -1168,8 +1186,9 @@ public sealed class SettingsBridgePayload // Navigation public bool BoostNavPriority { get; set; } /// - /// Options > Navigation > Vaulted Dungeons: the keeper's master switch (off by default). Nullable: - /// an engine that predates the row omits it, and absent = unchanged (never switches it off or on). + /// Options > Navigation > Vaulted Dungeons: RynthILT's keeper master switch, mirrored (RynthILT.Hub + /// GetSetting / SetSetting). Null when no server plugin offers it (no RynthILT, or off ILT): the + /// engine row then hides. Received: absent = unchanged; a value goes to RynthILT. /// public bool? EnableVaultedDungeons { get; set; } public float FollowNavMin { get; set; } diff --git a/Plugins/RynthCore.Plugin.RynthAi/Loot/InventoryManager.cs b/Plugins/RynthCore.Plugin.RynthAi/Loot/InventoryManager.cs index 9c778c9..82e7001 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Loot/InventoryManager.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Loot/InventoryManager.cs @@ -425,7 +425,7 @@ public sealed class InventoryManager internal static bool MergeProgressed(int targetBefore, int sourceBefore, int targetNow, int sourceNow) => targetBefore > 0 && sourceBefore > 0 && (targetNow > targetBefore || sourceNow < sourceBefore); - private static int GetMaxStackSize(WorldObject item) + internal static int GetMaxStackSize(WorldObject item) { int max = item.Values(LongValueKey.MaxStackSize, 0); if (max > 1) return max; diff --git a/Plugins/RynthCore.Plugin.RynthAi/Loot/T11ItemSupport.cs b/Plugins/RynthCore.Plugin.RynthAi/Loot/T11ItemSupport.cs index c312f2c..03fe5df 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Loot/T11ItemSupport.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Loot/T11ItemSupport.cs @@ -8,15 +8,17 @@ namespace RynthCore.Plugin.RynthAi.Loot; /// T11 (tier 11+ ACECustom) loot support for : /// answers the virtual T11 keys () and puts back the wield-requirement and /// rating properties the server strips from T11 appraisals. Parsed item text is cached per -/// object and re-parsed only when the text changes. Holds the player's "/aug" counters for -/// the "Can Wield" key. One character per process, so the state is static. +/// object and re-parsed only when the text changes. Holds the player's wield counters for the +/// "Can Wield" key; since 2026-10-20 the server plugin reports them (RynthILT reads ACECustom's +/// "/aug" reply and applies its item-aug override, then calls RynthAi.Hub SetPlayerCounter), so +/// without one they stay unknown, as on any retail-like server. One character per process, so +/// the state is static. ///
internal static class T11ItemSupport { /// The logged-in character's T11 wield counters. public static T11PlayerAugs Player { get; } = new(); - private static readonly T11AugReportParser AugParser = new(); private static readonly object Gate = new(); private static readonly Dictionary Parsed = new(); @@ -103,12 +105,19 @@ internal static class T11ItemSupport } } - /// Feeds a chat line to the "/aug" reader. Returns true when a counter changed. - public static bool OnChat(string? text) => AugParser.Feed(text, Environment.TickCount64, Player); - - /// Applies the saved item-aug override (-1 = automatic). Cheap; called every tick. - public static void SyncOverride(int itemAugsOverride) - => Player.ItemAugOverride = itemAugsOverride >= 0 ? itemAugsOverride : null; + /// + /// A wield counter from the server plugin (RynthAi.Hub SetPlayerCounter): + /// is the counter's Int64 property id (T11Counter), < 0 = unknown again. + /// False for an id that is no T11 counter. Any thread. + /// + public static bool SetCounter(uint propertyId, long value) + { + if (!Enum.IsDefined(typeof(T11Counter), unchecked((int)propertyId))) return false; + var counter = (T11Counter)unchecked((int)propertyId); + if (value < 0) Player.Forget(counter); + else Player.Set(counter, value); + return true; + } /// Drops the cached parse of a deleted object. public static void Forget(int objectId) diff --git a/Plugins/RynthCore.Plugin.RynthAi/MagToolsCommands.Extra.cs b/Plugins/RynthCore.Plugin.RynthAi/MagToolsCommands.Extra.cs new file mode 100644 index 0000000..df9b475 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAi/MagToolsCommands.Extra.cs @@ -0,0 +1,506 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using RynthCore.PluginSdk; +using RynthCore.Plugin.Shared; + +namespace RynthCore.Plugin.RynthAi; + +/// +/// The rest of Mag-Tools' /mt verbs (2026-10-17; checked against Mag-Tools PluginCore and +/// ub-IT's MagToUbCommandTranslator): send (keys), jump / sjump, trade, vendor buy/sell lists, +/// autopack, dumpspells, click, get xy, movement, client, plus ub-IT's config and strafe. +/// Partial class of RynthAiPlugin; dispatched from . +/// +public sealed partial class RynthAiPlugin +{ + // /mt vendor addbuy/addsell lists, sent by "/mt vendor buy" / "sell" (Mag-Tools keeps them in Decal). + private readonly List<(uint Id, string Name, int Amount)> _mtBuyList = new(); + private readonly List<(uint Id, string Name)> _mtSellList = new(); + + // ── Safety gates (2026-10-19) ─────────────────────────────────────────────── + // + // Two kinds of /mt verb can do real damage if a shared meta (or a stray chat line) drives them: + // * raw input into the game window (send, click, movement, strafe, client, the jump fallback): + // off unless the setting "Allow metas to send keystrokes (/mt send)" is on (default off); + // * acting on a vendor or a trade (vendor buy / sell, trade accept): only while a meta that is + // running executes the line. A typed line, a delayed line that did not come from a meta, or + // any other path is refused. + + // Nesting count of the meta chat-command handler (HandleMetaChatCommand) on the call stack. + private int _metaCommandDepth; + + // Verbs already told "off" this session (one chat line and one log line each, not one per meta pulse). + private readonly HashSet _keystrokeRefusalSaid = new(StringComparer.OrdinalIgnoreCase); + + /// True while a running meta (macro on, Meta on) is executing the line being handled: + /// inside one of its actions (MetaManager.IsExecutingAction) or a line replayed on its behalf. + internal bool MetaCommandActive + => (_metaCommandDepth > 0 || _metaManager?.IsExecutingAction == true) + && _dashboard?.Settings is { IsMacroRunning: true, EnableMeta: true }; + + /// Runs as a line a meta executes (see ). + private T RunAsMeta(Func action) + { + _metaCommandDepth++; + try { return action(); } + finally { _metaCommandDepth--; } + } + + /// + /// The setting "Allow metas to send keystrokes (/mt send)". False (and said once per verb) when + /// it is off, which is the default: the verb then does nothing. + /// + private bool KeystrokesAllowed(string verb) + { + if (_dashboard?.Settings.AllowMetaKeystrokes == true) return true; + if (_keystrokeRefusalSaid.Add(verb)) + { + string msg = $"[RynthAi] {verb} ignored: it sends keys or clicks to the game window, and 'Allow metas to send keystrokes (/mt send)' is off (Settings, Advanced). Said once."; + Log(msg); + ChatLine(msg); + } + return false; + } + + /// + /// True only when a running meta executes this line. Otherwise says why not and returns false, + /// so (an action on a vendor or a trade) is never run from a typed or + /// unrelated line. + /// + private bool RequireRunningMeta(string verb) + { + if (MetaCommandActive) return true; + string msg = $"[RynthAi] {verb} only runs from a meta that is running (macro and Meta on); refused."; + Log(msg); + ChatLine(msg); + return false; + } + + /// The verbs this file handles, from 's default branch. + private bool TryHandleMtExtra(string cmd, string[] parts, string fullCommand) + { + // jump, sjump, jumpw, sjumpwz ... (Mag-Tools matches "jump" anywhere after /mt). + if (cmd.StartsWith("jump", StringComparison.Ordinal) || cmd.StartsWith("sjump", StringComparison.Ordinal)) + return HandleMtJump(cmd, parts); + + switch (cmd) + { + case "test": + ChatLine("[RynthAi] /mt test: Mag-Tools' debug command - nothing to do."); + return true; + case "trade": return HandleMtTrade(parts); + case "vendor": return HandleMtVendor(parts); + case "autopack": + // Mag-Tools packs by its own rules; RynthAi's equivalent is a cram + stack pass. + _inventoryManager?.RunManual(cram: true, stack: true); + ChatLine("[RynthAi] Autopack: cramming items into side packs and stacking them."); + return true; + case "dumpspells": return HandleMtDumpSpells(); + case "click": return HandleMtClick(parts); + case "get": + if (parts.Length >= 3 && parts[2].Equals("xy", StringComparison.OrdinalIgnoreCase)) return HandleMtCursor(); + ChatLine("[RynthAi] Usage: /mt get xy"); + return true; + case "cursor": return HandleMtCursor(); + case "movement": return HandleMtMovement(parts); + case "strafe": return HandleMtStrafe(parts); + case "client": return HandleMtClient(parts); + case "config": + // ub-IT: /mt config = /mt opt (list when bare). + return parts.Length < 3 ? HandleMtOpt(new[] { "/mt", "opt", "list" }) : HandleMtOpt(parts); + default: + return false; + } + } + + // ── send: keys, as Mag-Tools ──────────────────────────────────────────────── + + /// + /// /mt send enter|pause|del|space|f4|f12|cntrl+<letter>|msg <text>: presses keys in the + /// game window, as Mag-Tools. A line starting with "/" is still sent as a chat command (what + /// this verb did before, which some metas use). + /// + private bool HandleMtSend(string[] parts, string fullCommand) + { + if (parts.Length < 3) { ChatLine("[RynthAi] Usage: /mt send enter|pause|del|space|f4|f12|cntrl+|msg "); return true; } + string arg = parts[2].ToLowerInvariant(); + if (parts[2].StartsWith('/')) + { + if (Host.HasInvokeChatParser) Host.InvokeChatParser(string.Join(" ", parts, 2, parts.Length - 2)); + return true; + } + if (!KeystrokesAllowed("/mt send")) return true; + if (!GameInput.Available) { ChatLine("[RynthAi] /mt send: the game window wasn't found."); return true; } + Log($"[RynthAi] /mt send {string.Join(" ", parts, 2, Math.Min(parts.Length - 2, 2))}: keys posted to the game window"); + switch (arg) + { + case "enter": GameInput.SendEnter(); return true; + case "pause": GameInput.SendPause(); return true; + case "del": GameInput.SendDel(); return true; + case "space": GameInput.SendSpace(); return true; + case "f4": GameInput.SendF4(); return true; + case "f12": GameInput.SendF12(); return true; + case "msg": + int at = fullCommand.IndexOf(" msg ", StringComparison.OrdinalIgnoreCase); + if (at < 0 || at + 5 >= fullCommand.Length) { ChatLine("[RynthAi] Usage: /mt send msg "); return true; } + GameInput.SendMsg(fullCommand[(at + 5)..]); + return true; + } + if (arg.StartsWith("cntrl+", StringComparison.Ordinal) && arg.Length >= 7) + { + GameInput.SendCntrl(arg[6]); + return true; + } + ChatLine("[RynthAi] Usage: /mt send enter|pause|del|space|f4|f12|cntrl+|msg "); + return true; + } + + // ── jump ───────────────────────────────────────────────────────────────────── + + /// /mt jump[w|z|x|c] [ms] and /mt sjump... (shift): RynthAi's jumper (the engine's own + /// jump), else the keys as Mag-Tools. + private bool HandleMtJump(string cmd, string[] parts) + { + bool shift = cmd.StartsWith("sjump", StringComparison.Ordinal); + string suffix = cmd[(shift ? 5 : 4)..]; + bool w = suffix.Contains('w'), z = suffix.Contains('z'), x = suffix.Contains('x'), c = suffix.Contains('c'); + int ms = 0; + if (parts.Length >= 3) int.TryParse(parts[2], out ms); + ms = Math.Clamp(ms, 0, 1000); + + string letters = (w ? "w" : "") + (x ? "x" : "") + (z ? "z" : "") + (c ? "c" : "") + (shift ? "s" : ""); + if (_jumper != null && _jumper.Start(letters, null, ms)) return true; + if (_jumper?.IsBusy == true) return true; // it said so in chat + if (!KeystrokesAllowed("/mt jump (keys)")) return true; + if (!GameInput.Available) { ChatLine("[RynthAi] /mt jump: no jump hook and no game window."); return true; } + GameInput.SendSpace(ms, shift, w, z, x, c); + return true; + } + + // ── trade ──────────────────────────────────────────────────────────────────── + + /// /mt trade add|addp <item> | accept | decline | reset | end. + private bool HandleMtTrade(string[] parts) + { + if (parts.Length < 3) { ChatLine("[RynthAi] Usage: /mt trade add|addp | accept | decline | reset | end"); return true; } + string sub = parts[2].ToLowerInvariant(); + // Completing a trade is only ever a running meta's doing (checked before anything else). + if (sub == "accept" && !RequireRunningMeta("/mt trade accept")) return true; + if (!Host.HasTrade) { ChatLine("[RynthAi] Trading needs a newer RynthCore engine."); return true; } + switch (sub) + { + case "add": + case "addp": + { + if (parts.Length < 4) { ChatLine($"[RynthAi] Usage: /mt trade {sub} "); return true; } + string name = string.Join(" ", parts, 3, parts.Length - 3); + var item = FindObject(name, inv: true, land: false, partial: sub == "addp"); + if (item == null) { ChatLine($"[RynthAi] Item not found: '{name}'"); return true; } + ChatLine(Host.TradeAdd(unchecked((uint)item.Id)) + ? $"[RynthAi] Added {item.Name} to the trade." : "[RynthAi] Could not add it to the trade."); + return true; + } + case "accept": + Log("[RynthAi] /mt trade accept (from the running meta)"); + Host.TradeAccept(); + return true; + case "decline": Host.TradeDecline(); return true; + case "reset": Host.TradeReset(); return true; + case "end": Host.TradeClose(); return true; + default: + ChatLine("[RynthAi] Usage: /mt trade add|addp | accept | decline | reset | end"); + return true; + } + } + + // ── vendor ─────────────────────────────────────────────────────────────────── + + /// + /// /mt vendor addbuy|addbuyp <item> [count] | addsell|addsellp <item> | buy | clearbuy | sell | + /// clearsell, with a vendor open: lists kept here, sent in one transaction by buy / sell. + /// + private bool HandleMtVendor(string[] parts) + { + const string usage = "[RynthAi] Usage: /mt vendor addbuy|addbuyp [count] | addsell|addsellp | buy | clearbuy | sell | clearsell"; + if (parts.Length < 3) { ChatLine(usage); return true; } + // Spending or selling is only ever a running meta's doing (checked before anything else). + string verb = parts[2].ToLowerInvariant(); + if (verb == "buy" && !RequireRunningMeta("/mt vendor buy")) return true; + if (verb == "sell" && !RequireRunningMeta("/mt vendor sell")) return true; + if (!Host.HasVendorTrade) { ChatLine("[RynthAi] Vendor trading needs a newer RynthCore engine."); return true; } + if (!Host.TryGetVendorInfo(out VendorInfo info) || info.VendorId == 0) + { + ChatLine("[RynthAi] No vendor is open."); + return true; + } + string sub = parts[2].ToLowerInvariant(); + switch (sub) + { + case "addbuy": + case "addbuyp": + { + if (parts.Length < 4) { ChatLine($"[RynthAi] Usage: /mt vendor {sub} [count]"); return true; } + var words = parts.Skip(3).ToList(); + int count = 1; + if (words.Count > 1 && int.TryParse(words[^1], out int n) && n > 0) { count = n; words.RemoveAt(words.Count - 1); } + string name = string.Join(" ", words); + bool partial = sub == "addbuyp"; + VendorItem? item = Host.GetVendorItems().FirstOrDefault(v => partial + ? v.Name.IndexOf(name, StringComparison.OrdinalIgnoreCase) >= 0 + : string.Equals(v.Name, name, StringComparison.OrdinalIgnoreCase)); + if (item == null) { ChatLine($"[RynthAi] {info.Name} doesn't sell '{name}'."); return true; } + _mtBuyList.Add((item.ObjectId, item.Name, count)); + ChatLine($"[RynthAi] Buy list: {count} x {item.Name} ({_mtBuyList.Count} entr{(_mtBuyList.Count == 1 ? "y" : "ies")})."); + return true; + } + case "addsell": + case "addsellp": + { + if (parts.Length < 4) { ChatLine($"[RynthAi] Usage: /mt vendor {sub} "); return true; } + string name = string.Join(" ", parts, 3, parts.Length - 3); + var item = FindObject(name, inv: true, land: false, partial: sub == "addsellp"); + if (item == null) { ChatLine($"[RynthAi] Item not found: '{name}'"); return true; } + uint id = unchecked((uint)item.Id); + if (!_mtSellList.Any(s => s.Id == id)) _mtSellList.Add((id, item.Name)); + ChatLine($"[RynthAi] Sell list: {item.Name} ({_mtSellList.Count} item(s))."); + return true; + } + case "buy": + { + if (_mtBuyList.Count == 0) { ChatLine("[RynthAi] The buy list is empty (/mt vendor addbuy [count])."); return true; } + var entries = _mtBuyList.Select(b => new VendorTradeEntryNative(b.Id, b.Amount)).ToList(); + Log($"[RynthAi] /mt vendor buy (from the running meta): {_mtBuyList.Count} entr{(_mtBuyList.Count == 1 ? "y" : "ies")} from {info.Name} 0x{info.VendorId:X8}: " + + string.Join(", ", _mtBuyList.Select(b => $"{b.Amount} x {b.Name}"))); + uint sent = Host.VendorBuy(info.VendorId, entries); + ChatLine(sent != 0 ? $"[RynthAi] Buying {_mtBuyList.Count} entr{(_mtBuyList.Count == 1 ? "y" : "ies")} from {info.Name}." + : "[RynthAi] The buy could not be sent."); + if (sent != 0) _mtBuyList.Clear(); + return true; + } + case "clearbuy": + _mtBuyList.Clear(); + ChatLine("[RynthAi] Buy list cleared."); + return true; + case "sell": + { + if (_mtSellList.Count == 0) { ChatLine("[RynthAi] The sell list is empty (/mt vendor addsell )."); return true; } + // Checked again now, not only when the item was listed: it may have been worn since, + // and RynthAi's own gear and consumables are never sold by a meta. + var toSell = new List<(uint Id, string Name)>(); + foreach (var (sid, sname) in _mtSellList) + { + WorldObject? so = _objectCache?[unchecked((int)sid)]; + string? why = so == null ? null : ItemProtectionReason(so, includeLootKeep: false); + if (why != null) Log($"[RynthAi] /mt vendor sell: skipped {sname} 0x{sid:X8} ({why})."); + else toSell.Add((sid, sname)); + } + if (toSell.Count == 0) + { + _mtSellList.Clear(); + ChatLine("[RynthAi] Nothing left to sell: every listed item is protected."); + return true; + } + Log($"[RynthAi] /mt vendor sell (from the running meta): {toSell.Count} item(s) to {info.Name} 0x{info.VendorId:X8}: " + + string.Join(", ", toSell.Select(s => s.Name))); + uint sent = Host.VendorSell(info.VendorId, toSell.Select(s => s.Id).ToList()); + ChatLine(sent != 0 ? $"[RynthAi] Selling {toSell.Count} item(s) to {info.Name}." : "[RynthAi] The sell could not be sent."); + if (sent != 0) _mtSellList.Clear(); + return true; + } + case "clearsell": + _mtSellList.Clear(); + ChatLine("[RynthAi] Sell list cleared."); + return true; + default: + ChatLine(usage); + return true; + } + } + + /// + /// Why a meta verb must not give or sell this item, or null when it may. Equipped gear, the + /// items RynthAi itself uses (the Weapons and Consumables lists, every monster rule's weapon and + /// off hand) and items the server won't let go (attuned, retained) are always protected. + /// adds the active loot profile's Keep / Keep # rules. + /// + internal string? ItemProtectionReason(WorldObject wo, bool includeLootKeep) + { + if (WorldObjectCache.IsWieldedByPlayer(Host, wo)) return "equipped"; + var s = _dashboard?.Settings; + if (s != null) + { + try + { + foreach (var r in s.ItemRules.ToList()) if (r.Id == wo.Id) return "on RynthAi's Weapons list"; + foreach (var c in s.ConsumableRules.ToList()) if (c.Id == wo.Id) return "on RynthAi's Consumables list"; + foreach (var m in s.MonsterRules.ToList()) + if (m.WeaponId == wo.Id || m.OffhandId == wo.Id) return "a monster rule's weapon"; + } + catch { return "RynthAi's item lists could not be read"; } + } + if (wo.Values(114 /* Attuned */, 0) > 0) return "attuned"; + uint id = unchecked((uint)wo.Id); + if (Host.HasGetObjectBitfield && Host.TryGetObjectBitfield(id, out uint bf) && (bf & 0x01000000u) != 0) return "retained"; + if (Host.HasGetObjectBoolProperty && Host.TryGetObjectBoolProperty(id, 91 /* Retained */, out bool retained) && retained) return "retained"; + if (includeLootKeep && IsKeptByLootProfile(wo)) return "kept by the loot profile"; + return null; + } + + /// The vendor closed: its buy / sell lists no longer mean anything. + private void ClearMtVendorLists() + { + _mtBuyList.Clear(); + _mtSellList.Clear(); + } + + // ── dumpspells ─────────────────────────────────────────────────────────────── + + /// /mt dumpspells: the spell table to RynthAi's folder (spelldump.txt: id, name, family, difficulty). + private bool HandleMtDumpSpells() + { + try + { + Dictionary byName = SpellDatabase.BuildNameToIdMap(); + var rows = byName.Select(kv => (Id: kv.Value, Name: kv.Key)).Distinct().OrderBy(r => r.Id).ToList(); + string path = Path.Combine(RynthCore.Install.RynthInstallPaths.RynthAiDir, "spelldump.txt"); + using (var w = new StreamWriter(path, false, new System.Text.UTF8Encoding(false))) + { + w.WriteLine("Id\tName\tFamily\tDifficulty"); + foreach (var (id, name) in rows) + { + SpellDatabase.TryGetSpellMeta(id, out int family, out int difficulty); + w.WriteLine($"{id}\t{name}\t{family}\t{difficulty}"); + } + } + ChatLine($"[RynthAi] {rows.Count} spells written to {path}"); + } + catch (Exception ex) { ChatLine($"[RynthAi] /mt dumpspells failed: {ex.Message}"); } + return true; + } + + // ── /ra equipfor (VTank /vt equipitemsfor) ─────────────────────────────────── + + /// + /// /ra equipfor <monster> (VTank's /vt equipitemsfor): wield the weapon and off hand set on that + /// monster's rule (the rule named exactly, else one whose name the monster's contains, else + /// Default). Items already wielded are left; a rule with no set weapon says so (combat picks + /// one itself when it fights). + /// + private void HandleEquipForCommand(string[] parts) + { + if (parts.Length < 3) { ChatLine("[RynthAi] Usage: /ra equipfor "); return; } + var rules = _dashboard?.Settings?.MonsterRules; + if (rules == null || rules.Count == 0) { ChatLine("[RynthAi] No monster rules loaded."); return; } + string monster = string.Join(" ", parts, 2, parts.Length - 2).Trim(); + + var rule = rules.FirstOrDefault(r => string.Equals(r.Name, monster, StringComparison.OrdinalIgnoreCase)) + ?? rules.Where(r => !string.Equals(r.Name, "Default", StringComparison.OrdinalIgnoreCase) + && r.Name.Length > 0 && monster.IndexOf(r.Name, StringComparison.OrdinalIgnoreCase) >= 0) + .OrderByDescending(r => r.Name.Length).FirstOrDefault() + ?? rules.FirstOrDefault(r => string.Equals(r.Name, "Default", StringComparison.OrdinalIgnoreCase)); + if (rule == null) { ChatLine($"[RynthAi] No monster rule for '{monster}'."); return; } + + var ids = new List(); + if (rule.WeaponId != 0) ids.Add(rule.WeaponId); + if (rule.OffhandId != 0) ids.Add(rule.OffhandId); + if (ids.Count == 0) + { + ChatLine($"[RynthAi] '{rule.Name}' has no set weapon (combat picks one when it fights '{monster}')."); + return; + } + if (!Host.HasUseObject) { ChatLine("[RynthAi] UseObject not available."); return; } + + int sent = 0; + foreach (int id in ids) + { + var wo = _objectCache?[id]; + if (wo == null) { ChatLine($"[RynthAi] '{rule.Name}': item 0x{(uint)id:X8} isn't carried."); continue; } + if (wo.Values(LongValueKey.CurrentWieldedLocation, 0) > 0) continue; // already wielded + Host.UseFor(unchecked((uint)id), "Command", "/ra equipfor", UseKind.Asked); + sent++; + } + ChatLine(sent > 0 ? $"[RynthAi] Equipping for '{monster}' ({rule.Name}): {sent} item(s)." + : $"[RynthAi] '{rule.Name}' gear for '{monster}' is already wielded."); + } + + // ── click, cursor, movement, strafe, client ───────────────────────────────── + + /// /mt click ok|yes|no|<x> <y>: a click in the game window (window coordinates). + private bool HandleMtClick(string[] parts) + { + if (parts.Length < 3) { ChatLine("[RynthAi] Usage: /mt click ok|yes|no| "); return true; } + if (!KeystrokesAllowed("/mt click")) return true; + if (!GameInput.Available) { ChatLine("[RynthAi] /mt click: the game window wasn't found."); return true; } + switch (parts[2].ToLowerInvariant()) + { + case "ok": GameInput.ClickOK(); return true; + case "yes": GameInput.ClickYes(); return true; + case "no": GameInput.ClickNo(); return true; + } + if (parts.Length >= 4 && int.TryParse(parts[2], out int x) && int.TryParse(parts[3], out int y)) + { + GameInput.SendMouseClick(x, y); + return true; + } + ChatLine("[RynthAi] Usage: /mt click ok|yes|no| "); + return true; + } + + /// /mt get xy (and ub-IT's /mt cursor): the cursor relative to the game window. + private bool HandleMtCursor() + { + ChatLine(GameInput.TryCursorInWindow(out int x, out int y) + ? $"[RynthAi] Current cursor position: {x},{y}" + : "[RynthAi] The cursor position couldn't be read."); + return true; + } + + /// /mt movement <key> <ms>: hold a movement key (AC's keymap letter) for ms. + private bool HandleMtMovement(string[] parts) + { + if (parts.Length != 4 || parts[2].Length != 1 || !int.TryParse(parts[3], out int ms) || ms < 0) + { + ChatLine("[RynthAi] Usage: /mt movement (e.g. /mt movement w 1500)"); + return true; + } + if (!KeystrokesAllowed("/mt movement")) return true; + if (!GameInput.Available) { ChatLine("[RynthAi] /mt movement: the game window wasn't found."); return true; } + GameInput.SendMovement(parts[2][0], ms); + return true; + } + + /// ub-IT's /mt strafe left|l|right|r <ms>: hold the side-step key (Z / C) for ms. + private bool HandleMtStrafe(string[] parts) + { + if (parts.Length != 4 || !int.TryParse(parts[3], out int ms) || ms < 0) + { + ChatLine("[RynthAi] Usage: /mt strafe left|l|right|r "); + return true; + } + char key = parts[2].ToLowerInvariant() switch { "left" or "l" => 'z', "right" or "r" => 'c', _ => '\0' }; + if (key == '\0') { ChatLine("[RynthAi] /mt strafe: left, l, right or r."); return true; } + if (!KeystrokesAllowed("/mt strafe")) return true; + if (!GameInput.Available) { ChatLine("[RynthAi] /mt strafe: the game window wasn't found."); return true; } + GameInput.SendMovement(key, ms); + return true; + } + + /// /mt client minimize|restore (ub-IT's frame apply|restore points to Settings > Display). + private bool HandleMtClient(string[] parts) + { + string sub = parts.Length >= 3 ? parts[2].ToLowerInvariant() : ""; + switch (sub) + { + case "minimize": if (KeystrokesAllowed("/mt client")) GameInput.Minimize(); return true; + case "restore": if (KeystrokesAllowed("/mt client")) GameInput.Restore(); return true; + case "frame": + ChatLine("[RynthAi] The window frame is RynthCore's: Settings > Display (Borderless Windowed, Reset Window Borders) or /rc window reset."); + return true; + default: + ChatLine("[RynthAi] Usage: /mt client minimize | restore"); + return true; + } + } +} diff --git a/Plugins/RynthCore.Plugin.RynthAi/MagToolsCommands.cs b/Plugins/RynthCore.Plugin.RynthAi/MagToolsCommands.cs index c7da49b..f034cb9 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/MagToolsCommands.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/MagToolsCommands.cs @@ -92,14 +92,14 @@ public sealed partial class RynthAiPlugin if (Host.HasInvokeChatParser) Host.InvokeChatParser("/rc quit"); return true; - // ── Send a chat line / slash command (VTank /mt send) ──────────── + // ── Keys in the game window (Mag-Tools /mt send); a "/" line is still sent as a command ── case "send": - if (parts.Length >= 3 && Host.HasInvokeChatParser) - Host.InvokeChatParser(string.Join(" ", parts, 2, parts.Length - 2)); - return true; + return HandleMtSend(parts, fullCommand); default: - return false; + // jump, trade, vendor, autopack, dumpspells, click, get xy, movement, client, config, + // strafe, test (MagToolsCommands.Extra.cs). + return TryHandleMtExtra(cmd, parts, fullCommand); } } @@ -302,11 +302,45 @@ public sealed partial class RynthAiPlugin private bool HandleMtFace(string[] parts) { - // /mt face - if (parts.Length < 3 || !float.TryParse(parts[2], out float degrees)) return false; - if (!Host.HasTurnToHeading) { ChatLine("[RynthAi] TurnToHeading not available."); return true; } + // /mt face (Mag-Tools) and /ub face (ub-IT, translated here). The heading + // may have decimals (getheadingto[] gives them), read the same on every PC; or a coordinate + // ("42.1N, 33.6E") to face that spot. + if (parts.Length < 3) return false; + string arg = string.Join(" ", parts, 2, parts.Length - 2).Trim(); + double heading; + if (double.TryParse(arg, System.Globalization.NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture, out double deg)) + heading = deg; + else if (!TryHeadingToCoords(arg, out heading)) + return false; - Host.TurnToHeadingBy("Command", degrees); + // The jumper holds navigation while it turns (nav would turn the character back) and turns + // again until it faces the heading, as ub-IT does; without it, one plain turn. + if (_jumper != null) _jumper.Face(heading); + else if (Host.HasTurnToHeading) Host.TurnToHeadingBy("Command", (float)(((heading % 360) + 360) % 360)); + else ChatLine("[RynthAi] TurnToHeading not available."); + return true; + } + + private static readonly System.Text.RegularExpressions.Regex FaceCoordsRx = new( + @"^\s*(?\d+(?:\.\d+)?)\s*(?[NnSs])[\s,]*(?\d+(?:\.\d+)?)\s*(?[EeWw])\s*$", + System.Text.RegularExpressions.RegexOptions.CultureInvariant); + + /// + /// The heading from the character to a "42.1N, 33.6E" coordinate (AC's: 0 north, 90 east, the + /// same as getheadingto[]). False when the text isn't a coordinate or our position is unknown. + /// + private bool TryHeadingToCoords(string text, out double heading) + { + heading = 0; + var m = FaceCoordsRx.Match(text); + if (!m.Success || !NavCoordinateHelper.TryGetNavCoords(Host, out double myNs, out double myEw)) return false; + var inv = System.Globalization.CultureInfo.InvariantCulture; + double ns = double.Parse(m.Groups["ns"].Value, inv) * (char.ToUpperInvariant(m.Groups["nsc"].Value[0]) == 'S' ? -1 : 1); + double ew = double.Parse(m.Groups["ew"].Value, inv) * (char.ToUpperInvariant(m.Groups["ewc"].Value[0]) == 'W' ? -1 : 1); + double dNs = ns - myNs, dEw = ew - myEw; + if (Math.Abs(dNs) < 1e-6 && Math.Abs(dEw) < 1e-6) return false; + heading = Math.Atan2(dEw, dNs) * (180.0 / Math.PI); + if (heading < 0) heading += 360.0; return true; } diff --git a/Plugins/RynthCore.Plugin.RynthAi/ManaStoneManager.cs b/Plugins/RynthCore.Plugin.RynthAi/ManaStoneManager.cs index d538a04..0224a8d 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/ManaStoneManager.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/ManaStoneManager.cs @@ -996,7 +996,10 @@ internal sealed class ManaStoneManager if (_tapTargetCooldownUntil.TryGetValue(item.Id, out long until) && now < until) continue; - // Skip equipped items + // Skip equipped items: worn per the tracker (a wield record can read 0 for worn gear), or + // per the item's own slot. + if (EquippedState.IsWielded(_host, item.Id) == true) + continue; if (_host.TryGetObjectIntProperty(unchecked((uint)item.Id), (uint)AcIntProperty.WieldedSlot, out int wield) && wield != 0) continue; @@ -1060,12 +1063,22 @@ internal sealed class ManaStoneManager if (IsManaStone(item)) continue; if (!IsOwnedByPlayer(item, playerId)) continue; - // The live slot read can fail off AC's thread; the cache's copy (what /ra wielded - // uses) is the fallback. - if (!_host.TryGetObjectIntProperty(unchecked((uint)item.Id), (uint)AcIntProperty.WieldedSlot, out int wield) || wield == 0) - wield = item.Values(LongValueKey.CurrentWieldedLocation, 0); - if (wield == 0) - continue; + // What is worn: the engine's tracker of the server's wield/move messages (API v87) when it + // has one. An item's own wield record goes stale once it is moved to a pack: those counted + // as worn ("worn=41" for a character wearing 20, 2026-10-20) and took the one appraisal a + // pass, while gear really worn whose mana couldn't be read waited, skipped as unreadable. + // Without a tracker: the live slot read, then the cache's copy (what /ra wielded uses). + if (EquippedState.IsWielded(_host, item.Id) is bool tracked) + { + if (!tracked) continue; + } + else + { + if (!_host.TryGetObjectIntProperty(unchecked((uint)item.Id), (uint)AcIntProperty.WieldedSlot, out int wield) || wield == 0) + wield = item.Values(LongValueKey.CurrentWieldedLocation, 0); + if (wield == 0) + continue; + } worn++; // Only items that actually consume mana matter. Off AC's thread an item's mana is diff --git a/Plugins/RynthCore.Plugin.RynthAi/Meta/ExpressionEngine.UbCompat.cs b/Plugins/RynthCore.Plugin.RynthAi/Meta/ExpressionEngine.UbCompat.cs new file mode 100644 index 0000000..4793421 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAi/Meta/ExpressionEngine.UbCompat.cs @@ -0,0 +1,373 @@ +using System; +using System.Collections.Generic; +using System.Globalization; +using RynthCore.Plugin.RynthAi.LegacyUi; +using RynthCore.Plugin.Shared; + +namespace RynthCore.Plugin.RynthAi.Meta; + +/// +/// ub-IT expression functions that were missing (2026-10-18 meta-compatibility pass), with +/// ub-IT's names, arguments and return values. Where RynthAi has no matching data (character +/// select, Decal views, ub-IT's own HUDs) the function still answers, with the value ub-IT gives +/// when there is nothing to report, so an expression that calls it keeps working. +/// +internal sealed partial class ExpressionEngine +{ + /// Corpses this character has opened (the plugin's loot bookkeeping), for + /// hascorpsebeenopenedbyme[] and getcorpsesunopenedbyme[]. Null: none known. + internal Func? CorpseOpenedByMe { get; set; } + + /// The meta manager's '/vt opt set' (VTank names, distances in landblock units, the + /// special options), for vtsetsetting[]; null: the plain settings map (an engine without one). + internal Func? VtOptionSetter { get; set; } + + /// The meta manager's '/vt opt get' (values read back in VTank's units), for vtgetsetting[]. + internal Func? VtOptionGetter { get; set; } + + // getcooldownexpiration: shared cooldowns are enchantments whose spell id has this bit. + private const uint CooldownSpellFlag = 0x8000; + + // ub-IT's QuestRefreshCooldownSeconds default (canrefreshquests[]). + private const double QuestRefreshCooldownSeconds = 60; + + // Character property ids (PropertyInt64): total experience, available luminance. + private const uint QuadTotalExperience = 1; + private const uint QuadAvailableLuminance = 6; + // PropertyInt StackSize. + private const uint IntStackSize = 12; + + // XP meter (xpreset/xpmeter/xpduration/xptotal/lumtotal/xpavg/lumavg). Starts on the + // first call after login or a reset; luminance counts gains only (spending isn't earning). + private long _xpStartMs = -1; + private long _xpBase, _lumLast, _lumGained; + + // Functions with no RynthAi data already logged (one line each per session). + private readonly HashSet _ubNoDataLogged = new(StringComparer.OrdinalIgnoreCase); + + /// + /// The functions above. Returns false for any other name, so the caller's unknown-function + /// fallback still logs real typos. + /// + private bool TryEvalUbCompat(string funcName, List rawArgs, Func A, out string value) + { + value = funcName switch + { + // ── Inventory actions (1 = attempted, 0 = busy or not possible) ────── + "actiontrymove" => EvalActionTryMove(A(0), A(1), rawArgs.Count > 2 ? A(2) : "0", rawArgs.Count > 3 ? A(3) : "1"), + "actiontrysplit" => EvalActionTrySplit(A(0), A(1), rawArgs.Count > 2 ? A(2) : "", rawArgs.Count > 3 ? A(3) : "0"), + "actiontrydrop" => NoData("actiontrydrop", "0"), + + // ── Vitals of an object (current values; the selected target or yourself) ── + "wobjectgethealthvalue" => EvalWobjectVital(A(0), 0), + "wobjectgetstaminavalue" => EvalWobjectVital(A(0), 1), + "wobjectgetmanavalue" => EvalWobjectVital(A(0), 2), + + // ── Corpses ────────────────────────────────────────────────────────── + "hascorpsebeenopenedbyme" => EvalCorpseOpenedByMe(A(0)), + "getcorpsesunopenedbyme" => EvalCorpsesUnopenedByMe(), + + // ── Casting, cooldowns, spell data ─────────────────────────────────── + "iscasting" => _host.HasGetCastBusyState && _host.GetCastBusyState() != 0 ? "1" : "0", + "getcooldownexpiration" => EvalCooldownExpiration(A(0)), + "spelldata" => EvalSpellData(A(0)), + + // ── Macro state and delayed expressions ────────────────────────────── + "vtmacroenabled" => _settings?.IsMacroRunning == true ? "1" : "0", + "clearexec" => EvalClearExec(A(0)), + + // ── Quests (myquests throttle; ACECustom quest bonus lives in RynthILT) ── + "canrefreshquests" => EvalCanRefreshQuests(), + "testquestbonus" => NoData("testquestbonus", "0"), + "isrefreshingquestbonuses" => "0", + "enlightenmentmaterials" => EvalEnlightenmentTokens(A(0), A(1)), + + // ── XP meter ───────────────────────────────────────────────────────── + "xpreset" => EvalXpReset(), + "xpduration" => FormatNumber(XpSeconds()), + "xptotal" => FormatNumber(XpTotal()), + "lumtotal" => FormatNumber(LumTotal()), + "xpavg" => FormatNumber(PerHour(XpTotal())), + "lumavg" => FormatNumber(PerHour(LumTotal())), + "xpmeter" => EvalXpMeterText(), + + // ── No RynthAi equivalent: ub-IT's "nothing here" values ───────────── + "getcharacterindex" => NoData("getcharacterindex", "-1"), + "setnextlogin" => NoData("setnextlogin", "0"), + "clearnextlogin" => NoData("clearnextlogin", "1"), + "netclients" => NoData("netclients", "[]"), + "statushud" => NoData("statushud", "1"), + "statushudcolored" => NoData("statushudcolored", "1"), + // Decal views: none exist here, so no view is found or shown. + "uiviewexists" => NoData("uiviewexists", "0"), + "uiviewvisible" => NoData("uiviewvisible", "0"), + "uisetvisible" => NoData("uisetvisible", "0"), + "uisetlabel" => NoData("uisetlabel", "0"), + "uigetcontrol" => NoData("uigetcontrol", "0"), + _ => null!, + }; + return value != null; + } + + /// The fixed answer of a function RynthAi has no data for; logged once per session. + private string NoData(string funcName, string result) + { + if (_ubNoDataLogged.Add(funcName)) + _host.Log($"[RynthAi] Expression {funcName}[]: ub-IT feature with no RynthAi equivalent; returns {result}."); + return result; + } + + // ── Inventory actions ──────────────────────────────────────────────────── + + private bool IsBusy() => _host.HasGetBusyState && _host.GetBusyState() > 0; + + private int StackSizeOf(uint id) + { + if (_worldObjectCache != null) + { + int n = _worldObjectCache.GetIntProperty(unchecked((int)id), IntStackSize, 0); + if (n > 0) return n; + } + return 1; + } + + /// actiontrymove[obj, container, slot=0, addToStack=1]: into a stack of the same + /// name in that container when there is one (and addToStack), else into the slot. + private string EvalActionTryMove(string objArg, string destArg, string slotArg, string stackArg) + { + if (!TryParseWobjectHandle(objArg, out uint id, out _) || id == 0) return "0"; + if (!TryParseWobjectHandle(destArg, out uint dest, out _) || dest == 0) return "0"; + if (IsBusy()) return "0"; + + if (ToBool(stackArg) && _worldObjectCache != null && _host.HasMergeStackInternal) + { + string name = _worldObjectCache[unchecked((int)id)]?.Name ?? ""; + foreach (var wo in _worldObjectCache.GetContainedItems(unchecked((int)dest))) + { + if (unchecked((uint)wo.Id) == id || !string.Equals(wo.Name, name, StringComparison.Ordinal)) continue; + if (StackSizeOf(unchecked((uint)wo.Id)) <= 1 && StackSizeOf(id) <= 1) continue; + return _host.MergeStackInternal(id, unchecked((uint)wo.Id)) ? "1" : "0"; + } + } + + if (!_host.HasMoveItemInternal) return "0"; + int slot = (int)Math.Max(0, ToDouble(slotArg)); + return _host.MoveItemInternal(id, dest, slot, StackSizeOf(id)) ? "1" : "0"; + } + + /// actiontrysplit[obj, newStackSize, container=player, slot=0]: splits newStackSize off the stack. + private string EvalActionTrySplit(string objArg, string countArg, string destArg, string slotArg) + { + if (!TryParseWobjectHandle(objArg, out uint id, out _) || id == 0) return "0"; + int count = (int)ToDouble(countArg); + if (count < 1 || count >= StackSizeOf(id)) return "0"; + uint dest = TryParseWobjectHandle(destArg, out uint d, out _) && d != 0 ? d : _playerId; + if (dest == 0 || IsBusy() || !_host.HasSplitStackInternal) return "0"; + int slot = (int)Math.Max(0, ToDouble(slotArg)); + return _host.SplitStackInternal(id, dest, slot, count) ? "1" : "0"; + } + + // ── Vitals ─────────────────────────────────────────────────────────────── + + /// Current health (0), stamina (1) or mana (2) of the object; -1 when unknown. The + /// game reports these for yourself and for the target you've selected (as ub-IT notes). + private string EvalWobjectVital(string objArg, int which) + { + if (!TryParseWobjectHandle(objArg, out uint id, out _) || id == 0) return "-1"; + uint hp, st, mp; + if (id == _playerId) + { + if (!_host.TryGetPlayerVitals(out hp, out _, out st, out _, out mp, out _)) return "-1"; + } + else if (!_host.TryGetTargetVitals(id, out hp, out _, out st, out _, out mp, out _)) + { + return "-1"; + } + uint v = which switch { 0 => hp, 1 => st, _ => mp }; + return v.ToString(CultureInfo.InvariantCulture); + } + + // ── Corpses ────────────────────────────────────────────────────────────── + + private string EvalCorpseOpenedByMe(string objArg) + { + if (!TryParseWobjectHandle(objArg, out uint id, out _) || id == 0) return "0"; + return CorpseOpenedByMe?.Invoke(unchecked((int)id)) == true ? "1" : "0"; + } + + /// Corpses in view this character hasn't opened, as a list of objects. + private string EvalCorpsesUnopenedByMe() + { + if (_worldObjectCache == null) return "[]"; + var items = new List(); + var seen = new HashSet(); + foreach (var wo in _worldObjectCache.GetLandscape()) + { + if (wo.ObjectClass != AcObjectClass.Corpse || !seen.Add(wo.Id)) continue; + if (CorpseOpenedByMe?.Invoke(wo.Id) == true) continue; + items.Add(MakeWobjectHandle(unchecked((uint)wo.Id), wo.Name)); + } + return NewList(items); + } + + // ── Casting, cooldowns, spell data ─────────────────────────────────────── + + /// Seconds until shared cooldown ends; 0 when it isn't running. + private string EvalCooldownExpiration(string idArg) + { + int want = (int)ToDouble(idArg); + if (want <= 0 || !_host.HasReadPlayerEnchantments || !_host.HasGetServerTime) return "0"; + double now = _host.GetServerTime(); + if (now <= 0) return "0"; + const int Max = 512; + uint[] ids = new uint[Max]; + double[] expiry = new double[Max]; + int count = _host.ReadPlayerEnchantments(ids, expiry, Max); + for (int i = 0; i < count; i++) + { + if ((ids[i] & CooldownSpellFlag) == 0 || (ids[i] & 0xFFF) != want) continue; + double left = expiry[i] - now; + return left > 0 ? ((int)Math.Ceiling(left)).ToString(CultureInfo.InvariantCulture) : "0"; + } + return "0"; + } + + /// spelldata[id]: a dictionary of what RynthAi's spell table knows (Id, Name, Family, + /// Difficulty, Category, Power, Level). Empty for an unknown spell, as in ub-IT. + private string EvalSpellData(string idArg) + { + int id = (int)ToDouble(idArg); + var d = new Dictionary(StringComparer.Ordinal); + if (id > 0 && SpellDatabase.HasSpell(id)) + { + d["Id"] = id.ToString(CultureInfo.InvariantCulture); + d["Name"] = SpellDatabase.GetSpellName(id); + if (SpellDatabase.TryGetSpellMeta(id, out int family, out int difficulty)) + { + d["Family"] = family.ToString(CultureInfo.InvariantCulture); + d["Difficulty"] = difficulty.ToString(CultureInfo.InvariantCulture); + } + if (SpellDatabase.TryGetCategoryAndPower(id, out int category, out int power)) + { + d["Category"] = category.ToString(CultureInfo.InvariantCulture); + d["Power"] = power.ToString(CultureInfo.InvariantCulture); + d["Level"] = SpellDatabase.LevelFromPower(power).ToString(CultureInfo.InvariantCulture); + } + } + return NewDict(d); + } + + // ── Delayed expressions ────────────────────────────────────────────────── + + /// clearexec[id]: cancels the delayexec that returned that id. 1 if one was pending. + private string EvalClearExec(string idArg) + { + long id = (long)ToDouble(idArg); + int removed = _delayedExecs.RemoveAll(e => e.Id == id); + return removed > 0 ? "1" : "0"; + } + + // ── Quests ─────────────────────────────────────────────────────────────── + + private string EvalCanRefreshQuests() + { + if (_questTracker == null) return "1"; + if (_questTracker.IsRefreshing) return "0"; + return (DateTime.UtcNow - _questTracker.LastRefreshUtc).TotalSeconds >= QuestRefreshCooldownSeconds ? "1" : "0"; + } + + /// enlightenmentmaterials[current, target]: ub-IT's token count. Levels 6-150 cost + /// (level - 5) tokens each; levels 1-5 cost none and later levels cost other items. + private static string EvalEnlightenmentTokens(string curArg, string tgtArg) + { + int cur = (int)ToDouble(curArg), tgt = (int)ToDouble(tgtArg); + long tokens = 0; + for (int level = Math.Max(cur + 1, 6); level <= Math.Min(tgt, 150); level++) + tokens += level - 5; + return tokens.ToString(CultureInfo.InvariantCulture); + } + + // ── XP meter ───────────────────────────────────────────────────────────── + + private long ReadQuad(uint stype) + => _playerId != 0 && _host.HasGetObjectQuadProperty && _host.TryGetObjectQuadProperty(_playerId, stype, out long v) ? v : 0; + + /// Starts the meter on first use and folds in luminance gained since the last look. + private void SampleXpMeter() + { + long lum = ReadQuad(QuadAvailableLuminance); + if (_xpStartMs < 0) + { + _xpStartMs = TickMs(); + _xpBase = ReadQuad(QuadTotalExperience); + _lumLast = lum; + _lumGained = 0; + return; + } + if (lum > _lumLast) _lumGained += lum - _lumLast; + _lumLast = lum; + } + + /// Forgets the meter when the character changes (called from SetPlayerId). + private void ResetXpMeter() => _xpStartMs = -1; + + private string EvalXpReset() + { + ResetXpMeter(); + SampleXpMeter(); + return "1"; + } + + private double XpSeconds() + { + SampleXpMeter(); + return Math.Max(0, (TickMs() - _xpStartMs) / 1000.0); + } + + private double XpTotal() + { + SampleXpMeter(); + return Math.Max(0, ReadQuad(QuadTotalExperience) - _xpBase); + } + + private double LumTotal() + { + SampleXpMeter(); + return _lumGained; + } + + private double PerHour(double amount) + { + double s = XpSeconds(); + return s <= 0 ? 0 : amount / s * 3600; + } + + /// ub-IT's meter text: "500m XP and 2k LUM, 51s, 35.39b XP/hr and 140k LUM/hr". + private string EvalXpMeterText() + { + double xp = XpTotal(), lum = LumTotal(), s = XpSeconds(); + string head = lum > 0 ? $"{ShortNumber(xp)} XP and {ShortNumber(lum)} LUM" : $"{ShortNumber(xp)} XP"; + string rate = lum > 0 ? $"{ShortNumber(PerHour(xp))} XP/hr and {ShortNumber(PerHour(lum))} LUM/hr" : $"{ShortNumber(PerHour(xp))} XP/hr"; + return $"{head}, {ShortDuration(s)}, {rate}"; + } + + private static string FormatNumber(double v) => Math.Round(v, 2).ToString("0.##", CultureInfo.InvariantCulture); + + /// 1234 -> 1.23k, 5.6e8 -> 560m, as ub-IT's formatExperience. + private static string ShortNumber(double v) + { + string[] units = { "", "k", "m", "b", "t", "q" }; + int u = 0; + while (Math.Abs(v) >= 1000 && u < units.Length - 1) { v /= 1000; u++; } + return (u == 0 ? Math.Round(v).ToString("0", CultureInfo.InvariantCulture) + : v.ToString("0.##", CultureInfo.InvariantCulture)) + units[u]; + } + + private static string ShortDuration(double seconds) + { + var t = TimeSpan.FromSeconds(Math.Max(0, seconds)); + if (t.TotalHours >= 1) return $"{(int)t.TotalHours}h {t.Minutes}m"; + if (t.TotalMinutes >= 1) return $"{t.Minutes}m {t.Seconds}s"; + return $"{t.Seconds}s"; + } +} diff --git a/Plugins/RynthCore.Plugin.RynthAi/Meta/ExpressionEngine.cs b/Plugins/RynthCore.Plugin.RynthAi/Meta/ExpressionEngine.cs index f622425..98e1f87 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Meta/ExpressionEngine.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Meta/ExpressionEngine.cs @@ -33,7 +33,7 @@ namespace RynthCore.Plugin.RynthAi.Meta; /// Lists are text ("[a,b]"); the list functions that change a list write it back to the /// variable it came from. Dictionaries and stopwatches are handles ("D:0", "SW:0"). ///
-internal sealed class ExpressionEngine +internal sealed partial class ExpressionEngine { private readonly RynthCoreHost _host; private WorldObjectCache? _worldObjectCache; @@ -71,7 +71,7 @@ internal sealed class ExpressionEngine if (_pvars != null) foreach (string v in _pvars.Values) Scan(v); if (_gvars != null) foreach (string v in _gvars.Values) Scan(v); foreach (string v in _options.Values) Scan(v); - foreach (var (_, expr) in _delayedExecs) Scan(expr); + foreach (var (_, _, expr) in _delayedExecs) Scan(expr); while (todo.Count > 0) foreach (var (k, v) in _dicts[todo.Dequeue()]) { Scan(k); Scan(v); } @@ -133,7 +133,8 @@ internal sealed class ExpressionEngine // hot-reload to fire into a freed engine). Instance-scoped so a hot-reload // discards pending execs. Single-threaded access (Evaluate and the pump // both run on the plugin-tick thread) → no lock needed. - private readonly List<(long DueMs, string Expr)> _delayedExecs = new(); + private readonly List<(long Id, long DueMs, string Expr)> _delayedExecs = new(); + private long _nextDelayedExecId; private uint _playerId; private LegacyUiSettings? _settings; @@ -187,6 +188,7 @@ internal sealed class ExpressionEngine FlushVars(force: true); // persist the old char's pending pvars first _pvars = null; _pvarPathCached = null; + ResetXpMeter(); } _playerId = id; } @@ -557,8 +559,12 @@ internal sealed class ExpressionEngine // UB vtgetmeta[]: the loaded meta's name (file name without extension). "vtgetmeta" or "ragetmeta" => string.IsNullOrEmpty(_settings?.CurrentMetaPath) ? "" : Path.GetFileNameWithoutExtension(_settings!.CurrentMetaPath), - "rasetsetting" or "vtsetsetting" => EvalVtSetSetting(Text(0), A(1)), - "ragetsetting" or "vtgetsetting" or "vtankgetsetting" => EvalVtGetSetting(Text(0)), + // vt*: VTank option names and units (landblock distances), the same as '/vt opt set|get'; + // ra*: RynthAi's own setting names, as they are. + "vtsetsetting" => VtOptionSetter != null && Text(0).Length > 0 ? (VtOptionSetter(Text(0), A(1)) ? "1" : "0") : EvalVtSetSetting(Text(0), A(1)), + "vtgetsetting" or "vtankgetsetting" => VtOptionGetter != null && Text(0).Length > 0 ? VtOptionGetter(Text(0)) ?? "" : EvalVtGetSetting(Text(0)), + "rasetsetting" => EvalVtSetSetting(Text(0), A(1)), + "ragetsetting" => EvalVtGetSetting(Text(0)), // ── Dynamic evaluation ──────────────────────────────────────────── "exec" => Evaluate(A(0)), @@ -583,7 +589,8 @@ internal sealed class ExpressionEngine // "Strings support slices like arrays. ie test[1:]": a word that isn't a function, // followed by [start:stop]. _ when TopLevelColon(argsStr) >= 0 => SliceBy(expr.Substring(0, lb).Trim(), argsStr), - _ => EvalUnknownFunction(funcName) + // ub-IT's remaining functions (ExpressionEngine.UbCompat.cs), then a real unknown. + _ => TryEvalUbCompat(funcName, rawArgs, A, out string ubValue) ? ubValue : EvalUnknownFunction(funcName) }; } @@ -3681,6 +3688,7 @@ internal sealed class ExpressionEngine ["CorpseApproachRangeMin"] = (() => D(s.CorpseApproachRangeMin), v => { if (double.TryParse(v, System.Globalization.NumberStyles.Any, CultureInfo.InvariantCulture, out double d)) s.CorpseApproachRangeMin = d; }), ["ManaStoneKeepCount"] = (() => I(s.ManaStoneKeepCount), v => { if (int.TryParse(v, out int i)) s.ManaStoneKeepCount = i; }), ["RebuffSecondsRemaining"] = (() => I(s.RebuffSecondsRemaining), v => { if (int.TryParse(v, out int i)) s.RebuffSecondsRemaining = i; }), + ["BlacklistTimeoutSec"] = (() => I(s.BlacklistTimeoutSec), v => { if (double.TryParse(v, NumberStyles.Float, CultureInfo.InvariantCulture, out double d) && d >= 0) s.BlacklistTimeoutSec = (int)Math.Round(d); }), ["RebuffTopOffSecondsRemaining"] = (() => I(s.RebuffTopOffSecondsRemaining), v => { if (int.TryParse(v, out int i)) s.RebuffTopOffSecondsRemaining = i; }), ["CastBuffsOverItemBuffs"] = (() => B(s.CastBuffsOverItemBuffs), v => s.CastBuffsOverItemBuffs = ToDouble(v) != 0), ["FastBuffChain"] = (() => B(s.FastBuffChain), v => s.FastBuffChain = ToDouble(v) != 0), @@ -3738,8 +3746,10 @@ internal sealed class ExpressionEngine CultureInfo.InvariantCulture, out double delayMs)) delayMs = 0; long ms = (long)Math.Max(0, delayMs); - _delayedExecs.Add((TickMs() + ms, exprArg)); - return "1"; + // ub-IT returns the job's id (for clearexec); ids start at 1 so the result stays true. + long id = ++_nextDelayedExecId; + _delayedExecs.Add((id, TickMs() + ms, exprArg)); + return id.ToString(CultureInfo.InvariantCulture); } /// diff --git a/Plugins/RynthCore.Plugin.RynthAi/Meta/ExpressionReference.txt b/Plugins/RynthCore.Plugin.RynthAi/Meta/ExpressionReference.txt index d84ffe8..ba39439 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Meta/ExpressionReference.txt +++ b/Plugins/RynthCore.Plugin.RynthAi/Meta/ExpressionReference.txt @@ -658,7 +658,8 @@ ifthen[value, trueexpr, falseexpr] delayexec[delay, text] Schedules text to be evaluated as an expression after delay milliseconds. - Returns "1" immediately. The evaluation runs on a background thread — + Returns the job's id (1, 2, 3 ... as ub-IT), which clearexec[id] cancels. The + evaluation runs on a background thread — avoid using delayexec with expressions that modify shared variables concurrently with the meta tick loop. delay: milliseconds (1 second = 1000). @@ -1690,6 +1691,23 @@ ragetsetting[setting] Example: ragetsetting[MonsterRange] → "50" Example: cnumber[ragetsetting[MonsterRange]] → 50 (as number) +vtsetsetting[option, value] / vtgetsetting[option] + The same as '/vt opt set|get': VTank option names and VTank units. A VTank + distance option (AttackDistance, ApproachDistance, DoorOpenRange, OpenDoorRange, + AttackRange, RingDistance, CorpseApproachRange[-Min|-Max], PetCustomRange, + NavCloseStopRange) given as a value up to 1 is landblock units (x240 = yards); + a value above 1 is taken as yards already. vtgetsetting reads such a distance + back in landblock units. No other option is scaled. rasetsetting/ragetsetting use + RynthAi's own names and units, always. + +ub-IT functions answered here (ExpressionEngine.UbCompat.cs): actiontrymove, actiontrysplit, +actiontrydrop (always "0": nothing drops items), wobjectgethealthvalue / staminavalue / +manavalue, hascorpsebeenopenedbyme, getcorpsesunopenedbyme, iscasting, getcooldownexpiration, +spelldata, vtmacroenabled, clearexec, canrefreshquests, enlightenmentmaterials, xpreset / +xpmeter / xpduration / xptotal / lumtotal / xpavg / lumavg. Functions about ub-IT's own HUDs, +Decal views and character select (statushud, uiview*, getcharacterindex, netclients, ...) +answer with the value ub-IT gives when there is nothing to report. + Supported setting names: Booleans: EnableCombat, EnableBuffing, EnableNavigation, EnableLooting, EnableMeta, EnableRaycasting, EnableAutostack, EnableAutocram, diff --git a/Plugins/RynthCore.Plugin.RynthAi/Meta/MetaManager.cs b/Plugins/RynthCore.Plugin.RynthAi/Meta/MetaManager.cs index 0bebed8..4b5fe77 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Meta/MetaManager.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Meta/MetaManager.cs @@ -179,6 +179,15 @@ internal sealed class MetaManager _expressions?.SetKillClock(clock); } + // Corpses this character opened (the plugin's loot bookkeeping), for ub-IT's + // hascorpsebeenopenedbyme[] / getcorpsesunopenedbyme[]. + private Func? _corpseOpenedByMe; + public void SetCorpseOpenedCheck(Func? check) + { + _corpseOpenedByMe = check; + if (_expressions != null) _expressions.CorpseOpenedByMe = check; + } + public void SetPlayerId(uint id) { _playerId = id; @@ -231,6 +240,10 @@ internal sealed class MetaManager engine.SetSettings(_settings); engine.SetCreatureStore(_creatureStore); engine.SetKillClock(_killClock); + engine.CorpseOpenedByMe = _corpseOpenedByMe; + // vtsetsetting[] / vtgetsetting[] take VTank names and units, as '/vt opt set|get' does. + engine.VtOptionSetter = TrySetVtOption; + engine.VtOptionGetter = GetVtOption; return engine; } @@ -824,7 +837,20 @@ internal sealed class MetaManager // ── Action execution ───────────────────────────────────────────────────── + // Depth of ExecuteAction on the call stack: a rule's action (a chat command, a chat expression, + // an expression action) is running. The plugin's MetaCommandActive reads it, so a command is + // known to come from a running meta whichever way it reaches the plugin. + private int _actionDepth; + internal bool IsExecutingAction => _actionDepth > 0; + private void ExecuteAction(MetaRule rule) + { + _actionDepth++; + try { ExecuteActionCore(rule); } + finally { _actionDepth--; } + } + + private void ExecuteActionCore(MetaRule rule) { string ProcessData(string raw) { @@ -1171,6 +1197,39 @@ internal sealed class MetaManager return true; } + // /vt e — VTank's macro toggle (ub-IT sends it to switch VTank on or off). + if (sub == "e") + { + _raCommandHandler?.Invoke(_settings.IsMacroRunning ? "/ra stop" : "/ra start"); + return true; + } + + // /vt jump [heading] [shift true|false] [holdms] — VTank's jump (universalremote.met, ub-IT): + // RynthAi's jumper through /ra jump[s] [heading] [holdtime]. + if (sub == "jump") + { + string heading = parts.Length >= 3 ? parts[2] : ""; + bool shift = parts.Length >= 4 && (parts[3].Equals("true", StringComparison.OrdinalIgnoreCase) || parts[3] == "1"); + string hold = parts.Length >= 5 ? parts[4] : ""; + _raCommandHandler?.Invoke(("/ra jump" + (shift ? "s" : "") + " " + heading + " " + hold).Trim()); + return true; + } + + // /vt tapjump — a quick jump with no charge. + if (sub == "tapjump") + { + if (!(_host.HasTapJump && _host.TapJump())) + _host.WriteToChat("[RynthAi] /vt tapjump: the engine's jump isn't available.", 1); + return true; + } + + // /vt equipitemsfor — wield what that monster's rule names (weapon, off hand). + if (sub == "equipitemsfor" && parts.Length >= 3) + { + _raCommandHandler?.Invoke("/ra equipfor " + string.Join(" ", parts, 2, parts.Length - 2)); + return true; + } + // /vt meta load — the same load as /ra meta load (LegacyDashboardRenderer.LoadMetaByName): // a meta in MetaFiles, or, when there is none by that name, a new blank one (2026-10-13). if (sub == "meta" && parts.Length >= 4 && @@ -1193,8 +1252,8 @@ internal sealed class MetaManager return true; } - // /vt loot load — load a loot profile - if ((sub == "loot" || sub == "lootprofile") && parts.Length >= 4 && + // /vt loot load — load a loot profile ("looting load" too: FoundryIzexi.met, Meta_Society.met) + if ((sub == "loot" || sub == "lootprofile" || sub == "looting") && parts.Length >= 4 && parts[2].Equals("load", StringComparison.OrdinalIgnoreCase)) { string name = string.Join(" ", parts, 3, parts.Length - 3).Trim().Trim('"'); @@ -1231,8 +1290,20 @@ internal sealed class MetaManager return true; } - // /vt settings load / loadchar — ignore silently - if (sub == "settings") return true; + // /vt settings loadchar|savechar — RynthAi's settings profiles (/ra settings ...); + // universalremote.met switches profiles this way. Any other /vt settings verb is ignored. + if (sub == "settings") + { + if (parts.Length >= 4 && (parts[2].Equals("loadchar", StringComparison.OrdinalIgnoreCase) + || parts[2].Equals("savechar", StringComparison.OrdinalIgnoreCase))) + _raCommandHandler?.Invoke($"/ra settings {parts[2].ToLowerInvariant()} {string.Join(" ", parts, 3, parts.Length - 3)}"); + return true; + } + + // /vt public Func? MiniRemoteTabCommand { get; set; } - /// True when the cached ILT options already say /myquests is off (skip the login refresh). - public bool SkipLoginQuestRefresh => _ctx.Ilt.IsIltWorld && _ctx.Ilt.IsOff(RynthIltHub.FeatureQuests); + /// True when the server plugin already says /myquests is off on its server (skip the login refresh). + public bool SkipLoginQuestRefresh => _ctx.ServerHub.ServerActive && _ctx.ServerHub.IsOff(RynthIltHub.FeatureQuests); // ── Lifecycle ─────────────────────────────────────────────────────────── @@ -144,7 +144,7 @@ internal sealed class MiniRemoteController RynthLog.Trace(LogCat.Quests, "RefreshQuests()"); QuestTracker? t = _quests(); if (t == null) return "Quest tracker not ready."; - if (_ctx.Ilt.IsOff(RynthIltHub.FeatureQuests) || t.Disabled) return "/myquests is disabled on this server."; + if (_ctx.ServerHub.IsOff(RynthIltHub.FeatureQuests) || t.Disabled) return "/myquests is disabled on this server."; long now = MiniRemoteContext.NowMs; if (now - _lastQuestRefreshAt < QuestRefreshCooldownMs) return $"Wait {(QuestRefreshCooldownMs - (now - _lastQuestRefreshAt)) / 1000}s (server allows one /myquests per minute)."; @@ -220,12 +220,14 @@ internal sealed class MiniRemoteController // ── Commands ──────────────────────────────────────────────────────────── /// - /// "/ra hub [show|hide|toggle|open pets|crafting [show|hide|toggle]|open breeding|tab pets|crafting|breeding|remote]", - /// "/ra quests [refresh]", "/ra pets [show|hide|toggle]"; every other "/ra hub ..." verb, - /// "/ra guardian ..." and "/ra bounty|bounties|bountys ..." go to RynthILT. The retired quest - /// verbs and tab names ("/ra quests window", "/ra hub open quests", ...) say where quests went, - /// and "/ra hub open|tab character" opens RynthOracle's Character tab (Huds/MovedTabs.cs). - /// Returns false if not handled. + /// "/ra hub [show|hide|toggle|open pets|crafting [show|hide|toggle]|open|tab <a server plugin's Pets + /// sub-tab>|tab pets|crafting|remote]", "/ra quests [refresh]", "/ra pets [show|hide|toggle]"; every + /// other "/ra hub ..." verb goes to the server plugin (RynthILT on Infinite Leaftide: "/ra hub bank", + /// "/ra hub open banking", ...), and without one it shows the help. The retired quest verbs and tab + /// names ("/ra quests window", "/ra hub open quests", ...) say where quests went, and "/ra hub + /// open|tab character" opens RynthOracle's Character tab (Huds/MovedTabs.cs). "/ra guardian", + /// "/ra bounty" and the like aren't the Mini Remote's (RynthAiPlugin passes them to the server + /// plugin). Returns false if not handled. /// public bool HandleCommand(string verb, string[] args) { @@ -242,10 +244,8 @@ internal sealed class MiniRemoteController OpenTab(MiniRemoteTabs.Pets, args.Length > 0 ? args[0] : "toggle"); return true; } - bool ilt = verb.Equals("guardian", StringComparison.OrdinalIgnoreCase) || IsBountyVerb(verb); - if (!ilt && !verb.Equals("hub", StringComparison.OrdinalIgnoreCase)) return false; + if (!verb.Equals("hub", StringComparison.OrdinalIgnoreCase)) return false; - if (!ilt) { string cmd = args.Length > 0 ? args[0].ToLowerInvariant() : "toggle"; // "/ra hub open|tab quests": the tab is RynthOracle's window now. @@ -270,8 +270,8 @@ internal sealed class MiniRemoteController // The Mini Remote is the Hub's main window. _ctx.Chat(MiniRemoteCommand != null ? MiniRemoteCommand(cmd) : "[Mini Remote] The Mini Remote is not available yet."); return true; - case "open" or "tab" when args.Length > 1 && IsBreedingTabName(args[1]): - OpenBreeding(cmd); + case "open" or "tab" when args.Length > 1 && Pets.FindSubTab(args[1]) is { } subTab: + OpenPetsSubTab(cmd, subTab); return true; case "open" when args.Length > 1 && MiniRemoteTabs.Parse(args[1]) is { } openTab: OpenTab(openTab, args.Length > 2 ? args[2] : "toggle"); @@ -283,52 +283,39 @@ internal sealed class MiniRemoteController } } - // Everything else is an Infinite Leaftide verb: RynthILT's. + // Everything else is the server plugin's (RynthILT's "/ra hub bank", "/ra hub open banking", ...). string line = (verb + " " + string.Join(" ", args)).Trim(); - if (_ctx.Ilt.Command(line)) return true; - if (verb.Equals("hub", StringComparison.OrdinalIgnoreCase) && args.Length > 0 && args[0].Equals("tab", StringComparison.OrdinalIgnoreCase)) + if (_ctx.ServerHub.Command(line)) return true; + if (args.Length > 0 && args[0].Equals("tab", StringComparison.OrdinalIgnoreCase)) { - // A tab RynthILT doesn't offer (not loaded): back to the remote rather than nothing. + // A tab no plugin offers (the engine's dashboard): back to the remote rather than nothing. MiniRemoteTabCommand?.Invoke(MiniRemoteTabs.Remote, "select"); return true; } - if (verb.Equals("hub", StringComparison.OrdinalIgnoreCase)) PrintHelp(); - _ctx.Chat("[Mini Remote] " + IltClient.NotLoaded); + PrintHelp(); return true; } private void PrintHelp() { - _ctx.Chat("[Mini Remote] /ra hub [show|hide|toggle] (Mini Remote) /ra hub open pets|crafting [show|hide|toggle] /ra hub open breeding (ILT)"); + _ctx.Chat("[Mini Remote] /ra hub [show|hide|toggle] (Mini Remote) /ra hub open pets|crafting [show|hide|toggle]"); _ctx.Chat("[Mini Remote] /ra quests refresh (quiet /myquests) /ra pets [show|hide] Quest list, timers and rewards: RynthOracle (/ro)."); - _ctx.Chat("[Mini Remote] Banking, gear, charms, games, the Guardian, bounties, /ra hub attr ...: Infinite Leaftide, the RynthILT plugin."); + _ctx.Chat("[Mini Remote] A server plugin adds its own tabs and /ra hub verbs here once it is loaded for your world."); _ctx.Chat("[Mini Remote] Character overview and session: RynthOracle (/ro character). Force a server: /rc diagnostics."); } - /// "breeding" / "breed": the Pets tab's Breeding sub-tab (RynthILT's tracker, Infinite Leaftide). - private static bool IsBreedingTabName(string text) => text.Trim().ToLowerInvariant() is "breeding" or "breed"; - /// - /// "/ra hub open|tab breeding": the Pets tab on its Breeding sub-tab when RynthILT offers it. "open" - /// shows the Mini Remote and says why when there is no Breeding sub-tab; "tab" (the engine's - /// dashboard) only switches tabs, to the Pets roster when there is none. + /// "/ra hub open|tab <sub-tab>": the Pets tab on a sub-tab the server plugin adds (RynthILT's + /// Breeding). "open" shows the Mini Remote; "tab" (the engine's dashboard) only switches tabs. /// - private void OpenBreeding(string cmd) + private void OpenPetsSubTab(string cmd, string subTab) { - bool offered = Pets.BreedingOffered; - if (offered) Pets.SelectBreeding(); + Pets.SelectSubTab(subTab); if (cmd == "tab") { MiniRemoteTabCommand?.Invoke(MiniRemoteTabs.Pets, "select"); return; } - if (!offered) - { - _ctx.Chat("[Mini Remote] " + (!_ctx.Ilt.Loaded ? IltClient.NotLoaded - : !_ctx.Ilt.IsIltWorld ? "Pet breeding is an Infinite Leaftide feature; this world isn't Infinite Leaftide." - : "This server reports pet breeding off.")); - return; - } OpenTab(MiniRemoteTabs.Pets, "show"); } @@ -339,12 +326,6 @@ internal sealed class MiniRemoteController private static bool IsQuestsName(string text) => text.Equals("quests", StringComparison.OrdinalIgnoreCase) || text.Equals("quest", StringComparison.OrdinalIgnoreCase); - /// "/ra bounty", "/ra bounties" and the "/ra bountys" spelling (RynthILT's Bounties window). - public static bool IsBountyVerb(string verb) - => verb.Equals("bounty", StringComparison.OrdinalIgnoreCase) - || verb.Equals("bounties", StringComparison.OrdinalIgnoreCase) - || verb.Equals("bountys", StringComparison.OrdinalIgnoreCase); - /// Applies show / hide / toggle to one of the Mini Remote's own tabs. Says what happened. private void OpenTab(string tab, string mode) { diff --git a/Plugins/RynthCore.Plugin.RynthAi/MiniRemote/MiniRemoteInventory.cs b/Plugins/RynthCore.Plugin.RynthAi/MiniRemote/MiniRemoteInventory.cs index a155f28..fa49e7c 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/MiniRemote/MiniRemoteInventory.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/MiniRemote/MiniRemoteInventory.cs @@ -3,9 +3,8 @@ // ILT Hub went to the RynthILT plugin 2026-10-13, which has its own copy for its ILT features). // // One place for: WCID lookups (cached), stack / use counts, "is it equipped", appraisal requests -// (throttled), the Summon Essence Refill / Universal Summoning Mastery charm status (ACECustom -// items the Pets tab's refill path reads; harmless anywhere else) and player int/bool reads. -// Pump-thread only. +// (throttled) and player int/bool reads. (The ACECustom pet charms' status went to RynthILT with +// the charms, 2026-10-20.) Pump-thread only. using System; using System.Collections.Generic; using System.Linq; @@ -14,16 +13,12 @@ using RynthCore.PluginSdk; namespace RynthCore.Plugin.RynthAi.MiniRemote; -/// Charm ON / OFF read from its appraisal text. -internal enum CharmState { Unknown = -1, Off = 0, On = 1 } - internal sealed class MiniRemoteInventory { - // ── Well-known WCIDs (ACECustom content the Pets tab recognises) ───────── + // ── Well-known WCIDs ──────────────────────────────────────────────────── + /// Encapsulated Spirit (pet essence refills; never a pet itself). public const uint WcidEncapsulatedSpirit = 49485; - public const uint WcidSummonRefillCharm = 78780030; - public const uint WcidUniversalMasteryCharm = 78780031; - public static readonly uint[] WcidInfiniteCastingStone = { 777700019, 777700055 }; + // ACECustom's pet charms and the Infinite Casting Stone moved to RynthILT (IltPetAutomation) 2026-10-20. // ── Property ids ──────────────────────────────────────────────────────── public const uint IntStackSize = 12; @@ -32,9 +27,6 @@ internal sealed class MiniRemoteInventory public const uint IntNumTimesTinkered = 171; public const uint IntImbuedEffect = 179; public const uint IntMaterialType = 131; - public const uint StrUse = 14; - public const uint BoolPyrealRefillActive = 9049; - public const uint BoolUniversalMasteryActive = 50038; private readonly RynthCoreHost _host; private readonly Func _cache; @@ -125,31 +117,6 @@ internal sealed class MiniRemoteInventory public IEnumerable AllByWcid(params uint[] wcids) => Items().Where(wo => Array.IndexOf(wcids, Wcid(wo)) >= 0); - /// - /// True when the player carries spell components or an Infinite Casting Stone that isn't - /// known to be switched OFF (an OFF stone doesn't waive components). - /// - public bool HasCastingSupplies() - => AllByWcid(WcidInfiniteCastingStone).Any(stone => CharmStatus(stone) != CharmState.Off) - || Items().Any(wo => wo.ObjectClass == AcObjectClass.SpellComponent); - - /// - /// ON/OFF/Unknown from the appraisal Use text ("... Status: ON"). Requests appraisal - /// (throttled) when the text isn't loaded yet. - /// - public CharmState CharmStatus(WorldObject charm) - { - string use = Str(charm, StrUse); - if (use.Length == 0) - { - RequestAppraisal(charm); - return CharmState.Unknown; - } - if (use.Contains("Status: ON", StringComparison.OrdinalIgnoreCase)) return CharmState.On; - if (use.Contains("Status: OFF", StringComparison.OrdinalIgnoreCase)) return CharmState.Off; - return CharmState.Unknown; - } - // ── Actions ───────────────────────────────────────────────────────────── public bool Use(WorldObject wo) => _host.HasUseObject && _host.UseObject(unchecked((uint)wo.Id)); diff --git a/Plugins/RynthCore.Plugin.RynthAi/MiniRemote/MiniRemoteState.cs b/Plugins/RynthCore.Plugin.RynthAi/MiniRemote/MiniRemoteState.cs index 0d218f0..e301026 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/MiniRemote/MiniRemoteState.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/MiniRemote/MiniRemoteState.cs @@ -100,9 +100,9 @@ public sealed class PetTabState public int PetTimeoutSeconds = 30; /// - /// Allow a combat summon from an EMPTY essence when the Summon Essence Refill Charm is - /// active (ACECustom: the server refills from banked pyreals). Still requires the server - /// flag to be on (RynthILT reports it). + /// Obsolete since 2026-10-20 (unused here, kept so miniremote.json still loads): the "summon from + /// empty essences" opt-in of ACECustom's refill charm. It is RynthILT's now, which copied this + /// value once (IltMigration.ImportRynthAiSettings). /// public bool UsePyrealRefillPath; @@ -120,10 +120,11 @@ public sealed class PetTabState /// Seconds to wait before re-summoning the cosmetic pet after it despawns. public int CosmeticRespawnSeconds = 15; - // Auto siphon-lens capture (ACECustom MonsterCapture; Mini Remote > Pets). - /// When on, use the selected siphon lens on a nearby creature once it is weak enough. + // Obsolete since 2026-10-20, as UsePyrealRefillPath: ACECustom's siphon auto-capture moved to + // RynthILT (IltPetAutomation), which copied these once. Unused here; kept so old files load. + /// Obsolete: auto-capture's switch (RynthILT's now). public bool AutoCaptureEnabled; - /// Index into (Flawed to Asheron). + /// Obsolete: auto-capture's lens (RynthILT's now). public int CaptureLensIndex; } @@ -256,7 +257,6 @@ internal sealed class MiniRemoteStore s.Pet.RosterKind = Math.Clamp(s.Pet.RosterKind, 0, 2); s.Pet.RosterSort = Math.Clamp(s.Pet.RosterSort, 0, 6); s.Pet.CosmeticRespawnSeconds = Math.Clamp(s.Pet.CosmeticRespawnSeconds, 5, 600); - s.Pet.CaptureLensIndex = Math.Clamp(s.Pet.CaptureLensIndex, 0, PetCaptureRules.Lenses.Length - 1); s.Quests ??= new QuestsTabState(); s.Quests.QuestFilter ??= string.Empty; s.Quests.QuestFavorites ??= new(); diff --git a/Plugins/RynthCore.Plugin.RynthAi/MiniRemote/PetsTab.cs b/Plugins/RynthCore.Plugin.RynthAi/MiniRemote/PetsTab.cs index 3052e60..cee9f62 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/MiniRemote/PetsTab.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/MiniRemote/PetsTab.cs @@ -1,9 +1,11 @@ // PetsTab.cs — The Mini Remote's Pets tab. // Originally SilentKelpie's IltPets (ILT Hub). Summoning is every server's, so the tab stayed in -// RynthAi when the ILT Hub went to the RynthILT plugin (2026-10-13). The ACECustom bits it reads -// (the refill / mastery charm server flags, whether this is an ILT world) come from RynthILT -// (RynthILT.Hub GetFeature / IsIltWorld; unknown without it, which never spends pyreals); the -// /pets and /shinies logs moved to RynthILT, which draws them at the bottom of this tab. +// RynthAi when the ILT Hub went to the RynthILT plugin (2026-10-13). What is a server's own lives +// in that server's plugin and is drawn here through its hub (ServerHubClient, RynthILT.Hub): RynthILT +// draws ACECustom's pet charms, siphon auto-capture and the /pets and /shinies logs under the +// roster, adds the Breeding sub-tab, and answers whether an empty essence may be summoned +// (2026-10-20: charms, capture and that gate moved out of this file). Without a server plugin the +// tab is the retail one. // // * Pet roster (UtilityBelt Pets-tab style): every carried pet essence with three stat // lines (bond / level / craft · sex / mutations / potency / mastery · ratings / uses / @@ -18,18 +20,14 @@ // - Cosmetic: the tick picks a display pet; "Keep cosmetic pet out" summons it in // peace mode and dismisses it when PetManager needs the slot for a fight. // Summon / Despawn act on the highlighted row (or the type's chosen pet). -// * Pet charms: Summon Essence Refill (server refills an empty essence from banked -// pyreals) and Universal Summoning Mastery, read from the charm appraisal text and the -// player bools the server stamps. Feeds PetManager.AllowSummonOnEmpty. +// * Summon from an empty essence: PetManager.AllowSummonOnEmpty asks the server plugin +// (RynthILT.Hub AllowSummonOnEmpty: ACECustom's refill charm); no server plugin = never. // * Healing pet (UB HealingBuddy subset): summons a heal pet when HP drops, dismisses it // after the heal lands, holds PetManager's combat summons while it is out. -// * Auto siphon capture (ACECustom MonsterCapture): when enabled, uses the chosen lens on the -// nearest attackable creature within 5 m once it is <=20% health or under 20 HP (Asheron's -// Lens skips the health gate). Resonance still needs a prior failed capture on the server. -// * /pets and /shinies logs: RynthILT's (RynthILT.Hub section "pets-logs", ILT only). -// * Breeding sub-tab (Infinite Leaftide only): the tab becomes Roster | Breeding when RynthILT -// offers it (an ILT world whose server hasn't reported pet breeding off). Its whole body is -// RynthILT's pet breeding tracker (RynthILT.Hub section "pets-breeding"); this tab only hosts it. +// * The server plugin's sections under the roster (RynthILT: "pets-charms", "pets-capture", +// "pets-logs"); each draws nothing off its server. +// * Sub-tabs: the tab becomes Roster | ... when the server plugin offers sub-tabs for it +// (GetSubTabs "pets"; RynthILT's Breeding). Each sub-tab's whole body is the plugin's section. using System; using System.Collections.Generic; using System.Linq; @@ -60,17 +58,6 @@ internal sealed class PetsTab private long _lastHealThink; private string _healStatus = "idle"; - // Auto siphon-lens capture (ACECustom MonsterCapture). - private long _lastCaptureThink; - private long _captureCooldownUntil; - private volatile string _captureStatus = "off"; - private const long CaptureThinkMs = 250; - private const long CaptureCooldownMs = 2500; - private const long CaptureFailBackoffMs = 8000; - // Hard cap on lens uses: the loop stops on reply strings we only guess at, so it is also bounded - // per creature and over all creatures (PetCaptureThrottle). - private readonly PetCaptureThrottle _captureThrottle = new(); - // Roster snapshot (rebuilt on the pump thread, read by the render thread). private volatile PetStats[] _pets = Array.Empty(); private long _lastPetScan; @@ -90,11 +77,6 @@ internal sealed class PetsTab /// Mini Remote pet status: "Out", "Ready", "Empty" or "Healing" (empty when there is no pet). public string HudPetStatus => _hudPetStatus; - // Charm / supply status cached for the render thread. - private volatile bool _uiRefillActive; - private volatile bool _uiMasteryActive; - private volatile bool _uiHasCasting = true; - // Render-thread only: highlighted row and the sorted view cache. private int _highlightId; private PetStats[]? _viewSource; @@ -227,38 +209,14 @@ internal sealed class PetsTab return _ctx.Inventory.Items().FirstOrDefault(wo => ClassifyKind(wo, out _) == PetKind.Healing); } - // ── Charms / gates ────────────────────────────────────────────────────── - - /// Summon Essence Refill charm is carried and switched on (or the server stamped the player bool). - public bool RefillCharmActive() - { - if (_ctx.Inventory.PlayerBool(MiniRemoteInventory.BoolPyrealRefillActive)) return true; - var charm = _ctx.Inventory.FindByWcid(MiniRemoteInventory.WcidSummonRefillCharm); - return charm != null && _ctx.Inventory.CharmStatus(charm) == CharmState.On; - } - - public bool MasteryCharmActive() - { - if (_ctx.Ilt.IsOff(RynthIltHub.FeatureUniversalMastery)) return false; - if (_ctx.Inventory.PlayerBool(MiniRemoteInventory.BoolUniversalMasteryActive)) return true; - var charm = _ctx.Inventory.FindByWcid(MiniRemoteInventory.WcidUniversalMasteryCharm); - return charm != null && _ctx.Inventory.CharmStatus(charm) == CharmState.On; - } + // ── Gates ─────────────────────────────────────────────────────────────── /// - /// PetManager hook: summon from an empty essence (spends banked pyreals) only when the - /// player opted in, the refill charm is active, and the server has positively confirmed - /// the feature: either /ilt features reported pet_refill on, or the server stamped the - /// player's refill bool. An unknown feature state never spends. + /// PetManager hook: summon from an empty essence only when the server plugin says the server + /// refills it (RynthILT: ACECustom's Summon Essence Refill charm, opted in and confirmed by the + /// server). Without a server plugin, or when it is unsure, never: an empty essence isn't used. /// - public bool AllowSummonOnEmpty() - { - if (!S.UsePyrealRefillPath || !_ctx.Ilt.IsIltWorld || !RefillCharmActive()) return false; - bool confirmed = _ctx.Ilt.IsOn(RynthIltHub.FeaturePetRefill) - || _ctx.Inventory.PlayerBool(MiniRemoteInventory.BoolPyrealRefillActive); - if (!confirmed) RynthLog.Trace(LogCat.Pets, "summon-on-empty refused: pet_refill not confirmed by the server"); - return confirmed; - } + public bool AllowSummonOnEmpty() => _ctx.ServerHub.AllowSummonOnEmpty(); /// PetManager hook: hold combat summons while the heal pet cycle is running. public bool HoldCombatSummons() => _heal != HealState.Idle; @@ -293,21 +251,12 @@ internal sealed class PetsTab { _lastPetScan = nowMs; RebuildPetSnapshot(autoAppraise: true); - // Host reads (and appraisal requests) happen here, never on the render thread. - _uiRefillActive = RefillCharmActive(); - _uiMasteryActive = MasteryCharmActive(); - _uiHasCasting = _ctx.Inventory.HasCastingSupplies(); } if (nowMs - _lastHealThink >= 250) { _lastHealThink = nowMs; TickHealing(nowMs); } - if (nowMs - _lastCaptureThink >= CaptureThinkMs) - { - _lastCaptureThink = nowMs; - TickCapture(nowMs); - } if (nowMs - _lastPresenceThink >= 1000) { _lastPresenceThink = nowMs; @@ -354,50 +303,9 @@ internal sealed class PetsTab } } - // ACECustom MonsterCapture replies — back off after a refuse so we don't burn lenses. - if (S.AutoCaptureEnabled && text.Length > 0) - { - long now = MiniRemoteContext.NowMs; - if (PetCaptureLines.IsSuccess(text)) - { - _captureStatus = "captured"; - _captureThrottle.RecordSuccess(); - _captureCooldownUntil = now + CaptureCooldownMs; - } - else if (ContainsAny(text, - "too strong", - "blind rage", - "cannot be siphoned", - "cannot be captured", - "No creatures nearby", - "already dead", - "already being captured", - "hasn't failed a capture", - "echo has faded", - "Failed to consume")) - { - _captureStatus = "refused: " + Truncate(text, 48); - _captureCooldownUntil = now + CaptureFailBackoffMs; - } - else if (ContainsAny(text, "siphon failed", "lens shatters", "resisted your capture", "resonance fades")) - { - _captureStatus = "failed (creature may enrage)"; - _captureCooldownUntil = now + CaptureFailBackoffMs; - } - } return false; } - private static bool ContainsAny(string text, params string[] parts) - { - foreach (string p in parts) - if (text.IndexOf(p, StringComparison.OrdinalIgnoreCase) >= 0) return true; - return false; - } - - private static string Truncate(string s, int max) - => s.Length <= max ? s : s[..(max - 3)] + "..."; - public void OnLogout() { _heal = HealState.Idle; @@ -406,9 +314,6 @@ internal sealed class PetsTab _lastSummonEssenceId = 0; _cosmeticOutEssenceId = 0; _cosmeticNextAt = 0; - _captureCooldownUntil = 0; - _captureStatus = "off"; - _captureThrottle.Reset(); } // ── Healing pet ───────────────────────────────────────────────────────── @@ -479,154 +384,6 @@ internal sealed class PetsTab // ── Active pet ────────────────────────────────────────────────────────── - // ── Auto siphon capture (ACECustom MonsterCapture) ─────────────────────── - - /// - /// When Auto Capture is on, use the chosen siphon lens on the nearest attackable creature - /// within 5 m once ACECustom's health gate is met (≤20% or under 20 HP; Asheron's skips it). - /// The server picks the nearest creature itself — we only fire when that nearest candidate is - /// already weak enough, so a full-health neighbour closer than the wounded target won't waste a lens. - /// - private void TickCapture(long now) - { - if (!S.AutoCaptureEnabled) - { - _captureStatus = "off"; - return; - } - if (_ctx.Ilt.Loaded && _ctx.Ilt.IsOff(RynthIltHub.FeatureMonsterCapture)) - { - _captureStatus = "monster capture disabled on this server"; - return; - } - if (now < _captureCooldownUntil) - { - long left = (_captureCooldownUntil - now + 999) / 1000; - if (!_captureStatus.StartsWith("waiting", StringComparison.Ordinal)) - _captureStatus = $"waiting {left}s"; - return; - } - if (_ctx.Inventory.IsBusy) { _captureStatus = "busy"; return; } - - var lens = PetCaptureRules.LensAt(S.CaptureLensIndex); - var lensItem = _ctx.Inventory.FindByWcid(lens.Wcid); - if (lensItem == null) - { - _captureStatus = $"no {lens.Name} carried"; - return; - } - - if (!TryFindNearestCaptureTarget(out WorldObject? target, out double distM, out uint curHp, out uint maxHp)) - { - _captureStatus = "no attackable creature within 5 m"; - return; - } - - if (!PetCaptureRules.InRange(distM)) - { - _captureStatus = $"{target!.Name} at {distM:0.0} m (need <={PetCaptureRules.CaptureRangeM:0} m)"; - return; - } - - if (!PetCaptureRules.CanAttempt(lens, curHp, maxHp)) - { - float pct = maxHp > 0 ? curHp * 100f / maxHp : -1f; - _captureStatus = pct >= 0 - ? $"{target!.Name} at {pct:0}% / {curHp} HP (need <={PetCaptureRules.CaptureMaxHealthFraction:P0} or <{PetCaptureRules.CaptureMaxHealthPoints} HP)" - : $"{target!.Name}: health unknown"; - return; - } - - if (!_captureThrottle.MayAttempt(target!.Id, now)) - { - _captureStatus = $"{target.Name}: {PetCaptureThrottle.MaxTriesPerTarget} tries, no capture; left alone for {_captureThrottle.BlockedSecondsLeft(target.Id, now)}s"; - return; - } - - if (!_ctx.Inventory.Use(lensItem)) - { - _captureStatus = "UseObject refused"; - return; - } - _captureThrottle.RecordAttempt(target.Id, now); - if (_captureThrottle.Exhausted) - { - // Backstop: this many lenses with no recognized capture means something is off. Stop, don't keep burning them. - S.AutoCaptureEnabled = false; - RynthLog.Write(LogCat.Pets, - $"[Pets] auto-capture: {PetCaptureThrottle.MaxTriesWithoutSuccess} lens uses without a capture reply; auto-capture switched off"); - } - - float shown = maxHp > 0 ? curHp * 100f / maxHp : 0f; - _captureStatus = $"using {lens.Name} on {target!.Name} ({shown:0}% / {curHp} HP)"; - _captureCooldownUntil = now + CaptureCooldownMs; - RynthLog.Write(LogCat.Pets, - $"[Pets] auto-capture: {lens.Name} -> 0x{target.Id:X8} '{target.Name}' d={distM:0.0}m hp={curHp}/{maxHp}"); - } - - /// - /// Nearest attackable landscape creature within capture range, with vitals from the host when - /// available else the cache health ratio (fraction-only gate). - /// - private bool TryFindNearestCaptureTarget(out WorldObject? best, out double bestDist, out uint curHp, out uint maxHp) - { - best = null; - bestDist = double.MaxValue; - curHp = maxHp = 0; - var cache = _ctx.Inventory.Cache; - if (cache == null) return false; - uint playerId = _ctx.Inventory.PlayerId; - if (playerId == 0) return false; - int pid = unchecked((int)playerId); - string ownPrefix = _ctx.CharName.Length > 0 ? _ctx.CharName + "'s " : string.Empty; - - foreach (var wo in cache.GetLandscape()) - { - if (wo == null || wo.Id == pid) continue; - if (wo.ObjectClass != AcObjectClass.Monster) continue; - if (ownPrefix.Length > 0 && wo.Name.StartsWith(ownPrefix, StringComparison.Ordinal)) continue; - // Skip corpses / non-attackable when the host can tell. - if (_ctx.Host.HasObjectIsAttackable && !_ctx.Host.ObjectIsAttackable(unchecked((uint)wo.Id))) - continue; - - double d = cache.Distance(pid, wo.Id); - if (d < 0 || d > PetCaptureRules.CaptureRangeM || d >= bestDist) continue; - - if (!TryReadCreatureVitals(wo.Id, cache, out uint c, out uint m)) - continue; - if (c == 0) continue; // dead - - best = wo; - bestDist = d; - curHp = c; - maxHp = m; - } - return best != null; - } - - /// - /// Absolute vitals via TryGetTargetVitals when bound; else cache health ratio as a 0–1000 scale - /// so only the fraction half of ACECustom's gate can fire. - /// - private bool TryReadCreatureVitals(int id, WorldObjectCache cache, out uint cur, out uint max) - { - cur = max = 0; - if (_ctx.Host.HasGetTargetVitals - && _ctx.Host.TryGetTargetVitals(unchecked((uint)id), out uint h, out uint mh, out _, out _, out _, out _) - && mh > 0) - { - cur = h; - max = mh; - return true; - } - float ratio = cache.GetHealthRatio(id); - if (ratio < 0f) return false; - // Synthetic scale: ratio 0.20 → 200/1000 so IsWeakEnough's fraction half matches. - max = 1000; - cur = (uint)Math.Clamp((int)Math.Round(ratio * 1000f), 1, 1000); - return true; - } - /// The live "<Me>'s …" creature (server pet naming), or null. private WorldObject? FindOwnPet() { @@ -909,28 +666,54 @@ internal sealed class PetsTab // ── UI (render thread) ────────────────────────────────────────────────── - /// Set from any thread: the next frame opens the Breeding sub-tab ("/ra hub open breeding"). - private volatile bool _selectBreeding; + /// Set from any thread: the sub-tab the next frame opens ("/ra hub open breeding"); null = none. + private volatile string? _selectSubTab; - /// Shows the Breeding sub-tab on the next frame (any thread). - public void SelectBreeding() => _selectBreeding = true; + /// Shows sub-tab (a server plugin's section id) on the next frame (any thread). + public void SelectSubTab(string id) => _selectSubTab = id; + + /// The sub-tab a command asked for and the next frame will open; null = none. For the tests. + internal string? PendingSubTab => _selectSubTab; + + /// The sub-tabs the server plugin adds to this tab now (RynthILT's Breeding); empty without one. + public IReadOnlyList SubTabs() => _ctx.ServerHub.SubTabs(RynthIltHub.TabParentPets); /// - /// RynthILT offers the Breeding sub-tab: it calls this world Infinite Leaftide and the server - /// hasn't reported pet breeding off. False without RynthILT. Any thread. + /// The shown sub-tab a "/ra hub open|tab <name>" names: its label ("Breeding"), its id, or its id + /// without the "pets-" prefix ("breeding"; at least four letters of it, "breed"), case-insensitive. + /// Null when the server plugin offers none such. /// - public bool BreedingOffered => _ctx.Ilt.IsIltWorld && !_ctx.Ilt.IsOff(RynthIltHub.FeaturePetBreeding); + public string? FindSubTab(string name) + { + string n = (name ?? string.Empty).Trim(); + if (n.Length == 0) return null; + foreach (ServerTabInfo t in SubTabs()) + { + if (!t.Shown) continue; + string shortId = t.Id.StartsWith(SubTabPrefix, StringComparison.OrdinalIgnoreCase) ? t.Id[SubTabPrefix.Length..] : t.Id; + if (t.Label.Equals(n, StringComparison.OrdinalIgnoreCase) || t.Id.Equals(n, StringComparison.OrdinalIgnoreCase) + || shortId.Equals(n, StringComparison.OrdinalIgnoreCase) + || (n.Length >= 4 && shortId.StartsWith(n, StringComparison.OrdinalIgnoreCase))) + return t.Id; + } + return null; + } + + private const string SubTabPrefix = RynthIltHub.TabParentPets + "-"; /// - /// The Pets tab: the universal roster, and on Infinite Leaftide the Roster | Breeding sub-tabs - /// (Breeding is drawn by RynthILT). + /// The Pets tab: the universal roster, and Roster | ... sub-tabs when the server plugin adds some + /// (each drawn by that plugin). /// public void Render() { var settings = _ctx.Settings; if (settings == null) { ImGui.TextDisabled("Not logged in."); return; } - if (!BreedingOffered) + var subTabs = SubTabs(); + bool any = false; + foreach (ServerTabInfo t in subTabs) any |= t.Shown; + if (!any) { RenderRoster(settings); return; @@ -941,19 +724,34 @@ internal sealed class PetsTab RenderRoster(settings); ImGui.EndTabItem(); } - ImGuiTabItemFlags breedFlags = _selectBreeding ? ImGuiTabItemFlags.SetSelected : ImGuiTabItemFlags.None; - _selectBreeding = false; - if (BeginTab(BreedingTabLabel, breedFlags)) + string? select = System.Threading.Interlocked.Exchange(ref _selectSubTab, null); + foreach (ServerTabInfo t in subTabs) { - // RynthILT's tracker; an older RynthILT (before 0.3.1) has no such section and draws nothing. - if (!_ctx.Ilt.RenderSection(RynthIltHub.SectionPetBreeding)) - ImGui.TextDisabled("This RynthILT has no pet breeding tracker; update RynthILT to 0.3.1 or later."); + if (!t.Shown) continue; + ImGuiTabItemFlags flags = select != null && select.Equals(t.Id, StringComparison.OrdinalIgnoreCase) + ? ImGuiTabItemFlags.SetSelected : ImGuiTabItemFlags.None; + if (!BeginTab(SubTabLabel(t), flags)) continue; + if (!_ctx.ServerHub.RenderSection(t.Id)) + SafeImGui.TextDisabled("Not ready (the server plugin isn't drawing it)."); ImGui.EndTabItem(); } ImGui.EndTabBar(); } - private static readonly byte[] BreedingTabLabel = System.Text.Encoding.UTF8.GetBytes("Breeding##petbreeding\0"); + // Sub-tab labels as NUL-terminated UTF-8, built once per label (the tab bar runs every frame). + private readonly Dictionary _subTabLabels = new(StringComparer.Ordinal); + + private byte[] SubTabLabel(ServerTabInfo t) + { + string key = t.Label + "##petsub_" + t.Id; + if (!_subTabLabels.TryGetValue(key, out byte[]? label)) + { + label = new byte[System.Text.Encoding.UTF8.GetByteCount(key) + 1]; + System.Text.Encoding.UTF8.GetBytes(key, 0, key.Length, label, 0); + _subTabLabels[key] = label; + } + return label; + } /// /// BeginTabItem with flags but no close button (ImGui.NET pairs the flags overload with p_open, @@ -965,58 +763,18 @@ internal sealed class PetsTab return ImGuiNative.igBeginTabItem(label, null, flags) != 0; } - /// The universal roster: types, summons, ILT charms, healing pets and RynthILT's /pets logs. + /// The universal roster: types, summons, healing pets, and the server plugin's sections. private void RenderRoster(LegacyUiSettings settings) { RenderRosterHeader(settings); RenderRosterTable(); - // The tab is universal; the charms and the /pets and /shinies logs are ILT's (the logs RynthILT's). - bool ilt = _ctx.Ilt.IsIltWorld; - if (ilt) - { - ImGui.Separator(); - RenderCharms(); - ImGui.Separator(); - RenderCapture(); - } + // The server plugin's own pet features (RynthILT: ACECustom's charms and siphon capture); + // each draws its own separator, and nothing off its server. + _ctx.ServerHub.RenderSection(RynthIltHub.SectionPetCharms); + _ctx.ServerHub.RenderSection(RynthIltHub.SectionPetCapture); ImGui.Separator(); RenderHealing(); - _ctx.Ilt.RenderSection(RynthIltHub.SectionPetLogs); - } - - /// ACECustom siphon-lens auto-capture (ILT only): enable + which lens to use. - private void RenderCapture() - { - ImGui.TextColored(LegacyDashboardRenderer.ColTeal, "Monster capture"); - bool captureOff = _ctx.Ilt.IsOff(RynthIltHub.FeatureMonsterCapture); - ImGui.BeginDisabled(captureOff); - bool en = S.AutoCaptureEnabled; - if (ImGui.Checkbox("Auto-capture when a creature is weak enough", ref en)) - { - S.AutoCaptureEnabled = en; - _captureThrottle.Reset(); - } - if (ImGui.IsItemHovered()) - { - SafeImGui.SetTooltip( - "Uses the selected siphon lens on the nearest attackable creature within 5 m once it is\n" + - "at or below 20% health or under 20 HP (ACECustom MonsterCapture). Asheron's Lens skips\n" + - "the health gate. Resonance Lens still needs a prior failed capture on the server.\n" + - "Off by default. Stops on its own after 5 tries on one creature (it is left alone for 2 min)\n" + - "or 15 lens uses in a row with no capture."); - } - ImGui.SameLine(); - ImGui.SetNextItemWidth(120); - int lens = Math.Clamp(S.CaptureLensIndex, 0, PetCaptureRules.LensNames.Length - 1); - if (ImGui.Combo("##petcapturelens", ref lens, PetCaptureRules.LensNames, PetCaptureRules.LensNames.Length)) - S.CaptureLensIndex = lens; - if (ImGui.IsItemHovered()) - SafeImGui.SetTooltip("Which siphon lens to use. Must be carried in your pack."); - ImGui.EndDisabled(); - if (captureOff) - SafeImGui.TextDisabled("Monster capture is disabled on this server."); - else - SafeImGui.TextDisabled("Status: " + _captureStatus); + _ctx.ServerHub.RenderSection(RynthIltHub.SectionPetLogs); } /// Type / Sort combos, action buttons, the active-summon line and per-type options. @@ -1189,22 +947,6 @@ internal sealed class PetsTab _ => new Vector4(0.95f, 0.95f, 0.95f, 1f), }; - private void RenderCharms() - { - ImGui.TextColored(LegacyDashboardRenderer.ColTeal, "Pet charms"); - bool refillOff = _ctx.Ilt.IsOff(RynthIltHub.FeaturePetRefill); - ImGui.TextUnformatted("Summon Essence Refill: " + (refillOff ? "disabled on this server" : _uiRefillActive ? "ON" : "off / not carried")); - ImGui.BeginDisabled(refillOff); - bool usePath = S.UsePyrealRefillPath; - if (ImGui.Checkbox("Summon from empty essences while the refill charm is ON (spends banked pyreals)", ref usePath)) - S.UsePyrealRefillPath = usePath; - ImGui.EndDisabled(); - ImGui.TextUnformatted("Universal Summoning Mastery: " - + (_ctx.Ilt.IsOff(RynthIltHub.FeatureUniversalMastery) ? "disabled on this server" : _uiMasteryActive ? "ON" : "off / not carried")); - if (!_ctx.Ilt.IsOff(RynthIltHub.FeatureRequireComps) && !_uiHasCasting) - ImGui.TextColored(LegacyDashboardRenderer.ColAmber, "No spell components or Infinite Casting Stone carried."); - } - private void RenderHealing() { if (!ImGui.CollapsingHeader("Healing pet settings")) return; diff --git a/Plugins/RynthCore.Plugin.RynthAi/MiniRemote/ServerHubClient.cs b/Plugins/RynthCore.Plugin.RynthAi/MiniRemote/ServerHubClient.cs new file mode 100644 index 0000000..30e6842 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAi/MiniRemote/ServerHubClient.cs @@ -0,0 +1,303 @@ +// ServerHubClient.cs - RynthAi's side of a server plugin's hub (the "RynthILT.Hub" table layout, +// Plugins/Shared/RynthIltHubApi.cs; was IltClient until 2026-10-20): the tabs, sub-tabs and sections +// the Mini Remote hosts for the server you're on, its feature bits (the Quests tab's /myquests bit), +// its texts and settings, its "/ra" verbs, and its pet gate. RynthAi knows no server's content: it +// shows what the plugin offers. +// +// The plugin is found by the engine's server list first (the active server's owner plugin, under the +// neutral name "RynthServer.Hub"), then RynthILT under "RynthILT.Hub" (every RynthILT answers that; +// older ones only that). Without one (not installed, too old, not loaded yet: any retail-like world) +// every call answers "nothing": no tab, no section, unknown feature bits, no verbs. The table is +// looked up on the pump thread (Tick) at most every RecheckMs and kept in a volatile field for the +// render thread; the plugin never frees it (Version goes to 0 on its shutdown), so reading a stale +// pointer is safe and a Version of 0 means "look again". +using System; +using System.Collections.Generic; +using System.Runtime.InteropServices; +using System.Text; +using RynthCore.Plugin.Shared; +using RynthCore.PluginSdk; + +namespace RynthCore.Plugin.RynthAi.MiniRemote; + +/// One tab as the server plugin describes it (a copy). +internal readonly record struct ServerTabInfo(string Id, string Label, float Width, float Height, bool Shown, bool Available); + +internal sealed unsafe class ServerHubClient +{ + private const long RecheckMs = 3000; + private const int MaxTabs = 16; + + private readonly RynthCoreHost _host; + private IntPtr _table; // volatile reads/writes: the render thread uses what the pump found + private long _checkedAt; + private bool _checkedOnce; // false: look now (a sentinel time would overflow "now - _checkedAt") + private readonly IltTabV1[] _tabBuf = new IltTabV1[MaxTabs]; + private readonly List _tabs = new(); + + private bool _pinned; // tests: a table handed in, never looked up + + public ServerHubClient(RynthCoreHost host) => _host = host; + + /// Tests only: use (a fake server plugin's table) and never look it up. + internal void UseTableForTests(IntPtr table) + { + _pinned = true; + _checkedOnce = true; + System.Threading.Volatile.Write(ref _table, table); + } + + /// Pump thread: look the table up again when it's due, missing or shut down. + public void Tick() + { + if (_pinned) return; + long now = Environment.TickCount64; + var t = (RynthIltHubApiV1*)System.Threading.Volatile.Read(ref _table); + if (!LookupDue(_checkedOnce, _checkedAt, now, haveTable: t != null, tableLive: t != null && t->Version >= 1)) return; + _checkedOnce = true; + _checkedAt = now; + IntPtr found = IntPtr.Zero; + if (_host.HasGetPluginInterface) + { + // The active server's own plugin (the engine's server list), under the neutral name ... + string owner = ActiveServerPlugin(); + if (owner.Length > 0) found = Look(owner, RynthIltHubApiV1.NeutralInterfaceName); + // ... else RynthILT under its own name (every RynthILT; it also follows its own world check). + if (found == IntPtr.Zero) found = Look(RynthIltHub.PluginName, RynthIltHubApiV1.InterfaceName); + } + System.Threading.Volatile.Write(ref _table, found); + } + + /// A hub table serves as , or 0. + private IntPtr Look(string plugin, string iface) + { + var p = (RynthIltHubApiV1*)_host.GetPluginInterface(plugin, iface, RynthIltHubApiV1.InterfaceVersion); + // Any table at least as big as the first release's: newer functions are checked with Has. + return p != null && p->Version >= 1 && p->StructSize >= RynthIltHubApiV1.BaseStructSize ? (IntPtr)p : IntPtr.Zero; + } + + /// The plugin that owns the engine's active server ("" when none, or the engine is pre-v86). Pump thread. + private string ActiveServerPlugin() + { + try + { + if (!_host.HasGetServerStateJson || !_host.TryGetServerStateJson(out string json)) return string.Empty; + return EngineServerState.Parse(json)?.ActivePlugin ?? string.Empty; + } + catch { return string.Empty; } + } + + /// Forget the table (login, logout); the next Tick looks again. + public void Reset() + { + _pinned = false; + System.Threading.Volatile.Write(ref _table, IntPtr.Zero); + _checkedOnce = false; + } + + /// + /// Whether Tick looks the table up again. Pure. Always on the first call (and after Reset), at + /// once when the table RynthILT gave is shut down (Version 0), else every . + /// + internal static bool LookupDue(bool checkedOnce, long checkedAt, long now, bool haveTable, bool tableLive) + { + if (!checkedOnce) return true; + if (haveTable && !tableLive) return true; + return now - checkedAt >= RecheckMs; + } + + private RynthIltHubApiV1* T + { + get + { + var t = (RynthIltHubApiV1*)System.Threading.Volatile.Read(ref _table); + return t != null && t->Version >= 1 ? t : null; + } + } + + /// A server plugin answers (any thread). + public bool Loaded => T != null; + + /// This world is the plugin's server (or forced there), as it sees it (RynthILT: Infinite Leaftide). Any thread. + public bool ServerActive + { + get + { + var t = T; + return t != null && t->IsIltWorld != null && t->IsIltWorld() != 0; + } + } + + /// The server's bit for a feature: -1 unknown (and always off its server / without a plugin), 0 off, 1 on. Any thread. + public int Feature(string key) + { + var t = T; + if (t == null || t->GetFeature == null) return -1; + using var k = new Utf8(key); + return t->GetFeature(k.P); + } + + /// The server positively reported the feature off. + public bool IsOff(string key) => Feature(key) == 0; + + /// The server positively reported the feature on. + public bool IsOn(string key) => Feature(key) == 1; + + /// + /// A short text from the server plugin (RynthIltHub.Text*: the session report's tail, its server id); + /// "" without one, from an older one, or for nothing. Any thread. + /// + public string Text(string id) + { + var t = T; + if (t == null || !RynthIltHubApiV1.Has(t, RynthIltHubApiV1.GetTextOffset) || t->GetText == null) return string.Empty; + byte* buf = stackalloc byte[256]; + buf[0] = 0; + int n; + using (var k = new Utf8(id)) n = t->GetText(k.P, buf, 256); + if (n <= 0) return string.Empty; + buf[255] = 0; + return Marshal.PtrToStringUTF8((IntPtr)buf) ?? string.Empty; + } + + /// + /// This character forces the plugin's server (RynthILT: "Treat this world as ILT"; set there or in + /// RynthCore's Options > Diagnostics, never by RynthAi). Any thread. + /// + public bool ServerForced + { + get + { + var t = T; + return t != null && t->GetForceIlt != null && t->GetForceIlt() != 0; + } + } + + /// Render thread: the plugin's tabs with their flags (empty without one). The list is reused. + public IReadOnlyList Tabs() + { + _tabs.Clear(); + var t = T; + if (t == null || t->GetTabs == null) return _tabs; + int n; + fixed (IltTabV1* buf = _tabBuf) n = t->GetTabs(buf, MaxTabs); + n = Math.Min(n, MaxTabs); + for (int i = 0; i < n; i++) + { + ref IltTabV1 tab = ref _tabBuf[i]; + string id, label; + fixed (byte* pid = tab.Id) id = Marshal.PtrToStringUTF8((IntPtr)pid) ?? string.Empty; + fixed (byte* plabel = tab.Label) label = Marshal.PtrToStringUTF8((IntPtr)plabel) ?? string.Empty; + if (id.Length == 0) continue; + _tabs.Add(new ServerTabInfo(id, label.Length > 0 ? label : id, tab.Width, tab.Height, + (tab.Flags & RynthIltHub.TabShown) != 0, (tab.Flags & RynthIltHub.TabAvailable) != 0)); + } + return _tabs; + } + + /// Render thread: one ILT tab's body into the current child window; false = nothing drawn. + public bool RenderTab(string id) + { + var t = T; + if (t == null || t->RenderTab == null) return false; + using var s = new Utf8(id); + return t->RenderTab(s.P) != 0; + } + + /// Render thread: an ILT section (RynthIltHub.Section*); false = nothing drawn (not ILT, or no RynthILT). + public bool RenderSection(string id) + { + var t = T; + if (t == null || t->RenderSection == null) return false; + using var s = new Utf8(id); + return t->RenderSection(s.P) != 0; + } + + /// An ILT "/ra" verb ("hub bank", "guardian handin", ...); false when RynthILT doesn't take it. + public bool Command(string text) + { + var t = T; + if (t == null || t->Command == null) return false; + using var s = new Utf8(text); + return t->Command(s.P) != 0; + } + + /// + /// The server plugin's answer to "may an EMPTY pet essence be summoned?" (the server refills it; + /// RynthILT: ACECustom's Summon Essence Refill charm). False without one, or from an older one + /// that doesn't answer: an empty essence is then never used. Any thread. + /// + public bool AllowSummonOnEmpty() + { + var t = T; + return t != null && RynthIltHubApiV1.Has(t, RynthIltHubApiV1.AllowSummonOnEmptyOffset) + && t->AllowSummonOnEmpty != null && t->AllowSummonOnEmpty() != 0; + } + + /// One of the server plugin's mirrored settings (RynthIltHub.Setting*): its value, -1 when not offered. Any thread. + public int Setting(string key) + { + var t = T; + if (t == null || !RynthIltHubApiV1.Has(t, RynthIltHubApiV1.GetSettingOffset) || t->GetSetting == null) return -1; + using var k = new Utf8(key); + return t->GetSetting(k.P); + } + + /// Changes one of those settings; false when the plugin doesn't take it. Any thread. + public bool SetSetting(string key, int value) + { + var t = T; + if (t == null || !RynthIltHubApiV1.Has(t, RynthIltHubApiV1.SetSettingOffset) || t->SetSetting == null) return false; + using var k = new Utf8(key); + return t->SetSetting(k.P, value) != 0; + } + + private const int MaxSubTabs = 8; + + /// + /// The sub-tabs the server plugin adds to one of the Mini Remote's tabs ( + /// "pets": RynthILT's Breeding). Each id is a RenderSection id. Empty without one. A new list each + /// call (the render thread draws them, a command looks one up). Any thread. + /// + public IReadOnlyList SubTabs(string parent) + { + var t = T; + if (t == null || !RynthIltHubApiV1.Has(t, RynthIltHubApiV1.GetSubTabsOffset) || t->GetSubTabs == null) + return Array.Empty(); + IltTabV1* buf = stackalloc IltTabV1[MaxSubTabs]; + int n; + using (var p = new Utf8(parent)) n = t->GetSubTabs(p.P, buf, MaxSubTabs); + n = Math.Min(n, MaxSubTabs); + if (n <= 0) return Array.Empty(); + var list = new List(n); + for (int i = 0; i < n; i++) + { + IltTabV1* tab = &buf[i]; + tab->Id[23] = 0; // never read past a buffer the other side filled to the brim + tab->Label[31] = 0; + string id = Marshal.PtrToStringUTF8((IntPtr)tab->Id) ?? string.Empty; + string label = Marshal.PtrToStringUTF8((IntPtr)tab->Label) ?? string.Empty; + if (id.Length == 0) continue; + list.Add(new ServerTabInfo(id, label.Length > 0 ? label : id, tab->Width, tab->Height, + (tab->Flags & RynthIltHub.TabShown) != 0, (tab->Flags & RynthIltHub.TabAvailable) != 0)); + } + return list; + } + + /// A NUL-terminated UTF-8 copy of a string for one call. + private readonly struct Utf8 : IDisposable + { + public readonly byte* P; + + public Utf8(string? s) + { + s ??= string.Empty; + int n = Encoding.UTF8.GetByteCount(s); + P = (byte*)NativeMemory.Alloc((nuint)(n + 1)); + fixed (char* c = s) Encoding.UTF8.GetBytes(c, s.Length, P, n); + P[n] = 0; + } + + public void Dispose() => NativeMemory.Free(P); + } +} diff --git a/Plugins/RynthCore.Plugin.RynthAi/NavigationEngine.cs b/Plugins/RynthCore.Plugin.RynthAi/NavigationEngine.cs index af4ef00..c4f285b 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/NavigationEngine.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/NavigationEngine.cs @@ -2970,9 +2970,24 @@ internal sealed class NavigationEngine } } + // Already stopped, StopMovement sends a reminder at most this often (as StartForward re-asserts). + private const long StopReassertMs = 1000; + private long _lastStopSentMs; + private bool _stopSent; + private void StopMovement() { + // The pause, chat, portal, settle and idle paths call this every tick. It sent autorun-off and + // both turn keys each time even with the character standing still: in portal space the game + // thread takes none of them, 137 piled up and ran 12.7 s late on the far side, against the next + // route leg (Dargoth Hera's report, 2026-10-19). Now it sends when something moves, and a + // reminder once a second while stopped (something else may have started the character). + bool moving = _isMovingForward || _isTurning || _tier1TurnDir != 0; _isTurning = false; + long now = Now; + if (!moving && _stopSent && now - _lastStopSentMs < StopReassertMs) return; + _stopSent = true; + _lastStopSentMs = now; StopForward(); ClearTurnMotions(); } diff --git a/Plugins/RynthCore.Plugin.RynthAi/PlayerCompass.cs b/Plugins/RynthCore.Plugin.RynthAi/PlayerCompass.cs new file mode 100644 index 0000000..89ecfa2 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAi/PlayerCompass.cs @@ -0,0 +1,23 @@ +using System; +using RynthCore.PluginSdk; + +namespace RynthCore.Plugin.RynthAi; + +/// +/// Your heading as a compass bearing (0 = North, clockwise), from the pose quaternion: the +/// basis of TurnToHeading, map bearings and every nav and combat steer. Host.TryGetPlayerHeading +/// is another basis (0 = East, counter-clockwise: the radar's; measured 2026-10-20, Freya's +/// quaternion 13.9 against its 76.1), so it is never compared with a bearing or turned to. +/// +internal static class PlayerCompass +{ + public static bool TryGet(RynthCoreHost host, out float heading) + { + heading = 0; + if (!host.HasGetPlayerPose || !host.TryGetPlayerPose(out _, out _, out _, out _, out float qw, out _, out _, out float qz)) + return false; + double yaw = 2.0 * Math.Atan2(qz, qw) * (180.0 / Math.PI); + heading = (float)((-yaw % 360.0 + 720.0) % 360.0); + return true; + } +} diff --git a/Plugins/RynthCore.Plugin.RynthAi/PluginExports.cs b/Plugins/RynthCore.Plugin.RynthAi/PluginExports.cs index 5be3c7b..53af1b2 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/PluginExports.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/PluginExports.cs @@ -754,34 +754,6 @@ public static unsafe class PluginExports } } - private static IntPtr _progressionPtr = IntPtr.Zero; - - /// - /// The Skills panel's Progression tab for an engine that still asks RynthAi: the planners went - /// to RynthILT (2026-10-13), so this passes on RynthILT's RynthILTGetProgressionJson - /// ({"available":false} without RynthILT). Same contract as before: one static buffer, valid - /// until the next call; the engine polls it from its pump thread only. (The Charms Tracking - /// export, RynthPluginGetCharmsJson, for engines up to 2026.10.5.35 is gone with the charms.) - /// - [UnmanagedCallersOnly(EntryPoint = "RynthPluginGetProgressionJson", CallConvs = new[] { typeof(CallConvCdecl) })] - public static IntPtr GetProgressionJson() - { - try - { - var host = Runtime.Plugin?.HostForIlt; - string? json = host is { HasGetPluginExportJson: true } h ? h.GetPluginExportJson("RynthILT", "RynthILTGetProgressionJson") : null; - IntPtr newPtr = Marshal.StringToHGlobalAnsi(string.IsNullOrEmpty(json) ? "{\"available\":false}" : json); - IntPtr oldPtr = Interlocked.Exchange(ref _progressionPtr, newPtr); - if (oldPtr != IntPtr.Zero) - Marshal.FreeHGlobal(oldPtr); - return newPtr; - } - catch - { - return IntPtr.Zero; - } - } - // ── Items bridge (engine-side Avalonia ItemsPanel) ────────────────────── private static IntPtr _itemsPtr = IntPtr.Zero; diff --git a/Plugins/RynthCore.Plugin.RynthAi/RynthAiCommands.cs b/Plugins/RynthCore.Plugin.RynthAi/RynthAiCommands.cs index 72b5a33..31ff466 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/RynthAiCommands.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/RynthAiCommands.cs @@ -41,7 +41,6 @@ public sealed partial class RynthAiPlugin ChatLine("[RynthAi] /ra attackable — check if target is attackable"); ChatLine("[RynthAi] /ra wielded — show wielded items"); ChatLine("[RynthAi] /ra dumpprops [0xId] — every property of the selection (else yourself)"); - ChatLine("[RynthAi] /ra t11 [augs |refresh|item] — T11 loot: wield counters, aug override, parsed item"); ChatLine("[RynthAi] /ra iteminfo [name] — the selected (or named) item's details, Mag-Tools style"); ChatLine("[RynthAi] /ra mexec — evaluate meta expression"); ChatLine("[RynthAi] /ra listvars — show session variables"); @@ -2497,6 +2496,12 @@ public sealed partial class RynthAiPlugin private enum GiveItemMatch { Exact, Partial, Regex } + /// + /// The most stacks one give-all command (/ra givea*, /ub give) queues. A line that matches more + /// than this gives the first MaxGiveAllPerCommand and says so; run it again for the rest. + /// + internal const int MaxGiveAllPerCommand = 500; + /// /// Hands of an item to a player or NPC with AC's give action /// (Event_GiveObjectRequest) when the engine has it; MoveItemExternal is move-to-container @@ -2597,9 +2602,41 @@ public sealed partial class RynthAiPlugin if (allItems) { + // Every match goes, except what must never be handed over: equipped gear, the items + // RynthAi uses (Weapons and Consumables lists, monster-rule weapons), attuned and retained + // items, and, for a line a running meta sends, whatever the loot profile keeps. One log + // line per stack queued or skipped, and a cap on how many one command queues. + bool fromMeta = MetaCommandActive; + var toGive = new List(); + int protectedCount = 0; foreach (var item in matches) + { + string? why = ItemProtectionReason(item, includeLootKeep: fromMeta); + if (why != null) + { + protectedCount++; + Log($"[Give] skipped 0x{(uint)item.Id:X8} '{item.Name}': {why}"); + continue; + } + toGive.Add(item); + } + bool capped = toGive.Count > MaxGiveAllPerCommand; + if (capped) + { + Log($"[Give] '{itemPart}' matched {toGive.Count} stacks; the cap is {MaxGiveAllPerCommand}, so only the first {MaxGiveAllPerCommand} are queued."); + toGive.RemoveRange(MaxGiveAllPerCommand, toGive.Count - MaxGiveAllPerCommand); + } + foreach (var item in toGive) + { EnqueueGive((uint)item.Id, (uint)target.Id, 0); // 0 = the whole stack, whatever it reads at send time - ChatLine($"[RynthAi] Queued {matches.Count} stack(s) matching '{itemPart}' → {target.Name}"); + Log($"[Give] queued 0x{(uint)item.Id:X8} '{item.Name}' x{Math.Max(1, item.Values(LongValueKey.StackCount, 1))} -> {target.Name}{(fromMeta ? " (from a running meta)" : "")}"); + } + string skippedNote = protectedCount > 0 ? $", {protectedCount} protected stack(s) skipped" : ""; + string capNote = capped ? $", capped at {MaxGiveAllPerCommand}: run it again for the rest" : ""; + if (toGive.Count == 0) + ChatLine($"[RynthAi] Nothing to give: every item matching '{itemPart}' is protected ({protectedCount} skipped)."); + else + ChatLine($"[RynthAi] Queued {toGive.Count} stack(s) matching '{itemPart}' → {target.Name}{skippedNote}{capNote}"); } else if (countGiven) { diff --git a/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.LocalFeatures.cs b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.LocalFeatures.cs index 17caff1..86197cf 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.LocalFeatures.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.LocalFeatures.cs @@ -1,6 +1,6 @@ // RynthAiPlugin.LocalFeatures.cs — the Mini Remote's universal tabs, floating HUDs, chat // translation, item info, the nav overlay and the UB damage seed. (The ILT Hub moved to the RynthILT -// plugin 2026-10-13: its tabs come through RynthILT.Hub, MiniRemote/IltClient.cs, and RynthILT +// plugin 2026-10-13: its tabs come through RynthILT.Hub, MiniRemote/ServerHubClient.cs, and RynthILT // borrows from RynthAi through RynthAi.Hub, HubInterface.cs.) // // The engine draws the main panels. These features draw their own ImGui windows from @@ -20,8 +20,8 @@ public sealed partial class RynthAiPlugin private NavBreadcrumbTracker? _navBreadcrumbs; private NavOverlayRenderer? _navOverlay; private MiniRemote.MiniRemoteController? _miniRemote; - // RynthILT's side of the Mini Remote (its ILT tabs, sections, feature bits); lives for the plugin. - private MiniRemote.IltClient? _ilt; + // The server plugin's side of the Mini Remote (its tabs, sections, feature bits, verbs; RynthILT on ILT); lives for the plugin. + private MiniRemote.ServerHubClient? _serverHub; private Huds.HudController? _huds; private Huds.HudIconCache? _hudIcons; private Translate.ChatTranslator? _translator; @@ -120,10 +120,14 @@ public sealed partial class RynthAiPlugin return; var dash = _dashboard; - _ilt ??= new MiniRemote.IltClient(Host); + _serverHub ??= new MiniRemote.ServerHubClient(Host); + // The engine's Settings window mirrors the server plugin's own settings (RynthILT's Vaulted Dungeons switch). + var ilt = _serverHub; + dash.ServerSettingGet = key => ilt.Setting(key); + dash.ServerSettingSet = (key, value) => ilt.SetSetting(key, value); _miniRemote = new MiniRemote.MiniRemoteController(Host, dash.CharFolder, () => _objectCache, () => dash.Settings, () => _questTracker, - () => dash.SaveSettings(), _ilt); + () => dash.SaveSettings(), _serverHub); _hudIcons ??= new Huds.HudIconCache(Host, () => _raycast?.GeometryLoader?.PortalDat); _huds = new Huds.HudController(Host, dash.CharFolder, () => _objectCache, dash, () => _miniRemote, _hudIcons, () => _combatManager?.activeTargetId ?? 0) @@ -159,9 +163,20 @@ public sealed partial class RynthAiPlugin internal MiniRemote.MiniRemoteController? MiniRemoteForIlt => _miniRemote; internal WorldObjectCache? ObjectCacheForIlt => _objectCache; internal RynthCore.Plugin.Shared.SessionStatsTracker? SessionStatsForIlt => _sessionStats; - /// The Vaulted Dungeons master switch (Settings > Navigation); false before login. + /// + /// RynthAi.Hub VaultedDungeonsEnabled (obsolete slot): the value the profile still carries, which + /// RynthILT copied once and owns since 2026-10-20 (an older RynthILT still reads it here); false before login. + /// internal bool VaultedDungeonsEnabledForIlt => _dashboard?.Settings.EnableVaultedDungeons == true; + /// RynthAi.Hub BackAwayFrom: combat's back-away (CombatManager.BackAwayFrom); not now before login. Pump thread. + internal int BackAwayForServer(uint objectId, float radiusYards, int holdMs) + { + var combat = _combatManager; + if (combat == null || !_loginComplete) return RynthCore.Plugin.Shared.RynthAiHub.BackAwayNotNow; + return combat.BackAwayFrom(unchecked((int)objectId), radiusYards, holdMs, "server plugin"); + } + /// Item Info window, created once settings exist. private void EnsureItemInfoUi() { @@ -177,8 +192,8 @@ public sealed partial class RynthAiPlugin catch (Exception ex) { Host.Log($"[RynthAi] diagnostics pump: {ex.Message}"); } try { _sessionStats?.Tick(); } catch (Exception ex) { RynthLog.Exception(LogCat.Huds, ex, "session stats tick"); } - try { _ilt?.Tick(); } - catch (Exception ex) { RynthLog.Exception(LogCat.UI, ex, "RynthILT lookup"); } + try { _serverHub?.Tick(); } + catch (Exception ex) { RynthLog.Exception(LogCat.UI, ex, "server plugin hub lookup"); } try { _miniRemote?.Tick(); } catch (Exception ex) { RynthLog.Exception(LogCat.UI, ex, "Mini Remote Tick"); } try { _huds?.Tick(); } @@ -191,7 +206,6 @@ public sealed partial class RynthAiPlugin catch (Exception ex) { RynthLog.Exception(LogCat.General, ex, "spells window tick"); } try { _navBreadcrumbs?.Tick(); } catch (Exception ex) { RynthLog.Exception(LogCat.Navigation, ex, "nav breadcrumbs tick"); } - Loot.T11ItemSupport.SyncOverride(_dashboard?.Settings.T11ItemAugsOverride ?? -1); } /// Drop per-character feature objects. The translator is disposed only on plugin shutdown. @@ -205,7 +219,7 @@ public sealed partial class RynthAiPlugin try { _miniRemote?.OnLogout(); } catch (Exception ex) { RynthLog.Exception(LogCat.UI, ex, "Mini Remote logout"); } _miniRemote = null; - _ilt?.Reset(); + _serverHub?.Reset(); try { _huds?.OnLogout(); } catch (Exception ex) { RynthLog.Exception(LogCat.Huds, ex, "logout"); } _huds = null; @@ -400,7 +414,8 @@ public sealed partial class RynthAiPlugin /// Remote sections (Huds/SectionsManifest.cs lists them), drawn into the engine's current /// window (and context, see ) at . /// is the size the view would like. False (nothing drawn) for an - /// unknown view, or until login and the view's owner exist (RynthILT for the ILT tabs). Render thread. + /// unknown view, or until login and the view's owner exist. (A server plugin's tab views are its own: + /// RynthILT draws its ILT tabs since 2026-10-20.) Render thread. /// public bool RenderEmbeddedSection(string surface, System.Numerics.Vector2 size, out System.Numerics.Vector2 want) { @@ -427,14 +442,6 @@ public sealed partial class RynthAiPlugin want = MiniRemoteTabs.Size(ownTab); draw = () => remote.RenderTab(ownTab); } - else if (Huds.SectionsManifest.TryIltTabOf(surface, out string iltTab)) - { - if (remote == null || !remote.Ilt.Loaded) return false; - foreach (IltTabInfo t in remote.Ilt.Tabs()) - if (string.Equals(t.Id, iltTab, StringComparison.OrdinalIgnoreCase) && t.Width > 0 && t.Height > 0) - want = new System.Numerics.Vector2(t.Width, t.Height); - draw = () => remote.Ilt.RenderTab(iltTab); - } else if (surface == Huds.SectionsManifest.SpellsSurface) { EnsureSpellsUi(); @@ -466,16 +473,14 @@ public sealed partial class RynthAiPlugin } /// - /// RynthPluginGetSectionsJson: what RynthAi adds to RynthCore's Mini Remote sections, from - /// what is available now (Huds/SectionsManifest.cs; RynthILT's tabs through RynthILT.Hub). - /// Null before login (RynthCore then shows none of RynthAi's views). Render thread. + /// RynthPluginGetSectionsJson: what RynthAi adds to RynthCore's Mini Remote sections (Huds/ + /// SectionsManifest.cs; a server plugin lists its own). Null before login (RynthCore then shows + /// none of RynthAi's views). Render thread. /// public string? BuildSectionsJson() { if (!_initialized || !_loginComplete) return null; - var remote = _miniRemote; - IReadOnlyList iltTabs = remote != null ? remote.Ilt.Tabs() : Array.Empty(); - return Huds.SectionsManifest.Build(Huds.SectionsManifest.Views(iltTabs), Huds.SectionsManifest.OwnSections); + return Huds.SectionsManifest.Build(Huds.SectionsManifest.Views(), Huds.SectionsManifest.OwnSections); } /// Chat Translate window in the dashboard colours (no-op while hidden). private void RenderTranslateWindow() @@ -494,16 +499,6 @@ public sealed partial class RynthAiPlugin ChatLine("[RynthAi] " + _huds.HandleCommand(which, mode)); } - /// - /// "prog ..." from an older engine's Skills panel (newer engines send it to RynthILT, which owns - /// the progression planners since 2026-10-13): passed on to RynthILT. Pump thread. - /// - private void HandleProgressionRemote(string value) - { - if (!Host.HasSendPluginCommand || !Host.SendPluginCommand("RynthILT", "prog", value)) - ChatLine("[RynthAi] Progression is an Infinite Leaftide feature: it comes with the RynthILT plugin."); - } - /// "/ra itemhud add <name>" and the inventory panel's "Add to item count HUD". Pump thread. private void HandleItemHudAdd(string name) { @@ -560,11 +555,6 @@ public sealed partial class RynthAiPlugin bool? state = ParseOnOff(action); bool isAll = target.Equals("all", StringComparison.OrdinalIgnoreCase); - if (target.Equals("ilt", StringComparison.OrdinalIgnoreCase)) - { - ChatLine("[RynthAi] The ILT features trace in RynthILT now: /ilt trace all on|off."); - return; - } if (isAll) { if (!state.HasValue) { foreach (string l in RynthLog.StatusLines()) ChatLine(l); return; } diff --git a/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.cs b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.cs index afd8590..9fe7345 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.cs @@ -282,6 +282,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase long t0 = Environment.TickCount64; try { _dashboard?.SaveSettings(); } catch { } try { _sessionStats?.Shutdown(); } catch { } + try { GameInput.Shutdown(); } catch { } // keys still held for /mt movement | jump | strafe // Release the Monster Editor process handle (if the toggle button // launched one) rather than leaking it on plugin unload/hot-reload. try { _dashboard?.ReleaseMonsterEditorHandle(); } catch { } @@ -742,8 +743,9 @@ public sealed partial class RynthAiPlugin : RynthPluginBase _combatManager.ManaReserveHold = spellId => _buffManager?.OffensiveCastHold(spellId); // the mana reserve _combatManager.ManaCanEverAfford = spellId => _buffManager?.CanEverAfford(spellId) ?? true; // script hook: never-payable spells _combatManager.SetStaleBusyCallback(OnCombatBusyStale); - // Empyrean Handler lethal-ring: face the Handler, run-back jump (Jumper "xs"), re-engage. - // Read _jumper at call time — it is constructed later in this session setup. + // A server plugin's back-away (RynthAi.Hub BackAwayFrom; RynthILT's Empyrean Handler ring): face + // the danger, run-back jump (Jumper "xs"), re-engage. Read _jumper at call time — it is + // constructed later in this session setup. _combatManager.RequestBackJump = (faceHeading, ms) => _jumper != null && _jumper.Start("xs", faceHeading, ms); _combatManager.JumpBusy = () => _jumper?.IsBusy == true; _buffManager?.SetStaleBusyCallback(OnCombatBusyStale); // a heal ahead of a leftover busy count @@ -778,7 +780,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase _metaManager = new MetaManager(_dashboard.Settings, Host, _vitals); _metaManager.SetPlayerId(_playerId); - _metaManager.SetMtCommandHandler(HandleMtCommand); + _metaManager.SetMtCommandHandler(HandleMetaChatCommand); _metaManager.SetRaCommandHandler(HandleRaCommand); if (_objectCache != null) _metaManager.SetObjectCache(_objectCache); _metaManager.SetFellowshipTracker(_fellowshipTracker); @@ -786,6 +788,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase if (_buffManager != null) _metaManager.SetBuffManager(_buffManager); _metaManager.SetCreatureStore(_creatureStore); _metaManager.SetKillClock(_killClock); + _metaManager.SetCorpseOpenedCheck(id => _completedCorpses.ContainsKey(id)); if (_dashboard != null) _dashboard.MetaSnapshotProvider = () => _metaManager?.GetStateSnapshot(); @@ -801,7 +804,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase CreateMiniRemote(); if (_miniRemote?.SkipLoginQuestRefresh == true) - Log("RynthAi: RynthILT says /myquests is off on this server; login quest refresh already ran."); + Log("RynthAi: the server plugin says /myquests is off on this server; login quest refresh already ran."); try { string hubChar = CurrentCharacterName(); @@ -995,13 +998,10 @@ public sealed partial class RynthAiPlugin : RynthPluginBase case "hub": case "quests": case "pets": - case "guardian": - case "bounty": - case "bounties": - case "bountys": // Dashboard Char launcher and its right-click menu (hub=tab
switches the - // Mini Remote's tab); value carries the "/ra hub|quests|pets|bounty" arguments. The - // Infinite Leaftide verbs go on to RynthILT (MiniRemoteController.HandleCommand). + // Mini Remote's tab); value carries the "/ra hub|quests|pets" arguments. A hub verb that + // isn't RynthAi's goes on to the server plugin (MiniRemoteController.HandleCommand), and so + // does any other action RynthAi doesn't have (default below: "guardian", "bounty", ...). if (_miniRemote == null) { ChatLine("[RynthAi] The Mini Remote isn't ready (log in first)."); break; } _miniRemote.HandleCommand(action.ToLowerInvariant(), value.Split(' ', StringSplitOptions.RemoveEmptyEntries)); break; @@ -1021,10 +1021,6 @@ public sealed partial class RynthAiPlugin : RynthPluginBase if (_huds == null) { ChatLine("[RynthAi] HUDs not ready (log in first)."); break; } if (!_huds.HandleRemoteSlot(value)) Host.Log($"[RynthAi] bad remoteslot value: {value}"); break; - case "prog": - // Skills panel Progression tab (augmentations / enlightenment edits). - HandleProgressionRemote(value); - break; case "trace": case "logs": case "iteminfo": @@ -1045,6 +1041,8 @@ public sealed partial class RynthAiPlugin : RynthPluginBase // movestart/movestop are applied DIRECTLY by the RynthRemote plugin (pure Host.SetAutoRun/ // SetMotion + its own dead-man watchdog) and are never forwarded here. default: + // The server plugin's verbs sent to RynthAi (an engine button for "/ra guardian", "/ra bounty", ...). + if (_serverHub != null && _serverHub.Command((action.ToLowerInvariant() + " " + value).Trim())) break; Host.Log($"[RynthAi] ignored unknown remote command: {action}={value}"); return; } @@ -1448,6 +1446,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase if (_loginComplete) PostDataWriteProblems(); // a save that failed / folder not writable: say so in chat CombatHook.ObserveUseDone(); // ctx.last.err: the answer to the hook's last cast TickDelayedCommands(); // /ub delay + GameInput.Pump(); // release keys held for /mt movement | jump | strafe DrainEngineCommands(); // fellowship command buttons (RynthCore's Fellowship section) TickPropertyDump(); // /ub propertydump: waits for the ID, chat in chunks if (_loginComplete) _dashboard?.TickPackSetup(_objectCache, _playerId); // new/copied profile items @@ -1623,7 +1622,6 @@ public sealed partial class RynthAiPlugin : RynthPluginBase if (diag) Host.Log("[RynthAi] OnTick: after quest tracker"); DrainGiveQueue(); if (diag) Host.Log("[RynthAi] OnTick: after drain give queue"); - Loot.T11ItemSupport.SyncOverride(_dashboard?.Settings.T11ItemAugsOverride ?? -1); _jumper?.Tick(); if (diag) Host.Log("[RynthAi] OnTick: after jumper tick"); @@ -2371,14 +2369,10 @@ public sealed partial class RynthAiPlugin : RynthPluginBase _combatManager?.TraceCastChat(text, chatType); _combatManager?.HandleChatForDebuffs(text); _combatManager?.HandleChatForDamage(text, chatType); - _combatManager?.HandleChatForRingEvade(text, chatType); _missileCraftingManager?.HandleChat(text); _scrollLearner?.OnChat(text); _metaManager?.HandleChat(text, chatType); _questTracker?.OnChatLine(text); - // The "/aug" reply carries the T11 wield counters (RynthILT's login probe requests it on ILT). - try { Loot.T11ItemSupport.OnChat(text); } - catch (Exception ex) { RynthLog.Exception(LogCat.Looting, ex, "T11 /aug parse"); } CheckChatForSafetyStops(text); try { OnOwnCorpseChat(text); } catch { } } @@ -3826,6 +3820,18 @@ public sealed partial class RynthAiPlugin : RynthPluginBase DispatchRaCommand(cmd, parts, ref eat); } + /// + /// An unknown "/ra" verb offered to the active server plugin (RynthILT.Hub Command, the words after + /// "/ra"). True when it took it (it answers in chat itself). Main / pump thread. + /// + private bool TryForwardToServerPlugin(string[] parts) + { + var server = _serverHub; + if (server == null || parts.Length < 2) return false; + try { return server.Command(string.Join(" ", parts, 1, parts.Length - 1)); } + catch (Exception ex) { RynthLog.Exception(LogCat.UI, ex, "server plugin command"); return false; } + } + private void DispatchRaCommand(string cmd, string[] parts, ref int eat) { // Need trimmed original for commands that use it @@ -3858,7 +3864,6 @@ public sealed partial class RynthAiPlugin : RynthPluginBase case "dumpprops": HandleDumpPropsCommand(parts); break; case "version": HandleVersionCommand(); break; case "server": HandleServerCommand(); break; - case "t11": HandleT11Command(parts); break; case "wielded": HandleWieldedCommand(); break; case "scan": HandleScanCommand(); break; case "buildinfo": HandleBuildInfoCommand(); break; @@ -3873,10 +3878,8 @@ public sealed partial class RynthAiPlugin : RynthPluginBase case "hub": case "quests": case "pets": - case "guardian": - case "bounty": - case "bounties": - case "bountys": + // The Mini Remote's verbs; "/ra guardian", "/ra bounty" and the like are the server + // plugin's (default below), as is any "/ra hub ..." verb RynthAi doesn't have. if (_miniRemote == null) { ChatLine("[RynthAi] The Mini Remote isn't ready (log in first)."); break; } _miniRemote.HandleCommand(cmd, parts.Length > 2 ? parts[2..] : Array.Empty()); break; @@ -3964,6 +3967,8 @@ public sealed partial class RynthAiPlugin : RynthPluginBase } break; case "settings": HandleSettingsCommand(parts); break; + // /ra equipfor : VTank's /vt equipitemsfor (MagToolsCommands.Extra.cs) + case "equipfor": HandleEquipForCommand(parts); break; case "autotrade": HandleAutoTradeRaCommand(parts); break; case "trade": HandleTradeCommand(parts); break; case "busyinfo": HandleBusyInfoCommand(); break; @@ -4021,6 +4026,9 @@ public sealed partial class RynthAiPlugin : RynthPluginBase HandleJumpCommand(cmd, parts); break; } + // A verb RynthAi doesn't have may be the server plugin's ("/ra t11", "/ra guardian", "/ra bounty" + // are RynthILT's on Infinite Leaftide); without one it goes on to the server, as any unknown "/ra". + if (TryForwardToServerPlugin(parts)) break; eat = 0; break; } diff --git a/Plugins/RynthCore.Plugin.RynthAi/RynthAiServerCommand.cs b/Plugins/RynthCore.Plugin.RynthAi/RynthAiServerCommand.cs index 1aaa8e4..5b3b154 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/RynthAiServerCommand.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/RynthAiServerCommand.cs @@ -11,7 +11,7 @@ public sealed partial class RynthAiPlugin /// /// /ra server: which server RynthCore says this is and why, every server it knows with this /// character's override, the plugin that owns the active server and what its settings say, - /// and whether the Mini Remote's ILT tabs (RynthILT.Hub) are connected. One check that every + /// and whether a server plugin's hub (the Mini Remote's server tabs) is connected. One check that every /// plugin is reading the same server identity. Plain ASCII (the AC chat can't draw more). /// private void HandleServerCommand() @@ -45,8 +45,15 @@ public sealed partial class RynthAiPlugin : $"[RynthAi] {st.ActivePlugin} sent no server settings ({RynthServerProfileApiV1.InterfaceName} not answered - an older plugin?)."); } - bool iltTabs = _ilt != null && _ilt.Loaded; - ChatLine($"[RynthAi] Mini Remote ILT tabs (RynthILT.Hub): {(iltTabs ? "connected" + (_ilt!.IsIltWorld ? ", ILT world" : ", not an ILT world") : "not connected")}."); + var hub = _serverHub; + if (hub == null || !hub.Loaded) + ChatLine("[RynthAi] Mini Remote server tabs: no server plugin hub connected (none loaded for this world)."); + else + { + string id = hub.Text(RynthIltHub.TextServerId); + ChatLine($"[RynthAi] Mini Remote server tabs: connected{(id.Length > 0 ? " (server '" + id + "')" : string.Empty)}, " + + (hub.ServerActive ? "its server is this world." : "its server is not this world (nothing shown).")); + } ChatLine("[RynthAi] Change the server: RynthCore Options > Diagnostics > Server, or /rc server pick |auto."); } } diff --git a/Plugins/RynthCore.Plugin.RynthAi/RynthAiT11Command.cs b/Plugins/RynthCore.Plugin.RynthAi/RynthAiT11Command.cs deleted file mode 100644 index 4839824..0000000 --- a/Plugins/RynthCore.Plugin.RynthAi/RynthAiT11Command.cs +++ /dev/null @@ -1,133 +0,0 @@ -using System; -using System.Globalization; -using System.Linq; -using RynthCore.Loot.T11; -using RynthCore.Plugin.RynthAi.Loot; - -namespace RynthCore.Plugin.RynthAi; - -public sealed partial class RynthAiPlugin -{ - /// - /// /ra t11 [augs <n|auto> | refresh | item [0xId]]: T11 loot support. - /// No argument shows the wield counters the loot rules use; "augs" sets or clears the - /// item-aug override; "refresh" asks the server for "/aug"; "item" shows how the selected - /// item's T11 text was read and the values its virtual loot keys return. - /// - private void HandleT11Command(string[] parts) - { - string sub = parts.Length >= 3 ? parts[2].ToLowerInvariant() : string.Empty; - switch (sub) - { - case "": - case "status": - PrintT11Status(); - break; - case "augs": - SetT11ItemAugOverride(parts.Length >= 4 ? parts[3] : string.Empty); - break; - case "refresh": - if (!Host.HasInvokeChatParser) { ChatLine("[RynthAi] This engine can't send chat commands."); break; } - Host.InvokeChatParser("/aug"); - ChatLine("[RynthAi] T11: sent /aug - the counters update from its reply."); - break; - case "item": - PrintT11Item(parts.Length >= 4 ? parts[3] : null); - break; - default: - ChatLine("[RynthAi] Usage: /ra t11 [augs | refresh | item [0xId]]"); - break; - } - } - - /// The counters the "T11: Can Wield" loot key compares wield gates against. - private void PrintT11Status() - { - T11PlayerAugs p = T11ItemSupport.Player; - int saved = _dashboard?.Settings.T11ItemAugsOverride ?? -1; - string updated = p.UpdatedUtc is DateTime t ? t.ToLocalTime().ToString("t", CultureInfo.CurrentCulture) : "never"; - ChatLine($"[RynthAi] === T11 loot (last /aug read: {updated}) ==="); - foreach ((T11Counter counter, string name) in T11Catalog.CounterNames) - { - long? v = p.Get(counter); - string source = counter == T11Counter.ItemAugmentations && saved >= 0 ? " (override)" : string.Empty; - ChatLine($"[RynthAi] {name}: {(v.HasValue ? v.Value.ToString("N0", CultureInfo.CurrentCulture) : "unknown")}{source}"); - } - if (p.UpdatedUtc == null && saved < 0) - ChatLine("[RynthAi] Unknown counters make \"T11: Can Wield\" -1. Use /ra t11 refresh, or /ra t11 augs ."); - } - - /// /ra t11 augs <n|auto>: saves the item-aug override (-1 = read from /aug). - private void SetT11ItemAugOverride(string arg) - { - if (_dashboard == null) { ChatLine("[RynthAi] Settings aren't loaded yet."); return; } - int value; - if (arg.Equals("auto", StringComparison.OrdinalIgnoreCase) || arg == "-1") - value = -1; - else if (!int.TryParse(arg.Replace(",", string.Empty), NumberStyles.Integer, CultureInfo.InvariantCulture, out value) || value < 0) - { - ChatLine("[RynthAi] Usage: /ra t11 augs (n = your item augmentation count)"); - return; - } - _dashboard.Settings.T11ItemAugsOverride = value; - _dashboard.SaveSettings(); - T11ItemSupport.SyncOverride(value); - ChatLine(value < 0 - ? "[RynthAi] T11: item augmentations now come from /aug." - : $"[RynthAi] T11: item augmentations fixed at {value:N0} for loot rules."); - } - - /// /ra t11 item [0xId]: the parsed T11 text of an item (selected item by default). - private void PrintT11Item(string? idArg) - { - uint id = 0; - if (!string.IsNullOrEmpty(idArg)) - uint.TryParse(idArg.StartsWith("0x", StringComparison.OrdinalIgnoreCase) ? idArg[2..] : idArg, - NumberStyles.HexNumber, CultureInfo.InvariantCulture, out id); - if (id == 0 && Host.HasGetSelectedItemId) id = Host.GetSelectedItemId(); - if (id == 0) { ChatLine("[RynthAi] T11: select an item first (or pass 0xId)."); return; } - - int iid = unchecked((int)id); - WorldObject item = _objectCache?[iid] - ?? new WorldObject(iid, Host.TryGetObjectName(id, out string n) ? n : string.Empty) { Cache = _objectCache }; - T11ItemInfo info = T11ItemSupport.Get(item); - if (!info.IsT11) - { - bool appraised = !Host.HasHasAppraisalData || Host.HasAppraisalData(id); - ChatLine(appraised - ? $"[RynthAi] T11: {item.Name} is not a T11 item." - : $"[RynthAi] T11: {item.Name} isn't appraised yet - ID it and try again."); - return; - } - - ChatLine($"[RynthAi] === T11: {item.Name} (0x{id:X8}) ==="); - ChatLine($"[RynthAi] Tier {(info.TierIsExact ? info.Tier.ToString(CultureInfo.InvariantCulture) : "~" + info.Tier.ToString(CultureInfo.InvariantCulture))}" - + (info.Grade != null ? $", grade {info.Grade} ({info.DamagePercent}% of max damage)" : string.Empty) - + (info.WeaponQuality >= 0 ? $", quality {info.WeaponQuality}/1000" : string.Empty) - + (info.GearGrade != null ? $", gear grade {info.GearGrade} ({info.GearGradeLines} lines)" : string.Empty) - + (info.ZoneLocked ? ", zone locked" : string.Empty)); - if (info.PropertySlots >= 0 || info.Tainted) - ChatLine("[RynthAi] Properties " - + (info.PropertySlots < 0 ? "?" : info.PropertySlotCap > 0 ? $"{info.PropertySlots} of {info.PropertySlotCap}" : info.PropertySlots.ToString(CultureInfo.InvariantCulture)) - + (info.Tainted ? ", tainted (bags no longer work)" : string.Empty)); - foreach (T11WieldGate g in info.WieldGates) - ChatLine($"[RynthAi] Wield requires {g.Amount:N0} {T11Catalog.CounterName(g.Counter)}"); - foreach (T11Modifier m in info.Modifiers) - { - string band = m.Min.HasValue && m.Max.HasValue ? $" [{m.Min}-{m.Max}] roll {m.RollPercent}%" : string.Empty; - string marks = (m.Tinkered != 0 ? $" ({m.Tinkered:+#;-#} tinkered)" : string.Empty) - + (m.BuiltIn ? " (built-in)" : string.Empty) + (m.Locked ? " (locked)" : string.Empty); - ChatLine($"[RynthAi] Mod {m.Name} {(m.IsSlotSpecial ? "(special)" : "+" + m.Value)}{band}{marks}"); - } - foreach ((string name, double chance) in info.Procs) - ChatLine($"[RynthAi] Cast on strike: {name} ({chance.ToString("0.#", CultureInfo.CurrentCulture)}%)"); - - int canWield = item.Values(T11Keys.CanWield, -1); - ChatLine($"[RynthAi] Can wield: {(canWield == 1 ? "yes" : canWield == 0 ? "no" : "unknown (no /aug read, or not appraised)")}" - + $", modifier ratings {info.ModifierRatingTotal}, average roll {info.AverageRollPercent}%"); - string keys = string.Join(", ", T11Keys.Names() - .Where(k => k.Id < T11Keys.ModifierBase) - .Select(k => $"{k.Name.Replace("T11: ", string.Empty)}={item.Values(k.Id, 0)}")); - ChatLine($"[RynthAi] Loot keys: {keys}"); - } -} diff --git a/Plugins/RynthCore.Plugin.RynthAi/RynthCore.Plugin.RynthAi.csproj b/Plugins/RynthCore.Plugin.RynthAi/RynthCore.Plugin.RynthAi.csproj index 50036ba..2eeaf02 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/RynthCore.Plugin.RynthAi.csproj +++ b/Plugins/RynthCore.Plugin.RynthAi/RynthCore.Plugin.RynthAi.csproj @@ -60,8 +60,6 @@ - - diff --git a/Plugins/RynthCore.Plugin.RynthAi/UtilityBeltCommands.cs b/Plugins/RynthCore.Plugin.RynthAi/UtilityBeltCommands.cs index 44b67b8..39d8de6 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/UtilityBeltCommands.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/UtilityBeltCommands.cs @@ -86,6 +86,14 @@ public sealed partial class RynthAiPlugin string cmd = parts[1].ToLower(); + // ub-Rythai's verbs: that plugin answers; handled here only in the sense of "not unknown". + if (IsUbRythaiCommand(cmd, SplitUbLine(fullCommand).Args)) + return true; + + // "/ub vtsetmetastate[State]" and the like: an expression, not a verb. + if (TryHandleUbExpression(fullCommand)) + return true; + // /ub jump[swzxc] [heading] [holdtime] — see Jumper.cs if (cmd.StartsWith("jump", StringComparison.Ordinal)) { @@ -176,6 +184,11 @@ public sealed partial class RynthAiPlugin if (TryHandleUbExtra(cmd, fullCommand)) return true; + // The rest of ub-IT's verbs: aliases, features, and accepted no-ops (UtilityBeltCompatCommands.cs). + // Before the /mt translation, so "/ub fellow dismiss" doesn't land on /mt fellow's usage line. + if (TryHandleUbCompat(cmd, fullCommand)) + return true; + // /ub closestportal: use the nearest portal (UtilityBelt's command). if (cmd == "closestportal") { diff --git a/Plugins/RynthCore.Plugin.RynthAi/UtilityBeltCompatCommands.cs b/Plugins/RynthCore.Plugin.RynthAi/UtilityBeltCompatCommands.cs new file mode 100644 index 0000000..6522ee9 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAi/UtilityBeltCompatCommands.cs @@ -0,0 +1,362 @@ +using System; +using System.Collections.Generic; +using System.Globalization; +using System.IO; +using RynthCore.Plugin.RynthAi.LegacyUi; +using RynthCore.PluginSdk; +using RynthCore.Plugin.Shared; + +namespace RynthCore.Plugin.RynthAi; + +/// +/// The rest of ub-IT's /ub verbs (2026-10-18 meta-compatibility pass). Three kinds: +/// 1. Aliases and features with a RynthAi, RynthNav, RynthSort, engine or server equivalent +/// (wear, getxy, stfl/stfr, arrow, navgoto, frame limits, fellow dismiss/leader/status, +/// qblist, augs, window save, packsort*, miniremote, meta/combat/sloot on|off, debug, lps). +/// 2. ub-Rythai's verbs, which RynthAi leaves to that plugin without a reply. +/// 3. ub-IT features that mean nothing here (videopatch, chat max, playeroption, ...): accepted +/// without error, said once per session, so a meta that sends them keeps running. +/// +public sealed partial class RynthAiPlugin +{ + /// Verbs the ub-Rythai plugin answers. Every plugin sees each /ub line, so RynthAi stays quiet for these. + private static readonly HashSet UbRythaiVerbs = new(StringComparer.OrdinalIgnoreCase) + { + "autopercent", "autotradeaccept", "bank", "build", "guard", "guardian", "ilt", "leaftide", + "log", "loginq", "p2", "periodic", "xpmeter", + }; + + /// + /// ub-IT verbs with no RynthAi equivalent: diagnostics of ub-IT's own tools, Decal UI and + /// client patches, and features RynthCore does its own way. Accepted so metas keep running. + /// + private static readonly HashSet UbNoEquivalentVerbs = new(StringComparer.OrdinalIgnoreCase) + { + "acobject", "autologin", "autoloot", "autosalvage", "autosalvagedebug", "autosalvagereload", + "bankparse", "breakallegiance", "bridge", "calcdamage", "chat", "chatfilter", "chunkaeth", + "chunkaetheria", "chunkdebug", "chunkreset", "chunkstatus", "clapstatus", "dispel", "dispeltool", + "egg", "element", "enlighten", "enlightenment", "getjob", "getui", "invcache", "joke", "keystore", + "login", "lsdclearcache", "lsdlb", "mtbridge", "nav", "navfollow", "navfollowarrival", + "onetouchheal", "pcap", "perf", "playeroption", "prepclick", "printcolors", "professor", + "questbonus", "queuestatus", "refreshqueues", "resolution", "revalidate", "setui", "shittalk", + "soak", "spell", "statushud", "storm", "surgingstrength", "swearallegiance", "testassessor", + "textures", "tinkcalc", "trace", "tracearmorbuffs", "ubhudrecover", "ucm", "unstack", + "vhudbridgestatus", "xp", "xpdebug", + }; + + // No-equivalent verbs already reported this session (one chat line each, not one per meta pulse). + private readonly HashSet _ubNoEquivalentSaid = new(StringComparer.OrdinalIgnoreCase); + + /// True when ub-Rythai owns this /ub verb. "/ub portal use|list" (portal gems) is + /// ub-Rythai's; "/ub portal <name>" (the nearest portal) is RynthAi's. + internal static bool IsUbRythaiCommand(string cmd, string args) + { + if (UbRythaiVerbs.Contains(cmd)) return true; + if (!cmd.Equals("portal", StringComparison.OrdinalIgnoreCase)) return false; + string first = args.Split(' ', 2, StringSplitOptions.RemoveEmptyEntries) is { Length: > 0 } w ? w[0] : ""; + return first.Length == 0 || first.Equals("use", StringComparison.OrdinalIgnoreCase) + || first.Equals("list", StringComparison.OrdinalIgnoreCase); + } + + /// The verb and its arguments from a "/ub verb args" line. + private static (string Cmd, string Args) SplitUbLine(string fullCommand) + { + string rest = fullCommand.Length > 3 ? fullCommand.Substring(3).Trim() : ""; + int sp = rest.IndexOf(' '); + return sp > 0 ? (rest.Substring(0, sp).ToLowerInvariant(), rest.Substring(sp + 1).Trim()) + : (rest.ToLowerInvariant(), ""); + } + + /// + /// A meta's chat-command line. /ub lines go to the /ub dispatcher (ub-IT meaning: "/ub give" gives + /// every match, where "/mt give" gives one). ub-Rythai's verbs return false, so the meta hands the + /// line to the chat parser, which every plugin's chat handler sees. Anything else is /mt. + /// The whole line runs as one a running meta executes (), which is + /// what lets /mt vendor buy|sell and /mt trade accept act, and what /ub give's stricter item + /// protection (the loot profile's Keep rules) is keyed on. MetaManager's chat-command and + /// chat-expression actions are the only callers. + /// + internal bool HandleMetaChatCommand(string cmd) => RunAsMeta(() => + { + if (cmd.StartsWith("/ub ", StringComparison.OrdinalIgnoreCase)) + { + var (verb, args) = SplitUbLine(cmd); + return !IsUbRythaiCommand(verb, args) && HandleUbCommand(cmd); + } + return HandleMtCommand(cmd); + }); + + /// The verbs above. Returns false for anything else. + internal bool TryHandleUbCompat(string cmd, string fullCommand) + { + string args = SplitUbLine(fullCommand).Args; + string[] w = args.Split(' ', StringSplitOptions.RemoveEmptyEntries); + string sub = w.Length > 0 ? w[0].ToLowerInvariant() : ""; + + switch (cmd) + { + // ── Aliases of commands RynthAi already has ───────────────────────── + case "wear": UbWear(args, partial: false); return true; + case "wearp": UbWear(args, partial: true); return true; + case "getxy": return HandleMtCursor(); + case "stfl": return HandleMtStrafe(new[] { "/mt", "strafe", "left", args }); + case "stfr": return HandleMtStrafe(new[] { "/mt", "strafe", "right", args }); + case "debug": HandleRaCommand(("/ra debug " + args).TrimEnd()); return true; + case "close": UbClose(sub); return true; + + case "bgframelimit": + case "globalframelimit": + UbFrameLimit(background: cmd == "bgframelimit", args); + return true; + + case "fellow" when sub is "dismiss" or "dismissp" or "leader" or "leaderp" or "status" or "recruitp": + UbFellow(sub, w.Length > 1 ? string.Join(" ", w, 1, w.Length - 1) : ""); + return true; + + // ── RynthNav: the arrow and travel to coordinates ─────────────────── + case "arrow": + if (sub == "point" && args.Length > 6) + SendToPlugin("RynthNav", "rnav", "arrow " + args.Substring(6).Trim(), "/ub arrow needs the RynthNav plugin."); + else + UbNoEquivalent(cmd, "\"arrow face\" has no RynthNav equivalent"); + return true; + case "navgoto": + UbNavGoto(w); + return true; + + // ── RynthSort: pack sorting ───────────────────────────────────────── + case "packsort": + case "packsortscansort": + case "packsortscanforcesort": + SendToPlugin("RynthSort", "rsort", "now", "/ub packsort needs the RynthSort plugin."); + return true; + case "packsortshow": + case "packsortlist": + SendToPlugin("RynthSort", "rsort", "status", "/ub packsort needs the RynthSort plugin."); + return true; + case "packsortreload": + case "packsortscan": + case "packsortscanforce": + UbNoEquivalent(cmd, "RynthSort reads its rules itself"); + return true; + + // ── A server's own commands (ub-IT's ACECustom verbs): the server plugin's (RynthILT) ── + case "qblist": + case "augs": + if (!TryForwardToServerPlugin(new[] { "/ra", "ub", cmd })) + UbNoEquivalent(cmd, "it is a server plugin's command (Infinite Leaftide: RynthILT), and none is loaded"); + return true; + + // ── RynthCore's window placement ──────────────────────────────────── + case "window": + if (sub == "save") InvokeServerCommand("/rc window save"); + else UbNoEquivalent(cmd + " " + sub, "RynthCore restores the saved window at login (/rc window save|reset)"); + return true; + + // ── RynthAi's Mini Remote ─────────────────────────────────────────── + case "miniremote": + if (sub is "show" or "hide" or "toggle") HandleHudCommand("miniremote", sub); + else UbNoEquivalent(cmd + " " + sub, "use /ub miniremote show|hide|toggle"); + return true; + + // ── Project Storm's switches onto RynthAi's macro features ────────── + case "meta": return UbStormSwitch(cmd, sub, "enablemeta", w); + case "combat": return UbStormSwitch(cmd, sub, "enablecombat", w); + case "sloot": return UbStormSwitch(cmd, sub, "enablelooting", w); + + case "lps": + case "lootprofilestatus": + { + string path = _dashboard?.Settings?.CurrentLootPath ?? ""; + ChatLine("[RynthAi] Loot profile: " + (path.Length > 0 ? Path.GetFileName(path) : "(none)")); + return true; + } + } + + // ── ub-IT features with no RynthAi equivalent ─────────────────────────── + if (UbNoEquivalentVerbs.Contains(cmd)) + { + UbNoEquivalent(cmd, null); + return true; + } + return false; + } + + /// + /// /ub close corpse|chest (ub-IT): closes the open container when it is that kind (a bare + /// "/ub close" closes whatever is open). Metas send it after looting a quest corpse. + /// + private void UbClose(string kind) + { + uint open = Host.HasGetGroundContainerId ? Host.GetGroundContainerId() : 0; + if (open == 0) { ChatLine("[RynthAi] No container is currently open."); return; } + WorldObject? wo = _objectCache?[unchecked((int)open)]; + bool fits = kind switch + { + "corpse" => wo == null || wo.ObjectClass == AcObjectClass.Corpse, + "chest" => wo == null || wo.ObjectClass == AcObjectClass.Container, + _ => true, + }; + if (!fits) return; // as ub-IT: the open container isn't that kind, nothing to do + bool closed = Host.HasCloseContainer ? Host.CloseContainer(open) : Host.UseFor(open, "Command", "/ub close", UseKind.Asked); + Log($"[RynthAi] /ub close {kind}: 0x{open:X8} {(closed ? "closed" : "close refused")}."); + } + + /// + /// "/ub <expression>": a /ub line whose verb is an expression call (S_BulbOfMornings broadcasts + /// "/ub bc /ub vtsetmetastate[State]" so every client switches state). ub-IT has no such + /// command; RynthAi evaluates the expression, which is what the meta means. True when it was one. + /// + internal bool TryHandleUbExpression(string fullCommand) + { + string rest = fullCommand.Length > 3 ? fullCommand.Substring(3).Trim() : ""; + int bracket = rest.IndexOf('['); + int space = rest.IndexOf(' '); + if (bracket <= 0 || (space >= 0 && space < bracket) || !rest.EndsWith("]", StringComparison.Ordinal)) return false; + string result = EvalExpr(rest); + Log($"[RynthAi] /ub {rest} evaluated as an expression -> '{result}'."); + return true; + } + + /// Says once per session that a /ub verb is accepted and ignored; every use is logged. + private void UbNoEquivalent(string what, string? note) + { + Log($"[RynthAi] /ub {what}: no RynthAi equivalent; ignored."); + if (_ubNoEquivalentSaid.Add(what)) + ChatLine($"[RynthAi] /ub {what} is a ub-IT feature with no RynthAi equivalent; it is accepted and ignored so metas keep running" + + (note != null ? $" ({note})." : ".")); + } + + /// Sends a chat line to the chat parser (server commands, /rc). + private void InvokeServerCommand(string line) + { + if (Host.HasInvokeChatParser) Host.InvokeChatParser(line); + else ChatLine($"[RynthAi] Can't send {line}: the chat parser isn't available."); + } + + /// A command for another plugin through the engine broker. + private void SendToPlugin(string plugin, string action, string value, string missing) + { + if (!(Host.HasSendPluginCommand && Host.SendPluginCommand(plugin, action, value))) + ChatLine("[RynthAi] " + missing); + } + + /// /ub wear[p] <name>: wield a carried item by name, skipping copies already worn + /// (using a worn item would take it off). + private void UbWear(string name, bool partial) + { + if (string.IsNullOrWhiteSpace(name)) { ChatLine("[RynthAi] Usage: /ub wear (wearp: partial name)"); return; } + if (_objectCache == null || !Host.HasUseObject) { ChatLine("[RynthAi] /ub wear: not ready (log in first)."); return; } + + bool sawWorn = false; + foreach (var wo in _objectCache.GetInventory()) + { + bool match = partial + ? wo.Name.IndexOf(name, StringComparison.OrdinalIgnoreCase) >= 0 + : string.Equals(wo.Name, name, StringComparison.OrdinalIgnoreCase); + if (!match) continue; + if (wo.Values(LongValueKey.CurrentWieldedLocation, 0) > 0) { sawWorn = true; continue; } + Host.UseFor(unchecked((uint)wo.Id), "Command", "/ub wear", UseKind.Asked); + Log($"[RynthAi] /ub wear: {wo.Name} (0x{(uint)wo.Id:X8})"); + return; + } + ChatLine(sawWorn ? $"[RynthAi] Already wearing '{name}'." : $"[RynthAi] Item not found: '{name}'"); + } + + /// /ub globalframelimit|bgframelimit <fps>: RynthAi's frame limit (Settings, Display). + /// 0 turns the limit off (global) or lifts the background cap to its maximum. + private void UbFrameLimit(bool background, string arg) + { + LegacyUiSettings? s = _dashboard?.Settings; + if (s == null) { ChatLine("[RynthAi] Settings aren't loaded yet."); return; } + if (!int.TryParse(arg.Trim(), NumberStyles.Integer, CultureInfo.InvariantCulture, out int fps) || fps < 0) + { + ChatLine($"[RynthAi] Usage: /ub {(background ? "bgframelimit" : "globalframelimit")} "); + return; + } + if (background) + { + s.TargetFPSBackground = fps == 0 ? 60 : Math.Clamp(fps, 5, 60); + s.EnableFPSLimit = true; + ChatLine($"[RynthAi] Background frame limit: {s.TargetFPSBackground} fps."); + } + else if (fps == 0) + { + s.EnableFPSLimit = false; + ChatLine("[RynthAi] Frame limit off."); + } + else + { + s.TargetFPSFocused = Math.Clamp(fps, 10, 240); + s.EnableFPSLimit = true; + ChatLine($"[RynthAi] Frame limit: {s.TargetFPSFocused} fps."); + } + try { _dashboard?.SaveSettings(); } catch { } + } + + /// /ub fellow dismiss[p]|leader[p] <name>, status, recruitp <name> (the p forms match part of a name). + private void UbFellow(string sub, string name) + { + if (sub == "status") { HandleFellowshipCommand(new[] { "/ra", "fellow", "status" }); return; } + if (name.Length == 0) { ChatLine($"[RynthAi] Usage: /ub fellow {sub} "); return; } + + bool partial = sub.EndsWith('p'); + string resolved = name; + if (partial && sub != "recruitp" && _fellowshipTracker != null) + { + foreach (string member in _fellowshipTracker.GetMemberNames()) + if (member.IndexOf(name, StringComparison.OrdinalIgnoreCase) >= 0) { resolved = member; break; } + } + else if (sub == "recruitp" && FindObject(name, inv: false, land: true, partial: true) is { } wo) + { + resolved = wo.Name; + } + + string verb = sub.TrimEnd('p'); + InvokeServerCommand($"/fellowship {verb} {resolved}"); + } + + /// /ub navgoto <ns> <ew> [walk|run]: ub-IT's signed coordinates (south and west + /// negative) to RynthNav's "/rnav go 42.1N, 33.6E". RynthNav picks its own pace. + private void UbNavGoto(string[] w) + { + if (w.Length < 2 + || !double.TryParse(w[0], NumberStyles.Float, CultureInfo.InvariantCulture, out double ns) + || !double.TryParse(w[1], NumberStyles.Float, CultureInfo.InvariantCulture, out double ew)) + { + ChatLine("[RynthAi] Usage: /ub navgoto [walk|run] (south and west are negative)"); + return; + } + string coords = FormattableString.Invariant($"{Math.Abs(ns):0.0#}{(ns < 0 ? 'S' : 'N')}, {Math.Abs(ew):0.0#}{(ew < 0 ? 'W' : 'E')}"); + SendToPlugin("RynthNav", "rnav", "go " + coords, "/ub navgoto needs the RynthNav plugin."); + } + + /// + /// Project Storm's /ub meta|combat|sloot: on/off switch the matching RynthAi macro feature + /// (enablemeta, enablecombat, enablelooting); "meta load <name>" and "meta state <name>" + /// are VTank's meta load and setmetastate. The other Storm verbs have no equivalent. + /// + private bool UbStormSwitch(string cmd, string sub, string vtOption, string[] w) + { + string rest = w.Length > 1 ? string.Join(" ", w, 1, w.Length - 1) : ""; + if (_metaManager == null) { ChatLine("[RynthAi] Not ready (log in first)."); return true; } + + switch (sub) + { + case "on" or "off": + _metaManager.TryHandleVtCommand($"/vt opt set {vtOption} {(sub == "on" ? "true" : "false")}"); + return true; + case "status" or "": + _metaManager.TryHandleVtCommand($"/vt opt get {vtOption}"); + return true; + case "load" when cmd == "meta" && rest.Length > 0: + _metaManager.TryHandleVtCommand("/vt meta load " + rest); + return true; + case "state" when cmd == "meta" && rest.Length > 0: + _metaManager.TryHandleVtCommand("/vt setmetastate " + rest); + return true; + } + UbNoEquivalent(cmd + " " + sub, "Project Storm's own engine; RynthAi is the macro here"); + return true; + } +} diff --git a/Plugins/RynthCore.Plugin.RynthAi/UtilityBeltExtraCommands.cs b/Plugins/RynthCore.Plugin.RynthAi/UtilityBeltExtraCommands.cs index 32cc716..ebe765c 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/UtilityBeltExtraCommands.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/UtilityBeltExtraCommands.cs @@ -22,7 +22,9 @@ namespace RynthCore.Plugin.RynthAi; public sealed partial class RynthAiPlugin { // ── /ub delay queue ───────────────────────────────────────────────────── - private readonly List<(long DueMs, string Command)> _delayedCommands = new(); + // FromMeta: the line was queued by a running meta, so it runs as one when due (it may be + // /mt vendor sell or /mt trade accept, which only act for a meta). + private readonly List<(long DueMs, string Command, bool FromMeta)> _delayedCommands = new(); /// Runs /ub delay commands that are due. Called every tick. private void TickDelayedCommands() @@ -35,8 +37,13 @@ public sealed partial class RynthAiPlugin { if (_delayedCommands[i].DueMs > now) continue; string cmd = _delayedCommands[i].Command; + bool fromMeta = _delayedCommands[i].FromMeta; _delayedCommands.RemoveAt(i--); - try { HandleRynthChatSubmit(cmd); } + try + { + if (fromMeta) RunAsMeta(() => { HandleRynthChatSubmit(cmd); return true; }); + else HandleRynthChatSubmit(cmd); + } catch (Exception ex) { Log($"[RynthAi] /ub delay: '{cmd}' threw {ex.Message}"); } } } @@ -109,7 +116,7 @@ public sealed partial class RynthAiPlugin } string command = args.Substring(sp + 1).Trim(); if (command.Length == 0) return; - _delayedCommands.Add((Environment.TickCount64 + ms, command)); + _delayedCommands.Add((Environment.TickCount64 + ms, command, MetaCommandActive)); } // /ub count {item | profile | player } [debug] [think] diff --git a/Plugins/RynthCore.Plugin.RynthAi/Vendor/AutoVendorManager.cs b/Plugins/RynthCore.Plugin.RynthAi/Vendor/AutoVendorManager.cs index 152e4b4..61a85ed 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Vendor/AutoVendorManager.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Vendor/AutoVendorManager.cs @@ -67,7 +67,7 @@ internal sealed class AutoVendorManager private bool _needsUpdateSaid; // ── Session ── - private enum Phase { Idle, Identifying, Ready, WaitTrade, WaitConfirm, WaitSplit } + private enum Phase { Idle, Identifying, Ready, WaitTrade, WaitConfirm, WaitSplit, WaitMerge } private Phase _phase = Phase.Idle; private VTankLootProfile? _profile; private string _profilePath = string.Empty; @@ -94,6 +94,13 @@ internal sealed class AutoVendorManager private int _splitAmount; private HashSet _splitBefore = new(); private long _splitDeadline; + // A split or merge that never shows up (no new stack / nothing moved): MaxFailures in a row ends the + // session instead of retrying every 10 s forever. + private int _tidyFails; + private int _tidySteps; // splits/merges since the last trade + private const int MaxTidySteps = 8; + private uint _mergeSource, _mergeTarget; + private int _mergeSourceCount, _mergeTargetCount; private int _pyrealStackSize; @@ -391,6 +398,7 @@ internal sealed class AutoVendorManager case Phase.WaitTrade: TickWaitTrade(now); break; case Phase.WaitConfirm: TickWaitConfirm(now); break; case Phase.WaitSplit: TickWaitSplit(now); break; + case Phase.WaitMerge: TickWaitMerge(now); break; } UpdateStatus(); } @@ -472,6 +480,8 @@ internal sealed class AutoVendorManager if (!silent) ThinkOrWrite($"AutoVendor finished: {_vendorName}"); _phase = Phase.Idle; + _tidyFails = 0; + _tidySteps = 0; _profile = null; _requestId = 0; _idQueue.Clear(); @@ -600,6 +610,20 @@ internal sealed class AutoVendorManager PackState pack = ReadPack(v, vi, inv); VendorPlan plan = AutoVendorPlanner.PlanNext(v, wants, sells, pack); + // Splits and merges only get the stacks ready for a trade: a run of them with no trade between + // is going in circles (split-merge-split, 2026-10-19), so it ends the session. + if (plan.Kind is PlanKind.Split or PlanKind.Merge) + { + if (++_tidySteps > MaxTidySteps) + { + ThinkOrWrite($"AutoVendor Fatal - {MaxTidySteps} splits/merges of {plan.SplitItem?.Name} without a sale"); + Stop(false); + return; + } + } + else + _tidySteps = 0; + switch (plan.Kind) { case PlanKind.Done: @@ -622,6 +646,10 @@ internal sealed class AutoVendorManager case PlanKind.Split: DoSplit(plan.SplitItem!, plan.SplitAmount, plan.Message, inv, now); break; + + case PlanKind.Merge: + DoMerge(plan.SplitItem!, plan.MergeTarget!, plan.Message, now); + break; } } @@ -819,8 +847,71 @@ internal sealed class AutoVendorManager { if (now < _nextPollAt) return; _nextPollAt = now + PollMs; - if (FindNewStack(Inventory(), _splitBefore, _splitName, _splitAmount) != 0 || now > _splitDeadline) + if (FindNewStack(Inventory(), _splitBefore, _splitName, _splitAmount) != 0) + { + _tidyFails = 0; _phase = Phase.Ready; + } + else if (now > _splitDeadline) + TidyFailed($"splitting {_splitAmount} off {_splitName} made no new stack"); + } + + private void DoMerge(SellItem source, SellItem target, string why, long now) + { + if (!_host.HasMergeStackInternal) + { + ThinkOrWrite("AutoVendor Fatal - this engine can't merge stacks"); + Stop(false); + return; + } + _mergeSource = source.Id; + _mergeTarget = target.Id; + _mergeSourceCount = source.StackSize; + _mergeTargetCount = target.StackSize; + _splitName = source.Name; + _host.Log($"[RynthAi] AutoVendor merge {source.Name}:{source.Id:X8} ({source.StackSize}) onto {target.Id:X8} ({target.StackSize}) - {why}"); + if (!_host.MergeStackInternal(source.Id, target.Id)) + { + TidyFailed($"could not merge {source.Name}"); + return; + } + Tool($"merging {source.Name} stacks ({why})"); + _splitDeadline = now + SplitWaitMs; + _nextPollAt = now + PollMs; + _bailAt = now; + _phase = Phase.WaitMerge; + } + + private void TickWaitMerge(long now) + { + if (now < _nextPollAt) return; + _nextPollAt = now + PollMs; + var inv = Inventory(); + var src = inv.FirstOrDefault(w => unchecked((uint)w.Id) == _mergeSource); + var tgt = inv.FirstOrDefault(w => unchecked((uint)w.Id) == _mergeTarget); + // Done when the source is used up, or either count moved (past the max the target fills and + // the source survives smaller). + if (src == null || StackOf(src) != _mergeSourceCount || (tgt != null && StackOf(tgt) != _mergeTargetCount)) + { + _tidyFails = 0; + _phase = Phase.Ready; + } + else if (now > _splitDeadline) + TidyFailed($"merging {_splitName} stacks moved nothing"); + } + + private void TidyFailed(string what) + { + _tidyFails++; + _host.Log($"[RynthAi] AutoVendor: {what} ({_tidyFails}/{MaxFailures})"); + if (_tidyFails >= MaxFailures) + { + _tidyFails = 0; + ThinkOrWrite($"AutoVendor Fatal - {what}, {MaxFailures} times in a row"); + Stop(false); + return; + } + _phase = Phase.Ready; } // ── Collect (UB GetBuyItems / GetSellItems) ── @@ -847,6 +938,7 @@ internal sealed class AutoVendorManager uint player = PlayerId(); var packOrder = PackOrder(inv, player); + var unitValues = TrueUnitValues(inv); foreach (var wo in inv) { uint id = unchecked((uint)wo.Id); @@ -871,6 +963,13 @@ internal sealed class AutoVendorManager int stack = StackOf(wo); bool isNote = wo.ObjectClass == AcObjectClass.TradeNote || (type & AutoVendorPlanner.ItemTypePromissoryNote) != 0; int unitValue = stack > 1 ? safety.Value / stack : safety.Value; + // A stack keeps its old Value after a split (100 peas' worth on a stack of 2 read "1,250,000 + // each", 2026-10-19), which hid it from the sell list and from the split planner. Use the + // per-unit value most of this item's units carry (TrueUnitValues). + bool stackable = InventoryManager.GetMaxStackSize(wo) > 1; + if (stackable && unitValues.TryGetValue(StackKey(wo), out int trueUnit) && trueUnit > 0) + unitValue = trueUnit; + int stackValue = stackable ? unitValue * Math.Max(1, stack) : safety.Value; if (unsafeWhy == null && !AutoVendorPlanner.VendorWillBuy(v, type, isNote, unitValue)) { // A Sell rule wanted it and the vendor won't take it: say why, once per name a @@ -915,10 +1014,12 @@ internal sealed class AutoVendorManager Class = wo.ObjectClass, ItemType = type, StackSize = stack, - Value = safety.Value, + Value = stackValue, RuleName = sd.RuleName, Location = main ? "Main Pack" : $"{packName} #{packIdx}", SortSlot = main ? Math.Max(0, wo.DirectSlot) : 1000 + 100 * packIdx + Math.Max(0, wo.DirectSlot), + MaxStack = InventoryManager.GetMaxStackSize(wo), + Wcid = _host.HasGetObjectWcid && _host.TryGetObjectWcid(id, out uint wcid) ? wcid : 0, }); } return result; @@ -984,7 +1085,7 @@ internal sealed class AutoVendorManager /// UB cancels a pending use by facing one degree away. private void CancelUse() { - if (_host.HasTurnToHeading && _host.TryGetPlayerHeading(out float h)) + if (_host.HasTurnToHeading && PlayerCompass.TryGet(_host, out float h)) _host.TurnToHeadingBy("Vendor", (h + 359f) % 360f); else if (_host.HasStopCompletely) _host.StopCompletelyBy("Vendor"); @@ -1330,6 +1431,34 @@ internal sealed class AutoVendorManager return count; } + /// + /// Per item (weenie, else name): the Value / StackSize that the most units carry. A stack's Value goes + /// stale after a split (too high) or a merge (too low); the untouched stacks outnumber them. + /// + private Dictionary TrueUnitValues(List inv) + { + var votes = new Dictionary>(StringComparer.Ordinal); + foreach (var wo in inv) + { + int stack = StackOf(wo); + int value = wo.Values(19 /* Value */, 0); + if (stack < 1 || value <= 0 || InventoryManager.GetMaxStackSize(wo) < 2) continue; + string key = StackKey(wo); + if (!votes.TryGetValue(key, out var byUnit)) votes[key] = byUnit = new Dictionary(); + int unit = value / stack; + byUnit[unit] = byUnit.GetValueOrDefault(unit) + stack; + } + var result = new Dictionary(StringComparer.Ordinal); + foreach (var (key, byUnit) in votes) + result[key] = AutoVendorPlanner.MostCarriedUnit(byUnit); + return result; + } + + private string StackKey(WorldObject wo) => + _host.HasGetObjectWcid && _host.TryGetObjectWcid(unchecked((uint)wo.Id), out uint wcid) && wcid != 0 + ? "w:" + wcid + : "n:" + wo.Name; + private uint FindNewStack(List inv, HashSet before, string name, int amount) { foreach (var wo in inv) @@ -1487,6 +1616,7 @@ internal sealed class AutoVendorManager Phase.WaitTrade => $"Waiting for the server - {_vendorName}", Phase.WaitConfirm => $"Confirming trade - {_vendorName}", Phase.WaitSplit => $"Splitting {_splitName} - {_vendorName}", + Phase.WaitMerge => $"Merging {_splitName} - {_vendorName}", _ => $"Vendoring {_vendorName} ({Path.GetFileName(_profilePath)})", }; if (_settings.AutoVendorTestMode && _phase != Phase.Idle) s += " [test mode]"; diff --git a/Plugins/RynthCore.Plugin.RynthAi/Vendor/AutoVendorPlanner.cs b/Plugins/RynthCore.Plugin.RynthAi/Vendor/AutoVendorPlanner.cs index 7427481..b64b77a 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Vendor/AutoVendorPlanner.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Vendor/AutoVendorPlanner.cs @@ -73,6 +73,10 @@ internal sealed class SellItem public string RuleName { get; init; } = string.Empty; public string Location { get; init; } = string.Empty; public int SortSlot { get; init; } + /// The item's max stack size (0 = unknown); a stack below it is a partial. + public int MaxStack { get; init; } + /// Weenie class id (0 = unknown): only the same weenie merges. + public uint Wcid { get; init; } public bool IsNote => Class == AcObjectClass.TradeNote || (ItemType & AutoVendorPlanner.ItemTypePromissoryNote) != 0; public int UnitValue => StackSize > 1 ? Value / StackSize : Value; @@ -96,6 +100,7 @@ internal enum PlanKind : byte Sell = 2, Split = 3, Fatal = 4, + Merge = 5, } internal readonly record struct BuyLine(Listing Item, int Amount); @@ -109,12 +114,16 @@ internal sealed class VendorPlan public long Total { get; init; } public SellItem? SplitItem { get; init; } public int SplitAmount { get; init; } + /// Merge: SplitItem goes onto MergeTarget. + public SellItem? MergeTarget { get; init; } public string Message { get; init; } = string.Empty; public static VendorPlan Done() => new() { Kind = PlanKind.Done }; public static VendorPlan Fatal(string msg) => new() { Kind = PlanKind.Fatal, Message = msg }; public static VendorPlan Split(SellItem item, int amount, string why) => new() { Kind = PlanKind.Split, SplitItem = item, SplitAmount = amount, Message = why }; + public static VendorPlan Merge(SellItem source, SellItem target, string why) => + new() { Kind = PlanKind.Merge, SplitItem = source, MergeTarget = target, Message = why }; } /// What the manager read about an inventory item for UB's "safe to get rid of" checks. @@ -430,7 +439,7 @@ internal static class AutoVendorPlanner if (single != null) return new VendorPlan { Kind = PlanKind.Sell, Sells = new List { single }, Total = VendorPays(v, true, single.Value) }; - return VendorPlan.Split(item, 1, $"one {item.Name} to afford {nextBuy.Name}"); + return SplitClean(v, sells, item, 1, $"one {item.Name} to afford {nextBuy.Name}"); } // Can't sell the whole stack? Split off what the pyreals will fit. @@ -441,7 +450,7 @@ internal static class AutoVendorPlanner int newStack = unit > 0 ? (int)Math.Floor((p.FreeMainSlots - 2) * (double)Math.Max(1, p.PyrealStackSize) / unit) : 0; newStack = Math.Min(newStack, stack - 1); if (newStack > 0) - return VendorPlan.Split(item, newStack, "the pyreals for the whole stack won't fit"); + return SplitClean(v, sells, item, newStack, "the pyreals for the whole stack won't fit"); return VendorPlan.Fatal($"AutoVendor Fatal - No inventory room to sell {item.Name}"); } break; @@ -457,6 +466,57 @@ internal static class AutoVendorPlanner return VendorPlan.Done(); } + /// + /// A split lands on another partial stack of the same item when there is one, instead of making + /// a new stack (the stack split from doesn't count), so the split-off amount never shows up to be + /// sold. Drakkon's Gold Peas looped split-wait-split for good once two partial stacks existed + /// (2026-10-19). So: first merge partials down to one; with one partial left, sell it whole if it + /// fits, else split from it (nothing else partial for the new stack to join); with none, split as + /// asked. An unknown max stack size keeps the old plain split. + /// + internal static VendorPlan SplitClean(VendorView v, IReadOnlyList sells, SellItem item, int amount, string why) + { + if (item.MaxStack <= 1) + return VendorPlan.Split(item, amount, why); + + var partials = sells + .Where(s => SameItem(s, item) && s.StackSize > 0 && s.StackSize < item.MaxStack) + .OrderByDescending(s => s.StackSize) + .ToList(); + + // A partial that fits is sold whole first: the stack a split just made, or any leftover. (Merging + // it back instead looped split-merge-split three times a second, 2026-10-19.) + SellItem? fits = partials.FirstOrDefault(s => s.StackSize <= amount); + if (fits != null) + return new VendorPlan { Kind = PlanKind.Sell, Sells = new List { fits }, Total = VendorPays(v, fits.IsNote, fits.Value) }; + + // Every partial is too big to sell whole: merge them down to one before splitting. + if (partials.Count >= 2) + return VendorPlan.Merge(partials[^1], partials[0], $"one partial {item.Name} stack, so the split makes a new stack"); + + if (partials.Count == 1 && partials[0].Id != item.Id) + return VendorPlan.Split(partials[0], amount, why); + + return VendorPlan.Split(item, amount, why); + } + + /// The unit value carrying the most units (ties: the higher value, the safe side for a vendor's max). + internal static int MostCarriedUnit(IReadOnlyDictionary unitsByValue) + { + int best = 0; + long bestUnits = -1; + foreach (var (unit, units) in unitsByValue) + if (units > bestUnits || (units == bestUnits && unit > best)) + { + best = unit; + bestUnits = units; + } + return best; + } + + private static bool SameItem(SellItem a, SellItem b) => + a.Wcid != 0 && b.Wcid != 0 ? a.Wcid == b.Wcid : string.Equals(a.Name, b.Name, StringComparison.Ordinal); + // ── /ub vendor addsell (UB AddItemToSellList) ──────────────────────────── /// diff --git a/Plugins/RynthCore.Plugin.RynthOracle/Data/Conquest.cs b/Plugins/RynthCore.Plugin.RynthConquest/Conquest/ConquestData.cs similarity index 96% rename from Plugins/RynthCore.Plugin.RynthOracle/Data/Conquest.cs rename to Plugins/RynthCore.Plugin.RynthConquest/Conquest/ConquestData.cs index 5422410..deaf617 100644 --- a/Plugins/RynthCore.Plugin.RynthOracle/Data/Conquest.cs +++ b/Plugins/RynthCore.Plugin.RynthConquest/Conquest/ConquestData.cs @@ -1,11 +1,13 @@ // Ported from Oracle of Dereth by Advis Eveldan (advis61), MIT. See THIRD_PARTY_NOTICES.md. +// Moved here from RynthOracle (Data/Conquest.cs) on 2026-10-20: Conquest-only features live in RynthConquest. using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Text.RegularExpressions; +using RynthCore.Plugin.ServerPack; -namespace RynthCore.Plugin.RynthOracle.Data; +namespace RynthCore.Plugin.RynthConquest; /// A labelled value from a server reply ("Pyreals" = "1,039,678,533 (4,158 MMDs)"). internal sealed class NamedValue @@ -110,11 +112,11 @@ internal sealed class ConquestBoard } /// -/// Everything ConquestAC-only (tag Conquest): bank balances and bank commands ("/b", "/bank"), +/// Everything Conquest-only: bank balances and bank commands ("/b", "/bank"), /// advanced augmentations ("/augs"), enlightenment augmentations ("/enl augs"), the XP bonus /// breakdown ("/bonus"), fellowships looking for members ("/fship list"), the /top boards, and -/// the void damage-over-time duration scaling. The plugin only feeds it chat and only shows it -/// while the server is ConquestAC; every reply regex is anchored at the start of the line (after +/// the void damage-over-time duration scaling. RynthConquest only feeds it chat while the server is +/// Conquest (and only loads there); every reply regex is anchored at the start of the line (after /// an optional chat timestamp), as upstream does, so a pasted copy in a chat channel can't /// overwrite your values. /// @@ -185,7 +187,7 @@ internal sealed class ConquestData BonusUtc = DateTime.MinValue, FshipUtc = DateTime.MinValue; public int Revision { get; private set; } - private readonly ChatRequest _bankReq = new(), _augReq = new(), _enlReq = new(), _bonusReq = new(), _fshipReq = new(), + private readonly ServerChatRequest _bankReq = new(), _augReq = new(), _enlReq = new(), _bonusReq = new(), _fshipReq = new(), _topReq = new(), _depositReq = new(); private ConquestBoard? _collecting; private long _collectingMs; @@ -230,7 +232,7 @@ internal sealed class ConquestData /// /// A chat line: true when it was a reply this module reads; = it - /// answers a request RynthOracle sent (eligible to be hidden). + /// answers a request RynthConquest sent (eligible to be hidden). /// public bool OnChatLine(string text, long now, out bool ours) { @@ -337,7 +339,7 @@ internal sealed class ConquestData return false; } - private bool Done(ChatRequest req, long now, out bool ours) + private bool Done(ServerChatRequest req, long now, out bool ours) { ours = req.Awaiting(now); req.Extend(now); diff --git a/Plugins/RynthCore.Plugin.RynthConquest/Conquest/ConquestFeature.cs b/Plugins/RynthCore.Plugin.RynthConquest/Conquest/ConquestFeature.cs new file mode 100644 index 0000000..c631271 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthConquest/Conquest/ConquestFeature.cs @@ -0,0 +1,143 @@ +// ConquestFeature.cs - What RynthConquest does on Conquest, without the host (ConquestPlugin.cs wires it +// to the engine, ConquestPages.cs draws it). Moved out of RynthOracle on 2026-10-20 so that only players +// who installed RynthConquest get Conquest's features, and the automatic /bank deposit with them: +// * reads the replies of Conquest's own commands (ConquestData: /b, /augs, /enl augs, /bonus, +// /fship list, /top) and the quest flags (/myquests, for the custom quest worklist), and hides +// the replies to its own requests when HideOwnReplies is on; +// * reads the advanced augmentations once after login (the Void DoT rule needs the Duration augs); +// * deposits everything at each ten-minute mark when AutoDeposit is on (off unless the player +// turned it on, in RynthOracle before or here); +// * works out the Void DoT duration rule for this character, which RynthOracle's Void timers read +// from the server profile ("voidDotDurationScale") instead of knowing about Conquest. +// Settings: rynthconquest.json (ServerPackSettings), taken over once from rynthoracle.json. +// Threads: everything here runs under Gate. Chat and tick come from the pump, the pages draw on the +// render thread holding it too; nothing in here calls the host. +// Pure: RynthServerPack.Tests covers it. +using System; +using RynthCore.Plugin.RynthOracle.Data; +using RynthCore.Plugin.ServerPack; + +namespace RynthCore.Plugin.RynthConquest; + +internal sealed class ConquestFeature +{ + public const string SettingAutoDeposit = "autoDeposit"; + public const string SettingHideOwnReplies = "hideOwnReplies"; + /// Set once rynthoracle.json's Conquest settings were taken over (they're never read again). + public const string MigrationMarker = "migratedFromRynthOracle"; + /// The profile value RynthOracle's Void timers apply ("RynthServer.Profile" values). + public const string VoidScaleKey = "voidDotDurationScale"; + /// After login, before the hidden /augs (RynthOracle's old timing: its quest read plus 4 s). + public const long AugsReadDelayMs = 10_000; + /// The character's level, XP and augmentation are read this often. + public const long CharacterReadMs = 1000; + + /// RynthConquest's pages (ConquestPages draws them): id, label, tooltip. + public static readonly (string Id, string Label, string Tooltip)[] PageList = + { + ("main", "Conquest", "Conquest: bank and auto-deposit, augmentations, levels past 275, fellowships and custom quests (RynthConquest)."), + ("boards", "Leaderboards", "Conquest's /top boards (RynthConquest)."), + }; + + /// Held for everything below (pump and render thread). + public readonly object Gate = new(); + public readonly ConquestData Data = new(); + public readonly QuestFlagStore Flags = new(); + + /// "/bank deposit" at every ten-minute mark (upstream's auto-deposit). Off by default. + public bool AutoDeposit; + /// Hide the replies to RynthConquest's own requests (a command typed by hand always shows). + public bool HideOwnReplies = true; + + // The character (ConquestPlugin reads them every CharacterReadMs). + public bool CharacterKnown; + public int Level, Enlightenment, ArchmagesEndurance; + public long TotalXp; + + private long _loginMs; + private bool _augsAsked; + private long _lastDepositBlock = -1; + + /// + /// Takes over the settings RynthOracle had for Conquest (rynthoracle.json at ), + /// once per settings file; a value that isn't there keeps this plugin's default (auto-deposit off, + /// hiding on, as they were in RynthOracle). True when it ran now. + /// + public static bool Migrate(ServerPackSettings settings, string oraclePath) => settings.MigrateOnce(MigrationMarker, s => + { + if (ServerPackSettings.ReadBoolFrom(oraclePath, "conquestAutoDeposit") is bool deposit) s.SetBool(SettingAutoDeposit, deposit); + if (ServerPackSettings.ReadBoolFrom(oraclePath, "hideOwnQuestReplies") is bool hide) s.SetBool(SettingHideOwnReplies, hide); + }); + + public void LoadSettings(ServerPackSettings s) + { + AutoDeposit = s.GetBool(SettingAutoDeposit, false); + HideOwnReplies = s.GetBool(SettingHideOwnReplies, true); + } + + public void SaveSettings(ServerPackSettings s) + { + bool changed = s.SetBool(SettingAutoDeposit, AutoDeposit); + changed |= s.SetBool(SettingHideOwnReplies, HideOwnReplies); + if (changed) s.Save(); + } + + /// A character logged in (or the plugin loaded in game): everything is read fresh. + public void Login(long nowMs) + { + _loginMs = nowMs; + _augsAsked = false; + Data.Clear(); + Flags.Clear(); + CharacterKnown = false; + Level = Enlightenment = ArchmagesEndurance = 0; + TotalXp = 0; + } + + public void Logout() + { + Data.Clear(); + Flags.Clear(); + CharacterKnown = false; + } + + /// + /// An incoming chat line on Conquest. True when it should be hidden: a reply to one of + /// RynthConquest's own requests, with HideOwnReplies on. + /// + public bool OnChatLine(string text, long nowMs) + { + string line = text.TrimEnd('\r', '\n'); + MyQuestsLine kind = Flags.OnChatLine(line, nowMs); + if (kind != MyQuestsLine.None) + return Flags.AwaitingOurs && HideOwnReplies && kind is MyQuestsLine.Quest or MyQuestsLine.Empty; + return Data.OnChatLine(line, nowMs, out bool ours) && ours && HideOwnReplies; + } + + /// The once-after-login /augs: the command to send now, or null. + public string? LoginAugsDue(long nowMs) + { + if (_augsAsked || nowMs - _loginMs <= AugsReadDelayMs) return null; + _augsAsked = true; + return Data.RequestAugs(nowMs); + } + + /// The automatic deposit: "/bank deposit" when one is due now, else null. + public string? AutoDepositDue(DateTime local, long nowMs) + => AutoDeposit && DepositDue(local, ref _lastDepositBlock) ? Data.AutoDeposit(nowMs) : null; + + /// + /// True once in each ten-minute block, at its first minute (:00, :10, :20 ... local time), as + /// upstream does; remembers the block already done. + /// + public static bool DepositDue(DateTime local, ref long lastBlock) + { + long block = local.Ticks / TimeSpan.TicksPerMinute / 10; + if (local.Minute % 10 != 0 || block == lastBlock) return false; + lastBlock = block; + return true; + } + + /// This character's Void DoT duration multiplier on Conquest (Archmage's Endurance and the Duration augs). + public double VoidScale => Data.VoidDurationMultiplier(ArchmagesEndurance); +} diff --git a/Plugins/RynthCore.Plugin.RynthConquest/Conquest/ConquestPages.cs b/Plugins/RynthCore.Plugin.RynthConquest/Conquest/ConquestPages.cs new file mode 100644 index 0000000..27e3fae --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthConquest/Conquest/ConquestPages.cs @@ -0,0 +1,417 @@ +// Ported from Oracle of Dereth by Advis Eveldan (advis61), MIT. See THIRD_PARTY_NOTICES.md. +// RynthOracle's Conquest tab (Views/ConquestTab.cs) and the Conquest half of its Leaderboards tab +// (Views/BoardsTab.cs), moved here on 2026-10-20 and redrawn with ImGui as RynthConquest's pages: +// sub-tabs of the Mini Remote's Server section while on Conquest, and tabs of the /rserver window. +using System; +using System.Collections.Generic; +using System.Linq; +using System.Numerics; +using ImGuiNET; +using RynthCore.Plugin.RynthOracle.Data; +using RynthCore.Plugin.ServerPack; +using RynthCore.Plugin.Shared; + +namespace RynthCore.Plugin.RynthConquest; + +/// +/// The Conquest page (bank balances and bank commands, advanced and enlightenment augmentations, +/// levels past 275 and the XP bonus breakdown, fellowships looking for members, the custom quest +/// worklist: upstream's Bank, Conquest Augs, Conquest XP, Fship and Custom tabs) and the +/// Leaderboards page (Conquest's /top boards: upstream's Top Players tab). +/// Render thread: each page draws holding the feature's lock, and queues what it sends for the tick. +/// +internal sealed class ConquestPages +{ + private static readonly Vector4 Gold = new(1.00f, 0.84f, 0.30f, 1f); + private static readonly Vector4 Green = new(0.45f, 0.85f, 0.45f, 1f); + private static readonly Vector4 Grey = new(0.55f, 0.57f, 0.60f, 1f); + private static readonly Vector4 Selected = new(0.26f, 0.45f, 0.70f, 1f); + + private static readonly string[] Views = { "Bank", "Augs", "Enlightenment", "Experience", "Fellowships", "Custom quests" }; + private static readonly string[] FshipSorts = { "Name", "Leader", "Most members", "Location" }; + + private readonly ConquestFeature _f; + private readonly Func _active; + private readonly Action _runOnTick; + private readonly Func _send; + private readonly Action _print; + private readonly Action _saveSettings; + private readonly ServerRefreshRow _refresh = new(); + + private int _view; + private int _withdrawIndex = ConquestData.DefaultWithdraw, _transferIndex = ConquestData.DefaultTransfer; + private string _withdrawAmount = "", _transferAmount = "", _transferTarget = ""; + private int _fshipSort; + private int _board; + + /// RynthConquest's server is this world. + /// Queues work for the plugin tick (ServerPackPlugin.RunOnTick). + /// Sends a chat command as if typed (pump thread). + /// A line in the chat window (pump thread). + /// Writes the feature's settings (pump thread). + public ConquestPages(ConquestFeature feature, Func active, Action runOnTick, Func send, + Action print, Action saveSettings) + { + _f = feature; + _active = active; + _runOnTick = runOnTick; + _send = send; + _print = print; + _saveSettings = saveSettings; + } + + public ServerPage[] Pages() + { + var list = ConquestFeature.PageList; + return new[] + { + new ServerPage(list[0].Id, list[0].Label, list[0].Tooltip, DrawConquest), + new ServerPage(list[1].Id, list[1].Label, list[1].Tooltip, DrawBoards), + }; + } + + /// Logout: the next character's status lines start empty. + public void Reset() => _refresh.Reset(); + + // ── Conquest page ─────────────────────────────────────────────────── + + private void DrawConquest() + { + if (!Ready()) return; + lock (_f.Gate) + { + for (int i = 0; i < Views.Length; i++) + { + if (i > 0) ImGui.SameLine(); + if (Toggle(Views[i] + "##cq_v" + i, i == _view)) _view = i; + } + _refresh.Draw("cq" + _view, ConquestHelp(), RefreshConquest); + ImGui.Separator(); + switch (_view) + { + case 0: DrawBank(); break; + case 1: DrawAugs(); break; + case 2: DrawEnl(); break; + case 3: DrawXp(); break; + case 4: DrawFships(); break; + default: DrawCustom(); break; + } + ImGui.Spacing(); + bool hide = _f.HideOwnReplies; + if (ImGui.Checkbox("Hide the replies to RynthConquest's own requests##cq_hide", ref hide)) + { + _f.HideOwnReplies = hide; + _runOnTick(_saveSettings); + } + Tooltip("/b, /augs, /top, /myquests and the like when RynthConquest sends them. A command you type yourself always shows its reply."); + } + } + + /// True when the page has something to show; otherwise says why. + private bool Ready() + { + if (_active()) return true; + SafeImGui.TextWrapped("These pages are for Conquest. RynthCore doesn't see this world as Conquest " + + "(check RynthCore Options > Diagnostics, or /rserver info)."); + return false; + } + + private static string ReadAt(DateTime utc) => utc == DateTime.MinValue ? "not read yet" : $"read at {utc.ToLocalTime():HH:mm}"; + + private void DrawBank() + { + ConquestData cq = _f.Data; + SafeImGui.TextDisabled(ReadAt(cq.BankUtc)); + foreach (NamedValue b in cq.Bank.OrderBy(b => b.Name, StringComparer.OrdinalIgnoreCase)) + { + SafeImGui.TextDisabled(Cut(b.Name, 34)); + ImGui.SameLine(260f); + SafeImGui.Text(b.Value); + } + if (cq.Bank.Count == 0) SafeImGui.TextDisabled("No balances read yet."); + + ImGui.SeparatorText("Deposit"); + if (ImGui.Button("Deposit everything##cq_dep")) Queue("/bank deposit"); + Tooltip("Sends /bank deposit."); + bool auto = _f.AutoDeposit; + if (ImGui.Checkbox("Deposit by itself every ten minutes##cq_auto", ref auto)) + { + _f.AutoDeposit = auto; + _runOnTick(_saveSettings); + } + Tooltip("At :00, :10, :20 ... while you're logged in on Conquest. Its reply is hidden."); + + ImGui.SeparatorText("Withdraw"); + string[] wl = ConquestData.Withdrawable.Select(c => c.Label).ToArray(); + ImGui.SetNextItemWidth(200f); + if (ImGui.Combo("Currency##cq_wcur", ref _withdrawIndex, wl, wl.Length)) _withdrawIndex = Math.Clamp(_withdrawIndex, 0, wl.Length - 1); + ImGui.SetNextItemWidth(200f); + ImGui.InputText("Amount##cq_wamt", ref _withdrawAmount, 16); + if (ImGui.Button("Withdraw##cq_withdraw")) + { + string? cmd = ConquestData.WithdrawCommand(ConquestData.Withdrawable[_withdrawIndex], _withdrawAmount); + if (cmd == null) Print("Withdraw: type a whole number above 0."); + else Queue(cmd); + } + + ImGui.SeparatorText("Transfer to a character"); + string[] tl = ConquestData.Transferable.Select(c => c.Label).ToArray(); + ImGui.SetNextItemWidth(200f); + if (ImGui.Combo("Currency##cq_tcur", ref _transferIndex, tl, tl.Length)) _transferIndex = Math.Clamp(_transferIndex, 0, tl.Length - 1); + ImGui.SetNextItemWidth(200f); + ImGui.InputText("Amount##cq_tamt", ref _transferAmount, 16); + ImGui.SetNextItemWidth(200f); + ImGui.InputText("Character##cq_tgt", ref _transferTarget, 40); + if (ImGui.Button("Transfer##cq_transfer")) + { + string? cmd = ConquestData.TransferCommand(ConquestData.Transferable[_transferIndex], _transferAmount, _transferTarget); + if (cmd == null) Print("Transfer: type a whole number above 0 (MMD notes: at most 1,000) and a character name."); + else Queue(cmd); + } + } + + private void DrawAugs() + { + ConquestData cq = _f.Data; + SafeImGui.TextDisabled($"{ReadAt(cq.AugsUtc)}, {cq.AugTotal} in total"); + ImGui.TextDisabled("Aug"); ImGui.SameLine(120f); ImGui.TextDisabled("Have"); ImGui.SameLine(170f); + ImGui.TextDisabled("Next costs"); ImGui.SameLine(330f); ImGui.TextDisabled("Effect now"); + foreach (ConquestAug a in cq.Augs) + { + SafeImGui.Text(a.Name); + ImGui.SameLine(120f); + SafeImGui.Text(a.Count.ToString()); + ImGui.SameLine(170f); + SafeImGui.Text(a.NextCostText()); + ImGui.SameLine(330f); + SafeImGui.TextDisabled(Cut(a.Effect(), 48)); + Tooltip(a.Effect()); + } + } + + private void DrawEnl() + { + ConquestData cq = _f.Data; + SafeImGui.TextDisabled(ReadAt(cq.EnlUtc)); + foreach (NamedValue a in cq.EnlAugs) + { + SafeImGui.Text(Cut(a.Name, 26)); + ImGui.SameLine(200f); + SafeImGui.Text(a.Value); + ImGui.SameLine(360f); + SafeImGui.TextDisabled(ConquestData.EnlCost(a.Name)); + } + if (cq.EnlAugs.Count == 0) ImGui.TextDisabled("Nothing read yet. Press Refresh."); + } + + private void DrawXp() + { + ConquestData cq = _f.Data; + int level = _f.Level; + if (!_f.CharacterKnown) ImGui.TextDisabled("Reading your character..."); + ImGui.SeparatorText($"Level {level}"); + if (level >= ConquestData.MaxLevel) ImGui.TextUnformatted("Maximum level."); + else if (level < 275) + { + // Retail levels: RynthOracle's Character tab has the progress to the next one. + SafeImGui.TextDisabled($"Conquest's own levels start at 276. {Number(Math.Max(0, ConquestData.XpForLevel(276) - _f.TotalXp))} XP to level 276."); + } + else + { + long start = level >= 276 ? ConquestData.XpForLevel(level) : 0; + long next = ConquestData.XpForLevel(level + 1); + long toNext = Math.Max(0, next - _f.TotalXp); + long begin = level == 275 ? 191_226_310_247 : start; + float frac = next > begin ? (float)Math.Clamp((double)(_f.TotalXp - begin) / (next - begin), 0, 1) : 1f; + ImGui.ProgressBar(frac, new Vector2(-1f, 0f), $"{Number(toNext)} to level {level + 1}"); + long toMax = Math.Max(0, ConquestData.XpForLevel(ConquestData.MaxLevel) - _f.TotalXp); + SafeImGui.TextDisabled($"{Number(toMax)} to level {ConquestData.MaxLevel}"); + } + int target = _f.Enlightenment + 1; + ImGui.SeparatorText($"Enlightenment {_f.Enlightenment}"); + SafeImGui.Text($"Next costs {Number(ConquestData.EnlCoinCost(target))} coins and {(ConquestData.EnlLuminanceCost(target) / 1_000_000.0):0.##}M luminance"); + + ImGui.SeparatorText("Experience bonuses"); + SafeImGui.TextDisabled(ReadAt(cq.BonusUtc)); + foreach (NamedValue b in cq.Bonuses) + { + SafeImGui.TextDisabled(b.Name); + ImGui.SameLine(200f); + SafeImGui.Text(b.Value.Length > 0 ? b.Value : "-"); + } + } + + private void DrawFships() + { + ConquestData cq = _f.Data; + SafeImGui.TextDisabled($"{ReadAt(cq.FshipUtc)}, {cq.Fellowships.Count} looking for members"); + ImGui.SetNextItemWidth(160f); + ImGui.Combo("Sort##cq_fsort", ref _fshipSort, FshipSorts, FshipSorts.Length); + IEnumerable list = _fshipSort switch + { + 1 => cq.Fellowships.OrderBy(f => f.Leader, StringComparer.OrdinalIgnoreCase), + 2 => cq.Fellowships.OrderByDescending(f => f.MemberCount), + 3 => cq.Fellowships.OrderBy(f => f.Location, StringComparer.OrdinalIgnoreCase), + _ => cq.Fellowships.OrderBy(f => f.Name, StringComparer.OrdinalIgnoreCase), + }; + if (ImGui.BeginChild("##cq_fships", new Vector2(0f, 220f), ImGuiChildFlags.Borders)) + { + foreach (ConquestFellowship f in list) + { + SafeImGui.Text(Cut(f.Name, 26)); + ImGui.SameLine(200f); + SafeImGui.Text(Cut(f.Leader, 20)); + ImGui.SameLine(350f); + SafeImGui.Text(f.Members); + if (f.Location.Length > 0) { ImGui.SameLine(410f); SafeImGui.TextDisabled(Cut(f.Location, 26)); } + } + if (cq.Fellowships.Count == 0) ImGui.TextDisabled("None read yet. Press Refresh."); + } + ImGui.EndChild(); + } + + private void DrawCustom() + { + DateTime now = DateTime.UtcNow; + int i = 0; + foreach (CustomQuest q in CustomQuestList.All) + { + bool done = q.IsComplete(_f.Flags, now); + SafeImGui.TextColored(done ? Green : Grey, done ? "done" : "--"); + ImGui.SameLine(50f); + string status = q.Status(_f.Flags, now); + CustomQuest row = q; + if (ImGui.Selectable(Cut(q.Name, 34) + "##cq_cust" + i++, false, ImGuiSelectableFlags.None, new Vector2(280f, 0f))) + PrintEntry(row.Name, row.Flag, status, row.Hint, row.Url); + Tooltip("Click: the quest's hint in chat."); + ImGui.SameLine(340f); + SafeImGui.Text(status); + } + if (CustomQuestList.All.Count == 0) ImGui.TextDisabled("No custom quests listed."); + if (_f.Flags.LastReadUtc == DateTime.MinValue) ImGui.TextDisabled("Press Refresh to read your quest flags (/myquests) for their status."); + } + + /// An entry's name, status, hint and link in chat (upstream "thinks" them). + private void PrintEntry(string name, string flag, string status, string details, string url) + { + Print(flag.Length > 0 ? $"{name} ({flag}){(status.Length > 0 ? " - " + status : "")}" : name); + if (details.Length > 0) Print(details); + if (url.Length > 0) Print(url); + } + + // ── Leaderboards page ─────────────────────────────────────────────── + + private void DrawBoards() + { + if (!Ready()) return; + lock (_f.Gate) + { + ConquestData cq = _f.Data; + _board = Math.Clamp(_board, 0, cq.Boards.Count - 1); + for (int i = 0; i < cq.Boards.Count; i++) + { + if (i > 0) ImGui.SameLine(); + if (Toggle(cq.Boards[i].Label + "##cb_tab" + i, i == _board)) _board = i; + } + ConquestBoard b = cq.Boards[_board]; + _refresh.Draw("board" + b.Key, $"Sends {b.Command} and reads the reply.", () => Ask("board" + b.Key, () => b.UpdatedUtc.Ticks, b.Command, + now => cq.RequestBoard(b, now))); + ImGui.Separator(); + SafeImGui.TextDisabled(b.UpdatedUtc == DateTime.MinValue ? "not read yet" : $"read at {b.UpdatedUtc.ToLocalTime():HH:mm}"); + if (b.You != null) SafeImGui.Text($"You: #{b.You.Rank} with {b.You.Value}"); + if (ImGui.BeginChild("##cb_rows", Vector2.Zero, ImGuiChildFlags.Borders)) + { + ImGui.TextDisabled("Rank"); ImGui.SameLine(60f); ImGui.TextDisabled("Name"); ImGui.SameLine(280f); ImGui.TextDisabled("Value"); + foreach (BoardRow r in b.Rows) + { + SafeImGui.Text(r.Rank.ToString()); + ImGui.SameLine(60f); + if (r.IsYou) SafeImGui.TextColored(Gold, Cut(r.Name, 30)); + else SafeImGui.Text(Cut(r.Name, 30)); + ImGui.SameLine(280f); + SafeImGui.Text(r.Value); + if (r.Extra.Length > 0) { ImGui.SameLine(420f); SafeImGui.TextDisabled(Cut(r.Extra, 40)); } + } + if (b.Rows.Count == 0) ImGui.TextDisabled("Nothing read yet. Press Refresh."); + } + ImGui.EndChild(); + } + } + + // ── Refresh (RynthOracle's RefreshBar, Conquest's part) ────────────── + + private ServerRefreshResult RefreshConquest() + { + ConquestData cq = _f.Data; + switch (_view) + { + case 0: return Ask("bank", () => cq.BankUtc.Ticks, "/b", now => cq.RequestBank(now)); + case 1: return Ask("augs", () => cq.AugsUtc.Ticks, "/augs", now => cq.RequestAugs(now)); + case 2: return Ask("enl", () => cq.EnlUtc.Ticks, "/enl augs", now => cq.RequestEnl(now)); + case 3: return Ask("bonus", () => cq.BonusUtc.Ticks, "/bonus", now => cq.RequestBonus(now)); + case 4: return Ask("fship", () => cq.FshipUtc.Ticks, "/fship list", now => cq.RequestFships(now)); + default: + if (_refresh.CoolingDown("quests", Environment.TickCount64)) return new ServerRefreshResult(ServerRefreshRow.TooSoon); + QuestFlagStore flags = _f.Flags; + int rev = flags.Revision; + int wait = flags.ThrottleSecondsLeft(Environment.TickCount64); + if (wait > 0) return new ServerRefreshResult($"The server answers one /myquests a minute; try again in {wait}s (the flags shown are kept)."); + _runOnTick(() => + { + lock (_f.Gate) flags.Request(_send, Environment.TickCount64); + }); + return new ServerRefreshResult("Asked the server for your quest flags (/myquests).", () => flags.Revision != rev); + } + } + + private string ConquestHelp() => _view switch + { + 0 => "Sends /b and reads your balances.", + 1 => "Sends /augs and reads your advanced augmentations.", + 2 => "Sends /enl augs and reads your enlightenment augmentations.", + 3 => "Sends /bonus for the experience bonuses (your level is read from the game).", + 4 => "Sends /fship list and reads the fellowships looking for members.", + _ => "Sends /myquests: the custom quests' status comes from your quest flags.", + }; + + /// + /// Sends one of the page's own commands on the next tick (marking it as RynthConquest's, so its + /// reply can be hidden) and waits for to change. + /// + private ServerRefreshResult Ask(string key, Func state, string command, Action markSent) + { + if (_refresh.CoolingDown(key, Environment.TickCount64)) return new ServerRefreshResult(ServerRefreshRow.TooSoon); + long before = state(); + _runOnTick(() => + { + lock (_f.Gate) markSent(Environment.TickCount64); + if (!_send(command)) _print($"Couldn't send {command} (not in the world)."); + }); + return new ServerRefreshResult($"Sent {command}.", () => state() != before); + } + + // ── Helpers ───────────────────────────────────────────────────────── + + /// A command from a button, sent on the next tick. + private void Queue(string command) => _runOnTick(() => _send(command)); + + /// A line in chat, written on the next tick. + private void Print(string text) => _runOnTick(() => _print(text)); + + private static bool Toggle(string label, bool selected) + { + if (selected) ImGui.PushStyleColor(ImGuiCol.Button, Selected); + bool clicked = ImGui.SmallButton(label); + if (selected) ImGui.PopStyleColor(); + return clicked; + } + + private static void Tooltip(string text) + { + if (ImGui.IsItemHovered()) SafeImGui.SetTooltip(text); + } + + private static string Cut(string s, int max) => s.Length <= max ? s : s.Substring(0, Math.Max(0, max - 3)) + "..."; + + private static string Number(long n) => TimeText.Number(n); +} diff --git a/Plugins/RynthCore.Plugin.RynthOracle/Data/CustomQuests.cs b/Plugins/RynthCore.Plugin.RynthConquest/Conquest/CustomQuests.cs similarity index 60% rename from Plugins/RynthCore.Plugin.RynthOracle/Data/CustomQuests.cs rename to Plugins/RynthCore.Plugin.RynthConquest/Conquest/CustomQuests.cs index e2e8ada..6d0e033 100644 --- a/Plugins/RynthCore.Plugin.RynthOracle/Data/CustomQuests.cs +++ b/Plugins/RynthCore.Plugin.RynthConquest/Conquest/CustomQuests.cs @@ -1,14 +1,19 @@ // Ported from Oracle of Dereth by Advis Eveldan (advis61), MIT. See THIRD_PARTY_NOTICES.md. +// Moved here from RynthOracle (Data/CustomQuests.cs) on 2026-10-20, with Resources\customquests.csv. using System; using System.Collections.Generic; using System.IO; +using System.Reflection; +using System.Text; +using RynthCore.Plugin.RynthOracle.Data; -namespace RynthCore.Plugin.RynthOracle.Data; +namespace RynthCore.Plugin.RynthConquest; /// -/// A server's custom quest worklist (customquests.csv: Server, Name, QuestFlag, Url, Hint). Each -/// row carries its server tag, so only the current server's rows show (today: ConquestAC's). -/// A repeatable counts as done only while on cooldown (upstream's rule). +/// Conquest's custom quest worklist (customquests.csv: Server, Name, QuestFlag, Url, Hint; every row +/// is Conquest's), upstream's Custom tab. The status comes from the character's quest flags +/// (/myquests, read with RynthOracle's parser, linked source). A repeatable counts as done only +/// while on cooldown (upstream's rule). /// internal sealed class CustomQuest { @@ -31,18 +36,17 @@ internal sealed class CustomQuest internal static class CustomQuestList { - public static List All { get; } = Load(); + /// The embedded list's logical name (RynthCore.Plugin.RynthConquest.csproj). + public const string ResourceName = "RynthConquest.customquests.csv"; - public static IEnumerable For(ServerIdentity server) - { - foreach (CustomQuest q in All) - if (server.Is(q.Server)) yield return q; - } + public static List All { get; } = Load(); private static List Load() { var list = new List(); - using StreamReader r = Csv.OpenEmbedded("customquests.csv"); + Stream? stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(ResourceName); + if (stream == null) return list; + using var r = new StreamReader(stream, Encoding.UTF8, detectEncodingFromByteOrderMarks: true); r.ReadLine(); // Server,Name,QuestFlag,Url,Hint while (r.ReadLine() is string line) { diff --git a/Plugins/RynthCore.Plugin.RynthConquest/ConquestPlugin.cs b/Plugins/RynthCore.Plugin.RynthConquest/ConquestPlugin.cs new file mode 100644 index 0000000..906ca89 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthConquest/ConquestPlugin.cs @@ -0,0 +1,118 @@ +// ConquestPlugin.cs - RynthConquest's own features, through the shared server plugin's hooks +// (Plugins/Shared/ServerPack/ServerPackPlugin.cs). Everything Conquest-specific that RynthOracle used to +// carry lives here since 2026-10-20 (Conquest/ConquestFeature.cs says what), so a player without +// RynthConquest gets none of it, the automatic /bank deposit included. +using System; +using System.IO; +using RynthCore.Plugin.RynthConquest; + +namespace RynthCore.Plugin.ServerPack; + +public sealed partial class ServerPackPlugin +{ + private readonly ConquestFeature _conquest = new(); + private ConquestPages? _conquestPages; + private long _nextConquestCharacterMs; + + /// Where RynthOracle kept the Conquest settings before they moved here (read once). + internal static string OracleSettingsPath => Path.Combine( + Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "RynthCore", "rynthoracle.json"); + + partial void ServerPages(System.Collections.Generic.List pages) + { + _conquestPages = new ConquestPages(_conquest, () => Active, RunOnTick, Send, + text => ChatLine($"[{RynthPluginInfo.Name}] {text}"), SaveConquestSettings); + pages.AddRange(_conquestPages.Pages()); + } + + partial void ServerInitialize() + { + if (ConquestFeature.Migrate(Settings, OracleSettingsPath)) + LogTagged("Took over RynthOracle's Conquest settings (auto-deposit, hiding own replies) from rynthoracle.json."); + lock (_conquest.Gate) _conquest.LoadSettings(Settings); + } + + private void SaveConquestSettings() + { + lock (_conquest.Gate) _conquest.SaveSettings(Settings); + } + + partial void ServerLoginComplete() + { + lock (_conquest.Gate) _conquest.Login(Environment.TickCount64); + _nextConquestCharacterMs = 0; + _conquestPages?.Reset(); + } + + partial void ServerLogout() + { + lock (_conquest.Gate) _conquest.Logout(); + _conquestPages?.Reset(); + } + + partial void ServerShutdown() => SaveConquestSettings(); + + partial void ServerChatText(string text, int chatType, ref bool eat) + { + if (!Active) return; + bool hide; + lock (_conquest.Gate) hide = _conquest.OnChatLine(text, Environment.TickCount64); + if (hide) eat = true; + } + + partial void ServerChatBar(string text) + { + // The player's own /myquests: its reply shows (QuestFlagStore tells it from RynthConquest's). + if (text.Equals("/myquests", StringComparison.OrdinalIgnoreCase)) _conquest.Flags.NoteTypedCommand(); + } + + partial void ServerTick(bool active) + { + if (!active) return; + long now = Environment.TickCount64; + string? augs, deposit; + lock (_conquest.Gate) + { + _conquest.Flags.Tick(now); + augs = _conquest.LoginAugsDue(now); + deposit = _conquest.AutoDepositDue(DateTime.Now, now); + } + if (augs != null) Send(augs); + if (deposit != null && Send(deposit)) ChatLine($"[{RynthPluginInfo.Name}] Auto-deposited to the bank."); + + if (now < _nextConquestCharacterMs) return; + _nextConquestCharacterMs = now + ConquestFeature.CharacterReadMs; + ReadConquestCharacter(); + } + + /// Level, XP, enlightenment and Archmage's Endurance (the Void DoT rule), then the rule for RynthOracle. + private void ReadConquestCharacter() + { + uint player = Host.HasGetPlayerId ? Host.GetPlayerId() : 0; + if (player == 0) return; + int level = Host.TryGetObjectIntProperty(player, 25, out int l) ? l : 0; // PropertyInt Level + int enl = Host.TryGetObjectIntProperty(player, 390, out int e) ? e : 0; // Enlightenment + int archmage = Host.TryGetObjectIntProperty(player, 238, out int a) ? a : 0; // AugmentationIncreasedSpellDuration + long xp = Host.HasGetObjectQuadProperty && Host.TryGetObjectQuadProperty(player, 1, out long x) ? x : 0; // TotalExperience + double scale; + lock (_conquest.Gate) + { + _conquest.Level = level; + _conquest.Enlightenment = enl; + _conquest.ArchmagesEndurance = archmage; + _conquest.TotalXp = xp; + _conquest.CharacterKnown = level > 0; + scale = _conquest.VoidScale; + } + SetProfileValue(ConquestFeature.VoidScaleKey, scale); + } + + partial void ServerInfoLines(Action line) + { + lock (_conquest.Gate) + { + line($"Auto-deposit {(_conquest.AutoDeposit ? "on" : "off")}; own replies {(_conquest.HideOwnReplies ? "hidden" : "shown")}" + + $"; Void DoT duration x{_conquest.VoidScale:0.##} ({_conquest.Data.DurationAugs} Duration augs)."); + } + } +} diff --git a/Plugins/RynthCore.Plugin.RynthOracle/Resources/customquests.csv b/Plugins/RynthCore.Plugin.RynthConquest/Resources/customquests.csv similarity index 100% rename from Plugins/RynthCore.Plugin.RynthOracle/Resources/customquests.csv rename to Plugins/RynthCore.Plugin.RynthConquest/Resources/customquests.csv diff --git a/Plugins/RynthCore.Plugin.RynthConquest/RynthCore.Plugin.RynthConquest.csproj b/Plugins/RynthCore.Plugin.RynthConquest/RynthCore.Plugin.RynthConquest.csproj index 2415f4d..da0377e 100644 --- a/Plugins/RynthCore.Plugin.RynthConquest/RynthCore.Plugin.RynthConquest.csproj +++ b/Plugins/RynthCore.Plugin.RynthConquest/RynthCore.Plugin.RynthConquest.csproj @@ -1,17 +1,37 @@ + (..\Shared\ServerPack\ServerPlugin.props); ServerData.cs holds what is known about the server. + Conquest's own features (ConquestPlugin.cs, Conquest\) came from RynthOracle on 2026-10-20: the + bank and its auto-deposit, augmentations, levels past 275, fellowships, custom quests and the + /top boards, as pages of the Mini Remote's Server section. --> RynthCore.Plugin.RynthConquest - 0.1.0 + 0.2.0 conquest Conquest acconquest.ddns.net Conquest|ConquestAC - Conquest only: the server card (rules, account limits, botting policy, links, account setup) in the Mini Remote. + Conquest only: the server card, and Conquest's bank (with auto-deposit), augmentations, levels past 275, fellowships, custom quests and leaderboards in the Mini Remote. + + + + + + + + + + + + + + + + diff --git a/Plugins/RynthCore.Plugin.RynthConquest/ServerData.cs b/Plugins/RynthCore.Plugin.RynthConquest/ServerData.cs index 9f5cfcb..b830bde 100644 --- a/Plugins/RynthCore.Plugin.RynthConquest/ServerData.cs +++ b/Plugins/RynthCore.Plugin.RynthConquest/ServerData.cs @@ -16,6 +16,7 @@ internal static class ServerData "Live events and deep crafting.", "Has a PK system on a PvE server.", "RynthOracle has a Conquest quest pack (quests.conquest.csv).", + "RynthConquest's pages (Server section, or /rserver): bank and auto-deposit, augmentations, levels past 275, fellowships, custom quests, leaderboards.", }, Discord = "https://discord.gg/Gsadhhv72S", Website = "https://dsc.gg/conquerac", diff --git a/Plugins/RynthCore.Plugin.RynthConquest/THIRD_PARTY_NOTICES.md b/Plugins/RynthCore.Plugin.RynthConquest/THIRD_PARTY_NOTICES.md new file mode 100644 index 0000000..ceba802 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthConquest/THIRD_PARTY_NOTICES.md @@ -0,0 +1,42 @@ +# Third-party notices: RynthConquest + +RynthConquest's Conquest features (the bank, advanced and enlightenment augmentations, XP bonuses +and levels past 275, the fellowship list, the /top boards, the custom quest worklist, the +auto-deposit and the Void damage-over-time duration rule) are ported from **Oracle of Dereth**, a +Decal plugin for Asheron's Call by **Advis Eveldan** (GitHub: +[advis61](https://github.com/advis61/OracleOfDereth)). They were part of RynthOracle until +2026-10-20 and moved here so that only Conquest players carry them. Thank you, Advis! + +- Upstream: https://github.com/advis61/OracleOfDereth +- Ported from commit `ee618c6847b98b656a47ca87cc347441d206c547` (2026-10-01, version 2.3.0). +- Licence: MIT. The upstream README states "License: MIT". The repository has no separate + LICENSE file and names no copyright line, so the standard MIT text is reproduced below + with the author and the years of the repository's history. + +What came from upstream: `Resources\customquests.csv` (copied unchanged), and the logic of the +features above, rewritten for RynthCore. Ported files say so in their header. RynthOracle's quest +flag parser (`QuestFlags.cs`, also ported from upstream) is compiled in as shared source. + +--- + +MIT License + +Copyright (c) 2024-2026 Advis Eveldan (GitHub: advis61) and contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/Plugins/RynthCore.Plugin.RynthILT/DataInterface.cs b/Plugins/RynthCore.Plugin.RynthILT/DataInterface.cs index 05e9619..a892bf8 100644 --- a/Plugins/RynthCore.Plugin.RynthILT/DataInterface.cs +++ b/Plugins/RynthCore.Plugin.RynthILT/DataInterface.cs @@ -1,7 +1,8 @@ // DataInterface.cs - RynthILT's side of the "RynthILT.Data" interface (Plugins/Shared/RynthIltDataApi.cs): // the charms list and the bank balances (every character RynthILT has seen on this server) the // Mini Remote's Charms and Banking tabs show, for other plugins to draw, with the charm Toggle and -// the bank verbs they send back; since version 2 also the pet breeding tracker's JSON and verbs. +// the bank verbs they send back; since version 2 also the pet breeding tracker's JSON and verbs; +// since version 3 the Temple guardians' JSON and verbs (RynthOracle's Quests tab). // // The table is allocated once per loaded copy of RynthILT and never freed (a plugin DLL is never // unloaded); after Release() it reports Version 0 and every function answers 0. Before login there @@ -37,6 +38,8 @@ internal static unsafe class DataInterface t->BankCommand = &BankCommand; t->GetPetBreedingJson = &GetPetBreedingJson; t->PetBreedingCommand = &PetBreedingCommand; + t->GetGuardianJson = &GetGuardianJson; + t->GuardianCommand = &GuardianCommand; t->Version = RynthIltDataApiV1.InterfaceVersion; _table = t; } @@ -128,6 +131,32 @@ internal static unsafe class DataInterface catch { return 0; } } + [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] + private static int GetGuardianJson(byte* buffer, int capacity) + { + try + { + string? json = Hub?.GuardianJson; + return string.IsNullOrEmpty(json) ? 0 : ProfileInterface.Write(json, buffer, capacity); + } + catch { return 0; } + } + + [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] + private static int GuardianCommand(byte* utf8) + { + try + { + IltHubController? hub = Hub; + if (hub == null) return 0; + string? line = ReadVerb(utf8); + if (line == null) return 0; + hub.RequestGuardianVerb(line); + return 1; + } + catch { return 0; } + } + /// A reader's verb line, or null when it is empty, too long or not plain ASCII (no control characters reach a chat command). private static string? ReadVerb(byte* utf8) { diff --git a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltFeatureCatalog.cs b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltFeatureCatalog.cs index 96b39c0..bd88c27 100644 --- a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltFeatureCatalog.cs +++ b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltFeatureCatalog.cs @@ -20,6 +20,8 @@ // Fellowship.cs), Zone Share (ZoneShareManager) and the fellowship luminance share. using System; using System.Collections.Generic; +using System.Globalization; +using System.Text; namespace RynthCore.Plugin.RynthILT.Hub; @@ -45,6 +47,16 @@ internal enum IltKnown ProfileOff, } +/// The quest bonus list as the profile JSON carries it ("questBonus"), for RynthOracle's Quests tab. +/// The server has /qb turned off. +/// Bumped per parsed "/qb list"; 0 = not loaded this session. +/// The server's quest bonus count; -1 = unknown. +/// One line on the last request ("loading...", "12 completed, 3 incomplete", ...). +/// Completed bonus flags, sorted. +/// Incomplete bonus flags, sorted. +internal sealed record IltQuestBonusInfo(bool Disabled, int Generation, long Count, string Status, + IReadOnlyList Completed, IReadOnlyList Incomplete); + internal static class IltFeatureCatalog { public const string GroupCharacter = "Character"; @@ -257,6 +269,83 @@ internal static class IltFeatureCatalog /// The fellowship member limit: ACECustom's 29 on an ILT world, retail's 9 elsewhere. public static int FellowshipMax(bool iltWorld) => iltWorld ? IltFellowshipMax : RetailFellowshipMax; + /// + /// The "RynthILT.Server" profile JSON (schema in Plugins/Shared/RynthIltServerApi.cs). Pure: + /// everything comes in as arguments, so the tests build it without a client. Plain ASCII. + /// + public static string BuildProfileJson(bool iltWorld, string world, bool forced, string source, DateTime checkedUtc, + Func bit, IltQuestBonusInfo? questBonus = null) + { + var sb = new StringBuilder(4096); + sb.Append("{\"ilt\":").Append(iltWorld ? "true" : "false"); + sb.Append(",\"world\":\"").Append(Escape(world)).Append('"'); + sb.Append(",\"forced\":").Append(forced ? "true" : "false"); + sb.Append(",\"source\":\"").Append(Escape(source)).Append('"'); + sb.Append(",\"checked\":\"") + .Append(checkedUtc == DateTime.MinValue ? "" : checkedUtc.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ", CultureInfo.InvariantCulture)) + .Append('"'); + + sb.Append(",\"features\":["); + for (int i = 0; i < All.Length; i++) + { + IltFeatureInfo f = All[i]; + if (i > 0) sb.Append(','); + sb.Append("{\"key\":\"").Append(Escape(f.Key)) + .Append("\",\"label\":\"").Append(Escape(f.Label)) + .Append("\",\"group\":\"").Append(Escape(f.Group)) + .Append("\",\"state\":").Append(((int)StateOf(f, iltWorld, bit)).ToString(CultureInfo.InvariantCulture)) + .Append(",\"where\":\"").Append(Escape(f.Where)).Append("\"}"); + } + sb.Append(']'); + + int State(string key) => (int)StateOf(Find(key)!, iltWorld, bit); + sb.Append(",\"fellowship\":{\"maxMembers\":").Append(FellowshipMax(iltWorld).ToString(CultureInfo.InvariantCulture)) + .Append(",\"zoneShare\":").Append(State("zone_share").ToString(CultureInfo.InvariantCulture)) + .Append(",\"blackjack\":").Append(State("fellowship_blackjack").ToString(CultureInfo.InvariantCulture)) + .Append(",\"luminanceShare\":").Append(State("fellowship_luminance").ToString(CultureInfo.InvariantCulture)) + .Append('}'); + + // The /qb list (ILT worlds only): RynthOracle's Quests tab draws it. + if (questBonus != null && iltWorld) + { + sb.Append(",\"questBonus\":{\"disabled\":").Append(questBonus.Disabled ? "true" : "false") + .Append(",\"generation\":").Append(questBonus.Generation.ToString(CultureInfo.InvariantCulture)) + .Append(",\"count\":").Append(questBonus.Count.ToString(CultureInfo.InvariantCulture)) + .Append(",\"status\":\"").Append(Escape(questBonus.Status)).Append('"'); + AppendList(sb, "completed", questBonus.Completed); + AppendList(sb, "incomplete", questBonus.Incomplete); + sb.Append('}'); + } + sb.Append('}'); + return sb.ToString(); + + static void AppendList(StringBuilder b, string name, IReadOnlyList items) + { + b.Append(",\"").Append(name).Append("\":["); + for (int i = 0; i < items.Count; i++) + { + if (i > 0) b.Append(','); + b.Append('"').Append(Escape(items[i])).Append('"'); + } + b.Append(']'); + } + } + + /// JSON string body: quotes, backslashes and control characters escaped, anything non-ASCII as \uXXXX. + private static string Escape(string? s) + { + if (string.IsNullOrEmpty(s)) return string.Empty; + var sb = new StringBuilder(s.Length + 8); + foreach (char c in s) + { + if (c == '"') sb.Append("\\\""); + else if (c == '\\') sb.Append("\\\\"); + else if (c < 0x20 || c > 0x7E) sb.Append("\\u").Append(((int)c).ToString("x4", CultureInfo.InvariantCulture)); + else sb.Append(c); + } + return sb.ToString(); + } + /// The chat listing for "/ra hub features": one line per feature, ASCII only. public static List BuildChatLines(bool iltWorld, Func bit) { diff --git a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltGuardian.cs b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltGuardian.cs index eb3975c..48ad99d 100644 --- a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltGuardian.cs +++ b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltGuardian.cs @@ -9,6 +9,8 @@ // nearest vendor (VendorBuy). Runs as a small pump-thread state machine with timeouts; the // client busy state is respected between steps. // * Attribute tracker: IltTempleAttributes. +// * Reader: the same state as JSON with verbs back ("RynthILT.Data" version 3), for RynthOracle's +// Quests tab. The automation (auto hand-in, buy if missing) stays here either way. // // Threading: OnChat / Tick / commands run on the pump thread; Render only reads volatile fields // and posts actions through IltHubContext.Post. @@ -426,6 +428,90 @@ internal sealed class IltGuardian : IIltFeature } } + // ── Reader ("RynthILT.Data" GetGuardianJson / GuardianCommand; RynthOracle's Quests tab) ── + + /// + /// The reader JSON (Plugins/Shared/RynthIltDataApi.cs header has the shape): the switches, the + /// last answer and hand-in status, and the attribute turn-in rows. Built on demand: everything it + /// reads is volatile or an immutable snapshot. Any thread. + /// + public string ReaderJson(string world) + { + TimeSpan age = LastAnswerAge; + return BuildJson(world, S.AutoDetectFromChat, S.AutoHandIn, S.BuyMissingFromVendor, S.CooldownHoursAssumed, + _lastAnswer, _lastNpc, age == TimeSpan.MaxValue ? -1 : (long)age.TotalSeconds, + IltGuardianPhrasebook.MessageOf(_lastLine), HandInRunning, _handInStatus, Attributes.SyncedUtc, Attributes.Snapshot); + } + + /// The reader JSON from its parts. Pure: the tests drive it. + internal static string BuildJson(string world, bool chat, bool auto, bool buy, int cooldownHours, + string answer, string npc, long answerAgeSec, string heard, bool running, string status, + DateTime syncedUtc, System.Collections.Generic.IReadOnlyList rows) + { + var sb = new System.Text.StringBuilder(1024); + sb.Append("{\"available\":true"); + Str(sb, "world", world); + sb.Append(",\"chat\":").Append(chat ? "true" : "false"); + sb.Append(",\"auto\":").Append(auto ? "true" : "false"); + sb.Append(",\"buy\":").Append(buy ? "true" : "false"); + sb.Append(",\"cooldownHours\":").Append(cooldownHours); + Str(sb, "answer", answer); + Str(sb, "npc", npc); + sb.Append(",\"answerAgeSec\":").Append(answerAgeSec); + Str(sb, "heard", heard); + sb.Append(",\"running\":").Append(running ? "true" : "false"); + Str(sb, "status", status); + Str(sb, "synced", syncedUtc == DateTime.MinValue ? "" : syncedUtc.ToString("yyyy-MM-ddTHH:mm:ssZ", System.Globalization.CultureInfo.InvariantCulture)); + sb.Append(",\"rows\":["); + for (int i = 0; i < rows.Count; i++) + { + IltTempleAttrStatus r = rows[i]; + if (i > 0) sb.Append(','); + sb.Append('{'); + Str(sb, "attribute", r.Attribute, first: true); + Str(sb, "npc", r.Npc); + sb.Append(",\"count\":").Append(r.Count); + Str(sb, "status", r.Status); + Str(sb, "eta", r.Eta); + sb.Append(",\"ready\":").Append(r.Ready ? "true" : "false"); + sb.Append(",\"exact\":").Append(r.FromMyQuests ? "true" : "false"); + sb.Append('}'); + } + sb.Append("]}"); + return sb.ToString(); + } + + private static void Str(System.Text.StringBuilder sb, string name, string? value, bool first = false) + { + if (!first) sb.Append(','); + sb.Append('"').Append(name).Append("\":\"").Append(IltStyle.JsonEscape(value ?? string.Empty)).Append('"'); + } + + /// + /// A reader's verb line (header of Plugins/Shared/RynthIltDataApi.cs): handin | stop | refresh | + /// chat on|off | auto on|off | buy on|off. The reader shows the new state, so the switches don't + /// echo in chat; hand-in and refresh report as the Guardian window's buttons do. Pump thread. + /// + public void RunVerb(string line) + { + string[] parts = line.Split(' ', StringSplitOptions.RemoveEmptyEntries); + if (parts.Length == 0) return; + string arg = parts.Length > 1 ? parts[1] : ""; + switch (parts[0].ToLowerInvariant()) + { + case "handin": StartHandIn(_lastAnswer, _lastNpc, asked: true); break; + case "stop": StopHandIn(); break; + case "refresh": _ctx.Chat("[ILT Guardian] " + Attributes.Refresh()); break; + case "chat": S.AutoDetectFromChat = Toggle(arg, S.AutoDetectFromChat); break; + case "auto": S.AutoHandIn = Toggle(arg, S.AutoHandIn); break; + case "buy": S.BuyMissingFromVendor = Toggle(arg, S.BuyMissingFromVendor); break; + default: + RynthLog.Trace(LogCat.IltHub, $"[IltGuardian] reader verb ignored: {line}"); + return; + } + RynthLog.Write(LogCat.IltHub, $"[IltGuardian] reader verb: {line}"); + } + private static bool Toggle(string mode, bool current) => mode.Trim().ToLowerInvariant() switch { "on" or "true" or "1" or "show" => true, diff --git a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltHubController.cs b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltHubController.cs index 7a74b7a..c92cd46 100644 --- a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltHubController.cs +++ b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltHubController.cs @@ -34,6 +34,8 @@ internal sealed class IltHubController private int _questGeneration; // RynthAi's /myquests refreshes seen (NoteQuestTrackerOutcome) private bool _availabilityAnnounced; // "open the Mini Remote" hint printed this session private volatile int _forceRequest = -1; // SetForceIlt from another thread, applied on the next tick + private long _tabDrawnAt = long.MinValue / 2; // a tab drawn as RynthCore's section view (render thread) + private const long TabDrawnMs = 2000; // "RynthILT.Data" (Plugins/Shared/RynthIltDataApi.cs): the charms and bank snapshots, rebuilt on // the pump every DataRebuildMs only while a reader has asked within DataWatchMs. @@ -45,6 +47,11 @@ internal sealed class IltHubController private long _charmsBuiltAt, _bankBuiltAt, _siblingsReadAt; private volatile string _charmsJson = string.Empty; private volatile string _bankJson = string.Empty; + + // "RynthILT.Server" profile JSON (RynthOracle: feature states, fellowship rules, the /qb list). Rebuilt ~1 s. + private const long ProfileRebuildMs = 1000; + private long _profileBuiltAt; + private volatile string _profileJson = string.Empty; private List _siblings = new(); public IltBanking Banking { get; } @@ -55,6 +62,8 @@ internal sealed class IltHubController public IltPetLogs PetLogs { get; } /// The pet breeding tracker (the Pets tab's Breeding sub-tab, and the "RynthILT.Data" breeding JSON). public IltPetBreeding Breeding { get; } + /// The Pets tab's ACECustom sections: pet charms, the summon-from-empty refill path, siphon auto-capture. + public IltPetAutomation PetAutomation { get; } public IltProgression Progression { get; } public IltGear Gear { get; } public IltGames Games { get; } @@ -64,8 +73,12 @@ internal sealed class IltHubController public IltCharms CharmsTab { get; } /// Temple guardians: riddle translator, hand-in, attribute turn-in tracker. public IltGuardian Guardian { get; } - /// Vaulted Dungeons keeper (Mini Remote tab). ILT-only and behind RynthAi's master switch, off by default. + /// Vaulted Dungeons keeper (Mini Remote tab). ILT-only and behind its master switch (State.VaultedDungeonsEnabled), off by default. public IltVaultedDungeons VaultedDungeons { get; } + /// The Empyrean Handler's lethal ring: asks RynthAi to back away (RynthAi.Hub BackAwayFrom). + public IltRingEvade RingEvade { get; } + /// T11 gear: the "/aug" wield counters for RynthAi's loot rules, "/ilt t11". + public IltT11 T11 { get; } /// True while this character's copy from RynthAi is unfinished (IltHubStore.WritesBlocked). /// The character's RynthAi folder while that copy is unfinished (read-only fallback). @@ -86,6 +99,7 @@ internal sealed class IltHubController Banking = new IltBanking(_ctx); PetLogs = new IltPetLogs(_ctx); Breeding = new IltPetBreeding(_ctx); + PetAutomation = new IltPetAutomation(_ctx); Rates = new IltSessionRates(_ctx); QuestBonus = new IltQuestBonus(_ctx); Progression = new IltProgression(_ctx); @@ -95,13 +109,33 @@ internal sealed class IltHubController CharmsTab = new IltCharms(_ctx, Charms); Guardian = new IltGuardian(_ctx, QuestBonus); VaultedDungeons = new IltVaultedDungeons(_ctx); - _features.AddRange(new IIltFeature[] { Banking, PetLogs, Breeding, Rates, QuestBonus, Progression, Gear, CharmsTab, Games, VaultedDungeons, Guardian }); + RingEvade = new IltRingEvade(_ctx); + T11 = new IltT11(_ctx); + _features.AddRange(new IIltFeature[] { Banking, PetLogs, Breeding, PetAutomation, Rates, QuestBonus, Progression, Gear, CharmsTab, Games, VaultedDungeons, Guardian, RingEvade, T11 }); Banking.BalanceChanged += Rates.OnBankBalanceChanged; Rates.MovingMoney = () => Banking.MovingMoney; options.ProbeReplyTap = OnProbeReply; _ui = new IltHubUi(this, _ctx); _ctx.ShowTab = section => _ctx.Ai.MiniRemoteTab(IltSections.TabId(section), "show"); + RebuildProfile(); + } + + /// + /// The latest "RynthILT.Server" profile JSON: Leaftide features, fellowship rules and the /qb + /// list (Plugins/Shared/RynthIltServerApi.cs). Rebuilt on the pump about once a second so any + /// thread (ServerInterface) may read it. + /// + public string ProfileJson => _profileJson; + + /// Rebuilds from the current server options. Pump thread. + private void RebuildProfile() + { + IltServerOptions o = _ctx.Options; + _profileJson = IltFeatureCatalog.BuildProfileJson( + o.IsIltLikeWorld, o.WorldName, _ctx.State.ForceLeaftideFeatures, + o.Source ?? string.Empty, o.LastRefreshUtc, o.Get, + QuestBonus.Snapshot()); } /// @@ -144,6 +178,20 @@ internal sealed class IltHubController Breeding.RunVerb(line); }); + /// + /// The Temple guardian JSON ("RynthILT.Data" GetGuardianJson): switches, last answer, hand-in + /// status and attribute turn-ins. "" off an ILT world. Any thread. + /// + public string GuardianJson => _ctx.Options.IsIltLikeWorld ? Guardian.ReaderJson(_ctx.Options.WorldName) : string.Empty; + + /// A reader's guardian verb line, posted to the pump (IltGuardian.RunVerb). Any thread. + public void RequestGuardianVerb(string line) + => _ctx.Post(() => + { + if (!_ctx.Options.IsIltLikeWorld) return; + Guardian.RunVerb(line); + }); + /// A reader's bank verb line, posted to the pump (IltBanking.RunVerb). Any thread. public void RequestBankVerb(string line) => _ctx.Post(() => @@ -195,7 +243,7 @@ internal sealed class IltHubController IltSection.Character => true, IltSection.Banking => Available && !_ctx.Options.IsOff(IltFeature.Bank), IltSection.Games => Available && Games.AnyGameAvailable, - // Content, not a server feature bit: an ILT world and the master switch (RynthAi's setting). + // Content, not a server feature bit: an ILT world and the master switch. IltSection.VaultedDungeons => _ctx.Options.IsIltLikeWorld && VaultedDungeons.MasterEnabled(), _ => Available, }; @@ -212,6 +260,9 @@ internal sealed class IltHubController /// Render thread: one Mini Remote ILT tab's body (RynthAi's MiniRemoteHud draws the tab bar). public void RenderTab(IltSection section) => _ui.RenderTab(section); + /// Render thread: a tab was just drawn as RynthCore's section view (it counts as the Mini Remote on screen). + public void NoteTabDrawn() => System.Threading.Interlocked.Exchange(ref _tabDrawnAt, IltHubContext.NowMs); + /// /// Render thread: the ILT session extras (coins, pyreals, item conversions) in RynthCore's Mini /// Remote "Session Stats" section, below RynthAi's session stats (surface "section:ilt-rates"). @@ -288,8 +339,18 @@ internal sealed class IltHubController try { RebuildReaderData(now); } catch (Exception ex) { RynthLog.Exception(LogCat.IltHub, ex, "RebuildReaderData"); } - // "Mini Remote on screen" gates bank auto-refresh and the gear / split-arrow scans. - _ctx.State.WindowVisible = _ctx.Ai.MiniRemoteVisible; + // The profile other plugins read ("RynthILT.Server"): world, feature states, fellowship, /qb. + if (now - _profileBuiltAt >= ProfileRebuildMs) + { + _profileBuiltAt = now; + try { RebuildProfile(); } + catch (Exception ex) { RynthLog.Exception(LogCat.IltHub, ex, "RebuildProfile"); } + } + + // "Mini Remote on screen" gates bank auto-refresh and the gear / split-arrow scans: RynthAi's Mini + // Remote, or one of the tabs drawn as RynthCore's section view in the last couple of seconds. + _ctx.State.WindowVisible = _ctx.Ai.MiniRemoteVisible + || now - System.Threading.Interlocked.Read(ref _tabDrawnAt) < TabDrawnMs; // One hint per session once the server confirms ILT features. The Mini Remote is separate // from the main RynthAi panel, so say how to open it. @@ -325,6 +386,59 @@ internal sealed class IltHubController } } + /// A creature's health update from the server (RynthPluginOnUpdateHealth): auto-capture's fallback health read. + public void OnUpdateHealth(uint objectId, float healthRatio) + { + if (!_ctx.Options.IsIltLikeWorld) return; + PetAutomation.NoteHealth(objectId, healthRatio); + } + + /// + /// The sub-tabs RynthILT adds to one of RynthAi's tabs (RynthILT.Hub GetSubTabs): the Pets tab's + /// Breeding on an ILT world whose server hasn't reported pet breeding off. (Id, label) pairs; the + /// id is a RenderSection id. Any thread. + /// + public (string Id, string Label)[] SubTabs(string parent) + { + if (!string.Equals(parent, RynthCore.Plugin.Shared.RynthIltHub.TabParentPets, StringComparison.OrdinalIgnoreCase) + || !_ctx.Options.IsIltLikeWorld || _ctx.Options.IsOff(RynthCore.Plugin.Shared.RynthIltHub.FeaturePetBreeding)) + return Array.Empty<(string, string)>(); + return new[] { (RynthCore.Plugin.Shared.RynthIltHub.SectionPetBreeding, "Breeding") }; + } + + /// + /// RynthILT.Hub GetSetting: a setting another plugin mirrors (RynthIltHub.Setting*), -1 when not offered + /// (unknown key, or off an ILT world: the engine row then hides). Any thread. + /// + public int GetSetting(string key) => key switch + { + RynthCore.Plugin.Shared.RynthIltHub.SettingVaultedDungeons when _ctx.Options.IsIltLikeWorld + => _ctx.State.VaultedDungeonsEnabled ? 1 : 0, + _ => -1, + }; + + /// + /// RynthILT.Hub GetText: a short text RynthAi shows (RynthIltHub.Text*); "" for an unknown id, and + /// the session tail off ILT. Any thread. + /// + public string GetText(string id) => id switch + { + RynthCore.Plugin.Shared.RynthIltHub.TextServerId => IltSectionsManifest.Server, + RynthCore.Plugin.Shared.RynthIltHub.TextSessionReport when _ctx.Options.IsIltLikeWorld => _ui.SessionReportTail(), + _ => string.Empty, + }; + + /// RynthILT.Hub SetSetting: false for an unknown key. Saved with the state (next periodic save). Any thread. + public bool SetSetting(string key, int value) + { + if (key != RynthCore.Plugin.Shared.RynthIltHub.SettingVaultedDungeons) return false; + bool on = value != 0; + if (_ctx.State.VaultedDungeonsEnabled != on) + RynthLog.Write(LogCat.IltHub, $"Vaulted Dungeons master switch {(on ? "on" : "off")} (Settings window)"); + _ctx.State.VaultedDungeonsEnabled = on; + return true; + } + /// The server's killer notification (pump thread): restarts the Vaulted Dungeons no-kill timer, on ILT only. public void OnKillNotification() { @@ -334,13 +448,16 @@ internal sealed class IltHubController } /// Pump-thread chat line. Returns true when the line should be hidden. - public bool OnChat(string text) + public bool OnChat(string text, int chatType = -1) { if (string.IsNullOrEmpty(text)) return false; string line = text.TrimEnd('\r', '\n'); _ctx.Options.OnChatLine(line); bool eat = _ctx.Capture.OnChatLine(line); if (!_ctx.Options.IsIltLikeWorld) return eat; + // The ring line needs its chat type (a player repeating it is ignored). + try { RingEvade.OnChatLine(line, chatType); } + catch (Exception ex) { RynthLog.Exception(LogCat.IltHub, ex, "IltRingEvade.OnChatLine"); } foreach (var f in _features) { try { eat |= f.OnChat(line); } @@ -353,7 +470,7 @@ internal sealed class IltHubController private static LogCat CategoryOf(IIltFeature f) => f switch { IltBanking => LogCat.IltBanking, - IltPetLogs or IltPetBreeding => LogCat.IltPets, + IltPetLogs or IltPetBreeding or IltPetAutomation => LogCat.IltPets, IltSessionRates => LogCat.IltRates, IltQuestBonus => LogCat.IltQuests, IltProgression => LogCat.IltProgression, @@ -513,7 +630,7 @@ internal sealed class IltHubController default: _ctx.Chat("[Mini Remote] /ra hub [show|hide|toggle] (Mini Remote)|refresh|bank|status|features|force on|off|servers [list]|clap|confirm|cancel"); _ctx.Chat("[Mini Remote] /ra hub open pets|banking|gear|charms|games|vaulted [show|hide|toggle] (Mini Remote tabs; character: /ro character, quests: /ro)"); - _ctx.Chat("[Mini Remote] /ilt vaulted [on|off|toggle|status] (Vaulted Dungeons; master switch: Settings > Navigation > Vaulted Dungeons)"); + _ctx.Chat("[Mini Remote] /ilt vaulted [on|off|toggle|status] (Vaulted Dungeons; master switch: /ilt settings or Settings > Navigation > Vaulted Dungeons)"); _ctx.Chat("[Mini Remote] /ra hub profile list|save [shared]|load /ra hub suit list|test|load [name]"); _ctx.Chat("[Mini Remote] /ra hub attr run|stop|costs|status|auto on|off|every |raise (Skills panel > Progression)"); _ctx.Chat("[Mini Remote] /ra quests refresh (quiet /myquests) /ra pets [show|hide] /ilt qb (the quest bonus list)"); @@ -602,7 +719,7 @@ internal sealed class IltHubController if (section == IltSection.VaultedDungeons && !SectionAvailable(section)) { _ctx.Chat(_ctx.Options.IsIltLikeWorld - ? "[Mini Remote] The Vaulted Dungeons tab is off: turn on \"Vaulted Dungeons\" in Settings > Navigation (the master switch, off by default)." + ? "[Mini Remote] The Vaulted Dungeons tab is off: turn on \"Vaulted Dungeons\" in the ILT settings (/ilt settings; also Settings > Navigation) (the master switch, off by default)." : "[Mini Remote] Vaulted Dungeons is not available on this server (Infinite Leaftide / ACECustom only)."); return; } diff --git a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltHubState.cs b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltHubState.cs index 97fffc0..c2d34dc 100644 --- a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltHubState.cs +++ b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltHubState.cs @@ -38,6 +38,12 @@ public sealed class IltHubState /// True once the one-time UtilityBelt sidecar import has run for this character. public bool UbSidecarsImported; + /// + /// True once the RynthAi settings that moved to RynthILT on 2026-10-20 (the Pets tab's ACECustom + /// options, ...) were copied from this character's RynthAi files (IltMigration.ImportRynthAiSettings). + /// + public bool RynthAiSettingsImported; + /// Last-seen server feature bits. Cache only — overwritten by every login refresh. public IltServerOptionsSnapshot ServerOptions = new(); @@ -47,6 +53,56 @@ public sealed class IltHubState public IltGearState Gear = new(); public IltGamesState Games = new(); public IltGuardianState Guardian = new(); + /// Infinite Leaftide combat helpers (moved from RynthAi's profile 2026-10-20). + public IltCombatState Combat = new(); + + /// + /// The Vaulted Dungeons keeper's master switch (off by default): while off it does nothing (no + /// recalls, no /rc quit, no tab). RynthAi's "Vaulted Dungeons" setting until 2026-10-20 (copied once); + /// set in the ILT settings ("/ilt settings") or the engine's Settings > Navigation row (RynthAi + /// mirrors it through RynthILT.Hub GetSetting / SetSetting). + /// + public bool VaultedDungeonsEnabled; + + /// ACECustom T11 gear (IltT11): the item-aug override (moved from RynthAi's profile 2026-10-20). + public IltT11State T11 = new(); + + /// The ILT sections of RynthAi's Remote tab (moved from RynthAi's huds.json 2026-10-20). + public IltRemoteState Remote = new(); +} + +// ── RynthAi's Remote tab ──────────────────────────────────────────────────── + +public sealed class IltRemoteState +{ + /// The Remote tab's Bank section (ILT bank balances). Was RynthAi's MiniShowBank. + public bool ShowBank = true; + /// The Remote tab's Guardian line (the last Temple guardian answer). Was RynthAi's MiniShowGuardian. + public bool ShowGuardian = true; +} + +// ── T11 ───────────────────────────────────────────────────────────────────── + +public sealed class IltT11State +{ + /// + /// The item augmentation count T11 wield gates use ("T11: Can Wield" in RynthAi's loot rules) instead + /// of the "/aug" reply's; -1 = automatic (read from /aug). "/ilt t11 augs <n|auto>". Was RynthAi's + /// T11ItemAugsOverride. + /// + public int ItemAugsOverride = -1; +} + +// ── Combat ────────────────────────────────────────────────────────────────── + +public sealed class IltCombatState +{ + /// + /// When the Empyrean Handler channels its lethal ring and the character is inside it, have RynthAi + /// back-jump away and re-engage (IltRingEvade; RynthAi acts only while its macro runs with combat + /// on). On by default because it is gated that way. Was RynthAi's HandlerRingEvade. + /// + public bool HandlerRingEvade = true; } /// Cached result of the server-options check (see IltServerOptions). @@ -110,8 +166,22 @@ public sealed class IltPetState public List ShinyLog = new(); /// The breeding tracker: rules this server showed, growth stage names, recent events (IltPetBreeding). public IltBreedingState Breeding = new(); - // The Pets tab's own settings (roster, healing / cosmetic pets, refill path) are RynthAi's - // (its miniremote.json); older ilt-hub.json files still carry them, and they are ignored here. + + // ACECustom's parts of the Pets tab (IltPetAutomation, moved from RynthAi 2026-10-20; copied once + // from RynthAi's miniremote.json by IltMigration.ImportRynthAiSettings). New names on purpose: an + // old ilt-hub.json copy still carries RynthAi's UsePyrealRefillPath / AutoCaptureEnabled / + // CaptureLensIndex from before 2026-10-13, and those stale values must not be read back. + /// + /// Summon from an EMPTY essence while the Summon Essence Refill charm is on (the server refills it + /// from banked pyreals). Still needs the server to confirm the feature (RynthAi.Hub's PetManager + /// asks AllowSummonOnEmpty). + /// + public bool RefillFromEmpty; + /// Use the chosen siphon lens on the nearest creature once it is weak enough (off by default). + public bool AutoCapture; + /// Index into PetCaptureRules.Lenses (Flawed to Asheron's). + public int CaptureLens; + // The Pets tab's own settings (roster, healing / cosmetic pets) are RynthAi's (its miniremote.json). } // ── Character ─────────────────────────────────────────────────────────────── diff --git a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltHubStore.cs b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltHubStore.cs index 970c033..4c15401 100644 --- a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltHubStore.cs +++ b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltHubStore.cs @@ -150,6 +150,7 @@ internal sealed class IltHubStore s.Pet.Breeding.StageNames ??= new(); s.Pet.Breeding.Log ??= new(); s.Pet.Breeding.LastDebug ??= new(); + s.Pet.CaptureLens = Math.Clamp(s.Pet.CaptureLens, 0, PetCaptureRules.Lenses.Length - 1); s.Pet.Breeding.Rules.RemoveAll(r => r == null || string.IsNullOrEmpty(r.Key)); s.Pet.Breeding.Log.RemoveAll(e => e == null); for (int i = 0; i < s.Pet.Breeding.StageNames.Count; i++) s.Pet.Breeding.StageNames[i] ??= string.Empty; @@ -169,6 +170,10 @@ internal sealed class IltHubStore s.Gear.DispelExclusions ??= new(); s.Gear.RingRuns = new Dictionary(s.Gear.RingRuns ?? new(), StringComparer.OrdinalIgnoreCase); s.Games ??= new IltGamesState(); + s.Combat ??= new IltCombatState(); + s.T11 ??= new IltT11State(); + s.Remote ??= new IltRemoteState(); + if (s.T11.ItemAugsOverride < -1) s.T11.ItemAugsOverride = -1; s.Guardian ??= new IltGuardianState(); s.Guardian.TurnInCounts = new Dictionary(s.Guardian.TurnInCounts ?? new(), StringComparer.OrdinalIgnoreCase); s.Guardian.CooldownUntilUtc = new Dictionary(s.Guardian.CooldownUntilUtc ?? new(), StringComparer.OrdinalIgnoreCase); diff --git a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltHubUi.cs b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltHubUi.cs index 6a9751d..1dcd3da 100644 --- a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltHubUi.cs +++ b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltHubUi.cs @@ -121,13 +121,21 @@ internal sealed class IltHubUi switch (id) { case RynthIltHub.SectionRemoteBank: - if (!o.IsIltLikeWorld || o.IsOff(IltFeature.Bank)) return false; + if (!o.IsIltLikeWorld || o.IsOff(IltFeature.Bank) || !_ctx.State.Remote.ShowBank) return false; RenderRemoteBank(); return true; case RynthIltHub.SectionRemoteGuardian: - if (!o.IsIltLikeWorld) return false; + if (!o.IsIltLikeWorld || !_ctx.State.Remote.ShowGuardian) return false; _hub.Guardian.RenderRemoteLine(); return true; + case RynthIltHub.SectionRemoteStats: + if (!o.IsIltLikeWorld) return false; + RenderRemoteStats(); + return true; + case RynthIltHub.SectionRemoteOptions: + if (!o.IsIltLikeWorld) return false; + RenderRemoteOptions(); + return true; case RynthIltHub.SectionQuestBonus: if (!o.IsIltLikeWorld) return false; _hub.QuestBonus.RenderSection(); @@ -140,6 +148,14 @@ internal sealed class IltHubUi if (!o.IsIltLikeWorld) return false; _hub.Breeding.RenderSection(); return true; + case RynthIltHub.SectionPetCharms: + if (!o.IsIltLikeWorld) return false; + _hub.PetAutomation.RenderCharms(); + return true; + case RynthIltHub.SectionPetCapture: + if (!o.IsIltLikeWorld) return false; + _hub.PetAutomation.RenderCapture(); + return true; case RynthIltHub.SectionIltStatus: return RenderIltStatus(); case RynthIltHub.SectionServerMenu: @@ -206,6 +222,34 @@ internal sealed class IltHubUi } } + // ── RynthAi's Mini Remote: the Remote tab's Stats lines and Options switches ── + + /// Coins and pyreals per hour under RynthAi's per-hour lines (the Remote tab's Stats). + private void RenderRemoteStats() + { + var r = _hub.Rates.Summary; + Stat("Coins:", Compact(r.CoinsPerHour) + "/h"); + Stat("Pyr:", Compact(r.PyrealsPerHour) + "/h"); + } + + /// The Remote tab's ILT sections' switches, in RynthAi's Options popup. + private void RenderRemoteOptions() + { + var st = _ctx.State.Remote; + bool bank = st.ShowBank, guardian = st.ShowGuardian; + if (ImGui.Checkbox("Bank##iltmrbank", ref bank)) st.ShowBank = bank; + if (ImGui.IsItemHovered()) ImGui.SetTooltip("Infinite Leaftide bank balances (RynthILT)."); + if (ImGui.Checkbox("Guardian answer##iltmrguardian", ref guardian)) st.ShowGuardian = guardian; + if (ImGui.IsItemHovered()) ImGui.SetTooltip("The last Temple guardian answer with a Give button (RynthILT)."); + } + + /// The tail of RynthAi's one-line session report: the coin / pyreal rates (RynthIltHub.TextSessionReport). + public string SessionReportTail() + { + var r = _hub.Rates.Summary; + return $", Coins {Compact(r.CoinsPerHour)}/h, Pyr {Compact(r.PyrealsPerHour)}/h"; + } + // ── RynthAi's Mini Remote: the Remote tab's Bank section ──────────────── private void RenderRemoteBank() diff --git a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltMigration.cs b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltMigration.cs index 636bd7a..0955cb8 100644 --- a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltMigration.cs +++ b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltMigration.cs @@ -23,11 +23,41 @@ using RynthCore.Plugin.Shared; namespace RynthCore.Plugin.RynthILT.Hub; -/// The two Server Features fields of a RynthAi profile (the rest of the file is ignored). +/// +/// The fields of a RynthAi profile RynthILT reads (the rest of the file is ignored): the two Server +/// Features fields, and the settings that moved to RynthILT on 2026-10-20 (null when the profile +/// predates them: the default applies). +/// public sealed class IltLegacyProfileFlags { public List? FeatureServerNames; public bool ForceServerFeatures; + /// RynthAi's Empyrean Handler ring evade (on by default there too). + public bool? HandlerRingEvade; + /// RynthAi's Vaulted Dungeons master switch (off by default). + public bool? EnableVaultedDungeons; + /// RynthAi's T11 item-aug override (-1 = automatic). + public int? T11ItemAugsOverride; +} + +/// The Remote tab switches of RynthAi's huds.json that moved to RynthILT (2026-10-20). +public sealed class IltLegacyHuds +{ + public bool? MiniShowBank; + public bool? MiniShowGuardian; +} + +/// The Pets tab fields of RynthAi's miniremote.json that moved to RynthILT (2026-10-20). +public sealed class IltLegacyMiniRemote +{ + public IltLegacyPetTab? Pet; +} + +public sealed class IltLegacyPetTab +{ + public bool? UsePyrealRefillPath; + public bool? AutoCaptureEnabled; + public int? CaptureLensIndex; } internal static class IltMigration @@ -67,6 +97,7 @@ internal static class IltMigration || File.Exists(Path.Combine(dir, "ilt-hub-transactions.json")) || Directory.Exists(Path.Combine(dir, "ilt-hub-profiles")) || File.Exists(Path.Combine(dir, "active_profile.txt")) + || File.Exists(Path.Combine(dir, LegacyMiniRemoteFile)) || File.Exists(Path.Combine(dir, "Default.json")))) return dir; return null; @@ -163,6 +194,70 @@ internal static class IltMigration return done; } + /// RynthAi's per-character Mini Remote file (the Pets tab's settings). + public const string LegacyMiniRemoteFile = "miniremote.json"; + + /// RynthAi's per-character HUD file (the Remote tab's section switches). + public const string LegacyHudsFile = "huds.json"; + + /// + /// Once per character (IltHubState.RynthAiSettingsImported): the RynthAi settings that moved to + /// RynthILT on 2026-10-20 are copied from the character's RynthAi files into : + /// from miniremote.json the Pets tab's ACECustom options (summon from empty with the refill + /// charm, siphon auto-capture and its lens); from the active profile (as ReadProfileFlags) the + /// Empyrean Handler ring evade, the Vaulted Dungeons master switch and the T11 item-aug override; + /// from huds.json the Remote tab's Bank / Guardian switches. The RynthAi files are only read (RynthAi keeps the + /// old fields readable and no longer uses them). A character with no RynthAi files keeps + /// RynthILT's defaults. Returns what was copied (for the log); empty when nothing was done. + /// + public static List ImportRynthAiSettings(IltHubState state, string world, string charName) + { + var done = new List(); + if (state.RynthAiSettingsImported || string.IsNullOrWhiteSpace(charName)) return done; + string? legacy = FindLegacyCharFolder(world, charName); + if (legacy != null) + { + if (ReadJson(Path.Combine(legacy, LegacyMiniRemoteFile), IltHubJsonContext.Default.IltLegacyMiniRemote) is { Pet: { } pet }) + { + if (pet.UsePyrealRefillPath is bool refill) { state.Pet.RefillFromEmpty = refill; done.Add($"summon from empty essences {(refill ? "on" : "off")}"); } + if (pet.AutoCaptureEnabled is bool capture) { state.Pet.AutoCapture = capture; done.Add($"auto-capture {(capture ? "on" : "off")}"); } + if (pet.CaptureLensIndex is int lens) + { + state.Pet.CaptureLens = Math.Clamp(lens, 0, PetCaptureRules.Lenses.Length - 1); + done.Add("capture lens " + PetCaptureRules.LensAt(state.Pet.CaptureLens).Name); + } + } + if (ReadJson(Path.Combine(legacy, LegacyHudsFile), IltHubJsonContext.Default.IltLegacyHuds) is { } huds) + { + if (huds.MiniShowBank is bool bank) { state.Remote.ShowBank = bank; if (!bank) done.Add("the Remote tab's Bank hidden"); } + if (huds.MiniShowGuardian is bool g) { state.Remote.ShowGuardian = g; if (!g) done.Add("the Remote tab's Guardian line hidden"); } + } + if (ReadProfileFlags(legacy, out IltLegacyProfileFlags flags)) + { + if (flags.HandlerRingEvade is bool ring) { state.Combat.HandlerRingEvade = ring; done.Add($"Empyrean Handler ring evade {(ring ? "on" : "off")}"); } + if (flags.EnableVaultedDungeons is bool vaulted) { state.VaultedDungeonsEnabled = vaulted; done.Add($"Vaulted Dungeons master switch {(vaulted ? "on" : "off")}"); } + if (flags.T11ItemAugsOverride is int augs && augs >= 0) { state.T11.ItemAugsOverride = augs; done.Add($"T11 item augmentations fixed at {augs:N0}"); } + } + } + state.RynthAiSettingsImported = true; + if (done.Count == 0) done.Add(legacy == null ? "no RynthAi settings for this character (defaults kept)" : "nothing set in RynthAi (defaults kept)"); + return done; + } + + /// A JSON file read with , or null (missing or unreadable: logged). + private static T? ReadJson(string path, System.Text.Json.Serialization.Metadata.JsonTypeInfo info) where T : class + { + try + { + return File.Exists(path) ? JsonSerializer.Deserialize(File.ReadAllText(path), info) : null; + } + catch (Exception ex) + { + RynthLog.Exception(LogCat.IltStore, ex, $"migration: read {path}"); + return null; + } + } + /// The character's active RynthAi profile's Server Features fields. internal static bool ReadProfileFlags(string legacyCharFolder, out IltLegacyProfileFlags flags) { diff --git a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltPetAutomation.cs b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltPetAutomation.cs new file mode 100644 index 0000000..e24efa5 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltPetAutomation.cs @@ -0,0 +1,394 @@ +// IltPetAutomation.cs — ACECustom's parts of RynthAi's Pets tab: the pet charms, the "summon from an +// empty essence" refill path and siphon-lens auto-capture. +// Moved out of RynthAi's MiniRemote/PetsTab.cs 2026-10-20 (originally SilentKelpie's IltPets, ILT +// Hub): summoning is every server's, so the roster, healing and cosmetic pets stay RynthAi's, but +// these three are ACECustom content and live here now. +// +// * Pet charms (section "pets-charms"): Summon Essence Refill (the server refills an empty essence +// from banked pyreals) and Universal Summoning Mastery, read from the charm's appraisal text and +// the player bools the server stamps, plus the "no spell components" warning when the server +// requires them. The refill opt-in feeds RynthAi's PetManager through RynthILT.Hub +// AllowSummonOnEmpty (cached here every tick; an unknown state never spends pyreals). +// * Auto siphon capture (section "pets-capture", ACECustom MonsterCapture): when enabled, uses the +// chosen lens on the nearest attackable creature within 5 m once it is <=20% health or under +// 20 HP (Asheron's Lens skips the health gate). Resonance still needs a prior failed capture on +// the server. Bounded per creature and overall (PetCaptureThrottle). +// Ticks only on an ILT-like world (IltHubController); the sections draw nothing elsewhere. +using System; +using ImGuiNET; +using RynthCore.Plugin.Shared; + +namespace RynthCore.Plugin.RynthILT.Hub; + +internal sealed class IltPetAutomation : IIltFeature +{ + private const long CaptureThinkMs = 250; + private const long CaptureCooldownMs = 2500; + private const long CaptureFailBackoffMs = 8000; + private const long CharmScanMs = 2000; + private const long GateMs = 500; + + private readonly IltHubContext _ctx; + private readonly PetCaptureThrottle _captureThrottle = new(); + private long _lastCaptureThink; + private long _captureCooldownUntil; + private long _lastCharmScan; + private long _lastGate; + + // Read by the render thread and (AllowSummonOnEmpty) by RynthAi's pump. + private volatile string _captureStatus = "off"; + private volatile bool _uiRefillActive; + private volatile bool _uiMasteryActive; + private volatile bool _uiHasCasting = true; + private volatile bool _allowSummonOnEmpty; + + // The server's health updates (RynthPluginOnUpdateHealth), for creatures the client has no vitals for. + private const int MaxHealthEntries = 512; + private readonly object _healthGate = new(); + private readonly System.Collections.Generic.Dictionary _healthRatios = new(); + + public IltPetAutomation(IltHubContext ctx) => _ctx = ctx; + + private IltPetState S => _ctx.State.Pet; + + /// The auto-capture line under the switch (render thread). + public string CaptureStatus => _captureStatus; + + /// + /// RynthILT.Hub AllowSummonOnEmpty: the last tick's answer, false off an ILT world. Any thread. + /// + public bool AllowSummonOnEmpty => _ctx.Options.IsIltLikeWorld && _allowSummonOnEmpty; + + // ── Charms / gates ────────────────────────────────────────────────────── + + /// Summon Essence Refill charm is carried and switched on (or the server stamped the player bool). + public bool RefillCharmActive() + { + var inv = _ctx.Inventory; + if (inv.PlayerBool(IltInventory.BoolPyrealRefillActive)) return true; + var charm = inv.FindByWcid(IltInventory.WcidSummonRefillCharm); + return charm != null && inv.CharmStatus(charm) == IltTri.On; + } + + public bool MasteryCharmActive() + { + if (_ctx.Options.IsOff(IltFeature.UniversalMastery)) return false; + var inv = _ctx.Inventory; + if (inv.PlayerBool(IltInventory.BoolUniversalMasteryActive)) return true; + var charm = inv.FindByWcid(IltInventory.WcidUniversalMasteryCharm); + return charm != null && inv.CharmStatus(charm) == IltTri.On; + } + + /// + /// Summon from an empty essence (spends banked pyreals) only when the player opted in, the refill + /// charm is active, and the server has positively confirmed the feature: either the feature check + /// reported pet_refill on, or the server stamped the player's refill bool. Pump thread. + /// + internal bool ComputeAllowSummonOnEmpty() + { + if (!S.RefillFromEmpty || !_ctx.Options.IsIltLikeWorld || !RefillCharmActive()) return false; + bool confirmed = _ctx.Options.IsOn(IltFeature.PetRefill) + || _ctx.Inventory.PlayerBool(IltInventory.BoolPyrealRefillActive); + if (!confirmed) RynthLog.Trace(LogCat.IltPets, "summon-on-empty refused: pet_refill not confirmed by the server"); + return confirmed; + } + + // ── IIltFeature ───────────────────────────────────────────────────────── + + public void Tick(long nowMs) + { + if (nowMs - _lastGate >= GateMs) + { + _lastGate = nowMs; + _allowSummonOnEmpty = ComputeAllowSummonOnEmpty(); + } + if (nowMs - _lastCharmScan >= CharmScanMs) + { + _lastCharmScan = nowMs; + // Host reads (and appraisal requests) happen here, never on the render thread. + _uiRefillActive = RefillCharmActive(); + _uiMasteryActive = MasteryCharmActive(); + _uiHasCasting = _ctx.Inventory.HasCastingSupplies(); + } + if (nowMs - _lastCaptureThink >= CaptureThinkMs) + { + _lastCaptureThink = nowMs; + TickCapture(nowMs); + } + } + + /// ACECustom MonsterCapture replies: back off after a refuse so lenses aren't burned. Never eats. + public bool OnChat(string text) + { + if (!S.AutoCapture || string.IsNullOrEmpty(text)) return false; + long now = IltHubContext.NowMs; + if (PetCaptureLines.IsSuccess(text)) + { + _captureStatus = "captured"; + _captureThrottle.RecordSuccess(); + _captureCooldownUntil = now + CaptureCooldownMs; + } + else if (ContainsAny(text, + "too strong", + "blind rage", + "cannot be siphoned", + "cannot be captured", + "No creatures nearby", + "already dead", + "already being captured", + "hasn't failed a capture", + "echo has faded", + "Failed to consume")) + { + _captureStatus = "refused: " + Truncate(text, 48); + _captureCooldownUntil = now + CaptureFailBackoffMs; + } + else if (ContainsAny(text, "siphon failed", "lens shatters", "resisted your capture", "resonance fades")) + { + _captureStatus = "failed (creature may enrage)"; + _captureCooldownUntil = now + CaptureFailBackoffMs; + } + return false; + } + + /// A creature's health ratio from the server (RynthPluginOnUpdateHealth; any thread). + public void NoteHealth(uint objectId, float ratio) + { + if (objectId == 0 || float.IsNaN(ratio)) return; + lock (_healthGate) + { + if (_healthRatios.Count >= MaxHealthEntries) _healthRatios.Clear(); + _healthRatios[unchecked((int)objectId)] = Math.Clamp(ratio, 0f, 1f); + } + } + + /// The last health ratio the server sent for a creature, -1 when none. + private float HealthRatio(int id) + { + lock (_healthGate) return _healthRatios.TryGetValue(id, out float v) ? v : -1f; + } + + public void OnLogout() + { + lock (_healthGate) _healthRatios.Clear(); + _captureCooldownUntil = 0; + _captureStatus = "off"; + _captureThrottle.Reset(); + _allowSummonOnEmpty = false; + } + + private static bool ContainsAny(string text, params string[] parts) + { + foreach (string p in parts) + if (text.IndexOf(p, StringComparison.OrdinalIgnoreCase) >= 0) return true; + return false; + } + + private static string Truncate(string s, int max) => s.Length <= max ? s : s[..(max - 3)] + "..."; + + // ── Auto siphon capture (ACECustom MonsterCapture) ─────────────────────── + + /// + /// When Auto Capture is on, use the chosen siphon lens on the nearest attackable creature within + /// 5 m once ACECustom's health gate is met (≤20% or under 20 HP; Asheron's skips it). The server + /// picks the nearest creature itself, so this fires only when that nearest candidate is already + /// weak enough: a full-health neighbour closer than the wounded target won't waste a lens. + /// + internal void TickCapture(long now) + { + if (!S.AutoCapture) + { + _captureStatus = "off"; + return; + } + if (_ctx.Options.IsOff(RynthIltHub.FeatureMonsterCapture)) + { + _captureStatus = "monster capture disabled on this server"; + return; + } + if (now < _captureCooldownUntil) + { + long left = (_captureCooldownUntil - now + 999) / 1000; + if (!_captureStatus.StartsWith("waiting", StringComparison.Ordinal)) + _captureStatus = $"waiting {left}s"; + return; + } + var inv = _ctx.Inventory; + if (inv.IsBusy) { _captureStatus = "busy"; return; } + + var lens = PetCaptureRules.LensAt(S.CaptureLens); + var lensItem = inv.FindByWcid(lens.Wcid); + if (lensItem == null) + { + _captureStatus = $"no {lens.Name} carried"; + return; + } + + if (!TryFindNearestCaptureTarget(out WorldObject? target, out double distM, out uint curHp, out uint maxHp)) + { + _captureStatus = "no attackable creature within 5 m"; + return; + } + + if (!PetCaptureRules.InRange(distM)) + { + _captureStatus = $"{target!.Name} at {distM:0.0} m (need <={PetCaptureRules.CaptureRangeM:0} m)"; + return; + } + + if (!PetCaptureRules.CanAttempt(lens, curHp, maxHp)) + { + float pct = maxHp > 0 ? curHp * 100f / maxHp : -1f; + _captureStatus = pct >= 0 + ? $"{target!.Name} at {pct:0}% / {curHp} HP (need <={PetCaptureRules.CaptureMaxHealthFraction:P0} or <{PetCaptureRules.CaptureMaxHealthPoints} HP)" + : $"{target!.Name}: health unknown"; + return; + } + + if (!_captureThrottle.MayAttempt(target!.Id, now)) + { + _captureStatus = $"{target.Name}: {PetCaptureThrottle.MaxTriesPerTarget} tries, no capture; left alone for {_captureThrottle.BlockedSecondsLeft(target.Id, now)}s"; + return; + } + + if (!inv.Use(lensItem)) + { + _captureStatus = "UseObject refused"; + return; + } + _captureThrottle.RecordAttempt(target.Id, now); + if (_captureThrottle.Exhausted) + { + // Backstop: this many lenses with no recognized capture means something is off. Stop, don't keep burning them. + S.AutoCapture = false; + RynthLog.Write(LogCat.IltPets, + $"auto-capture: {PetCaptureThrottle.MaxTriesWithoutSuccess} lens uses without a capture reply; auto-capture switched off"); + } + + float shown = maxHp > 0 ? curHp * 100f / maxHp : 0f; + _captureStatus = $"using {lens.Name} on {target.Name} ({shown:0}% / {curHp} HP)"; + _captureCooldownUntil = now + CaptureCooldownMs; + RynthLog.Write(LogCat.IltPets, + $"auto-capture: {lens.Name} -> 0x{target.Id:X8} '{target.Name}' d={distM:0.0}m hp={curHp}/{maxHp}"); + } + + /// + /// Nearest attackable landscape creature within capture range, with vitals from the host when + /// available, else the server's last health ratio (fraction-only gate). A creature with neither + /// is skipped: no health, no capture decision. + /// + private bool TryFindNearestCaptureTarget(out WorldObject? best, out double bestDist, out uint curHp, out uint maxHp) + { + best = null; + bestDist = double.MaxValue; + curHp = maxHp = 0; + var host = _ctx.Host; + var objects = _ctx.Inventory.Cache; + uint playerId = _ctx.Inventory.PlayerId; + if (playerId == 0) return false; + int pid = unchecked((int)playerId); + string ownPrefix = _ctx.CharName.Length > 0 ? _ctx.CharName + "'s " : string.Empty; + + foreach (var wo in objects.GetLandscape()) + { + if (wo == null || wo.Id == pid) continue; + if (wo.ObjectClass != RynthCore.Loot.AcObjectClass.Monster) continue; + if (ownPrefix.Length > 0 && wo.Name.StartsWith(ownPrefix, StringComparison.Ordinal)) continue; + // Skip corpses / non-attackable when the host can tell. + if (host.HasObjectIsAttackable && !host.ObjectIsAttackable(unchecked((uint)wo.Id))) continue; + + double d = objects.Distance(pid, wo.Id); + if (d < 0 || d > PetCaptureRules.CaptureRangeM || d >= bestDist) continue; + + if (!TryReadCreatureVitals(wo.Id, out uint h, out uint mh)) continue; + if (h == 0) continue; // dead + + best = wo; + bestDist = d; + curHp = h; + maxHp = mh; + } + return best != null; + } + + /// + /// Absolute vitals via TryGetTargetVitals when bound; else the health ratio as a 0-1000 scale so + /// only the fraction half of ACECustom's gate can fire. + /// + private bool TryReadCreatureVitals(int id, out uint cur, out uint max) + { + cur = max = 0; + var host = _ctx.Host; + if (host.HasGetTargetVitals + && host.TryGetTargetVitals(unchecked((uint)id), out uint h, out uint mh, out _, out _, out _, out _) + && mh > 0) + { + cur = h; + max = mh; + return true; + } + float ratio = HealthRatio(id); + if (ratio < 0f) return false; + // Synthetic scale: ratio 0.20 -> 200/1000 so IsWeakEnough's fraction half matches. + max = 1000; + cur = (uint)Math.Clamp((int)Math.Round(ratio * 1000f), 1, 1000); + return true; + } + + // ── UI (render thread): the Pets tab's ACECustom sections ──────────────── + + /// The pet charms and the refill opt-in (section "pets-charms"). + public void RenderCharms() + { + ImGui.Separator(); + SafeImGui.TextColored(IltStyle.ColTeal, "Pet charms"); + var o = _ctx.Options; + bool refillOff = o.IsOff(IltFeature.PetRefill); + ImGui.TextUnformatted("Summon Essence Refill: " + (refillOff ? "disabled on this server" : _uiRefillActive ? "ON" : "off / not carried")); + ImGui.BeginDisabled(refillOff); + bool usePath = S.RefillFromEmpty; + if (ImGui.Checkbox("Summon from empty essences while the refill charm is ON (spends banked pyreals)", ref usePath)) + S.RefillFromEmpty = usePath; + ImGui.EndDisabled(); + ImGui.TextUnformatted("Universal Summoning Mastery: " + + (o.IsOff(IltFeature.UniversalMastery) ? "disabled on this server" : _uiMasteryActive ? "ON" : "off / not carried")); + if (!o.IsOff(IltFeature.RequireComps) && !_uiHasCasting) + SafeImGui.TextColored(IltStyle.ColAmber, "No spell components or Infinite Casting Stone carried."); + } + + /// Siphon-lens auto-capture: enable + which lens to use (section "pets-capture"). + public void RenderCapture() + { + ImGui.Separator(); + SafeImGui.TextColored(IltStyle.ColTeal, "Monster capture"); + bool captureOff = _ctx.Options.IsOff(RynthIltHub.FeatureMonsterCapture); + ImGui.BeginDisabled(captureOff); + bool en = S.AutoCapture; + if (ImGui.Checkbox("Auto-capture when a creature is weak enough", ref en)) + { + S.AutoCapture = en; + _ctx.Post(_captureThrottle.Reset); + } + if (ImGui.IsItemHovered()) + { + SafeImGui.SetTooltip( + "Uses the selected siphon lens on the nearest attackable creature within 5 m once it is\n" + + "at or below 20% health or under 20 HP (ACECustom MonsterCapture). Asheron's Lens skips\n" + + "the health gate. Resonance Lens still needs a prior failed capture on the server.\n" + + "Off by default. Stops on its own after 5 tries on one creature (it is left alone for 2 min)\n" + + "or 15 lens uses in a row with no capture."); + } + ImGui.SameLine(); + ImGui.SetNextItemWidth(120); + int lens = Math.Clamp(S.CaptureLens, 0, PetCaptureRules.LensNames.Length - 1); + if (ImGui.Combo("##petcapturelens", ref lens, PetCaptureRules.LensNames, PetCaptureRules.LensNames.Length)) + S.CaptureLens = lens; + if (ImGui.IsItemHovered()) + SafeImGui.SetTooltip("Which siphon lens to use. Must be carried in your pack."); + ImGui.EndDisabled(); + if (captureOff) + SafeImGui.TextDisabled("Monster capture is disabled on this server."); + else + SafeImGui.TextDisabled("Status: " + _captureStatus); + } +} diff --git a/Plugins/RynthCore.Plugin.RynthAi/MiniRemote/PetCaptureRules.cs b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltPetCaptureRules.cs similarity index 93% rename from Plugins/RynthCore.Plugin.RynthAi/MiniRemote/PetCaptureRules.cs rename to Plugins/RynthCore.Plugin.RynthILT/Hub/IltPetCaptureRules.cs index 3b3e1e9..c978268 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/MiniRemote/PetCaptureRules.cs +++ b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltPetCaptureRules.cs @@ -1,4 +1,6 @@ -// PetCaptureRules.cs — ACECustom MonsterCapture thresholds for siphon lenses (pure; no host). +// IltPetCaptureRules.cs — ACECustom MonsterCapture thresholds for siphon lenses (pure; no host). +// Moved from RynthAi's Pets tab (MiniRemote/PetCaptureRules.cs) 2026-10-20 with the auto-capture +// itself (IltPetAutomation): monster capture is ACECustom's, so it is RynthILT's. // // Copied from ACECustom Source/ACE.Server/Entity/MonsterCapture.cs so the client can tell when // a creature is weak enough to siphon before using a lens. Keep these numbers in lockstep with @@ -7,10 +9,10 @@ using System; using System.Collections.Generic; -namespace RynthCore.Plugin.RynthAi.MiniRemote; +namespace RynthCore.Plugin.RynthILT.Hub; /// One siphon lens the Pets tab can auto-use (name, WCID, whether health is gated). -public readonly struct PetCaptureLens +internal readonly struct PetCaptureLens { public PetCaptureLens(string name, uint wcid, bool bypassesHealthGate) { @@ -30,7 +32,7 @@ public readonly struct PetCaptureLens /// A creature is weak enough when its health fraction is ≤ 20% OR its current HP is under 20 /// (whichever comes first). Asheron's Lens skips that check. /// -public static class PetCaptureRules +internal static class PetCaptureRules { /// A lens targets the nearest attackable creature within this many meters. public const float CaptureRangeM = 5.0f; @@ -100,12 +102,12 @@ public static class PetCaptureRules } /// -/// A brake on the auto-capture loop. The Pets tab fires a lens every couple of seconds and only stops +/// A brake on the auto-capture loop. Auto-capture fires a lens every couple of seconds and only stops /// on reply strings it guesses at, so an unrecognized reply (or a creature the server never lets go of) /// would burn lenses without end. This caps consecutive tries per target and, as a backstop, consecutive /// tries over all targets; both reset on a recognized success. Pure: the tests drive it. /// -public sealed class PetCaptureThrottle +internal sealed class PetCaptureThrottle { /// Lens uses on one creature, with no success in between, before it is left alone. public const int MaxTriesPerTarget = 5; diff --git a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltPetLogs.cs b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltPetLogs.cs index 8db5181..e32b9be 100644 --- a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltPetLogs.cs +++ b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltPetLogs.cs @@ -2,8 +2,9 @@ // (RynthILT.Hub section "pets-logs"). // Originally the roster-capture part of SilentKelpie's IltPets (ILT Hub, RynthAi); split out and // moved to RynthILT 2026-10-13. The Pets tab itself (essence roster, combat / healing / cosmetic -// pets, the refill charm path) stayed in RynthAi (MiniRemote/PetsTab.cs): summoning is every -// server's, these two commands are ACECustom's. +// pets) stayed in RynthAi (MiniRemote/PetsTab.cs): summoning is every server's, these two commands +// are ACECustom's (as are the pet charms, the refill path and siphon capture: IltPetAutomation, +// moved 2026-10-20). using System; using System.Collections.Generic; using ImGuiNET; diff --git a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltQuestBonus.cs b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltQuestBonus.cs index a95f9cb..991a923 100644 --- a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltQuestBonus.cs +++ b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltQuestBonus.cs @@ -125,6 +125,12 @@ internal sealed class IltQuestBonus : IIltFeature /// Increments each time a "/qb list" reply is parsed (0 = not loaded this session). public int QbGeneration => _qbGeneration; + /// + /// Snapshot for the "RynthILT.Server" profile JSON (Oracle Quests / Fellowship). Pump thread. + /// + public IltQuestBonusInfo Snapshot() => + new(_ctx.Options.IsOff(IltFeature.Qb), _qbGeneration, _qbCount, _qbStatus, _qbCompleted, _qbIncomplete); + /// True when the last "/qb list" (completed or incomplete) contains the flag. public bool QbHasFlag(string flag) { diff --git a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltRingEvade.cs b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltRingEvade.cs new file mode 100644 index 0000000..aa7eb6d --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltRingEvade.cs @@ -0,0 +1,121 @@ +// IltRingEvade.cs — Infinite Leaftide's Empyrean Handler lethal ring: hear it, and have RynthAi jump clear. +// Moved out of RynthAi's CombatManager 2026-10-20 (Silentkelpie's PR 12): the Handler is ACECustom +// content, so the detection and its setting are RynthILT's; RynthAi keeps the generic back-away it +// does on request (RynthAi.Hub BackAwayFrom: face the danger, run-back jump, hold attacks until the +// jump settles, re-engage the same target; only while its macro runs with combat on). +// +// ACECustom's Handler emote: "The handler briefly channels infused Empyrean hatred to release a lethal +// ring." The ring can't be melee-evaded; inside its cast radius the character dies. On that line, when +// an Empyrean Handler is near, ask RynthAi to back away from the nearest one (12 yards, or Ring Range +// when RynthAi's is larger). One request per HandlerRingCooldownMs. +// Setting: IltHubState.Combat.HandlerRingEvade (on by default; the ILT settings view, "/ilt settings"). +using System; +using RynthCore.Loot; +using RynthCore.Plugin.Shared; + +namespace RynthCore.Plugin.RynthILT.Hub; + +internal sealed class IltRingEvade : IIltFeature +{ + internal const string ChannelHint = "channels infused Empyrean hatred to release a lethal ring"; + internal const string ChannelStart = "The handler briefly channels"; + internal const string HandlerName = "Empyrean Handler"; + /// Yards: the Handler's lethal ring is treated as at least this wide (RynthAi widens it to Ring Range). + internal const float DangerYards = 12f; + /// Back-jump charge (ms): run-back + jump must clear about the ring's radius. + internal const int JumpHoldMs = 750; + internal const long CooldownMs = 4_000; + + private readonly IltHubContext _ctx; + private long _lastRequestAt = long.MinValue; + + public IltRingEvade(IltHubContext ctx) => _ctx = ctx; + + /// What the last ring line did (for the log and the tests). + public string LastOutcome { get; private set; } = string.Empty; + + /// + /// True when is the Handler's channel line (not a player repeating it). + /// The channel is an Emote (0x0C), which counts as player speech elsewhere, so it is anchored on + /// the phrase that starts the line; mid-line only for a chat type that can't be player speech. + /// + internal static bool IsChannelLine(string? text, int chatType) + { + if (string.IsNullOrEmpty(text)) return false; + bool anchored = + ChatSource.StartsWithMarker(text, ChannelStart, StringComparison.OrdinalIgnoreCase) + || (ChatSource.StartsWithMarker(text, "The handler", StringComparison.OrdinalIgnoreCase) + && text.IndexOf(ChannelHint, StringComparison.OrdinalIgnoreCase) >= 0); + if (anchored) return true; + // Mid-line only when the type is clearly not player speech (some clients strip "The "). + if (chatType is ChatSource.Speech or ChatSource.Tell or ChatSource.OutgoingTell or ChatSource.Channel + or ChatSource.ChannelSend or ChatSource.Allegiance or ChatSource.Fellowship) + return false; + if (text.IndexOf(ChannelHint, StringComparison.OrdinalIgnoreCase) < 0) return false; + return text.IndexOf(" says,", StringComparison.OrdinalIgnoreCase) < 0 + && text.IndexOf(" tells you,", StringComparison.OrdinalIgnoreCase) < 0; + } + + /// + /// A chat line with its type (pump thread; IltHubController.OnChat, ILT only). On the Handler's + /// channel line asks RynthAi to back away from the nearest Handler. Never eats the line. + /// + public void OnChatLine(string text, int chatType) + { + if (!_ctx.State.Combat.HandlerRingEvade || !IsChannelLine(text, chatType)) return; + long now = IltHubContext.NowMs; + if (_lastRequestAt != long.MinValue && now - _lastRequestAt < CooldownMs) return; + + if (!TryFindNearestHandler(out int handlerId, out double dist)) + { + Outcome("Handler lethal-ring channel heard, but no Empyrean Handler is nearby: no jump."); + return; + } + _lastRequestAt = now; + int r = _ctx.Ai.BackAwayFrom(unchecked((uint)handlerId), DangerYards, JumpHoldMs); + Outcome(r switch + { + RynthAiHub.BackAwayStarted => $"Empyrean Handler lethal ring: RynthAi backs away from it ({dist:0.0} m).", + RynthAiHub.BackAwayOutside => $"Empyrean Handler lethal ring: the Handler is {dist:0.0} m away, outside the ring; staying put.", + RynthAiHub.BackAwayUnknownObject => "Empyrean Handler lethal ring: RynthAi has no position for the Handler; no jump.", + RynthAiHub.BackAwayJumpRefused => "Empyrean Handler lethal ring: in range, but RynthAi's back-jump did not start.", + int.MinValue => "Empyrean Handler lethal ring: " + RynthAiClient.NotLoaded + " (the back-away is RynthAi's).", + _ => "Empyrean Handler lethal ring: RynthAi isn't fighting (macro or combat off), so it doesn't take the keyboard.", + }); + } + + private void Outcome(string text) + { + LastOutcome = text; + RynthLog.Write(LogCat.IltHub, "[RingEvade] " + text); + } + + /// The nearest Empyrean Handler the client knows (a creature with that in its name). + private bool TryFindNearestHandler(out int id, out double dist) + { + id = 0; + dist = double.MaxValue; + var objects = _ctx.Inventory.Cache; + int me = unchecked((int)_ctx.Inventory.PlayerId); + if (me == 0) return false; + foreach (var wo in objects.GetLandscape()) + { + if (wo == null || wo.ObjectClass != AcObjectClass.Monster) continue; + if (wo.Name.IndexOf(HandlerName, StringComparison.OrdinalIgnoreCase) < 0) continue; + double d = objects.Distance(me, wo.Id); + if (d >= dist) continue; + dist = d; + id = wo.Id; + } + return id != 0; + } + + // ── IIltFeature ───────────────────────────────────────────────────────── + + public void Tick(long nowMs) { } + + /// Unused: the controller passes the chat type (OnChatLine). + public bool OnChat(string text) => false; + + public void OnLogout() => _lastRequestAt = long.MinValue; +} diff --git a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltSalvage.cs b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltSalvage.cs index 5682bc5..342c92a 100644 --- a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltSalvage.cs +++ b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltSalvage.cs @@ -15,6 +15,15 @@ namespace RynthCore.Plugin.RynthILT.Hub; internal static class IltSalvage { + /// + /// Leaftide trinkets (compass, goggles, scarab, watch, puzzle box, tops): jewelry that takes the + /// Trinkets bench's recipes (UB-IT's IsLeaftideTrinketJewelry; RynthAi's TinkerCatalog.IsTrinket until + /// 2026-10-20). Sent in the profile's "trinkets" (RynthServer.Profile). + /// + internal static readonly string[] TrinketNames = { "compass", "goggles", "scarab", "watch", "puzzle box", "top" }; + /// "top" but not "topaz". + internal static readonly string[] TrinketExcept = { "topaz" }; + // MaterialType (131) ids. private const int Wool = 8, BlackGarnet = 15, Diamond = 20, GreenJade = 24, Ruby = 38, TigerEye = 42, Tourmaline = 43, Turquoise = 44, WhiteQuartz = 46, YellowGarnet = 48, Leather = 52, GromnieHide = 54, Copper = 59, Pyreal = 62, diff --git a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltSections.cs b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltSections.cs index 3ca9153..0972686 100644 --- a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltSections.cs +++ b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltSections.cs @@ -31,7 +31,7 @@ internal enum IltSection Games, /// /// Vaulted Dungeons keeper (portal-recall gem + kill-client). A Mini Remote tab on ILT worlds only, - /// and only while RynthAi's "Vaulted Dungeons" master switch (Settings > Navigation) is on. + /// and only while its "Vaulted Dungeons" master switch (/ilt settings, Settings > Navigation) is on. /// VaultedDungeons, /// Registry charms (acquired / status / tier / server) and the Guardian Hand. diff --git a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltSessionRates.cs b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltSessionRates.cs index 813b7f7..0a5f326 100644 --- a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltSessionRates.cs +++ b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltSessionRates.cs @@ -105,6 +105,7 @@ internal sealed class IltSessionRates : IIltFeature public void Tick(long nowMs) { + FollowSharedSession(); // The shared stats move every 0.5 s; their rows refresh each second, coins every 5 s. if (nowMs - _lastSampleAt < SampleIntervalMs) { @@ -138,6 +139,23 @@ internal sealed class IltSessionRates : IIltFeature BuildRows(); } + private long _sharedStartTicks; // RynthAi's session start as last seen (0 = not yet) + + /// + /// The coins / pyreals start over with RynthAi's shared session (its Reset XP, or a session that + /// restarted): one clock for both, without RynthAi telling RynthILT. Pump thread. + /// + private void FollowSharedSession() + { + if (!_ctx.Ai.TryGetSessionStats(out SessionStatsV1 s) || s.StartUtcTicks == 0) return; + if (_sharedStartTicks != 0 && s.StartUtcTicks > _sharedStartTicks) + { + RynthLog.Trace(LogCat.IltRates, "RynthAi's session restarted: coins and pyreals start over too"); + Reset(); + } + _sharedStartTicks = s.StartUtcTicks; + } + /// Positive change since the last sample; the first sample only sets the baseline. private static long Gain(ref long last, long current) { diff --git a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltSettings.cs b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltSettings.cs index 404b5e4..ed96a5f 100644 --- a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltSettings.cs +++ b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltSettings.cs @@ -86,6 +86,8 @@ internal static class IltSettingsStore [JsonSerializable(typeof(List), TypeInfoPropertyName = "IltBankTransactionList")] [JsonSerializable(typeof(IltAugCostFile))] [JsonSerializable(typeof(IltLegacyProfileFlags))] +[JsonSerializable(typeof(IltLegacyMiniRemote))] +[JsonSerializable(typeof(IltLegacyHuds))] [JsonSourceGenerationOptions( WriteIndented = true, IncludeFields = true, diff --git a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltT11.cs b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltT11.cs new file mode 100644 index 0000000..1c7d642 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltT11.cs @@ -0,0 +1,213 @@ +// IltT11.cs — ACECustom T11 (tier 11+ gear): the player's wield counters for RynthAi's loot rules, and +// "/ilt t11" (also "/ra t11", which RynthAi passes on). +// Moved out of RynthAi 2026-10-20 (RynthAiT11Command.cs and its "/aug" chat feed): the counters and the +// command are ACECustom's, so RynthILT reads them; RynthAi keeps the loot keys and the evaluator +// (Loot/T11ItemSupport.cs, users' .utl profiles use them) and gets the counters through RynthAi.Hub +// SetPlayerCounter. +// +// * Counters: ACECustom doesn't send them at login ([SendOnLogin] is off), so they come from the +// "/aug" reply (RynthILT's login probe asks for it on ILT), read by the shared T11AugReportParser. +// The item-aug override (IltHubState.T11.ItemAugsOverride, "/ilt t11 augs ") replaces the +// /aug Item count. Each change is reported to RynthAi, and every ResendMs anyway (RynthAi may have +// reloaded or logged in later); -1 = unknown. +// * "/ilt t11 [status | augs | refresh | item [0xId]]": the counters, the override, a fresh +// "/aug", and how the selected item's T11 text reads (tier, grade, modifiers, the loot keys' values). +// Ticks only on an ILT-like world (IltHubController): elsewhere RynthAi's counters stay unknown. +using System; +using System.Globalization; +using System.Linq; +using RynthCore.Loot.T11; + +namespace RynthCore.Plugin.RynthILT.Hub; + +internal sealed class IltT11 : IIltFeature +{ + private const long ResendMs = 5_000; + + // ACE string properties of an item's appraisal (RynthAi's StringValueKey). + private const uint StrName = 1, StrUse = 14, StrLongDesc = 16; + + private readonly IltHubContext _ctx; + private readonly T11AugReportParser _parser = new(); + private long _sentAt = long.MinValue; + private bool _dirty = true; + private int _overrideApplied = int.MinValue; + + public IltT11(IltHubContext ctx) => _ctx = ctx; + + /// The counters this character's "/aug" reply gave, with the override applied. + public T11PlayerAugs Player { get; } = new(); + + /// How many counters the last report to RynthAi carried (for the tests). + public int LastReported { get; private set; } + + private IltT11State S => _ctx.State.T11; + + // ── IIltFeature ───────────────────────────────────────────────────────── + + public void Tick(long nowMs) + { + int ov = S.ItemAugsOverride; + if (ov != _overrideApplied) + { + _overrideApplied = ov; + Player.ItemAugOverride = ov >= 0 ? ov : null; + _dirty = true; + } + if (!_dirty && _sentAt != long.MinValue && nowMs - _sentAt < ResendMs) return; + Report(); + _sentAt = nowMs; + _dirty = false; + } + + /// The "/aug" reply's counter lines. Never eats (the login probe's capture decides that). + public bool OnChat(string text) + { + if (_parser.Feed(text, IltHubContext.NowMs, Player)) _dirty = true; + return false; + } + + public void OnLogout() + { + Player.Clear(); + _dirty = true; + _sentAt = long.MinValue; + } + + /// Every counter to RynthAi (-1 for an unknown one). Pump thread. + private void Report() + { + int n = 0; + foreach ((T11Counter counter, _) in T11Catalog.CounterNames) + { + long? v = Player.Get(counter); + if (_ctx.Ai.SetPlayerCounter(unchecked((uint)counter), v ?? -1)) n++; + } + LastReported = n; + } + + // ── "/ilt t11 ..." ────────────────────────────────────────────────────── + + /// "/ilt t11 [status | augs <n|auto> | refresh | item [0xId]]" (args after "t11"). Pump thread. + public void HandleCommand(string[] args) + { + string sub = args.Length >= 1 ? args[0].ToLowerInvariant() : string.Empty; + switch (sub) + { + case "": + case "status": + PrintStatus(); + break; + case "augs": + SetOverride(args.Length >= 2 ? args[1] : string.Empty); + break; + case "refresh": + if (!_ctx.Host.HasInvokeChatParser) { _ctx.Chat("[RynthILT] This engine can't send chat commands."); break; } + _ctx.Host.InvokeChatParser("/aug"); + _ctx.Chat("[RynthILT] T11: sent /aug - the counters update from its reply."); + break; + case "item": + PrintItem(args.Length >= 2 ? args[1] : null); + break; + default: + _ctx.Chat("[RynthILT] Usage: /ilt t11 [augs | refresh | item [0xId]] (also /ra t11)"); + break; + } + } + + /// The counters the "T11: Can Wield" loot key compares wield gates against. + private void PrintStatus() + { + string updated = Player.UpdatedUtc is DateTime t ? t.ToLocalTime().ToString("t", CultureInfo.CurrentCulture) : "never"; + _ctx.Chat($"[RynthILT] === T11 loot (last /aug read: {updated}) ==="); + foreach ((T11Counter counter, string name) in T11Catalog.CounterNames) + { + long? v = Player.Get(counter); + string source = counter == T11Counter.ItemAugmentations && S.ItemAugsOverride >= 0 ? " (override)" : string.Empty; + _ctx.Chat($"[RynthILT] {name}: {(v.HasValue ? v.Value.ToString("N0", CultureInfo.CurrentCulture) : "unknown")}{source}"); + } + if (Player.UpdatedUtc == null && S.ItemAugsOverride < 0) + _ctx.Chat("[RynthILT] Unknown counters make \"T11: Can Wield\" -1. Use /ilt t11 refresh, or /ilt t11 augs ."); + if (!_ctx.Ai.Available) + _ctx.Chat("[RynthILT] (The loot rules are RynthAi's; it isn't loaded, so nothing uses these yet.)"); + } + + /// "/ilt t11 augs <n|auto>": the item-aug override (-1 = read from /aug), saved with the Hub's state. + private void SetOverride(string arg) + { + int value; + if (arg.Equals("auto", StringComparison.OrdinalIgnoreCase) || arg == "-1") + value = -1; + else if (!int.TryParse(arg.Replace(",", string.Empty), NumberStyles.Integer, CultureInfo.InvariantCulture, out value) || value < 0) + { + _ctx.Chat("[RynthILT] Usage: /ilt t11 augs (n = your item augmentation count)"); + return; + } + S.ItemAugsOverride = value; + Tick(IltHubContext.NowMs); // applied and reported now + _ctx.Chat(value < 0 + ? "[RynthILT] T11: item augmentations now come from /aug." + : $"[RynthILT] T11: item augmentations fixed at {value:N0} for loot rules."); + } + + /// "/ilt t11 item [0xId]": the parsed T11 text of an item (the selected item by default). + private void PrintItem(string? idArg) + { + var host = _ctx.Host; + uint id = 0; + if (!string.IsNullOrEmpty(idArg)) + uint.TryParse(idArg.StartsWith("0x", StringComparison.OrdinalIgnoreCase) ? idArg[2..] : idArg, + NumberStyles.HexNumber, CultureInfo.InvariantCulture, out id); + if (id == 0 && host.HasGetSelectedItemId) id = host.GetSelectedItemId(); + if (id == 0) { _ctx.Chat("[RynthILT] T11: select an item first (or pass 0xId)."); return; } + + int iid = unchecked((int)id); + var inv = _ctx.Inventory; + WorldObject? item = inv.Cache[iid]; + string name = item?.Name ?? string.Empty; + if (item == null) { _ctx.Chat($"[RynthILT] T11: the client doesn't know 0x{id:X8}."); return; } + if (name.Length == 0) name = inv.Str(item, StrName); + var server = new T11ServerProps(inv.Int(item, (uint)T11Catalog.PropZcTier, 0), + inv.Int(item, (uint)T11Catalog.PropWeaponAugScaleTier, 0), + inv.Int(item, (uint)T11Catalog.PropWeaponAugScaleQuality, -1)); + T11ItemInfo info = T11ItemInfo.Parse(name, inv.Str(item, StrLongDesc), inv.Str(item, StrUse), server); + if (!info.IsT11) + { + bool appraised = !host.HasHasAppraisalData || host.HasAppraisalData(id); + _ctx.Chat(appraised + ? $"[RynthILT] T11: {name} is not a T11 item." + : $"[RynthILT] T11: {name} isn't appraised yet - ID it and try again."); + return; + } + + _ctx.Chat($"[RynthILT] === T11: {name} (0x{id:X8}) ==="); + _ctx.Chat($"[RynthILT] Tier {(info.TierIsExact ? info.Tier.ToString(CultureInfo.InvariantCulture) : "~" + info.Tier.ToString(CultureInfo.InvariantCulture))}" + + (info.Grade != null ? $", grade {info.Grade} ({info.DamagePercent}% of max damage)" : string.Empty) + + (info.WeaponQuality >= 0 ? $", quality {info.WeaponQuality}/1000" : string.Empty) + + (info.GearGrade != null ? $", gear grade {info.GearGrade} ({info.GearGradeLines} lines)" : string.Empty) + + (info.ZoneLocked ? ", zone locked" : string.Empty)); + if (info.PropertySlots >= 0 || info.Tainted) + _ctx.Chat("[RynthILT] Properties " + + (info.PropertySlots < 0 ? "?" : info.PropertySlotCap > 0 ? $"{info.PropertySlots} of {info.PropertySlotCap}" : info.PropertySlots.ToString(CultureInfo.InvariantCulture)) + + (info.Tainted ? ", tainted (bags no longer work)" : string.Empty)); + foreach (T11WieldGate g in info.WieldGates) + _ctx.Chat($"[RynthILT] Wield requires {g.Amount:N0} {T11Catalog.CounterName(g.Counter)}"); + foreach (T11Modifier m in info.Modifiers) + { + string band = m.Min.HasValue && m.Max.HasValue ? $" [{m.Min}-{m.Max}] roll {m.RollPercent}%" : string.Empty; + string marks = (m.Tinkered != 0 ? $" ({m.Tinkered:+#;-#} tinkered)" : string.Empty) + + (m.BuiltIn ? " (built-in)" : string.Empty) + (m.Locked ? " (locked)" : string.Empty); + _ctx.Chat($"[RynthILT] Mod {m.Name} {(m.IsSlotSpecial ? "(special)" : "+" + m.Value)}{band}{marks}"); + } + foreach ((string proc, double chance) in info.Procs) + _ctx.Chat($"[RynthILT] Cast on strike: {proc} ({chance.ToString("0.#", CultureInfo.CurrentCulture)}%)"); + + int canWield = T11Keys.TryGetValue(info, T11Keys.CanWield, Player, out int cw) ? cw : -1; + _ctx.Chat($"[RynthILT] Can wield: {(canWield == 1 ? "yes" : canWield == 0 ? "no" : "unknown (no /aug read, or not appraised)")}" + + $", modifier ratings {info.ModifierRatingTotal}, average roll {info.AverageRollPercent}%"); + string keys = string.Join(", ", T11Keys.Names() + .Where(k => k.Id < T11Keys.ModifierBase) + .Select(k => $"{k.Name.Replace("T11: ", string.Empty)}={(T11Keys.TryGetValue(info, k.Id, Player, out int v) ? v : 0)}")); + _ctx.Chat($"[RynthILT] Loot keys (RynthAi's loot rules read the same): {keys}"); + } +} diff --git a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltVaultedDungeons.cs b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltVaultedDungeons.cs index 3520562..18d362f 100644 --- a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltVaultedDungeons.cs +++ b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltVaultedDungeons.cs @@ -7,8 +7,9 @@ // * ILT only. The module does nothing (no tick work, no recall, no quit, no tab) unless // IltServerOptions.IsIltLikeWorld says this is an Infinite Leaftide / ACECustom world, the same // verdict every other ILT feature follows. A command answers "not available on this server". -// * Master switch, off by default: RynthAi's "Vaulted Dungeons" setting (Settings > Navigation), -// read through RynthAi.Hub VaultedDungeonsEnabled. It is the only copy. While it is off the module +// * Master switch, off by default: IltHubState.VaultedDungeonsEnabled (the ILT settings, and the +// engine's Settings > Navigation row RynthAi mirrors; RynthAi's profile setting until 2026-10-20, +// copied once). It is the only copy. While it is off the module // ignores AutoStart, never ticks, sends no recall and no /rc quit, and the tab is hidden. Turning // it off while running stops the keeper at once and says so once. // * Active is never resumed from the saved settings. It starts when the player turns it on, or on @@ -122,7 +123,7 @@ internal sealed class IltVaultedDungeons : IIltFeature public IltVaultedDungeons(IltHubContext ctx) { _ctx = ctx; - MasterEnabled = () => _ctx.Ai.VaultedDungeonsEnabled; + MasterEnabled = () => _ctx.State.VaultedDungeonsEnabled; Activity = () => _ctx.Ai.Activity(); UseGem = gemName => { @@ -152,7 +153,7 @@ internal sealed class IltVaultedDungeons : IIltFeature private static string? GateReply(string gate) => gate switch { GateWorld => "Not available on this server (Infinite Leaftide / ACECustom only).", - GateMaster => "Off: turn on \"Vaulted Dungeons\" in Settings > Navigation first (the master switch, off by default).", + GateMaster => "Off: turn on \"Vaulted Dungeons\" in the ILT settings (/ilt settings; also Settings > Navigation) first (the master switch, off by default).", _ => null, }; @@ -431,7 +432,7 @@ internal sealed class IltVaultedDungeons : IIltFeature _state = "paused"; _ctx.Chat("[Vaulted Dungeons] Stopped: " + (gate == GateWorld ? "this is not an Infinite Leaftide / ACECustom world." - : "\"Vaulted Dungeons\" was turned off in Settings > Navigation.")); + : "\"Vaulted Dungeons\" (the master switch) was turned off.")); SaveIfDirty(); } @@ -552,7 +553,7 @@ internal sealed class IltVaultedDungeons : IIltFeature ? GemNames[_cfg.Gem - 1] : "(none)"; _ctx.Chat($"[Vaulted Dungeons] {(_cfg.Active ? "On" : "Off")} — dungeon={d}, gem={g}, " + $"kill-client={(_cfg.Quit ? $"{_cfg.QuitMinutes}m" : "off")}, state={_state}."); - _ctx.Chat("[Vaulted Dungeons] /ilt vaulted [on|off|toggle|status] (Mini Remote tab; master switch: Settings > Navigation > Vaulted Dungeons)"); + _ctx.Chat("[Vaulted Dungeons] /ilt vaulted [on|off|toggle|status] (Mini Remote tab; master switch: /ilt settings or Settings > Navigation > Vaulted Dungeons)"); return true; } } diff --git a/Plugins/RynthCore.Plugin.RynthILT/Hub/RynthAiClient.cs b/Plugins/RynthCore.Plugin.RynthILT/Hub/RynthAiClient.cs index d06001a..7053f4d 100644 --- a/Plugins/RynthCore.Plugin.RynthILT/Hub/RynthAiClient.cs +++ b/Plugins/RynthCore.Plugin.RynthILT/Hub/RynthAiClient.cs @@ -51,11 +51,23 @@ internal sealed unsafe class RynthAiClient private bool _checked; private long _checkedAt; + private bool _pinned; // tests: a table handed in, never looked up + public RynthAiClient(RynthCoreHost host) => _host = host; + /// Tests only: use (a fake RynthAi's table) and never look it up. + internal void UseTableForTests(IntPtr table) + { + _pinned = true; + _t = (RynthAiHubApiV1*)table; + _checked = true; + System.Threading.Volatile.Write(ref _renderTable, table); + } + /// Forget the table; the next call looks it up again (login, logout, RynthAi reload). public void Reset() { + if (_pinned) return; _t = null; _checked = false; System.Threading.Volatile.Write(ref _renderTable, IntPtr.Zero); @@ -66,6 +78,7 @@ internal sealed unsafe class RynthAiClient { get { + if (_pinned) return _t; long now = Environment.TickCount64; if (_checked && now - _checkedAt < RecheckMs && (_t == null || _t->Version >= 1)) return _t; _checked = true; @@ -123,22 +136,9 @@ internal sealed unsafe class RynthAiClient } } - // ── Vaulted Dungeons (master switch, activity) ────────────────────────── - - /// - /// RynthAi's "Vaulted Dungeons" setting (Settings > Navigation): the master switch of the Vaulted - /// Dungeons keeper, and the only place it is stored. False when RynthAi isn't loaded, is older than - /// the call, hasn't logged in, or has it off (the default): the keeper then does nothing. Any thread. - /// - public bool VaultedDungeonsEnabled - { - get - { - var t = AnyThreadTable; - return t != null && RynthAiHubApiV1.Has(t, RynthAiHubApiV1.VaultedDungeonsEnabledOffset) - && t->VaultedDungeonsEnabled != null && t->VaultedDungeonsEnabled() != 0; - } - } + // ── Vaulted Dungeons (activity) ───────────────────────────────────────── + // The master switch is RynthILT's own since 2026-10-20 (IltHubState.VaultedDungeonsEnabled); + // RynthAi.Hub VaultedDungeonsEnabled is no longer read. /// /// What RynthAi is doing now (its "RynthAi.Activity" interface: combat, buffing, loot, a use or cast @@ -161,6 +161,31 @@ internal sealed unsafe class RynthAiClient } } + // ── Combat ────────────────────────────────────────────────────────────── + + /// + /// Asks RynthAi to back away from (RynthAi.Hub BackAwayFrom): a + /// RynthAiHub.BackAway* result, or int.MinValue when RynthAi isn't loaded or is older than the + /// call. Pump thread. + /// + public int BackAwayFrom(uint objectId, float radiusYards, int holdMs) + { + var t = Table; + if (t == null || !RynthAiHubApiV1.Has(t, RynthAiHubApiV1.BackAwayFromOffset) || t->BackAwayFrom == null) return int.MinValue; + return t->BackAwayFrom(objectId, radiusYards, holdMs); + } + + /// + /// Reports one player wield counter to RynthAi's loot rules (RynthAi.Hub SetPlayerCounter; the T11 + /// "Can Wield" key): < 0 = unknown. False without RynthAi (or an older one). Pump thread. + /// + public bool SetPlayerCounter(uint propertyId, long value) + { + var t = Table; + return t != null && RynthAiHubApiV1.Has(t, RynthAiHubApiV1.SetPlayerCounterOffset) + && t->SetPlayerCounter != null && t->SetPlayerCounter(propertyId, value) != 0; + } + // ── Quests (/myquests) ────────────────────────────────────────────────── /// A /myquests flag from RynthAi's tracker (pump thread). diff --git a/Plugins/RynthCore.Plugin.RynthILT/HubInterface.cs b/Plugins/RynthCore.Plugin.RynthILT/HubInterface.cs index 657eaa1..48b69f0 100644 --- a/Plugins/RynthCore.Plugin.RynthILT/HubInterface.cs +++ b/Plugins/RynthCore.Plugin.RynthILT/HubInterface.cs @@ -27,7 +27,9 @@ internal static unsafe class HubInterface /// The table for (, ), or 0 when it isn't ours. public static IntPtr Query(string iface, uint version) { - if (iface != RynthIltHubApiV1.InterfaceName || version < 1 || version > RynthIltHubApiV1.InterfaceVersion || _released) + // Its own name, and the neutral one RynthAi asks the active server's owner for (the same table). + if ((iface != RynthIltHubApiV1.InterfaceName && iface != RynthIltHubApiV1.NeutralInterfaceName) + || version < 1 || version > RynthIltHubApiV1.InterfaceVersion || _released) return IntPtr.Zero; if (_table == null) { @@ -42,6 +44,11 @@ internal static unsafe class HubInterface t->RenderTab = &RenderTab; t->RenderSection = &RenderSection; t->Command = &Command; + t->AllowSummonOnEmpty = &AllowSummonOnEmpty; + t->GetSubTabs = &GetSubTabs; + t->GetSetting = &GetSetting; + t->SetSetting = &SetSetting; + t->GetText = &GetText; t->Version = RynthIltHubApiV1.InterfaceVersion; _table = t; } @@ -186,6 +193,82 @@ internal static unsafe class HubInterface catch { return 0; } } + /// The Pets tab's summon-from-empty gate (IltPetAutomation's last tick; 0 off ILT). + [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] + private static int AllowSummonOnEmpty() + { + try { return Hub?.PetAutomation.AllowSummonOnEmpty == true ? 1 : 0; } + catch { return 0; } + } + + [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] + private static int GetSubTabs(byte* parent, IltTabV1* tabs, int capacity) + { + try + { + var hub = Hub; + string? p = Utf8(parent); + if (hub == null || p == null) return 0; + var all = hub.SubTabs(p); + if (tabs != null) + { + for (int i = 0; i < all.Length && i < capacity; i++) + { + IltTabV1* t = &tabs[i]; + WriteUtf8(all[i].Id, t->Id, 24); + WriteUtf8(all[i].Label, t->Label, 32); + t->Width = 0; + t->Height = 0; + t->Flags = RynthIltHub.TabShown | RynthIltHub.TabAvailable; + } + } + return all.Length; + } + catch { return 0; } + } + + [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] + private static int GetSetting(byte* key) + { + try + { + var hub = Hub; + string? k = Utf8(key); + return hub == null || k == null ? -1 : hub.GetSetting(k); + } + catch { return -1; } + } + + [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] + private static int SetSetting(byte* key, int value) + { + try + { + var hub = Hub; + string? k = Utf8(key); + return hub != null && k != null && hub.SetSetting(k, value) ? 1 : 0; + } + catch { return 0; } + } + + [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] + private static int GetText(byte* id, byte* buffer, int capacity) + { + try + { + var hub = Hub; + string? k = Utf8(id); + if (hub == null || k == null || buffer == null || capacity <= 0) return 0; + string text = hub.GetText(k); + if (text.Length == 0) { buffer[0] = 0; return 0; } + WriteUtf8(text, buffer, capacity); + int n = 0; + while (n < capacity && buffer[n] != 0) n++; + return n; + } + catch { return 0; } + } + /// Writes as NUL-terminated UTF-8 into a fixed buffer, truncated to fit. private static void WriteUtf8(string s, byte* dest, int capacity) { diff --git a/Plugins/RynthCore.Plugin.RynthILT/IltSectionsManifest.cs b/Plugins/RynthCore.Plugin.RynthILT/IltSectionsManifest.cs new file mode 100644 index 0000000..5cfac69 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthILT/IltSectionsManifest.cs @@ -0,0 +1,129 @@ +// IltSectionsManifest.cs - What RynthILT adds to RynthCore's Mini Remote sections (RynthPluginGetSectionsJson, +// schema 1: UI/Sections/SectionManifest.cs in RynthCore). +// +// always (Infinite Leaftide views, shown while RynthCore treats this world as ILT) +// Session Stats ("char") the ILT session extras section:ilt-rates +// Fellowship ILT's /fship commands section:ilt-fellowship +// Quests (RynthILT's own) the /qb list section:ilt-questbonus +// while the Hub shows them (an ILT world; each once the server reports its feature) +// Inventory Gear, Charms, Banking section:gear|charms|banking +// Games (RynthILT's own) Games section:games +// Nav Vaulted Dungeons (master switch) section:vaulted +// The Mini Remote tabs were listed by RynthAi, which hosted them, until 2026-10-20; RynthILT lists and +// draws them itself now (RynthPluginRenderEmbed "section:"), so RynthAi's manifest names no +// server's tabs. Their names stay the same, so "/rc miniremote tab charms|banking" finds them. +// Pure: the tabs come in as a list, so the tests build it offline. +using System.Collections.Generic; +using System.IO; +using System.Text; +using System.Text.Json; +using RynthCore.Plugin.RynthILT.Hub; + +namespace RynthCore.Plugin.RynthILT; + +internal static class IltSectionsManifest +{ + /// RynthCore's id for Infinite Leaftide. + public const string Server = "ilt"; + + /// One Mini Remote tab as the Hub has it now. + internal readonly record struct Tab(string Id, float Width, float Height, bool Shown, bool Available); + + private const string NotReportedNote = "Shows once the server reports this ILT feature on (the ILT settings can ask again)."; + + /// Where each tab goes: section, label, order, tooltip. A tab not listed here isn't offered. + internal static readonly Dictionary Placement = new() + { + ["gear"] = ("inventory", "Gear", 210, "ILT gear tools (RynthILT)."), + ["charms"] = ("inventory", "Charms", 220, "ILT charms and Guardian Hands: acquired, status, tier, toggles (RynthILT)."), + ["banking"] = ("inventory", "Banking", 230, "Your ILT bank: balances, deposits, withdrawals and transfers (RynthILT)."), + ["games"] = ("games", "Games", 100, "ILT games (RynthILT)."), + // Listed only while the Hub shows the tab: the master switch is on, on an ILT world. + ["vaulted"] = ("nav", "Vaulted Dungeons", 220, + "Keep the character in one Vaulted Dungeon (RynthILT; master switch: /ilt settings or Settings > Navigation)."), + }; + + /// The surface of a tab's view ("section:gear"). + public static string SurfaceOf(string tabId) => "section:" + tabId; + + /// The tab a "section:<tab>" surface draws, when it names one placed here. + public static bool TryTabOf(string surface, out IltSection section) + { + section = IltSection.Gear; + if (!surface.StartsWith("section:", System.StringComparison.Ordinal)) return false; + string id = surface.Substring("section:".Length); + if (!Placement.ContainsKey(id) || !IltSections.TryParse(id, out section) || !IltSections.IsTab(section)) return false; + return IltSections.TabId(section) == id; + } + + /// The Hub's tabs now (empty without a Hub). Render thread. + public static List TabsOf(IltHubController? hub) + { + var list = new List(); + if (hub == null) return list; + foreach (IltSection s in IltSections.Tabs) + { + var size = IltSections.TabSize(s); + list.Add(new Tab(IltSections.TabId(s), size.X, size.Y, hub.TabShown(s), hub.SectionAvailable(s))); + } + return list; + } + + /// The manifest JSON (UTF-8 text, schema 1). + public static string Build(IReadOnlyList tabs) + { + using var stream = new MemoryStream(4096); + using (var w = new Utf8JsonWriter(stream)) + { + w.WriteStartObject(); + w.WriteNumber("version", 1); + w.WriteStartArray("sections"); + Section(w, "quests", "Quests", 1160); + Section(w, "games", "Games", 1150); + w.WriteEndArray(); + w.WriteStartArray("contributions"); + View(w, "char", "ILT session rates (RynthILT)", RynthILTPlugin.RatesSurface, primary: false, 0, 220, enabled: true, note: "", + "Enlightened Coins, pyreals and item conversions this session, on the same clock as RynthAi's session stats (RynthILT).", 120); + View(w, "fellowship", "ILT fellowship (RynthILT)", RynthILTPlugin.FellowshipSurface, primary: false, 0, 110, enabled: true, note: "", + "Infinite Leaftide's /fship commands: create, invite, dismiss, invite your landblock, list nearby, leave, disband (RynthILT; also /ilt fellow).", 120); + View(w, "quests", "Quest bonus (/qb)", RynthILTPlugin.QuestBonusSurface, primary: true, 520, 440, enabled: true, note: "", + "Infinite Leaftide's quest bonus list: completed and incomplete /qb flags (RynthILT; the quest list, timers and rewards are RynthOracle's, /ro).", 100); + foreach (Tab t in tabs) + { + if (!t.Shown || !Placement.TryGetValue(t.Id, out var place)) continue; + View(w, place.Section, place.Label, SurfaceOf(t.Id), primary: true, t.Width, t.Height, t.Available, + t.Available ? string.Empty : NotReportedNote, place.Tooltip, place.Order); + } + w.WriteEndArray(); + w.WriteEndObject(); + } + return Encoding.UTF8.GetString(stream.ToArray()); + } + + private static void Section(Utf8JsonWriter w, string id, string label, int order) + { + w.WriteStartObject(); + w.WriteString("id", id); + w.WriteString("label", label); + w.WriteNumber("order", order); + w.WriteEndObject(); + } + + private static void View(Utf8JsonWriter w, string section, string label, string surface, bool primary, float width, float height, + bool enabled, string note, string tooltip, int order) + { + w.WriteStartObject(); + w.WriteString("section", section); + w.WriteString("server", Server); + w.WriteString("label", label); + w.WriteString("surface", surface); + w.WriteBoolean("primary", primary); + if (width > 0) w.WriteNumber("width", width); + if (height > 0) w.WriteNumber("height", height); + w.WriteBoolean("enabled", enabled); + if (note.Length > 0) w.WriteString("note", note); + if (tooltip.Length > 0) w.WriteString("tooltip", tooltip); + w.WriteNumber("order", order); + w.WriteEndObject(); + } +} diff --git a/Plugins/RynthCore.Plugin.RynthILT/IltSettingsView/IltSettingsUi.cs b/Plugins/RynthCore.Plugin.RynthILT/IltSettingsView/IltSettingsUi.cs index 0d10361..187cc48 100644 --- a/Plugins/RynthCore.Plugin.RynthILT/IltSettingsView/IltSettingsUi.cs +++ b/Plugins/RynthCore.Plugin.RynthILT/IltSettingsView/IltSettingsUi.cs @@ -1,8 +1,10 @@ // IltSettingsUi.cs - The "ILT settings" view: RynthILT's copy of the Infinite Leaftide settings. // // Drawn in its own window ("/ilt settings"). Shows RynthCore's verdict and reason, this character's -// Auto / On / Off override, the ILT world names (edited through RynthCore), and every ILT feature -// with the state RynthILT's Hub read from the server (IltSettingsModel has where each comes from). +// Auto / On / Off override, the ILT world names (edited through RynthCore), this character's ILT +// options (the settings that moved here from RynthAi on 2026-10-20: the Empyrean Handler ring +// evade, ...; saved in the Hub's state), and every ILT feature with the state RynthILT's Hub read +// from the server (IltSettingsModel has where each comes from). // Edits are RynthCore commands, queued for the plugin tick; the next server-list poll shows the // result. Render thread only. using System; @@ -25,6 +27,7 @@ internal sealed class IltSettingsUi private readonly IltSettingsModel _model; private readonly Action _runCommand; private readonly Func _refreshFeatures; + private readonly Func _hub; private string _newName = string.Empty; private string _status = string.Empty; @@ -33,11 +36,13 @@ internal sealed class IltSettingsUi /// Queues a RynthCore command (run on the plugin tick). /// Asks the Hub to read the server's features again; false before it exists. - public IltSettingsUi(IltSettingsModel model, Action runCommand, Func refreshFeatures) + /// This character's Hub (its options live in the Hub's state); null before login. + public IltSettingsUi(IltSettingsModel model, Action runCommand, Func refreshFeatures, Func? hub = null) { _model = model; _runCommand = runCommand; _refreshFeatures = refreshFeatures; + _hub = hub ?? (() => null); } /// The standalone window, while open. @@ -56,6 +61,8 @@ internal sealed class IltSettingsUi { RenderVerdict(); ImGui.Separator(); + RenderCharacterOptions(); + ImGui.Separator(); RenderFeatures(); if (_status.Length > 0) { @@ -123,6 +130,38 @@ internal sealed class IltSettingsUi } } + /// + /// This character's Infinite Leaftide options: the ones that were RynthAi settings until + /// 2026-10-20 (copied over once). Saved with the Hub's state. + /// + private void RenderCharacterOptions() + { + ImGui.TextUnformatted("This character"); + IltHubController? hub = _hub(); + if (hub == null) + { + ImGui.TextDisabled("Shown once this character is logged in."); + return; + } + IltHubState st = hub.State; + bool vaulted = st.VaultedDungeonsEnabled; + if (ImGui.Checkbox("Vaulted Dungeons (the keeper's master switch)##iltvaulted", ref vaulted)) st.VaultedDungeonsEnabled = vaulted; + if (ImGui.IsItemHovered()) + ImGui.SetTooltip("Off by default. While off the Vaulted Dungeons keeper does nothing: no recalls, no /rc quit, no Mini\n" + + "Remote tab. On: the \"Vaulted Dungeons\" tab shows, where you pick a dungeon and a tied Portal Recall\n" + + "Gem and start it (/ilt vaulted on). Also in RynthCore's Settings > Navigation (it was a RynthAi setting)."); + bool ring = st.Combat.HandlerRingEvade; + if (ImGui.Checkbox("Evade the Empyrean Handler's lethal ring##iltring", ref ring)) st.Combat.HandlerRingEvade = ring; + if (ImGui.IsItemHovered()) + ImGui.SetTooltip("When an Empyrean Handler channels its lethal ring and you are within 12 yards (or RynthAi's\n" + + "Ring Range if larger), RynthAi back-jumps away and re-engages. Only while RynthAi's macro\n" + + "is running with combat on. On by default (it was RynthAi's \"Evade Handler Ring\")."); + int augs = st.T11.ItemAugsOverride; + SafeImGui.TextDisabled(augs >= 0 + ? $"T11 item augmentations: fixed at {augs:N0} for RynthAi's loot rules (/ilt t11 augs auto to read /aug)" + : "T11 item augmentations: read from /aug (/ilt t11 augs fixes them; /ilt t11 shows the counters)"); + } + /// /// The server's ILT features, one collapsible section per group (Character, Items, Pets, /// Fellowship, Combat, Activities, then the charms and any other bit chat or a probe set), with diff --git a/Plugins/RynthCore.Plugin.RynthILT/PluginExports.cs b/Plugins/RynthCore.Plugin.RynthILT/PluginExports.cs index 30653ef..2f8d57d 100644 --- a/Plugins/RynthCore.Plugin.RynthILT/PluginExports.cs +++ b/Plugins/RynthCore.Plugin.RynthILT/PluginExports.cs @@ -15,8 +15,10 @@ public static unsafe class PluginExports // sections RynthAi's Mini Remote hosts (Plugins/Shared/RynthIltHubApi.cs, HubInterface.cs), and // "RynthServer.Profile" v1, ILT's settings and tinkering salvage for any reader, as every server // plugin serves its own (Plugins/Shared/RynthServerProfileApi.cs, ProfileInterface.cs), and - // "RynthILT.Data" v1, the charms list and bank balances with their actions - // (Plugins/Shared/RynthIltDataApi.cs, DataInterface.cs). + // "RynthILT.Data" v1..v3, the charms list and bank balances with their actions, the pet breeding + // tracker and the Temple guardians (Plugins/Shared/RynthIltDataApi.cs, DataInterface.cs), and + // "RynthILT.Server" v1, the Leaftide feature / fellowship / quest bonus profile RynthOracle reads + // (Plugins/Shared/RynthIltServerApi.cs, ServerInterface.cs). // Fixed signature: void* (const char* iface, uint version). [UnmanagedCallersOnly(EntryPoint = "RynthPluginQueryInterface", CallConvs = new[] { typeof(CallConvCdecl) })] private static IntPtr QueryInterface(IntPtr ifaceAnsi, uint version) @@ -26,6 +28,8 @@ public static unsafe class PluginExports string iface = ifaceAnsi == IntPtr.Zero ? "" : Marshal.PtrToStringAnsi(ifaceAnsi) ?? ""; IntPtr table = HubInterface.Query(iface, version); if (table != IntPtr.Zero) return table; + table = ServerInterface.Query(iface, version); + if (table != IntPtr.Zero) return table; table = ProfileInterface.Query(iface, version); return table != IntPtr.Zero ? table : DataInterface.Query(iface, version); } @@ -44,6 +48,7 @@ public static unsafe class PluginExports // An exception escaping an UnmanagedCallersOnly export fail-fasts the client under NativeAOT. try { Runtime.Shutdown(); } catch { } try { HubInterface.Release(); } catch { } + try { ServerInterface.Release(); } catch { } try { ProfileInterface.Release(); } catch { } try { DataInterface.Release(); } catch { } foreach (IntPtr p in new[] { Interlocked.Exchange(ref _bountiesPtr, IntPtr.Zero), Interlocked.Exchange(ref _progressionPtr, IntPtr.Zero), @@ -92,7 +97,9 @@ public static unsafe class PluginExports /// still asks) are RynthCore's Mini Remote sections. ":popout" is added when one is popped out /// into a window of its own, and RynthILT draws in the engine's current context either way. The /// Guardian panel is user-sized (want echoes the size given); a section reports the height it - /// used. 1 = drawn, 0 = not ready / unknown surface. + /// used. "section:gear|charms|banking|games|vaulted" are the Mini Remote ILT tabs as RynthCore's + /// section views (RynthILT lists them since 2026-10-20; RynthAi did before), sized to the tab. + /// 1 = drawn, 0 = not ready / unknown surface. /// [UnmanagedCallersOnly(EntryPoint = "RynthPluginRenderEmbed", CallConvs = new[] { typeof(CallConvCdecl) })] public static int RenderEmbed(byte* surface, float width, float height, float* wantWidth, float* wantHeight) @@ -116,7 +123,16 @@ public static unsafe class PluginExports : name.SequenceEqual("section:ilt-rates"u8) ? RynthILTPlugin.RatesSurface : name.SequenceEqual("section:ilt-questbonus"u8) ? RynthILTPlugin.QuestBonusSurface : null; - if (view == null || !plugin.RenderEmbedded(view, out float wantH)) return 0; + if (view == null) + { + // "section:gear", "section:banking", ...: the Mini Remote ILT tabs RynthILT lists (IltSectionsManifest). + if (name.Length > 64 || !name.StartsWith("section:"u8)) return 0; + if (!plugin.RenderEmbeddedTab(System.Text.Encoding.UTF8.GetString(name), out float tabW, out float tabH)) return 0; + if (wantWidth != null) *wantWidth = tabW > 0 ? tabW : width; + if (wantHeight != null) *wantHeight = tabH > 0 ? tabH : height; + return 1; + } + if (!plugin.RenderEmbedded(view, out float wantH)) return 0; if (wantWidth != null) *wantWidth = width; if (wantHeight != null) *wantHeight = wantH; return 1; @@ -132,6 +148,11 @@ public static unsafe class PluginExports public static void OnChatBarEnter(IntPtr textUtf16, IntPtr eatFlag) => Runtime.OnChatBarEnter(textUtf16, eatFlag); + // Creatures' health from the server (siphon auto-capture's fallback health read, IltPetAutomation). + [UnmanagedCallersOnly(EntryPoint = "RynthPluginOnUpdateHealth", CallConvs = new[] { typeof(CallConvCdecl) })] + public static void OnUpdateHealth(uint targetId, float healthRatio, uint currentHealth, uint maxHealth) + => Runtime.OnUpdateHealth(targetId, healthRatio, currentHealth, maxHealth); + // This character's kills re-read the bounty list (while the Bounties window is open). [UnmanagedCallersOnly(EntryPoint = "RynthPluginOnKillNotification", CallConvs = new[] { typeof(CallConvCdecl) })] public static void OnKillNotification(IntPtr textUtf16) => Runtime.OnKillNotification(textUtf16); diff --git a/Plugins/RynthCore.Plugin.RynthILT/ProfileInterface.cs b/Plugins/RynthCore.Plugin.RynthILT/ProfileInterface.cs index 1e7d28c..6398efd 100644 --- a/Plugins/RynthCore.Plugin.RynthILT/ProfileInterface.cs +++ b/Plugins/RynthCore.Plugin.RynthILT/ProfileInterface.cs @@ -29,6 +29,9 @@ internal static unsafe class ProfileInterface { Emulator = "ACE", Salvage = IltSalvage.Rows, + // Leaftide trinkets (UB-IT's IsLeaftideTrinketJewelry): the Crafting tab's Trinkets bench, not Jewelry. + TrinketNames = IltSalvage.TrinketNames, + TrinketExcept = IltSalvage.TrinketExcept, Source = "RynthILT; salvage from UB-IT's LeaftideImbueHelper (via SilentKelpie)", }; diff --git a/Plugins/RynthCore.Plugin.RynthILT/RynthCore.Plugin.RynthILT.csproj b/Plugins/RynthCore.Plugin.RynthILT/RynthCore.Plugin.RynthILT.csproj index 5172b35..03e6930 100644 --- a/Plugins/RynthCore.Plugin.RynthILT/RynthCore.Plugin.RynthILT.csproj +++ b/Plugins/RynthCore.Plugin.RynthILT/RynthCore.Plugin.RynthILT.csproj @@ -13,7 +13,15 @@ RynthILT borrows from RynthAi through RynthAi.Hub (Plugins/Shared/RynthIltHubApi.cs, RynthAiHubApi.cs). IltSettingsView/ a copy of the ILT settings (RynthCore's verdict, this character's override, the - ILT world names, the Hub's feature read) in its own window ("/ilt settings"). + ILT world names, the Hub's feature read) in its own window ("/ilt settings"), + with this character's ILT options (Vaulted Dungeons master switch, Handler + ring evade, T11 item augs). + Moved out of RynthAi 2026-10-20 (Hub/): the Pets tab's ACECustom parts (IltPetAutomation: + pet charms, summon from empty, siphon capture), the Empyrean Handler ring + detection (IltRingEvade; RynthAi does the back-away), the T11 /aug counters + and "/ilt t11" (IltT11; RynthAi keeps the loot keys), the Vaulted Dungeons + switch, the Remote tab's ILT parts, the Mini Remote tab views on the rail + (IltSectionsManifest.cs) and the Leaftide trinket list (the profile). IltFellowship/ ILT's /fship commands as buttons ("/ilt fellow"). --> @@ -43,7 +51,7 @@ Infinite Leaftide infiniteleaftide.online InfiniteLeaftide|*Leaftide* - Infinite Leaftide (ACECustom) features: the ILT Hub (the Mini Remote's ILT tabs: banking, gear, charms, games), the Guardian, bounties, progression, the attribute raiser, the ring inscription chain, the ILT settings and the /fship fellowship commands. + Infinite Leaftide (ACECustom) features: the ILT Hub (the Mini Remote's ILT tabs: banking, gear, charms, games, Vaulted Dungeons; the Pets tab's charms, siphon capture and breeding), the Guardian, bounties, progression, the attribute raiser, the ring inscription chain, the Empyrean Handler ring evade, the T11 loot counters, the ILT settings and the /fship fellowship commands. @@ -56,12 +64,16 @@ + + + + + + + + + diff --git a/Plugins/RynthCore.Plugin.RynthILT/RynthILTPlugin.cs b/Plugins/RynthCore.Plugin.RynthILT/RynthILTPlugin.cs index 58948b4..eacb5c2 100644 --- a/Plugins/RynthCore.Plugin.RynthILT/RynthILTPlugin.cs +++ b/Plugins/RynthCore.Plugin.RynthILT/RynthILTPlugin.cs @@ -22,6 +22,13 @@ // comes from RynthCore's server list (plugin API v86, polled every 2 s), and the Hub follows it // once one arrives (IltEngineVerdict). // +// Moved from RynthAi on 2026-10-20 (Hub/): the Pets tab's ACECustom parts (IltPetAutomation), the +// Empyrean Handler ring detection (IltRingEvade; RynthAi.Hub BackAwayFrom does the jump), the T11 +// "/aug" counters and "/ilt t11" (IltT11; RynthAi.Hub SetPlayerCounter), the Vaulted Dungeons +// master switch, the Remote tab's ILT parts, and the Mini Remote ILT tab views on RynthCore's rail +// (IltSectionsManifest.cs, RenderEmbeddedTab). Their settings were copied once from the +// character's RynthAi files (IltMigration.ImportRynthAiSettings, at the Hub's start). +// // Third: ILT's fellowship commands (IltFellowship/, ACECustom /fship) as buttons in RynthCore's // Fellowship section and their own window ("/ilt fellow"). While ILT is active the list is also // sent to RynthAi ("servercommands"), whose Fellowship view draws them; an empty list clears it. @@ -50,8 +57,8 @@ namespace RynthCore.Plugin.RynthILT; public sealed class RynthILTPlugin : RynthPluginBase { internal static readonly IntPtr NamePointer = Marshal.StringToHGlobalAnsi("RynthILT"); - // Previous release: 0.3.1. - internal static readonly IntPtr VersionPointer = Marshal.StringToHGlobalAnsi("0.3.2"); + // Previous release: 0.3.2. + internal static readonly IntPtr VersionPointer = Marshal.StringToHGlobalAnsi("0.3.3"); /// /// The settings view's surface. Not in the sections manifest (the force-server override lives @@ -83,7 +90,7 @@ public sealed class RynthILTPlugin : RynthPluginBase public RynthILTPlugin() { - _settingsUi = new IltSettingsUi(_settingsModel, cmd => QueueChatCommand(cmd), RefreshFeatures); + _settingsUi = new IltSettingsUi(_settingsModel, cmd => QueueChatCommand(cmd), RefreshFeatures, () => _hub); _fellowshipUi = new IltFellowshipUi(QueueChatCommand); IltEngineVerdict.Attach(_settingsModel); } @@ -353,27 +360,50 @@ public sealed class RynthILTPlugin : RynthPluginBase /// /// RynthPluginGetSectionsJson (schema 1, UI/Sections/SectionManifest.cs in RynthCore): the ILT - /// session extras in Session Stats ("char"), the fellowship commands in Fellowship and the /qb - /// list in a Quests section of RynthILT's own, all Infinite Leaftide areas (shown while RynthCore - /// treats this world as ILT). The Mini Remote ILT tabs (Banking, Gear, Charms, Games) are listed - /// by RynthAi, which hosts them. Null before login. + /// session extras in Session Stats ("char"), the fellowship commands in Fellowship, the /qb list in + /// a Quests section of RynthILT's own, and the Mini Remote ILT tabs the Hub shows (Gear, Charms, + /// Banking in Inventory, Games in a section of RynthILT's own, Vaulted Dungeons in Nav), all + /// Infinite Leaftide areas (shown while RynthCore treats this world as ILT). IltSectionsManifest.cs. + /// The tabs were listed by RynthAi, which hosted them, until 2026-10-20. Null before login. /// - internal string? BuildSectionsJson() => _loginComplete ? SectionsJson : null; + internal string? BuildSectionsJson() => _loginComplete ? IltSectionsManifest.Build(IltSectionsManifest.TabsOf(_hub)) : null; - internal const string SectionsJson = - "{\"version\":1,\"sections\":[{\"id\":\"quests\",\"label\":\"Quests\",\"order\":1160}],\"contributions\":[" + - "{\"section\":\"char\",\"server\":\"ilt\"," + - "\"label\":\"ILT session rates (RynthILT)\",\"surface\":\"" + RatesSurface + "\",\"primary\":false," + - "\"height\":220,\"enabled\":true,\"tooltip\":\"Enlightened Coins, pyreals and item conversions this session, " + - "on the same clock as RynthAi's session stats (RynthILT).\",\"order\":120}," + - "{\"section\":\"fellowship\",\"server\":\"ilt\"," + - "\"label\":\"ILT fellowship (RynthILT)\",\"surface\":\"" + FellowshipSurface + "\",\"primary\":false," + - "\"height\":110,\"enabled\":true,\"tooltip\":\"Infinite Leaftide's /fship commands: create, invite, dismiss, " + - "invite your landblock, list nearby, leave, disband (RynthILT; also /ilt fellow).\",\"order\":120}," + - "{\"section\":\"quests\",\"server\":\"ilt\"," + - "\"label\":\"Quest bonus (/qb)\",\"surface\":\"" + QuestBonusSurface + "\",\"primary\":true," + - "\"width\":520,\"height\":440,\"enabled\":true,\"tooltip\":\"Infinite Leaftide's quest bonus list: completed and " + - "incomplete /qb flags (RynthILT; the quest list, timers and rewards are RynthOracle's, /ro).\",\"order\":100}]}"; + /// + /// RynthPluginRenderEmbed "section:<tab>": one Mini Remote ILT tab as RynthCore's section view + /// (IltSectionsManifest lists them), drawn into the engine's current window and context in the + /// dashboard colours. / are the tab's + /// size. False until the Hub exists, or for a surface that is no ILT tab. Render thread. + /// + internal bool RenderEmbeddedTab(string surface, out float wantWidth, out float wantHeight) + { + wantWidth = wantHeight = 0; + IltHubController? hub = _hub; + if (!_loginComplete || hub == null || !IltSectionsManifest.TryTabOf(surface, out IltSection section)) return false; + IntPtr previous = ImGui.GetCurrentContext(); + IntPtr context = previous != IntPtr.Zero ? previous : Host.ImGuiContext; + if (context == IntPtr.Zero) return false; + ImGui.SetCurrentContext(context); + int pushed = IltStyle.PushDashboardStyle(); + try + { + var size = IltSections.TabSize(section); + wantWidth = size.X; + wantHeight = size.Y; + hub.NoteTabDrawn(); + hub.RenderTab(section); + return true; + } + catch (Exception ex) + { + RynthLog.Exception(LogCat.IltHub, ex, "RenderEmbeddedTab " + surface); + return false; + } + finally + { + ImGui.PopStyleColor(pushed); + ImGui.SetCurrentContext(previous); + } + } /// Plugin tick: runs the settings and fellowship views' chat commands through the engine. private void DrainChatCommands() @@ -486,7 +516,7 @@ public sealed class RynthILTPlugin : RynthPluginBase try { // The Hub eats its own probe / capture replies (IltChatCapture). - if (_hub?.OnChat(text) == true) eat = 1; + if (_hub?.OnChat(text, chatType) == true) eat = 1; } catch (Exception ex) { RynthLog.Exception(LogCat.IltHub, ex, "OnChat"); } if (_bounties == null) return; @@ -519,6 +549,13 @@ public sealed class RynthILTPlugin : RynthPluginBase _commands.Enqueue(trimmed.Split(' ', StringSplitOptions.RemoveEmptyEntries)); } + // A creature's health from the server: siphon auto-capture's fallback health read (ILT only). + public override void OnUpdateHealth(uint targetId, float healthRatio, uint currentHealth, uint maxHealth) + { + try { _hub?.OnUpdateHealth(targetId, healthRatio); } + catch (Exception ex) { RynthLog.Exception(LogCat.IltHub, ex, "OnUpdateHealth"); } + } + // The server's killer notification: this character landed the killing blow. public override void OnKillNotification(string? deathMessage) { @@ -624,15 +661,18 @@ public sealed class RynthILTPlugin : RynthPluginBase /// /// The verbs RynthILT answers: the ILT "/ra hub" verbs (not RynthAi's Quests / Pets tabs or its - /// Remote tab), "/ra guardian", "/ra bounty|bounties|bountys" and "rates". + /// Remote tab), "/ra guardian", "/ra bounty|bounties|bountys", "rates" and "t11". /// internal static bool IsIltVerb(string[] words) { string verb = words[0].ToLowerInvariant(); switch (verb) { - case "guardian": case "bounty": case "bounties": case "bountys": case "rates": + case "guardian": case "bounty": case "bounties": case "bountys": case "rates": case "t11": return true; + case "ub": + // ub-IT's ACECustom verbs RynthAi passes on ("/ub qblist", "/ub augs"). + return words.Length >= 2 && words[1].ToLowerInvariant() is "qblist" or "augs"; case "hub": if (words.Length < 2) return false; // "/ra hub" alone toggles RynthAi's Mini Remote string sub = words[1].ToLowerInvariant(); @@ -678,6 +718,23 @@ public sealed class RynthILTPlugin : RynthPluginBase case "hub": case "rates": break; + case "ub": + { + // ub-IT's "/ub qblist" and "/ub augs" (RynthAi passes them on): ACECustom's own commands. + string sub = args.Length > 0 ? args[0].ToLowerInvariant() : string.Empty; + string? server = sub == "qblist" ? "/qb list" : sub == "augs" ? "/aug" : null; + if (server == null) { ChatLine("[RynthILT] /ub qblist or /ub augs"); return; } + if (_hub?.Options.IsIltLikeWorld != true) { ChatLine($"[RynthILT] /ub {sub}: not an Infinite Leaftide world."); return; } + if (!Host.HasInvokeChatParser || !Host.InvokeChatParser(server)) ChatLine("[RynthILT] RynthCore didn't take: " + server); + return; + } + case "t11": + { + // "/ilt t11 ..." and RynthAi's "/ra t11 ..." (T11 loot counters; IltT11). + if (_hub == null) { ChatLine("[RynthILT] ILT features not ready (log in first)."); return; } + _hub.T11.HandleCommand(args); + return; + } case "vaulted": case "vaulteddungeons": { @@ -707,7 +764,8 @@ public sealed class RynthILTPlugin : RynthPluginBase case "help": ChatLine("[RynthILT] /ilt hub ... (the Mini Remote's ILT tabs; same as /ra hub ...), /ilt guardian ..., /ilt servers [list||default],"); ChatLine("[RynthILT] /ilt bounty [list|refresh] - the tracked ACECustom bounties (the Bounties window: the ILT button on the RynthCore bar, or /rc bounties),"); - ChatLine("[RynthILT] /ilt vaulted [on|off|toggle|status] - Vaulted Dungeons keeper (ILT only; master switch: RynthAi Settings > Navigation > Vaulted Dungeons, off by default),"); + ChatLine("[RynthILT] /ilt vaulted [on|off|toggle|status] - Vaulted Dungeons keeper (ILT only; master switch: /ilt settings or Settings > Navigation > Vaulted Dungeons, off by default),"); + ChatLine("[RynthILT] /ilt t11 [augs |refresh|item [0xId]] - T11 loot: the /aug wield counters RynthAi's loot rules use, the item-aug override, an item's T11 text (also /ra t11),"); ChatLine("[RynthILT] /ilt settings [show|hide|toggle] - the ILT settings: the world verdict, the ILT world names and the server's features (force a server: RynthCore Options > Diagnostics),"); ChatLine("[RynthILT] /ilt fellow [show|hide|toggle] - ILT's /fship commands as buttons (also in the Mini Remote's Fellowship section),"); ChatLine("[RynthILT] /ilt trace [on|off], /ilt debug [on|off]."); @@ -835,6 +893,10 @@ public sealed class RynthILTPlugin : RynthPluginBase { _hub = new IltHubController(Host, folder, _settings, _ai, () => _hubWritesBlocked, pending ? IltMigration.FindLegacyCharFolder(world, charName) : null); + // Once per character: the RynthAi settings that moved here on 2026-10-20. + var imported = IltMigration.ImportRynthAiSettings(_hub.State, world, charName); + if (imported.Count > 0) + RynthLog.Write(LogCat.IltStore, $"Carried {charName}'s RynthAi settings that moved to RynthILT over: {string.Join(", ", imported)}."); _hub.OnLoginComplete(charName, force); } catch (Exception ex) diff --git a/Plugins/RynthCore.Plugin.RynthILT/ServerInterface.cs b/Plugins/RynthCore.Plugin.RynthILT/ServerInterface.cs new file mode 100644 index 0000000..8771b58 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthILT/ServerInterface.cs @@ -0,0 +1,81 @@ +// ServerInterface.cs - RynthILT's side of the "RynthILT.Server" interface (Plugins/Shared/RynthIltServerApi.cs): +// the profile JSON other plugins read (RynthOracle's Fellowship / Quests qb list / feature list): +// the Leaftide feature list with the server's state for each, and the server's fellowship rules. +// +// Restored 2026-10-16: this export was dropped when "RynthServer.Profile" (salvage / identity) was +// added, so Oracle still detected ILT via RynthCore but never received feature / qb / fellowship +// data from RynthILT. Hub + Data stay separate; this table is the feature-profile channel. +// +// The table is allocated once per loaded copy of RynthILT and never freed (a plugin DLL is never +// unloaded); after Release() it reports Version 0 and GetProfileJson answers 0. Before login there +// is no controller, so the profile is the not-ILT default (every feature unknown, retail fellowships). +using System; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using System.Text; +using RynthCore.Plugin.RynthILT.Hub; +using RynthCore.Plugin.Shared; + +namespace RynthCore.Plugin.RynthILT; + +internal static unsafe class ServerInterface +{ + private static RynthIltServerApiV1* _table; + private static volatile bool _released; + + /// The profile before any login: not an ILT world, nothing known (built once). + private static readonly string NotLoggedInJson = + IltFeatureCatalog.BuildProfileJson(false, string.Empty, false, string.Empty, DateTime.MinValue, _ => IltTri.Unknown); + + /// The table for (, ), or 0 when it isn't ours. + public static IntPtr Query(string iface, uint version) + { + if (iface != RynthIltServerApiV1.InterfaceName || version < 1 || version > RynthIltServerApiV1.InterfaceVersion || _released) + return IntPtr.Zero; + if (_table == null) + { + var t = (RynthIltServerApiV1*)NativeMemory.AllocZeroed((nuint)sizeof(RynthIltServerApiV1)); + t->StructSize = (uint)sizeof(RynthIltServerApiV1); + t->GetProfileJson = &GetProfileJson; + t->Version = RynthIltServerApiV1.InterfaceVersion; + _table = t; + } + return (IntPtr)_table; + } + + /// Plugin shutdown: readers see Version 0 and re-query; GetProfileJson answers 0. + public static void Release() + { + _released = true; + if (_table != null) _table->Version = 0; + } + + /// The JSON to hand out now: the live controller's snapshot, or the not-logged-in default. + internal static string CurrentJson() + => (_released ? null : PluginExports.Runtime.Plugin?.Hub?.ProfileJson) ?? NotLoggedInJson; + + [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] + private static int GetProfileJson(byte* buffer, int capacity) + { + try + { + if (_released) return 0; + return ProfileInterface.Write(CurrentJson(), buffer, capacity); + } + catch { return 0; } + } + + /// + /// Copies as NUL-terminated UTF-8 into the caller's buffer when it fits, + /// and returns its byte length either way (length >= capacity: too small, nothing written). + /// + internal static int Write(string json, byte* buffer, int capacity) + { + int length = Encoding.UTF8.GetByteCount(json); + if (buffer == null || capacity <= length) return length; + fixed (char* src = json) + Encoding.UTF8.GetBytes(src, json.Length, buffer, capacity); + buffer[length] = 0; + return length; + } +} diff --git a/Plugins/RynthCore.Plugin.RynthInventory/Data/BankRoster.cs b/Plugins/RynthCore.Plugin.RynthInventory/Data/BankRoster.cs new file mode 100644 index 0000000..e9b6d09 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthInventory/Data/BankRoster.cs @@ -0,0 +1,78 @@ +using System; +using System.Collections.Generic; +using RynthCore.Plugin.Shared; + +namespace RynthCore.Plugin.RynthInventory.Data; + +/// One character on the Banking tab: its saved balances (null = never read) and account. +internal sealed record BankRosterEntry(string Name, string Account, bool Current, IltBankRow? Bank); + +/// +/// The Banking tab's character list (2026-10-13; the Mini Remote's Banking tab moved here). Every +/// character RynthILT has bank balances for on this server (its saved per-character state, so every +/// account played on this PC), plus every character Global Inventory has recorded on the same +/// server without a balance yet, so the list covers the same characters as the inventory does. +/// Pure: the tests feed it a parsed bank view and an index. +/// +internal static class BankRoster +{ + /// + /// The merged list: the logged-in character first, then by name. A name in both lists keeps + /// RynthILT's balances and the inventory's account. + /// + public static List Build(IltBankView bank, InventoryIndex? index) + { + var byName = new Dictionary(StringComparer.OrdinalIgnoreCase); + foreach (IltBankRow r in bank.Characters) + byName[r.Name] = new BankRosterEntry(r.Name, string.Empty, r.Current, r); + + if (index != null) + { + foreach (CharacterInfo ci in index.Characters) + { + // Same server only: a bank belongs to one world. + if (!SameServer(ci, bank)) continue; + string account = !string.IsNullOrEmpty(ci.Account) && ci.Account != "unknown" ? ci.Account : string.Empty; + if (byName.TryGetValue(ci.Name, out BankRosterEntry? have)) + byName[ci.Name] = have with { Account = account, Current = have.Current || ci.IsCurrentCharacter }; + else + byName[ci.Name] = new BankRosterEntry(ci.Name, account, ci.IsCurrentCharacter, null); + } + } + + var list = new List(byName.Values); + list.Sort((a, b) => a.Current != b.Current ? (a.Current ? -1 : 1) : string.Compare(a.Name, b.Name, StringComparison.OrdinalIgnoreCase)); + return list; + } + + /// + /// A recorded character is on the bank's server: the world RynthILT names when it gave one, + /// otherwise the server Global Inventory says you are on now. + /// + private static bool SameServer(CharacterInfo ci, IltBankView bank) => + bank.World.Length > 0 ? InventoryIndex.SameName(ci.Server, bank.World) : ci.IsCurrentServer; + + /// The sums over every character with a balance (one row of the same shape). + public static IltBankRow Totals(IReadOnlyList roster) + { + long py = 0, lum = 0, lk = 0, mk = 0, ec = 0, wec = 0, pc = 0; + foreach (BankRosterEntry e in roster) + { + if (e.Bank is not { } b) continue; + py += b.Pyreals; lum += b.Luminance; lk += b.LegendaryKeys; mk += b.MythicalKeys; + ec += b.EnlightenedCoins; wec += b.WeaklyEnlightenedCoins; pc += b.PrestigeCoins; + } + return new IltBankRow("Total", false, py, lum, lk, mk, ec, wec, pc, DateTime.MinValue); + } + + /// + /// The withdraw / transfer amount typed in the form: a positive whole number (commas and spaces + /// allowed), or 0 when it isn't one. + /// + public static long ParseAmount(string? text) + { + if (string.IsNullOrWhiteSpace(text)) return 0; + string digits = text.Replace(",", string.Empty).Replace(" ", string.Empty).Trim(); + return long.TryParse(digits, System.Globalization.NumberStyles.None, System.Globalization.CultureInfo.InvariantCulture, out long n) && n > 0 ? n : 0; + } +} diff --git a/Plugins/RynthCore.Plugin.RynthInventory/Data/ExternalStorage.cs b/Plugins/RynthCore.Plugin.RynthInventory/Data/ExternalStorage.cs new file mode 100644 index 0000000..510d5b4 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthInventory/Data/ExternalStorage.cs @@ -0,0 +1,48 @@ +using System; +using System.Collections.Generic; +using RynthCore.Plugin.Shared; + +namespace RynthCore.Plugin.RynthInventory.Data; + +/// +/// Storage another plugin read for us (Plugins/Shared/StorageFeed.cs): a server-side store the client +/// is never shown, e.g. Aelrynth's account vault from RynthAelrynth. Filed with the character's storage +/// like a container that was opened; RynthInventory itself knows nothing about any server's store. +/// Pure: RynthInventory.Tests covers it. +/// +internal static class ExternalStorage +{ + /// The feed's record as a storage record, seen now (). + public static StorageRecord ToRecord(StorageFeedRecord feed, DateTime seenUtc) + { + var items = new List(feed.Items.Count); + foreach (StorageFeedItem f in feed.Items) + { + var it = new ItemRecord + { + Id = f.Id, + Wcid = f.Wcid, + Name = f.Name, + Icon = f.Icon, + Underlay = f.Underlay, + Overlay = f.Overlay, + Stack = Math.Max(1, f.Stack), + MaxStack = f.MaxStack, + ItemType = f.ItemType, + Place = ItemPlace.Storage, + }; + it.Category = ItemCategory.FromItemType(it.ItemType); + items.Add(it); + } + return new StorageRecord { Id = feed.Id, Name = feed.Name, Label = feed.Label, Cell = 0, SeenUtc = seenUtc, Items = items }; + } + + /// A copy of with in it (replacing the one with its id). + public static List FileInto(IReadOnlyList storage, StorageRecord record) + { + var list = new List(storage); + int i = list.FindIndex(s => s.Id == record.Id); + if (i >= 0) list[i] = record; else list.Add(record); + return list; + } +} diff --git a/Plugins/RynthCore.Plugin.RynthInventory/InventoryContext.cs b/Plugins/RynthCore.Plugin.RynthInventory/InventoryContext.cs index 8e8ff6f..705e7ce 100644 --- a/Plugins/RynthCore.Plugin.RynthInventory/InventoryContext.cs +++ b/Plugins/RynthCore.Plugin.RynthInventory/InventoryContext.cs @@ -35,6 +35,13 @@ internal sealed class InventoryContext public bool IconsAvailable; public DateTime UtcNow; + /// RynthILT's "RynthILT.Data" (the Banking tab's balances and bank commands). + public readonly RynthCore.Plugin.Shared.RynthIltDataClient IltData = new(); + /// The bank RynthILT last reported (None without RynthILT); read while the window shows. + public RynthCore.Plugin.Shared.IltBankView Bank = RynthCore.Plugin.Shared.IltBankView.None; + /// Set by the plugin: queues a bank verb with RynthILT (IltBankView.*Verb); false when refused. + public Func BankCommand = _ => false; + public Action RequestRescan = () => { }; public Action RequestReload = () => { }; /// Forgets a character (moves its file aside). Returns a message for the player. diff --git a/Plugins/RynthCore.Plugin.RynthInventory/PluginExports.cs b/Plugins/RynthCore.Plugin.RynthInventory/PluginExports.cs index e830c0b..aa4b122 100644 --- a/Plugins/RynthCore.Plugin.RynthInventory/PluginExports.cs +++ b/Plugins/RynthCore.Plugin.RynthInventory/PluginExports.cs @@ -37,7 +37,7 @@ public static unsafe class PluginExports [UnmanagedCallersOnly(EntryPoint = "RynthPluginVersion", CallConvs = new[] { typeof(CallConvCdecl) })] public static IntPtr GetVersion() { - try { return LiteralPointer("0.1.0"u8); } + try { return LiteralPointer("0.1.1"u8); } catch { return IntPtr.Zero; } } @@ -59,8 +59,23 @@ public static unsafe class PluginExports [UnmanagedCallersOnly(EntryPoint = "RynthPluginOnChatBarEnter", CallConvs = new[] { typeof(CallConvCdecl) })] public static void OnChatBarEnter(IntPtr textUtf16, IntPtr eatFlag) => Runtime.OnChatBarEnter(textUtf16, eatFlag); - [UnmanagedCallersOnly(EntryPoint = "RynthPluginOnChatWindowText", CallConvs = new[] { typeof(CallConvCdecl) })] - public static void OnChatWindowText(IntPtr textUtf16, int chatType, IntPtr eatFlag) => Runtime.OnChatWindowText(textUtf16, chatType, eatFlag); + /// + /// The engine's plugin-command broker: "storage" from another plugin (StorageFeed.cs, e.g. Aelrynth's + /// account vault from RynthAelrynth). The ANSI strings are copied before returning; the payload is + /// only queued, so any thread is fine. + /// + [UnmanagedCallersOnly(EntryPoint = "RynthPluginApplyRemoteCommand", CallConvs = new[] { typeof(CallConvCdecl) })] + public static void ApplyRemoteCommand(IntPtr actionAnsi, IntPtr valueAnsi) + { + try + { + string action = actionAnsi != IntPtr.Zero ? (Marshal.PtrToStringAnsi(actionAnsi) ?? string.Empty) : string.Empty; + if (action.Length == 0 || action.Length > 32) return; + string value = valueAnsi != IntPtr.Zero ? (Marshal.PtrToStringAnsi(valueAnsi) ?? string.Empty) : string.Empty; + Runtime.Plugin?.ApplyRemoteCommand(action, value); + } + catch { /* never let a managed exception cross the native boundary */ } + } // Inventory change triggers (the scan's poll catches the rest, e.g. moves from a corpse). [UnmanagedCallersOnly(EntryPoint = "RynthPluginOnCreateObject", CallConvs = new[] { typeof(CallConvCdecl) })] diff --git a/Plugins/RynthCore.Plugin.RynthInventory/RynthCore.Plugin.RynthInventory.csproj b/Plugins/RynthCore.Plugin.RynthInventory/RynthCore.Plugin.RynthInventory.csproj index e450edf..2e6da18 100644 --- a/Plugins/RynthCore.Plugin.RynthInventory/RynthCore.Plugin.RynthInventory.csproj +++ b/Plugins/RynthCore.Plugin.RynthInventory/RynthCore.Plugin.RynthInventory.csproj @@ -39,8 +39,10 @@ - - + + + + diff --git a/Plugins/RynthCore.Plugin.RynthInventory/RynthInventoryPlugin.cs b/Plugins/RynthCore.Plugin.RynthInventory/RynthInventoryPlugin.cs index 41a94e2..a82aa53 100644 --- a/Plugins/RynthCore.Plugin.RynthInventory/RynthInventoryPlugin.cs +++ b/Plugins/RynthCore.Plugin.RynthInventory/RynthInventoryPlugin.cs @@ -7,6 +7,7 @@ using RynthCore.Plugin.RynthInventory.Data; using RynthCore.Plugin.RynthInventory.Scanning; using RynthCore.Plugin.RynthInventory.Ui; using RynthCore.Plugin.RynthInventory.Views; +using RynthCore.Plugin.Shared; using RynthCore.PluginCore; using RynthCore.PluginSdk; @@ -17,7 +18,9 @@ namespace RynthCore.Plugin.RynthInventory; /// (like Virindi Global Inventory). Each client scans the character it is logged into (a full /// scan after login, then whenever the inventory changes, debounced) and writes one file per /// character per server; storage the character opens (house storage, banks, vaults) is -/// recorded when it is opened. /ginv opens a window that merges every file. +/// recorded when it is opened, and storage another plugin reads for it (a server plugin's +/// server-side store, through Plugins/Shared/StorageFeed.cs) when that arrives. /ginv opens a +/// window that merges every file. /// /// Everything runs on the plugin pump (OnTick and the events the engine drains into it) /// except OnChatBarEnter, which the engine may call on AC's thread: it only queues the @@ -26,7 +29,14 @@ namespace RynthCore.Plugin.RynthInventory; /// public sealed class RynthInventoryPlugin : RynthPluginBase { - public const string Version = "0.1.0"; + // Previous release: 0.1.0. Keep in step with PluginExports.GetVersion. + public const string Version = "0.1.1"; + + // RynthILT's bank JSON: every BankTabReadMs on the Banking tab, every BankIdleReadMs with the + // window on another tab (so the Banking button appears on ILT worlds), never with it closed. + private const long BankTabReadMs = 2000, BankIdleReadMs = 10_000; + private long _nextBankReadMs; + private string _bankJson = string.Empty; private const long IdentityRetryMs = 1000; private const long AccountWaitMs = 15_000; @@ -47,10 +57,12 @@ public sealed class RynthInventoryPlugin : RynthPluginBase private InventoryView? _view; private readonly ConcurrentQueue _commands = new(); - // The Aelrynth account vault (/mule-data), read a few seconds after login and every VaultRefreshMs. - private const long VaultFirstAskMs = 8_000, VaultRefreshMs = 10 * 60_000; - private VaultFeed? _vault; - private long _nextVaultAskMs; + // Storage other plugins read for us ("storage" plugin commands, StorageFeed.cs): queued by + // ApplyRemoteCommand (any thread), filed on the tick once the character is known. Aelrynth's + // account vault comes this way from RynthAelrynth (it was read here until 2026-10-20). + private readonly ConcurrentQueue _storagePushes = new(); + private const int MaxQueuedPushes = 8; + private string _lastPush = string.Empty; private bool _identityKnown; private long _loginMs; @@ -86,8 +98,8 @@ public sealed class RynthInventoryPlugin : RynthPluginBase _c.RequestRescan = () => { _scheduler.RequestFullScan(); _forceWrite = true; }; _c.RequestReload = () => { _reloadWanted = true; _files.Clear(); }; _c.Forget = ForgetCharacter; + _c.BankCommand = SendBankVerb; _ui.Log = msg => Host.Log(msg); - _vault = new VaultFeed(text => Host.InvokeChatParser(text)); _view = new InventoryView(_c); // No bar button of its own: opened from the engine Inventory window's GInv button, the @@ -115,17 +127,50 @@ public sealed class RynthInventoryPlugin : RynthPluginBase _c.LastSavedUtc = default; _c.LastSaveError = string.Empty; _scanner.Reset(); - _vault?.Reset(); - _nextVaultAskMs = 0; CloseStorage(); _lastViewed = 0; _lastWriteMs = 0; _carriedIds.Clear(); _carriedPacks.Clear(); RefreshIconSupport(); + ClearBank(); if (_window != null) { _window.Visible = _c.Settings.MainWindowOpen; _window.NeedsPass = true; } } + /// Forgets the last bank read (login, logout): the next character's comes fresh. + private void ClearBank() + { + _c.Bank = Shared.IltBankView.None; + _bankJson = string.Empty; + _nextBankReadMs = 0; + } + + /// The Banking tab's actions: a verb line for RynthILT, then a quick re-read for its reply. + private bool SendBankVerb(string verb) + { + long now = Environment.TickCount64; + bool ok = _c.InWorld && _c.IltData.BankCommand(Host, now, verb); + _nextBankReadMs = now + 500; + if (_window != null) _window.NeedsPass = true; + return ok; + } + + /// + /// Reads RynthILT's bank JSON while the window is open (more often on the Banking tab) and + /// redraws when it changed. Reading is what tells RynthILT someone is looking. + /// + private void TickBank(long now) + { + if (!_c.InWorld || _window == null || _view == null || !_window.Visible) return; + if (now < _nextBankReadMs) return; + _nextBankReadMs = now + (_view.Tab == InventoryView.TabBanking ? BankTabReadMs : BankIdleReadMs); + string json = _c.IltData.ReadBank(Host, now); + if (string.Equals(json, _bankJson, StringComparison.Ordinal)) return; + _bankJson = json; + _c.Bank = Shared.IltBankView.Parse(json); + _window.NeedsPass = true; + } + public override void OnLogout() { // Last word for this character: write what it has now (also refreshes its "scanned" time). @@ -138,6 +183,9 @@ public sealed class RynthInventoryPlugin : RynthPluginBase _ui.SubmitEmpty(Host); _c.Live = null; _indexDirty = true; + ClearBank(); + while (_storagePushes.TryDequeue(out _)) { } // the next character's come fresh + _lastPush = string.Empty; } public override void Shutdown() @@ -226,11 +274,6 @@ public sealed class RynthInventoryPlugin : RynthPluginBase case "keep": KeepOpenContainer(); break; - case "vault": - if (_vault == null || !Host.HasInvokeChatParser) { _c.Print("This engine can't send commands for the plugin, so the vault can't be read."); break; } - _nextVaultAskMs = Environment.TickCount64 + VaultRefreshMs; - _c.Print(_vault.Ask(Environment.TickCount64, force: true) ? "Reading the vault (/mule-data)..." : "The vault is already being read: " + _vault.Describe()); - break; case "reload": _reloadWanted = true; _files.Clear(); @@ -239,9 +282,16 @@ public sealed class RynthInventoryPlugin : RynthPluginBase case "status": PrintStatus(); break; + case "bank": + case "banking": + // The Banking tab: every character's Infinite Leaftide bank (RynthILT's data). Shows, never toggles off. + _view?.ShowBanking(); + _nextBankReadMs = 0; + if (_window != null) { _window.Visible = true; _window.NeedsPass = true; } + break; case "help": case "?": - _c.Print("/ginv (window), /ginv (search), /ginv scan (rescan and save now), /ginv keep (record the open container as storage), /ginv vault (read the Aelrynth account vault now), /ginv reload, /ginv status"); + _c.Print("/ginv (window), /ginv (search), /ginv bank (every character's Infinite Leaftide bank), /ginv scan (rescan and save now), /ginv keep (record the open container as storage), /ginv reload, /ginv status"); break; default: _view?.SetSearch(arg); @@ -261,7 +311,7 @@ public sealed class RynthInventoryPlugin : RynthPluginBase int items = _c.Live?.Items.Count ?? 0, storage = _c.Live?.Storage.Count ?? 0; string saved = _c.LastSavedUtc == default ? "not saved yet" : "saved " + InventoryIndex.Age(_c.LastSavedUtc, DateTime.UtcNow); _c.Print($"{who}: {items} items carried, {storage} storage container(s), {saved}. {_c.Index?.Characters.Count ?? 0} characters in {_c.Store.Root}."); - if (_vault != null) _c.Print("Aelrynth vault: " + _vault.Describe() + "."); + if (_lastPush.Length > 0) _c.Print("From other plugins: " + _lastPush + "."); if (_c.LastSaveError.Length > 0) _c.Print("Last save failed: " + _c.LastSaveError); } @@ -309,6 +359,7 @@ public sealed class RynthInventoryPlugin : RynthPluginBase } TickWrite(now); TickIndex(now); + TickBank(now); if (!Host.HasUi || _window == null || _view == null) return; Record(_window, now, 2000, _view.Draw); @@ -345,48 +396,42 @@ public sealed class RynthInventoryPlugin : RynthPluginBase if (_openStorage != 0 && now >= _nextStorageScanMs) ScanStorage(now, final: false); - TickVault(now); + TickStoragePushes(now); } - // ── The account vault ─────────────────────────────────────────────────── + // ── Storage from other plugins ────────────────────────────────────────── /// - /// Asks the server for the vault after login and now and then, and files what comes back with the - /// character's storage (one record, the same id on every character of the account). + /// RynthPluginApplyRemoteCommand: "storage" (StorageFeed.Action) carries a whole store another + /// plugin read. Any thread: the payload is only queued (the newest few). /// - private void TickVault(long now) + internal void ApplyRemoteCommand(string action, string value) { - VaultFeed? v = _vault; - if (v == null || _c.Live == null || !Host.HasInvokeChatParser) return; - - if (_nextVaultAskMs == 0) _nextVaultAskMs = now + VaultFirstAskMs; - else if (now >= _nextVaultAskMs && v.Status != VaultFeed.State.Unsupported) - { - _nextVaultAskMs = now + VaultRefreshMs; - v.Ask(now); - } - - v.Tick(now, _c.Account); - if (v.TakeChanged() && v.Record != null) FileVault(v.Record, now); + if (!action.Equals(StorageFeed.Action, StringComparison.OrdinalIgnoreCase) || value.Length == 0 || value.Length > StorageFeed.MaxJsonLength) return; + _storagePushes.Enqueue(value); + while (_storagePushes.Count > MaxQueuedPushes && _storagePushes.TryDequeue(out _)) { } } - private void FileVault(StorageRecord vault, long now) + /// Files what other plugins sent, once the character (and so its storage) is known. Plugin tick. + private void TickStoragePushes(long now) { if (_c.Live == null) return; - var storage = new List(_c.Live.Storage); - int i = storage.FindIndex(s => s.Id == vault.Id); - if (i >= 0) storage[i] = vault; else storage.Add(vault); - CharacterSnapshot snap = NewSnapshot(_c.Live.Items, storage); - snap.ScannedUtc = _c.Live.ScannedUtc; - _c.Live = snap; - _indexDirty = true; - _scheduler.ContentChanged(now, snap.ContentHash()); - } - - // May run on AC's thread: the feed only queues. - public override void OnChatWindowText(string? text, int chatType, ref int eat) - { - if (eat == 0 && _vault != null && _vault.ShouldEat(text, chatType)) eat = 1; + while (_storagePushes.TryDequeue(out string? json)) + { + StorageFeedRecord? feed = StorageFeed.Parse(json, out string error); + if (feed == null) + { + Host.Log("[RynthInventory] storage from another plugin refused: " + error); + continue; + } + StorageRecord record = ExternalStorage.ToRecord(feed, DateTime.UtcNow); + CharacterSnapshot snap = NewSnapshot(_c.Live.Items, ExternalStorage.FileInto(_c.Live.Storage, record)); + snap.ScannedUtc = _c.Live.ScannedUtc; + _c.Live = snap; + _indexDirty = true; + _scheduler.ContentChanged(now, snap.ContentHash()); + _lastPush = $"{record.Label} ({record.Items.Count} item(s)) at {DateTime.Now:HH:mm}"; + } } private void StartCharacter(long now, uint player, string server, string account, string character) diff --git a/Plugins/RynthCore.Plugin.RynthInventory/Views/BankingTab.cs b/Plugins/RynthCore.Plugin.RynthInventory/Views/BankingTab.cs new file mode 100644 index 0000000..e3ab000 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthInventory/Views/BankingTab.cs @@ -0,0 +1,237 @@ +using System; +using System.Collections.Generic; +using System.Globalization; +using RynthCore.Plugin.RynthInventory.Data; +using RynthCore.Plugin.RynthInventory.Ui; +using RynthCore.Plugin.Shared; + +namespace RynthCore.Plugin.RynthInventory.Views; + +/// +/// Banking: the Infinite Leaftide bank of every character on this server (the Mini Remote's Banking +/// tab moved here 2026-10-13). Balances, form choices and the last reply come from RynthILT's +/// "RynthILT.Data" bank JSON; the character list adds the inventory's characters on the same server +/// (BankRoster). Deposits, withdrawals, transfers and balance reads go back to RynthILT as verb lines; +/// a transfer is confirmed here first (RynthILT doesn't ask again). +/// +internal sealed partial class InventoryView +{ + private const int MaxTransactionsShown = 20; + private const float ColPyreals = 150f, ColLum = 270f, ColKeys = 380f, ColCoins = 450f, ColUpdated = 560f; + + private int _depositIndex, _withdrawIndex, _withdrawNote, _transferIndex, _transferNote; + private string _withdrawAmount = string.Empty, _transferAmount = string.Empty, _transferTo = string.Empty; + /// The transfer waiting for "Yes, send": its verb line and the sentence shown. + private (string Verb, string Text)? _confirmTransfer; + private string _bankMessage = string.Empty; + + /// + /// The Banking tab button shows when RynthILT answered on an ILT world, or when the tab was asked + /// for (/ginv bank) so it can say what is missing. + /// + private bool BankingShown => Tab == TabBanking || (_c.Bank.Loaded && _c.Bank.Available); + + /// Opens on the Banking tab ("/ginv bank", RynthAi's and RynthILT's bank links). + public void ShowBanking() + { + Tab = TabBanking; + _confirmTransfer = null; + } + + private void DrawBanking(UiWindow w) + { + IltBankView b = _c.Bank; + if (!b.Loaded) + { + w.TextDisabled("The bank comes from RynthILT (Infinite Leaftide). Load RynthILT to see every character's bank here."); + return; + } + if (!b.Available) + { + w.TextDisabled("This isn't an Infinite Leaftide world, so there is no bank to show."); + return; + } + + w.Text($"Bank on {(b.World.Length > 0 ? b.World : "this server")}"); + w.SameLine(); + w.SmallButton("Refresh", "b.refresh", () => SendBank(IltBankView.RefreshVerb(), "Reading the balance...")); + w.Tooltip("A quiet /bank balance read for the character you're on (other characters update when they log in)."); + if (b.Enabled == 0) w.TextColored(UiColors.Red, "This server has no /bank command."); + else if (b.Enabled < 0) w.TextDisabled("Whether this server has /bank isn't known yet."); + if (b.Result.Length > 0) w.TextColored(UiColors.Gold, b.Result); + if (_bankMessage.Length > 0) w.TextColored(UiColors.Yellow, _bankMessage); + + List roster = BankRoster.Build(b, _c.Index); + DrawBankTable(w, roster); + if (b.Enabled != 0) + { + DrawDeposit(w, b); + DrawWithdraw(w, b); + DrawTransfer(w, b, roster); + } + DrawTransactions(w, b); + } + + private void DrawBankTable(UiWindow w, List roster) + { + w.SeparatorText($"Characters ({roster.Count})"); + w.TextDisabled("Character"); + w.SameLine(ColPyreals); w.TextDisabled("Pyreals"); + w.SameLine(ColLum); w.TextDisabled("Luminance"); + w.SameLine(ColKeys); w.TextDisabled("Keys L/M"); + w.SameLine(ColCoins); w.TextDisabled("Coins E/W/P"); + w.SameLine(ColUpdated); w.TextDisabled("Updated"); + foreach (BankRosterEntry e in roster) + { + string name = e.Current ? e.Name + " (you)" : e.Name; + if (e.Bank is { } r) + { + w.Text(name); + if (e.Account.Length > 0) w.Tooltip("Account: " + e.Account); + BankCells(w, r); + w.SameLine(ColUpdated); + w.TextDisabled(r.UpdatedUtc == DateTime.MinValue ? "-" : InventoryIndex.Age(r.UpdatedUtc, _c.UtcNow)); + } + else + { + w.TextDisabled(name); + if (e.Account.Length > 0) w.Tooltip("Account: " + e.Account); + w.SameLine(ColPyreals); + w.TextDisabled("not read yet: log in with RynthILT loaded"); + } + } + if (roster.Count == 0) w.TextDisabled("No characters on this server yet."); + else + { + w.TextColored(UiColors.Gold, "Total"); + BankCells(w, BankRoster.Totals(roster)); + } + } + + /// The balance columns of one row (Pyreals .. Coins). + private static void BankCells(UiWindow w, IltBankRow r) + { + w.SameLine(ColPyreals); w.Text(N(r.Pyreals)); + w.SameLine(ColLum); w.Text(N(r.Luminance)); + w.SameLine(ColKeys); w.Text($"{N(r.LegendaryKeys)}/{N(r.MythicalKeys)}"); + w.SameLine(ColCoins); w.Text($"{N(r.EnlightenedCoins)}/{N(r.WeaklyEnlightenedCoins)}/{N(r.PrestigeCoins)}"); + } + + private void DrawDeposit(UiWindow w, IltBankView b) + { + if (b.Deposits.Count == 0) return; + w.SeparatorText("Deposit"); + _depositIndex = Math.Clamp(_depositIndex, 0, b.Deposits.Count - 1); + w.Combo("What", "b.dep.what", _depositIndex, b.Deposits, i => _depositIndex = i); + w.SameLine(); + int di = _depositIndex; + string label = b.Deposits[di]; + w.SmallButton("Deposit", "b.dep.go", () => SendBank(IltBankView.DepositVerb(di), "Depositing " + label + "...")); + } + + private void DrawWithdraw(UiWindow w, IltBankView b) + { + if (b.Withdrawals.Count == 0) return; + w.SeparatorText("Withdraw"); + _withdrawIndex = Math.Clamp(_withdrawIndex, 0, b.Withdrawals.Count - 1); + w.Combo("Currency", "b.wd.what", _withdrawIndex, Labels(b.Withdrawals), i => _withdrawIndex = i); + IltBankChoice choice = b.Withdrawals[_withdrawIndex]; + w.InputText(choice.Notes ? "Notes" : "Amount", "b.wd.amt", _withdrawAmount, 20, v => _withdrawAmount = v); + int note = NoteCombo(w, b, choice, "b.wd.note", _withdrawNote, i => _withdrawNote = i); + w.SameLine(); + int wi = _withdrawIndex; + w.SmallButton("Withdraw", "b.wd.go", () => + { + long amount = BankRoster.ParseAmount(_withdrawAmount); + if (amount <= 0) { _bankMessage = "Type a whole number to withdraw."; return; } + SendBank(IltBankView.WithdrawVerb(wi, amount, note), $"Withdrawing {N(amount)} {choice.Label}..."); + }); + } + + private void DrawTransfer(UiWindow w, IltBankView b, List roster) + { + if (b.Transfers.Count == 0) return; + w.SeparatorText("Transfer"); + _transferIndex = Math.Clamp(_transferIndex, 0, b.Transfers.Count - 1); + w.Combo("Currency", "b.tx.what", _transferIndex, Labels(b.Transfers), i => { _transferIndex = i; _confirmTransfer = null; }); + IltBankChoice choice = b.Transfers[_transferIndex]; + w.InputText(choice.Notes ? "Notes" : "Amount", "b.tx.amt", _transferAmount, 20, v => { _transferAmount = v; _confirmTransfer = null; }); + int note = NoteCombo(w, b, choice, "b.tx.note", _transferNote, i => { _transferNote = i; _confirmTransfer = null; }); + w.InputText("To", "b.tx.to", _transferTo, 40, v => { _transferTo = v; _confirmTransfer = null; }); + + // The other characters on this server, to fill "To" with one click. + var others = new List { "Pick a character..." }; + foreach (BankRosterEntry e in roster) if (!e.Current) others.Add(e.Name); + if (others.Count > 1) + { + w.SameLine(); + w.Combo("##pick", "b.tx.pick", 0, others, i => { if (i > 0 && i < others.Count) { _transferTo = others[i]; _confirmTransfer = null; } }); + } + + if (_confirmTransfer is { } pending) + { + w.TextColored(UiColors.Red, pending.Text); + w.SmallButton("Yes, send", "b.tx.yes", () => + { + _confirmTransfer = null; + SendBank(pending.Verb, "Transfer sent..."); + }); + w.SameLine(); + w.SmallButton("Cancel", "b.tx.no", () => _confirmTransfer = null); + return; + } + int ti = _transferIndex; + w.SmallButton("Transfer...", "b.tx.go", () => + { + long amount = BankRoster.ParseAmount(_transferAmount); + string to = (_transferTo ?? string.Empty).Trim(); + if (amount <= 0) { _bankMessage = "Type a whole number to transfer."; return; } + if (to.Length == 0) { _bankMessage = "Type (or pick) who gets the transfer."; return; } + string what = choice.Notes && note < b.Notes.Count ? $"{N(amount)} x {b.Notes[note].Label}" : $"{N(amount)} {choice.Label}"; + _confirmTransfer = (IltBankView.TransferVerb(ti, amount, note, to), $"Send {what} to {to}? This can't be undone."); + _bankMessage = string.Empty; + }); + } + + /// + /// The trade-note combo for a choice that counts notes; returns the note index in use (0 when + /// the choice isn't notes). A pick arrives as an event and lands in . + /// + private static int NoteCombo(UiWindow w, IltBankView b, IltBankChoice choice, string id, int index, Action set) + { + if (!choice.Notes || b.Notes.Count == 0) return 0; + var labels = new List(b.Notes.Count); + foreach (IltBankNote n in b.Notes) labels.Add($"{n.Label} ({N(n.Value)} pyreals)"); + index = Math.Clamp(index, 0, b.Notes.Count - 1); + w.Combo("Note", id, index, labels, set); + return index; + } + + private void DrawTransactions(UiWindow w, IltBankView b) + { + if (b.Transactions.Count == 0) return; + if (!w.CollapsingHeader($"Recent transfers ({b.Transactions.Count})", "b.txlog")) return; + int shown = 0; + foreach (IltBankTx t in b.Transactions) + { + if (shown++ >= MaxTransactionsShown) { w.TextDisabled($"...and {b.Transactions.Count - MaxTransactionsShown} more."); break; } + string dir = t.Type.Length > 0 ? t.Type : "?"; + w.Text($"{t.When} {dir} {N(t.Amount)} {t.Currency}{(t.Player.Length > 0 ? " - " + t.Player : "")}"); + } + } + + /// Hands a verb to RynthILT; says so when it was refused. + private void SendBank(string verb, string sending) + { + _bankMessage = _c.BankCommand(verb) ? sending : "RynthILT didn't take that (is it loaded, and are you logged in?)."; + } + + private static List Labels(IReadOnlyList choices) + { + var list = new List(choices.Count); + foreach (IltBankChoice c in choices) list.Add(c.Label); + return list; + } + + private static string N(long n) => n.ToString("N0", CultureInfo.InvariantCulture); +} diff --git a/Plugins/RynthCore.Plugin.RynthInventory/Views/InventoryView.cs b/Plugins/RynthCore.Plugin.RynthInventory/Views/InventoryView.cs index e671018..2ca75ee 100644 --- a/Plugins/RynthCore.Plugin.RynthInventory/Views/InventoryView.cs +++ b/Plugins/RynthCore.Plugin.RynthInventory/Views/InventoryView.cs @@ -8,12 +8,12 @@ namespace RynthCore.Plugin.RynthInventory.Views; /// /// The Global Inventory window: a search page (every character on every server, filters, -/// totals, results, details) and a characters page (snapshot ages, forget). Recorded on the -/// pump thread, replayed by the engine. +/// totals, results, details), a characters page (snapshot ages, forget) and, with RynthILT, a +/// Banking page (Views\BankingTab.cs). Recorded on the pump thread, replayed by the engine. /// -internal sealed class InventoryView +internal sealed partial class InventoryView { - public const int TabSearch = 0, TabCharacters = 1; + public const int TabSearch = 0, TabCharacters = 1, TabBanking = 2; private const int PageSize = 100; private const float RowIcon = 18f, DetailIcon = 32f, DetailsHeight = 190f; @@ -58,10 +58,21 @@ internal sealed class InventoryView w.SameLine(); int chars = _c.Index?.Characters.Count ?? 0; w.ToggleButton($"Characters ({chars})", "tab.chars", Tab == TabCharacters, () => Tab = TabCharacters, small: true); + if (BankingShown) + { + w.SameLine(); + w.ToggleButton("Banking", "tab.bank", Tab == TabBanking, () => Tab = TabBanking, small: true); + } w.SameLine(); w.TextDisabled(StatusLine()); w.Separator(); + // The bank comes from RynthILT, not the inventory files: it draws before they are read. + if (Tab == TabBanking) + { + DrawBanking(w); + return; + } if (_c.Index == null) { w.TextDisabled(_c.Loading ? "Reading the inventory files..." : "No inventory read yet."); @@ -222,6 +233,17 @@ internal sealed class InventoryView private void Select(string key) => _selectedKey = _selectedKey == key ? null : key; + /// + /// Clicking one of the logged-in character's own items also selects it in the game (the bag and + /// the selection panel), as clicking it in the pack would. Another character's item can't be. + /// A problem report asked for this (R-20261016-213300-1737). + /// + private void SelectInGame(InventoryRow? r) + { + if (r == null || !r.Owner.IsCurrentCharacter || r.Item.Id == 0 || !_c.Host.HasSelectItem) return; + _c.Host.SelectItem(r.Item.Id); + } + private void DrawRow(UiWindow w, InventoryRow r) { ItemRecord it = r.Item; @@ -234,7 +256,7 @@ internal sealed class InventoryView string key = RowKey(r); uint? color = !r.Owner.IsCurrentServer ? UiColors.OtherServer : IsStale(r.SeenUtc) ? UiColors.Stale : null; if (color != null) w.PushStyleColor(UiFormat.ColText, color.Value); - w.Selectable(label, "r." + key, _selectedKey == key, () => Select(key), 0f, icons ? RowIcon : 0f); + w.Selectable(label, "r." + key, _selectedKey == key, () => { Select(key); SelectInGame(r); }, 0f, icons ? RowIcon : 0f); if (color != null) w.PopStyleColor(); } @@ -245,7 +267,9 @@ internal sealed class InventoryView string label = $"{t.Name} x{t.Count.ToString("N0", CultureInfo.InvariantCulture)} - {t.Characters} character{(t.Characters == 1 ? "" : "s")}"; if (t.Servers > 1) label += $", {t.Servers} servers"; string key = GroupKey(t); - w.Selectable(label, "g." + key, _selectedKey == key, () => Select(key), 0f, icons ? RowIcon : 0f); + // A total across characters: select the logged-in character's own stack, if it has one. + w.Selectable(label, "g." + key, _selectedKey == key, + () => { Select(key); SelectInGame(t.Holders.Find(h => h.Owner.IsCurrentCharacter)); }, 0f, icons ? RowIcon : 0f); } /// diff --git a/Plugins/RynthCore.Plugin.RynthNav/AutoRunGate.cs b/Plugins/RynthCore.Plugin.RynthNav/AutoRunGate.cs new file mode 100644 index 0000000..2160244 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthNav/AutoRunGate.cs @@ -0,0 +1,76 @@ +using System; + +namespace RynthCore.Plugin.RynthNav; + +// Autorun and stops sent when they change, not every tick (2026-10-19). The goto sent +// SetAutoRun(False) every tick while it settled after a teleport, turned in place or stood at a +// portal, SetAutoRun(True) every tick while it ran, and SetAutoRun(False) + StopCompletely every +// tick while it held in the Town Network: about 55 calls a second. The plugin tick isn't AC's main +// thread, so every call takes a slot in the engine's action ring (256), and the ring is held +// through portal space. On a recall + Town Network trip (Matron Hive East, 10-19 16:38-16:40) it +// filled: 1,204 queued actions refused (anyone's, not only ours), 256 stale stops run 12 s late. +// Now a change goes out at once, "on" is sent again every ReassertMs (a cast, a stance change or a +// server stop turns autorun off without telling us; RynthAi's nav re-asserts the same way), and +// "off" and a halt go out once. A call the engine refuses isn't taken as sent: it is tried again +// after RetryMs, not every tick. Stop() is for a goto's start and end and a teleport: it always sends. +internal sealed class AutoRunGate +{ + public const long ReassertMs = 500; + public const long RetryMs = 250; + + private readonly Func _setAutoRun; + private readonly Func _stopCompletely; + private readonly Func _now; + + private int _run = -1; // the last SetAutoRun that went through: 1 on, 0 off, -1 not known + private long _runMs; // when it went through + private bool _halted; // a StopCompletely went through and nothing has started since + private long _retryAtMs; // a call was refused: nothing but Stop() before this + + public AutoRunGate(Func setAutoRun, Func stopCompletely, Func now) + { + _setAutoRun = setAutoRun; + _stopCompletely = stopCompletely; + _now = now; + } + + /// Autorun on or off: sent when it's a change, and "on" again every ReassertMs. + public void Run(bool on) + { + long now = _now(); + int want = on ? 1 : 0; + if (want == _run && !(on && now - _runMs >= ReassertMs)) return; + if (now < _retryAtMs) return; + bool ok = _setAutoRun(on); + _run = ok ? want : -1; + _runMs = now; + if (ok && on) _halted = false; + _retryAtMs = ok ? 0 : now + RetryMs; + } + + /// Autorun off and StopCompletely, unless that's what was sent last. + public void Halt() + { + if (_halted) return; + if (_now() < _retryAtMs) return; + Stop(); + } + + /// Autorun off and StopCompletely, always (a goto's start and end, a teleport). + public void Stop() + { + long now = _now(); + bool off = _setAutoRun(false); + bool stopped = _stopCompletely(); + _run = off ? 0 : -1; + _runMs = now; + _halted = off && stopped; + _retryAtMs = _halted ? 0 : now + RetryMs; + } + + /// What the client has on isn't known any more (a new goto: the d-pad or another plugin may have moved it). + public void Forget() + { + _run = -1; _runMs = 0; _halted = false; _retryAtMs = 0; + } +} diff --git a/Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.PortalAim.cs b/Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.PortalAim.cs index acc0e52..adc9e70 100644 --- a/Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.PortalAim.cs +++ b/Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.PortalAim.cs @@ -106,7 +106,7 @@ public sealed partial class RynthNavPlugin // 20:42). Within PortalUseUnits with the live portal seen: stand still and use it every 3 s. if (_portalLiveId != 0 && Host.HasUseObject && d <= PortalUseUnits) { - Host.SetAutoRun(false); + AutoRun.Run(false); if (now - _portalLastUseMs > 3000) { _portalLastUseMs = now; diff --git a/Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.Settle.cs b/Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.Settle.cs index 879f6b4..6d41b49 100644 --- a/Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.Settle.cs +++ b/Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.Settle.cs @@ -22,7 +22,7 @@ public sealed partial class RynthNavPlugin _settleJumpMs = NowMs; _settleQuietSince = 0; _settleSawPortal = Host.HasIsPortaling && Host.IsPortaling(); - Host.SetAutoRun(false); + AutoRun.Run(false); lock (_gate) _status = "arriving…"; } @@ -30,7 +30,7 @@ public sealed partial class RynthNavPlugin { long now = NowMs; bool portaling = Host.HasIsPortaling && Host.IsPortaling(); - Host.SetAutoRun(false); + AutoRun.Run(false); if (portaling) { _settleSawPortal = true; diff --git a/Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.TownNet.cs b/Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.TownNet.cs index edcfe69..3d7d5f3 100644 --- a/Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.TownNet.cs +++ b/Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.TownNet.cs @@ -110,11 +110,7 @@ public sealed partial class RynthNavPlugin private double LocalX => _wx - ((_cellId >> 24) & 0xFF) * 192.0; private double LocalY => _wy - ((_cellId >> 16) & 0xFF) * 192.0; - private void HubHalt() - { - Host.SetAutoRun(false); - Host.StopCompletely(); - } + private void HubHalt() => AutoRun.Halt(); /// One tick of a hub step: wait for the landing inside, walk to the exit, take it. private void StepHub() diff --git a/Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.Travel.cs b/Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.Travel.cs index 5668df3..5242055 100644 --- a/Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.Travel.cs +++ b/Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.Travel.cs @@ -726,7 +726,7 @@ public sealed partial class RynthNavPlugin _recallWandTried = false; _recallChangedStance = false; _recallSent = false; _recallWasPortaling = false; _recallPreLb = CurrentLandblock; _recallPreWx = _wx; _recallPreWy = _wy; BeginWand(); - Host.SetAutoRun(false); Host.StopCompletely(); + AutoRun.Stop(); RecallOption? o = CurrentRecallOption(); lock (_gate) _status = o == null ? "recall step: unknown recall" : $"recalling: {o.Name}"; Host.Log($"[RynthNav] recall step: {o?.Name ?? "?"}"); @@ -758,7 +758,7 @@ public sealed partial class RynthNavPlugin Host.Log($"[RynthNav] recall {o.Name}: teleported (moved {moved:F0}u)"); _lastLandMs = NowMs; EndRecall(); - Host.SetAutoRun(false); Host.StopCompletely(); + AutoRun.Stop(); RefreshTiles(CurrentLandblock); BeginSettle(); return; diff --git a/Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.Turn.cs b/Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.Turn.cs index 1bbdeab..4a0b565 100644 --- a/Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.Turn.cs +++ b/Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.Turn.cs @@ -42,9 +42,13 @@ public sealed partial class RynthNavPlugin double next = current + Math.Clamp(error, -maxStep, maxStep); Host.TurnToHeading((float)(((next % 360.0) + 360.0) % 360.0)); } - Host.SetAutoRun(!_turnInPlace); + AutoRun.Run(!_turnInPlace); } + // SetAutoRun/StopCompletely for the goto, sent when they change (AutoRunGate.cs). + private AutoRunGate? _autoRun; + private AutoRunGate AutoRun => _autoRun ??= new AutoRunGate(on => Host.SetAutoRun(on), () => Host.StopCompletely(), () => NowMs); + /// A fresh start for the turn servo (a new goto, a teleport). private void ResetTurn() { _turnInPlace = false; _lastTurnMs = 0; } } diff --git a/Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.cs b/Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.cs index 25c8853..bb7505b 100644 --- a/Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.cs +++ b/Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.cs @@ -440,7 +440,7 @@ public sealed partial class RynthNavPlugin : RynthPluginBase // A new goto (not the re-plan after "no route over land") may re-plan once again. if (!landReplan) { _landReplanned = false; _enterPortal = enter.Length > 0 ? _nextEnterPortal : ""; _nextEnterPortal = ""; } // Whatever was running stops first: a refused goto must not leave the old one half-changed. - if (_gotoActive) { _gotoActive = false; _route = null; _portalWait = false; ResetHub(); Host.SetAutoRun(false); Host.StopCompletely(); HideMarkers("a new goto"); } + if (_gotoActive) { _gotoActive = false; _route = null; _portalWait = false; ResetHub(); AutoRun.Stop(); HideMarkers("a new goto"); } double twx = NavCoords.WorldX(tew), twy = NavCoords.WorldY(tns); int gLbX = (int)Math.Floor(twx / 192.0), gLbY = (int)Math.Floor(twy / 192.0); if (double.IsNaN(twx) || double.IsNaN(twy) || gLbX < 0 || gLbX > 255 || gLbY < 0 || gLbY > 255) @@ -524,6 +524,7 @@ public sealed partial class RynthNavPlugin : RynthPluginBase Say($"goto: the target's landblock 0x{goalLb:X4} has no tile; walking as far as the navmesh goes"); SetTrip(_route, name, tns, tew, recalls, enter, live: true); + AutoRun.Forget(); // the d-pad or another plugin may have moved since: the first call goes out _gotoActive = true; _gotoName = name; _gotoType = type; _walkHaveLast = false; @@ -624,14 +625,14 @@ public sealed partial class RynthNavPlugin : RynthPluginBase // A teleport on a walking leg is never planned: a portal we touched by accident. Stop. bool portalingNow = Host.HasIsPortaling && Host.IsPortaling(); double jump = _walkHaveLast ? Math.Sqrt((_wx - _walkLastWx) * (_wx - _walkLastWx) + (_wy - _walkLastWy) * (_wy - _walkLastWy)) : 0; - if (portalingNow && !_walkHaveLast) { Host.SetAutoRun(false); return; } // still arriving from the last step's teleport + if (portalingNow && !_walkHaveLast) { AutoRun.Run(false); return; } // still arriving from the last step's teleport // The client can show portal space a second or more AFTER the position jump that ended a // recall or portal step (seen live: @lifestone jumped at 19:45:11, portal space began at // 19:45:12). That portal space is the step's own: wait it out, and count the landing from // its end, rather than calling it a stray portal. if (portalingNow && NowMs - _lastLandMs < SettleAfterTeleportMs) { - Host.SetAutoRun(false); + AutoRun.Run(false); _walkHaveLast = false; _lastLandMs = NowMs; return; @@ -701,7 +702,7 @@ public sealed partial class RynthNavPlugin : RynthPluginBase if (_coarseHoldTicks > 0 && _coarse == null && _gotoActive) { _coarseHoldTicks--; - Host.SetAutoRun(false); + AutoRun.Run(false); lock (_gate) _status = "planning the way…"; return; } @@ -740,7 +741,7 @@ public sealed partial class RynthNavPlugin : RynthPluginBase } else if (_blindTicks++ == BlindPushTicks) { - Host.SetAutoRun(false); + AutoRun.Run(false); } return; } @@ -818,7 +819,7 @@ public sealed partial class RynthNavPlugin : RynthPluginBase ResetHub(); _avoid.Clear(); _coarseHoldTicks = 0; ResetBlocked(); - Host.SetAutoRun(false); Host.StopCompletely(); + AutoRun.Stop(); lock (_gate) _status = status; Host.Log($"[RynthNav] goto: {status}"); Say(status == "arrived" && _gotoName.Length > 0 ? $"goto: arrived at {_gotoName}" : $"goto: {status}"); @@ -841,7 +842,7 @@ public sealed partial class RynthNavPlugin : RynthPluginBase if (teleported) { - Host.SetAutoRun(false); Host.StopCompletely(); + AutoRun.Stop(); _portalWait = false; _lastLandMs = NowMs; Host.Log($"[RynthNav] teleport detected (lb 0x{_prePortalLb:X4}->0x{CurrentLandblock:X4}, moved {moved:F0}u) — next leg"); @@ -871,7 +872,7 @@ public sealed partial class RynthNavPlugin : RynthPluginBase double away = Math.Atan2(-dew, -dns) * 180.0 / Math.PI; DriveTo(away); } - else { Host.SetAutoRun(false); Host.StopCompletely(); } + else AutoRun.Halt(); _portalWaitTicks = 0; _portalTryStartMs = NowMs; // the cooldown isn't a failed try if (!_cooldownSaid) { _cooldownSaid = true; Host.Log($"[RynthNav] waiting {(PortalCooldownMs - sinceTeleport) / 1000.0:F1} s before the portal (teleported {sinceTeleport} ms ago)"); } diff --git a/Plugins/RynthCore.Plugin.RynthOracle/Data/ChatRequest.cs b/Plugins/RynthCore.Plugin.RynthOracle/Data/ChatRequest.cs deleted file mode 100644 index 1da2d80..0000000 --- a/Plugins/RynthCore.Plugin.RynthOracle/Data/ChatRequest.cs +++ /dev/null @@ -1,24 +0,0 @@ -// Ported from Oracle of Dereth by Advis Eveldan (advis61), MIT. See THIRD_PARTY_NOTICES.md. -namespace RynthCore.Plugin.RynthOracle.Data; - -/// -/// RynthOracle sent a server command and expects its reply for a few seconds, so the chat -/// handler can tell its own reply from the same command typed by hand (only ours may be hidden). -/// A time window, as upstream: these replies carry nothing tying them to the request. Each line -/// of the reply extends it, so a long reply stays ours to its end. -/// -internal sealed class ChatRequest -{ - private const long WindowMs = 5000; - private long _untilMs; - - public void Sent(long nowMs) => _untilMs = nowMs + WindowMs; - public void Clear() => _untilMs = 0; - public bool Awaiting(long nowMs) => nowMs < _untilMs; - - /// A reply line arrived: keep the window open a little longer. - public void Extend(long nowMs) - { - if (Awaiting(nowMs)) _untilMs = nowMs + 2000 > _untilMs ? nowMs + 2000 : _untilMs; - } -} diff --git a/Plugins/RynthCore.Plugin.RynthOracle/Data/DynamicStamps.cs b/Plugins/RynthCore.Plugin.RynthOracle/Data/DynamicStamps.cs new file mode 100644 index 0000000..d504d52 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthOracle/Data/DynamicStamps.cs @@ -0,0 +1,170 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; + +namespace RynthCore.Plugin.RynthOracle.Data; + +/// +/// One Infinite Leaftide Dynamic Stamp (dynstamps.csv): an NPC hand-in that puts a +/// "Dynamic_N_..." quest flag on the character. List from the players' "ExtraDyn" sheet +/// (10.13.2026, one sheet per area, the wiki's Dynamic Stamps page); NPCs that give no stamp +/// are left out. A stamp is a one-time flag: having it in /myquests means it's done. +/// +internal sealed class DynamicStamp +{ + public string Area = ""; + /// Where in the area (a town, a dungeon, coordinates), or "". + public string Place = ""; + public string Npc = ""; + /// What the NPC gives back (the sheet's "X gives you Y"), or "". + public string Reward = ""; + /// The quest flag, lower case (as QuestFlagStore keys it). + public string Stamp = ""; + public string Note = ""; + + /// The NPC, else the place (a few sheet rows only name the spot). + public string Label => Npc.Length > 0 ? Npc : Place; + + /// + /// The flag this character has for the stamp, or null. The sheet has a few stamps copied + /// without their closing "!" or cut short: those also match with "!" added and, when at + /// least long, the one Dynamic flag on the character starting + /// with them. + /// + public string? MatchedFlag(QuestFlagStore flags) + { + if (flags.TryGet(Stamp, out _)) return Stamp; + if (Stamp.EndsWith('!')) return null; + if (flags.TryGet(Stamp + "!", out _)) return Stamp + "!"; + if (Stamp.Length < MinPrefixLength) return null; + string? only = null; + foreach (string key in flags.Flags.Keys) + { + if (!key.StartsWith(Stamp, StringComparison.OrdinalIgnoreCase)) continue; + if (only != null) return null; // more than one: can't tell which + only = key; + } + return only; + } + + public bool Have(QuestFlagStore flags) => MatchedFlag(flags) != null; + + // Sheet areas that are groupings, not places on the map. + private static readonly HashSet NotPlaces = new(StringComparer.OrdinalIgnoreCase) + { + "Looking Around", "Odd Stamps", "Odd Stamps 2", + }; + + /// + /// Where RynthNav should go for this stamp, best first (RynthNav takes the first that is on its + /// map): the coordinates in the note or the place, the place and its parts ("Mhoire Castle - + /// Great Hall" also tries "Mhoire Castle"), the NPC, then the area. Empty when there is nothing. + /// + public List NavCandidates() + { + var list = new List(); + void Add(string s) + { + s = s.Trim().Trim('.', ',', ';', ':').Trim(); + if (s.Length >= 4 && !char.IsDigit(s[0]) && !list.Contains(s, StringComparer.OrdinalIgnoreCase)) list.Add(s); + } + + foreach (string text in new[] { Note, Place }) + if (NavTargets.FirstCoords(text) is string c && !list.Contains(c)) list.Add(c); + + string place = NavTargets.WithoutCoords(Place); + place = System.Text.RegularExpressions.Regex.Replace(place, @"\b(at|in the|nearby)\b", " ", System.Text.RegularExpressions.RegexOptions.IgnoreCase); + place = System.Text.RegularExpressions.Regex.Replace(place, @"\s+", " ").Trim(); + Add(place); + foreach (string part in place.Split(new[] { " - ", " / ", "(", ")" }, StringSplitOptions.RemoveEmptyEntries)) + Add(part); + Add(Npc); + if (!NotPlaces.Contains(Area)) Add(Area); + return list; + } + + /// A truncated stamp shorter than this is matched exactly only (too many flags share a short stem). + public const int MinPrefixLength = 14; +} + +internal static class DynamicStampList +{ + /// Dynamic stamp quest flags start with this (lower case). + public const string FlagPrefix = "dynamic_"; + + public static List All { get; } = Load(); + + /// The areas in list order (Facility Hub, Looking Around, ...). + public static List Areas { get; } = BuildAreas(); + + /// + /// Dynamic stamps on this character that the list doesn't have (new or unlisted NPCs), so the + /// tab can show them and the count isn't only what the sheet knows. + /// + public static List Unlisted(QuestFlagStore flags) + { + var matched = new HashSet(StringComparer.OrdinalIgnoreCase); + foreach (DynamicStamp s in All) + if (s.MatchedFlag(flags) is string f) matched.Add(f); + var extra = new List(); + foreach (string key in flags.Flags.Keys) + if (key.StartsWith(FlagPrefix, StringComparison.OrdinalIgnoreCase) && !matched.Contains(key)) + extra.Add(key); + extra.Sort(StringComparer.OrdinalIgnoreCase); + return extra; + } + + private static List Load() + { + try + { + using StreamReader r = Csv.OpenEmbedded("dynstamps.csv"); + return Parse(r); + } + catch (Exception) + { + // A missing or unreadable list must not take the Quests page down with it. + return new List(); + } + } + + /// + /// Reads a dynstamps.csv (a header row, then one NPC hand-in a row). A row whose stamp isn't a + /// "dynamic_" flag, or repeats one already read, is skipped; a missing column reads as empty. + /// Internal for the tests. + /// + internal static List Parse(TextReader r) + { + var list = new List(); + Dictionary col = Csv.MapColumns(r.ReadLine() ?? ""); + int cArea = Csv.Column(col, "Area"), cPlace = Csv.Column(col, "Place"), cNpc = Csv.Column(col, "Npc"), + cReward = Csv.Column(col, "Reward"), cStamp = Csv.Column(col, "Stamp"), cNote = Csv.Column(col, "Note"); + var seen = new HashSet(StringComparer.OrdinalIgnoreCase); + while (r.ReadLine() is string line) + { + if (string.IsNullOrWhiteSpace(line)) continue; + string[] f = Csv.ParseLine(line); + string stamp = Csv.Field(f, cStamp).Trim().ToLowerInvariant(); + if (!stamp.StartsWith(FlagPrefix, StringComparison.Ordinal) || !seen.Add(stamp)) continue; + list.Add(new DynamicStamp + { + Area = Csv.Field(f, cArea), + Place = Csv.Field(f, cPlace), + Npc = Csv.Field(f, cNpc), + Reward = Csv.Field(f, cReward), + Stamp = stamp, + Note = Csv.Field(f, cNote), + }); + } + return list; + } + + private static List BuildAreas() + { + var areas = new List(); + foreach (DynamicStamp s in All) + if (!areas.Contains(s.Area)) areas.Add(s.Area); + return areas; + } +} diff --git a/Plugins/RynthCore.Plugin.RynthOracle/Data/IltServerProfile.cs b/Plugins/RynthCore.Plugin.RynthOracle/Data/IltServerProfile.cs new file mode 100644 index 0000000..38bc2ef --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthOracle/Data/IltServerProfile.cs @@ -0,0 +1,232 @@ +using System; +using System.Collections.Generic; +using System.Globalization; +using System.Text; +using System.Text.Json; +using RynthCore.Plugin.Shared; +using RynthCore.PluginSdk; + +namespace RynthCore.Plugin.RynthOracle.Data; + +/// One Leaftide feature from RynthILT's profile: its state on this server and where it lives. +internal sealed record IltFeature(string Key, string Label, string Group, int State, string Where); + +/// +/// The ACECustom quest bonus list ("/qb list") as RynthILT last read it (the profile's "questBonus" +/// object). 0 = not loaded this session; -1 = unknown. +/// +internal sealed record IltQuestBonusList(bool Disabled, int Generation, long Count, string Status, + IReadOnlyList Completed, IReadOnlyList Incomplete); + +/// +/// What RynthILT reports about the Infinite Leaftide server (the "RynthILT.Server" profile JSON, +/// Plugins/Shared/RynthIltServerApi.cs): whether this is an ILT world, the Leaftide features with +/// their server state, and the fellowship rules. without RynthILT; every field is +/// read leniently so an older or newer RynthILT still parses. +/// +internal sealed class IltServerProfile +{ + /// No RynthILT (or nothing parsed): a retail fellowship and no features. + public static readonly IltServerProfile None = new(); + + /// RynthILT answered with a profile. + public bool Available { get; private init; } + public bool Ilt { get; private init; } + public string World { get; private init; } = ""; + public bool Forced { get; private init; } + public string Source { get; private init; } = ""; + /// Last server-options check (UTC); MinValue = never. + public DateTime CheckedUtc { get; private init; } = DateTime.MinValue; + public IReadOnlyList Features { get; private init; } = Array.Empty(); + + /// The server's fellowship size limit (retail 9 without RynthILT or off ILT). + public int FellowshipMax { get; private init; } = RynthIltServer.RetailFellowshipMax; + /// Fellowship feature states (RynthIltServer.State*): Zone Share, Fellowship Blackjack, luminance share. + public int ZoneShare { get; private init; } = RynthIltServer.StateUnknown; + public int Blackjack { get; private init; } = RynthIltServer.StateUnknown; + public int LuminanceShare { get; private init; } = RynthIltServer.StateUnknown; + + /// The /qb list (ILT worlds with RynthILT 0.2.3 or later); null = none offered. + public IltQuestBonusList? QuestBonus { get; private init; } + + /// The features in one group, in RynthILT's order. + public IEnumerable InGroup(string group) + { + foreach (IltFeature f in Features) + if (string.Equals(f.Group, group, StringComparison.OrdinalIgnoreCase)) yield return f; + } + + /// Parses the profile JSON; when it is empty or not JSON. + public static IltServerProfile Parse(string? json) + { + if (string.IsNullOrWhiteSpace(json)) return None; + try + { + using JsonDocument doc = JsonDocument.Parse(json); + JsonElement root = doc.RootElement; + if (root.ValueKind != JsonValueKind.Object) return None; + + var features = new List(); + if (root.TryGetProperty("features", out JsonElement fs) && fs.ValueKind == JsonValueKind.Array) + { + foreach (JsonElement f in fs.EnumerateArray()) + { + if (f.ValueKind != JsonValueKind.Object) continue; + string key = Str(f, "key"); + if (key.Length == 0) continue; + string label = Str(f, "label"); + features.Add(new IltFeature(key, label.Length > 0 ? label : key, Str(f, "group"), + Int(f, "state", RynthIltServer.StateUnknown), Str(f, "where"))); + } + } + + bool ilt = Bool(root, "ilt"); + int max = RynthIltServer.RetailFellowshipMax; + int zone = RynthIltServer.StateUnknown, bj = RynthIltServer.StateUnknown, lum = RynthIltServer.StateUnknown; + if (root.TryGetProperty("fellowship", out JsonElement fel) && fel.ValueKind == JsonValueKind.Object) + { + max = Int(fel, "maxMembers", max); + zone = Int(fel, "zoneShare", zone); + bj = Int(fel, "blackjack", bj); + lum = Int(fel, "luminanceShare", lum); + } + // A bogus size would let the tab claim room nobody has; stay within what the reader handles. + if (max < 1 || max > 64) max = RynthIltServer.RetailFellowshipMax; + + DateTime checkedUtc = DateTime.MinValue; + string when = Str(root, "checked"); + if (when.Length > 0 + && DateTime.TryParse(when, CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal | DateTimeStyles.AssumeUniversal, out DateTime t)) + checkedUtc = t; + + return new IltServerProfile + { + Available = true, + Ilt = ilt, + World = Str(root, "world"), + Forced = Bool(root, "forced"), + Source = Str(root, "source"), + CheckedUtc = checkedUtc, + Features = features, + FellowshipMax = max, + ZoneShare = zone, + Blackjack = bj, + LuminanceShare = lum, + QuestBonus = ParseQuestBonus(root), + }; + } + catch (JsonException) + { + return None; + } + } + + /// The "questBonus" object, or null when the profile has none. + private static IltQuestBonusList? ParseQuestBonus(JsonElement root) + { + if (!root.TryGetProperty("questBonus", out JsonElement q) || q.ValueKind != JsonValueKind.Object) return null; + long count = q.TryGetProperty("count", out JsonElement c) && c.ValueKind == JsonValueKind.Number && c.TryGetInt64(out long n) ? n : -1; + return new IltQuestBonusList(Bool(q, "disabled"), Int(q, "generation", 0), count, Str(q, "status"), + Strings(q, "completed"), Strings(q, "incomplete")); + } + + private static string[] Strings(JsonElement o, string name) + { + if (!o.TryGetProperty(name, out JsonElement a) || a.ValueKind != JsonValueKind.Array) return Array.Empty(); + var list = new List(a.GetArrayLength()); + foreach (JsonElement e in a.EnumerateArray()) + if (e.ValueKind == JsonValueKind.String && e.GetString() is { Length: > 0 } s) list.Add(s); + return list.ToArray(); + } + + /// "on", "off" or "checking" for a feature state. + public static string StateText(int state) => state switch + { + RynthIltServer.StateOn => "on", + RynthIltServer.StateOff => "off", + _ => "checking", + }; + + private static string Str(JsonElement o, string name) => + o.TryGetProperty(name, out JsonElement v) && v.ValueKind == JsonValueKind.String ? v.GetString() ?? "" : ""; + + private static bool Bool(JsonElement o, string name) => + o.TryGetProperty(name, out JsonElement v) && v.ValueKind == JsonValueKind.True; + + private static int Int(JsonElement o, string name, int fallback) => + o.TryGetProperty(name, out JsonElement v) && v.ValueKind == JsonValueKind.Number && v.TryGetInt32(out int i) ? i : fallback; +} + +/// +/// Reads RynthILT's "RynthILT.Server" interface on the plugin pump. Looks the table up through the +/// host (re-checked while RynthILT is missing or after it unloads, Version 0) and copies the JSON +/// out every ; goes up when the profile changes. +/// +internal sealed unsafe class IltServerLink +{ + private const long PollMs = 2000; + private const long RequeryMs = 10_000; + // Room for the /qb list (hundreds of flags) on top of the features. + private const int MaxBuffer = 512 * 1024; + + private RynthIltServerApiV1* _table; + private long _nextPollAt, _nextQueryAt; + private byte[] _buffer = new byte[8192]; + private string _lastJson = ""; + + public IltServerProfile Profile { get; private set; } = IltServerProfile.None; + public int Revision { get; private set; } + + /// Forget the profile (logout); the next poll reads it again. + public void Clear() + { + _nextPollAt = 0; + SetJson(""); + } + + /// Pump thread. Cheap when not due. + public void Poll(RynthCoreHost host, long now) + { + if (now < _nextPollAt) return; + _nextPollAt = now + PollMs; + RynthIltServerApiV1* t = Table(host, now); + SetJson(t == null ? "" : Read(t)); + } + + /// The table, re-queried when it is missing or RynthILT has shut down (Version 0). + private RynthIltServerApiV1* Table(RynthCoreHost host, long now) + { + if (_table != null && _table->Version >= 1) return _table; + _table = null; + if (now < _nextQueryAt || !host.HasGetPluginInterface) return null; + _nextQueryAt = now + RequeryMs; + var p = (RynthIltServerApiV1*)host.GetPluginInterface(RynthIltServer.PluginName, RynthIltServerApiV1.InterfaceName, RynthIltServerApiV1.InterfaceVersion); + if (p != null && p->Version >= 1 && p->StructSize >= (uint)sizeof(RynthIltServerApiV1) && p->GetProfileJson != null) + _table = p; + return _table; + } + + /// Copies the JSON out, growing the buffer once when RynthILT says it didn't fit. + private string Read(RynthIltServerApiV1* t) + { + for (int attempt = 0; attempt < 2; attempt++) + { + int len; + fixed (byte* b = _buffer) len = t->GetProfileJson(b, _buffer.Length); + if (len <= 0) return ""; + if (len < _buffer.Length) return Encoding.UTF8.GetString(_buffer, 0, len); + if (len + 1 > MaxBuffer) return ""; + _buffer = new byte[len + 1024]; + } + return ""; + } + + /// Takes a profile JSON (internal: the tests feed one without RynthILT). + internal void SetJson(string json) + { + if (json == _lastJson) return; + _lastJson = json; + Profile = IltServerProfile.Parse(json); + Revision++; + } +} diff --git a/Plugins/RynthCore.Plugin.RynthOracle/Data/Legendary.cs b/Plugins/RynthCore.Plugin.RynthOracle/Data/Legendary.cs new file mode 100644 index 0000000..46c4ef1 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthOracle/Data/Legendary.cs @@ -0,0 +1,135 @@ +using System; +using System.Collections.Generic; +using System.IO; + +namespace RynthCore.Plugin.RynthOracle.Data; + +/// +/// One Legendary Key quest (legendary.csv; list and notes from the "Arwic John Route" sheet). +/// The quest's own /myquests flags say whether it was ever done and when it can be run again: +/// the first flag is its completion stamp, any others only add their repeat timers (a key pickup +/// timer, say). John in Arwic counts 30 different ones (legendaryquestcounter_0913). +/// +internal sealed class LegendaryQuest +{ + public string Group = ""; + public string Name = ""; + /// The short name players use ("RTW", "HMD"), or "". + public string CommonName = ""; + public int Luminance; + public string[] Flags = Array.Empty(); + public string Url = ""; + public string Note = ""; + public string Video = ""; + + /// The short name when the sheet has one, else the quest name. + public string Label => CommonName.Length > 0 ? $"{Name} ({CommonName})" : Name; + + /// Done at least once: any of its flags is on this character. + public bool Have(QuestFlagStore flags) + { + foreach (string f in Flags) + if (flags.TryGet(f, out _)) return true; + return false; + } + + /// + /// Time until it can be run again: the longest wait among its flags that have a repeat timer; + /// zero when every timer is up (or it has none). Null when it was never done. + /// + public TimeSpan? TimeLeft(QuestFlagStore flags, DateTime utcNow) + { + bool any = false; + TimeSpan left = TimeSpan.Zero; + foreach (string f in Flags) + { + if (!flags.TryGet(f, out QuestFlag q)) continue; + any = true; + if (q.RepeatTime <= TimeSpan.Zero || q.CompletedOnUtc == DateTime.MinValue) continue; + TimeSpan d = q.NextAvailableTime(utcNow); + if (d > left) left = d; + } + return any ? left : null; + } + + /// "missing", "ready" or the time left ("14h 3m"). + public string Status(QuestFlagStore flags, DateTime utcNow) + { + TimeSpan? left = TimeLeft(flags, utcNow); + if (left == null) return "missing"; + return left.Value.TotalSeconds > 0 ? TimeText.Friendly(left.Value) : "ready"; + } +} + +internal static class LegendaryList +{ + /// John's count of different Legendary Key quests done (needs 30). + public const string CounterFlag = "legendaryquestcounter_0913"; + /// Legendary Key quests John asks for. + public const int JohnTarget = 30; + + public static List All { get; } = Load(); + + /// The groups in list order (Graveyard, Rynthid, ...). + public static List Groups { get; } = BuildGroups(); + + /// John's counter for this character; null when /myquests doesn't have it (not started). + public static int? JohnCount(QuestFlagStore flags) => + flags.TryGet(CounterFlag, out QuestFlag q) ? q.Solves : null; + + private static List Load() + { + try + { + using StreamReader r = Csv.OpenEmbedded("legendary.csv"); + return Parse(r); + } + catch (Exception) + { + // A missing or unreadable list must not take the Quests page down with it. + return new List(); + } + } + + /// + /// Reads a legendary.csv (a header row, then one quest a row). A row without a quest name is + /// skipped; a missing column or a luminance that isn't a number reads as empty / 0, so one bad + /// line never costs the rest of the list. Internal for the tests. + /// + internal static List Parse(TextReader r) + { + var list = new List(); + Dictionary col = Csv.MapColumns(r.ReadLine() ?? ""); + int cGroup = Csv.Column(col, "Group"), cName = Csv.Column(col, "Quest"), cCommon = Csv.Column(col, "CommonName"), + cLum = Csv.Column(col, "Luminance"), cFlags = Csv.Column(col, "Flags"), cUrl = Csv.Column(col, "Url"), + cNote = Csv.Column(col, "Note"), cVideo = Csv.Column(col, "Video"); + while (r.ReadLine() is string line) + { + if (string.IsNullOrWhiteSpace(line)) continue; + string[] f = Csv.ParseLine(line); + string name = Csv.Field(f, cName); + if (name.Length == 0) continue; + list.Add(new LegendaryQuest + { + Group = Csv.Field(f, cGroup), + Name = name, + CommonName = Csv.Field(f, cCommon), + Luminance = int.TryParse(Csv.Field(f, cLum), out int lum) ? lum : 0, + Flags = Csv.Field(f, cFlags).ToLowerInvariant() + .Split(';', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries), + Url = Csv.Field(f, cUrl), + Note = Csv.Field(f, cNote), + Video = Csv.Field(f, cVideo), + }); + } + return list; + } + + private static List BuildGroups() + { + var groups = new List(); + foreach (LegendaryQuest q in All) + if (!groups.Contains(q.Group)) groups.Add(q.Group); + return groups; + } +} diff --git a/Plugins/RynthCore.Plugin.RynthOracle/Data/NavTargets.cs b/Plugins/RynthCore.Plugin.RynthOracle/Data/NavTargets.cs new file mode 100644 index 0000000..6e7e17c --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthOracle/Data/NavTargets.cs @@ -0,0 +1,86 @@ +using System; +using System.Collections.Generic; +using System.Globalization; +using System.Text.RegularExpressions; + +namespace RynthCore.Plugin.RynthOracle.Data; + +/// +/// Coordinates in Oracle's text (quest walkthroughs, Dynamic Stamp notes) as RynthNav targets. +/// The lists write them every which way: "59.6S 88.0W", "8.8S, 53.1E", "42.6n 62.4e". +/// +internal static class NavTargets +{ + private static readonly Regex CoordsRx = new( + @"(?\d+(?:\.\d+)?)\s*(?[NnSs])[\s,]*(?\d+(?:\.\d+)?)\s*(?[EeWw])\b", + RegexOptions.CultureInvariant); + + /// One place to go: what the text calls it (may be empty) and its coordinates ("59.6S, 88.0W"). + internal readonly record struct Stop(string Label, string Coords) + { + /// The RynthNav target: the coordinates, then the label (RynthNav uses an Atlas + /// place of that name there, e.g. a dungeon's entrance). + public string Target => Label.Length > 0 ? Coords + " " + Label : Coords; + + /// How a picker shows it: "Kill Mukkir Progenitor - 86.5N, 57.3E". + public string Display => Label.Length > 0 ? Label + " - " + Coords : Coords; + } + + /// + /// A named place with no coordinates (an exploration marker's location): its name is the whole + /// RynthNav target, and RynthNav finds it on its Atlas. + /// + public static Stop Place(string name) => new("", name.Trim()); + + /// The first coordinates in , written "8.8S, 53.1E", or null. + public static string? FirstCoords(string? text) + { + if (string.IsNullOrEmpty(text)) return null; + Match m = CoordsRx.Match(text); + return m.Success ? Format(m) : null; + } + + /// with its coordinates taken out. + public static string WithoutCoords(string? text) => string.IsNullOrEmpty(text) ? "" : CoordsRx.Replace(text, " "); + + /// + /// Every coordinate pair in , in order, each labelled with the words just + /// before it in its step (walkthroughs separate steps with " - "): "Speak with Hoshar ibn Jalaq + /// 59.6S 88.0W - Kill Mukkir Progenitor 86.5N 57.3E" gives two stops. The same coordinates + /// twice are one stop. + /// + public static List Stops(string? text) + { + var stops = new List(); + if (string.IsNullOrEmpty(text)) return stops; + foreach (Match m in CoordsRx.Matches(text)) + { + string coords = Format(m); + if (stops.Exists(s => s.Coords == coords)) continue; + stops.Add(new Stop(LabelBefore(text, m.Index), coords)); + } + return stops; + } + + /// The words between the previous step break (" - ", ". ", "; ", "|") or coordinates and . + private static string LabelBefore(string text, int at) + { + int from = 0; + foreach (string sep in new[] { " - ", ". ", "; ", "|", "(" }) + { + int i = text.LastIndexOf(sep, Math.Max(0, at - 1), StringComparison.Ordinal); + if (i >= 0 && i + sep.Length <= at) from = Math.Max(from, i + sep.Length); + } + // Not back past the previous coordinates ("Cragstone 26.0N 47.0E Speak with ..."). + foreach (Match m in CoordsRx.Matches(text.Substring(0, at))) + from = Math.Max(from, m.Index + m.Length); + string label = text.Substring(from, at - from).Trim(' ', ',', ':', '-', '.', '(', ')'); + // "at 42.1N ..." and "Meet at 42.1N ...": the little words around the coordinates aren't the place. + label = Regex.Replace(label, @"^(at|in|near|to)\s+|\s+(at|in|near|to)$", "", RegexOptions.IgnoreCase).Trim(); + return label.Length > 60 ? label.Substring(0, 60).TrimEnd() : label; + } + + private static string Format(Match m) => + string.Create(CultureInfo.InvariantCulture, + $"{m.Groups["ns"].Value}{char.ToUpperInvariant(m.Groups["nsc"].Value[0])}, {m.Groups["ew"].Value}{char.ToUpperInvariant(m.Groups["ewc"].Value[0])}"); +} diff --git a/Plugins/RynthCore.Plugin.RynthOracle/Data/QuestFlags.cs b/Plugins/RynthCore.Plugin.RynthOracle/Data/QuestFlags.cs index 26f4dcc..98634f8 100644 --- a/Plugins/RynthCore.Plugin.RynthOracle/Data/QuestFlags.cs +++ b/Plugins/RynthCore.Plugin.RynthOracle/Data/QuestFlags.cs @@ -33,7 +33,7 @@ internal sealed class QuestFlag } /// What one chat line is, as far as /myquests goes. -internal enum MyQuestsLine { None, Quest, Empty, Disabled } +internal enum MyQuestsLine { None, Quest, Empty, Disabled, Throttled } /// /// The character's quest flags, read from the server's /myquests reply (ACE: one Broadcast line @@ -55,10 +55,21 @@ internal sealed class QuestFlagStore public const string EmptyText = "Quest list is empty."; public const string DisabledText = "The command \"myquests\" is not currently enabled on this server."; + /// ACECustom's per-session throttle reply ("... may only be run once every 60 seconds."). + public const string ThrottledText = "[MyQuests] This command may only be run once every"; private const int QuietMs = 1500; // a reply is complete once no line came for this long private const int RequestTimeoutMs = 10_000; private const int MinRequestGapMs = 5_000; + /// ACECustom answers one /myquests a minute per session (whoever sent the last one). + private const int ServerThrottleMs = 60_000; + /// + /// A reply this much smaller than the flags already held is taken as cut short (chat lines + /// dropped before they reached the plugin), so it updates the flags instead of replacing them. + /// + private const double PartialReplyRatio = 0.8; + /// Below this many flags held, a smaller reply always replaces (nothing much to lose). + private const int PartialReplyMinHeld = 20; public Dictionary Flags { get; private set; } = new(StringComparer.OrdinalIgnoreCase); private Dictionary? _pending; @@ -66,6 +77,15 @@ internal sealed class QuestFlagStore public DateTime LastReadUtc { get; private set; } = DateTime.MinValue; public bool ServerDisabled { get; private set; } + /// The server refused the last /myquests (its once-a-minute limit) until this tick. + public long ThrottledUntilMs { get; private set; } = long.MinValue / 2; + /// This server has shown its throttle line this session, so every reply starts its minute. + private bool _serverThrottles; + /// + /// Set when the last reply looked cut short and was merged into the held flags (lines in the + /// reply, flags held before it). The plugin logs it once and clears it. + /// + public (int Got, int Had)? LastPartialReply { get; set; } /// Bumps whenever the flags change (views rebuild their caches on it). public int Revision { get; private set; } @@ -77,10 +97,16 @@ internal sealed class QuestFlagStore public bool Loading => _pending != null || AwaitingOurs; + /// Seconds left on the server's /myquests limit (0 when a request would be answered). + public int ThrottleSecondsLeft(long nowMs) => + nowMs < ThrottledUntilMs ? (int)((ThrottledUntilMs - nowMs + 999) / 1000) : 0; + /// Sends /myquests unless one went out moments ago. Returns false if nothing was sent. public bool Request(Func invokeChat, long nowMs) { if (nowMs - _requestedMs < MinRequestGapMs) return false; + // The server would only answer with its throttle line; don't spend the request. + if (nowMs < ThrottledUntilMs) return false; _requestedMs = nowMs; Interlocked.Increment(ref _selfSends); if (!invokeChat("/myquests")) @@ -120,6 +146,16 @@ internal sealed class QuestFlagStore Revision++; return MyQuestsLine.Disabled; } + if (line.Contains(ThrottledText, StringComparison.Ordinal)) + { + // No reply is coming: stop "Reading..." and keep the flags already held. The minute + // really started at the last answered request; a full minute from now is the safe side. + _serverThrottles = true; + ThrottledUntilMs = nowMs + ServerThrottleMs; + AwaitingOurs = false; + Revision++; + return MyQuestsLine.Throttled; + } if (line.IndexOf(" solves (", StringComparison.Ordinal) < 0) return MyQuestsLine.None; QuestFlag? flag = Parse(line); @@ -139,9 +175,27 @@ internal sealed class QuestFlagStore if (_pending != null && nowMs - _lastLineMs >= QuietMs) { - Flags = _pending; + Dictionary reply = _pending; _pending = null; + int had = Flags.Count; + // A full reply replaces the list (a flag the server dropped goes away). One much + // smaller than what is held lost lines on the way (the engine's chat queue drops the + // oldest of a long burst): update what came and keep the rest, rather than blanking. + if (had >= PartialReplyMinHeld && reply.Count > 0 && reply.Count < had * PartialReplyRatio) + { + var merged = new Dictionary(Flags, StringComparer.OrdinalIgnoreCase); + foreach (KeyValuePair kv in reply) merged[kv.Key] = kv.Value; + Flags = merged; + LastPartialReply = (reply.Count, had); + } + else + { + Flags = reply; + } LastReadUtc = DateTime.UtcNow; + // On a throttling server any reply (ours, the player's, RynthAi's poll) starts its minute. + if (_serverThrottles) + ThrottledUntilMs = nowMs + ServerThrottleMs - QuietMs; AwaitingOurs = false; Revision++; } @@ -158,6 +212,9 @@ internal sealed class QuestFlagStore AwaitingOurs = false; LastReadUtc = DateTime.MinValue; ServerDisabled = false; + ThrottledUntilMs = long.MinValue / 2; + _serverThrottles = false; + LastPartialReply = null; Revision++; } diff --git a/Plugins/RynthCore.Plugin.RynthOracle/Data/ServerIdentity.cs b/Plugins/RynthCore.Plugin.RynthOracle/Data/ServerIdentity.cs index 050a628..cc78c30 100644 --- a/Plugins/RynthCore.Plugin.RynthOracle/Data/ServerIdentity.cs +++ b/Plugins/RynthCore.Plugin.RynthOracle/Data/ServerIdentity.cs @@ -10,9 +10,11 @@ internal static class ServerTags public const string Aelrynth = "Aelrynth"; public const string Conquest = "Conquest"; public const string Levistras = "Levistras"; + /// Infinite Leaftide (ACECustom). Its server rules come from RynthILT ("RynthILT.Server"). + public const string InfiniteLeaftide = "InfiniteLeaftide"; /// Tags with a quest pack (Resources\quests.<tag>.csv) or features. - public static readonly string[] Known = { Aelrynth, Conquest, Levistras }; + public static readonly string[] Known = { Aelrynth, Conquest, Levistras, InfiniteLeaftide }; } /// @@ -31,8 +33,9 @@ internal static class ServerTags /// mod's player properties 9101-9103, which only Aelrynth sends. /// Aelrynth's live config still names the world "Aeshnidae" (its earlier name); both count. /// ConquestAC and Levistras are matched on their world names, as upstream does -/// (Decal's CharacterFilter.Server). Infinite Leaftide has no RynthOracle pages: its screens are -/// RynthILT's, so RynthCore's "ilt" server gives no tag here. +/// (Decal's CharacterFilter.Server). Infinite Leaftide is matched on a world name containing +/// "Leaftide", or on RynthILT's own verdict (its world list or the character's override) when +/// RynthILT is loaded. /// internal sealed class ServerIdentity { @@ -55,11 +58,12 @@ internal sealed class ServerIdentity Set("", "", "not logged in"); } + /// RynthILT's profile reports an ILT world (IltServerLink); false without RynthILT. /// /// RynthCore's server list (plugin API v86, ServerStateClient); null on older engines. When there, /// it decides: it already applies this character's overrides and the Diagnostics page's pick. /// - public void Refresh(RynthCoreHost host, uint playerId, EngineServerState? engine = null) + public void Refresh(RynthCoreHost host, uint playerId, bool rynthIltSaysIlt = false, EngineServerState? engine = null) { if (engine != null) { @@ -98,6 +102,11 @@ internal sealed class ServerIdentity source = "the Aelrynth Bank properties (older engine)"; } } + if (tag.Length == 0 && rynthIltSaysIlt) + { + tag = ServerTags.InfiniteLeaftide; + source = "RynthILT: an Infinite Leaftide world"; + } Set(tag, world, source); } @@ -139,6 +148,7 @@ internal sealed class ServerIdentity /// The tag for a RynthCore server id; "" for servers without RynthOracle features. public static string TagForEngineId(string? id) => (id ?? "").Trim().ToLowerInvariant() switch { + EngineServerState.IltId => ServerTags.InfiniteLeaftide, EngineServerState.AelrynthId => ServerTags.Aelrynth, "conquest" => ServerTags.Conquest, "levistras" => ServerTags.Levistras, @@ -148,6 +158,7 @@ internal sealed class ServerIdentity /// The RynthCore server id for a tag; "" for none. public static string EngineIdForTag(string? tag) => tag switch { + ServerTags.InfiniteLeaftide => EngineServerState.IltId, ServerTags.Aelrynth => EngineServerState.AelrynthId, ServerTags.Conquest => "conquest", ServerTags.Levistras => "levistras", @@ -165,6 +176,9 @@ internal sealed class ServerIdentity return ServerTags.Conquest; if (w.Equals(ServerTags.Levistras, StringComparison.OrdinalIgnoreCase)) return ServerTags.Levistras; + // "InfiniteLeaftide", "Infinite Leaftide", staging copies: RynthILT's own world rule. + if (w.IndexOf("Leaftide", StringComparison.OrdinalIgnoreCase) >= 0) + return ServerTags.InfiniteLeaftide; return ""; } diff --git a/Plugins/RynthCore.Plugin.RynthOracle/Data/VoidTracker.cs b/Plugins/RynthCore.Plugin.RynthOracle/Data/VoidTracker.cs index 74ae72b..f582f62 100644 --- a/Plugins/RynthCore.Plugin.RynthOracle/Data/VoidTracker.cs +++ b/Plugins/RynthCore.Plugin.RynthOracle/Data/VoidTracker.cs @@ -20,7 +20,7 @@ internal sealed class VoidDot /// Cast while Surge of Destruction was up (shown highlighted). public bool Destruction; - /// ConquestAC scales void DoT duration by the caster's augs (1.0 elsewhere). + /// A server's own rule scales void DoT duration (Conquest's, from RynthConquest's profile; 1.0 elsewhere). public double DurationScale = 1.0; /// Corrosion 15 s, Corruption and Destructive Curse 30 s (upstream's retail values), times the server's scale. diff --git a/Plugins/RynthCore.Plugin.RynthOracle/OracleContext.cs b/Plugins/RynthCore.Plugin.RynthOracle/OracleContext.cs index aa5dbef..494f0d0 100644 --- a/Plugins/RynthCore.Plugin.RynthOracle/OracleContext.cs +++ b/Plugins/RynthCore.Plugin.RynthOracle/OracleContext.cs @@ -20,6 +20,24 @@ internal sealed class OracleContext public readonly VoidTracker Void = new(); public readonly FellowshipTracker Fellowship = new(); public readonly ServerIdentity Server = new(); + /// RynthILT's server profile (Leaftide features, fellowship rules, the /qb list); None without RynthILT. + public readonly IltServerLink Ilt = new(); + /// RynthILT's "RynthILT.Data" (charms, pet breeding, the Temple guardians). + public readonly RynthCore.Plugin.Shared.RynthIltDataClient IltData = new(); + /// The charms RynthILT last reported (None without RynthILT); read while the Character tab shows. + public RynthCore.Plugin.Shared.IltCharmsView Charms = RynthCore.Plugin.Shared.IltCharmsView.None; + /// The last charm Toggle's outcome, shown under the charms list. + public string CharmMessage = ""; + /// RynthILT's pet breeding tracker (None without it); read while the Pet Breeding tab shows. + public RynthCore.Plugin.Shared.IltBreedingView Breeding = RynthCore.Plugin.Shared.IltBreedingView.None; + /// The last breeding button's outcome, shown under the tab's buttons. + public string BreedingMessage = ""; + /// RynthILT's Temple guardians (None without RynthILT 0.3.3+); read while the Quests tab shows on Infinite Leaftide. + public RynthCore.Plugin.Shared.IltGuardianView Guardian = RynthCore.Plugin.Shared.IltGuardianView.None; + /// Goes up each time changes, so the Quests list rebuilds its guardian rows. + public int GuardianRevision; + /// The last guardian button's outcome, shown under the guardian controls. + public string GuardianMessage = ""; /// RynthAi's session (the one session every tracker shows); read while the Character tab shows. public readonly RynthCore.Plugin.Shared.RynthAiSessionClient AiSession = new(); /// The last session RynthAi reported; SessionKnown false without RynthAi. @@ -27,10 +45,11 @@ internal sealed class OracleContext public bool SessionKnown; /// RynthCore's server list (API v86) and the active server owner's settings; State null on older engines. public readonly RynthCore.Plugin.Shared.ServerStateClient ServerState = new(); - /// ConquestAC-only data (tag Conquest); fed only while on ConquestAC. - public readonly ConquestData Conquest = new(); - /// Aelrynth's leaderboards (tag Aelrynth); fed only while on Aelrynth. - public readonly AelrynthBoards Boards = new(); + /// + /// The active server's Void DoT duration rule: its plugin's profile value "voidDotDurationScale" + /// (RynthConquest publishes Conquest's), 1 on every other server or without the plugin. + /// + public double VoidDotScale = 1.0; /// Titles the character holds (engine API v75); TitlesKnown false until the engine has the list. public readonly System.Collections.Generic.HashSet EarnedTitles = new(); @@ -64,6 +83,34 @@ internal sealed class OracleContext /// Set by the plugin: runs a chat command through RynthCore's plugin dispatch (another plugin's window). public Func RunCommand = _ => false; + /// Set by the plugin: asks RynthILT to use a carried charm or Guardian Hand (its toggle id). + public Func ToggleCharm = _ => false; + + /// Set by the plugin: sends a verb to RynthILT's breeding tracker (RynthIltDataApi PetBreedingCommand). + public Func BreedingCommand = _ => false; + + /// Set by the plugin: sends a verb to RynthILT's guardians (RynthIltDataApi GuardianCommand). + public Func GuardianCommand = _ => false; + + /// Set by the plugin: "<verb> <targets>" for RynthNav's /rnav (go, route, arrow); false when RynthNav isn't there. + public Func SendNav = _ => false; + + /// Set by the plugin: the name of a Parchment carried (null when none). Null here: the Quests tab doesn't look. + public Func? ParchmentFinder; + + /// + /// Set by the plugin: RynthAi is loaded and so can take the Quests tab's "/ub give" (the Give + /// Parchment button). False disables the button with a tooltip. + /// + public Func UbGiveAvailable = () => false; + /// + /// The loaded RynthAi answered a "/ub give" with "Unrecognized /ub command": it has no such verb, + /// so the Give Parchment button stays disabled (set by the plugin from the chat line). + /// + public bool UbGiveMissing; + /// When the Give Parchment button last sent "/ub give" (NowMs), so a rejection in chat can be tied to it. + public long UbGiveSentMs = long.MinValue / 2; + /// Set by the plugin: shows or hides the Quest Timers window. public Action SetQuestTimersWindow = _ => { }; /// Set by the plugin: whether the Quest Timers window is showing. @@ -71,6 +118,18 @@ internal sealed class OracleContext public Func Props => id => Character.Int(Host, id); + /// + /// A chat line seen just after the Give Parchment button sent "/ub give": RynthAi's "Unrecognized + /// /ub command" means this RynthAi has no such verb, so the button stays off. True when it did. + /// + public bool NoteChatLineForGive(string line, long nowMs) + { + if (nowMs - UbGiveSentMs >= 5000 || UbGiveMissing) return false; + if (line.IndexOf("Unrecognized /ub", StringComparison.OrdinalIgnoreCase) < 0) return false; + UbGiveMissing = true; + return true; + } + /// A line in the player's chat window only (nothing is sent to the server). public void Print(string text) { diff --git a/Plugins/RynthCore.Plugin.RynthOracle/OracleSettings.cs b/Plugins/RynthCore.Plugin.RynthOracle/OracleSettings.cs index 4aa69dc..b251aaf 100644 --- a/Plugins/RynthCore.Plugin.RynthOracle/OracleSettings.cs +++ b/Plugins/RynthCore.Plugin.RynthOracle/OracleSettings.cs @@ -27,16 +27,32 @@ internal sealed class OracleSettings public bool QuestTimersOpen; /// The selected tab, by name (the set of tabs depends on the server). public string TabName = "Quests"; - /// ConquestAC: "/bank deposit" at every ten-minute mark (upstream's auto-deposit; off by default). - public bool ConquestAutoDeposit; /// Say so in chat when a tracked quest's timer comes up. public bool AlertTimers = true; /// false: only tracked quests are watched; true: every quest the character holds. public bool AlertAllTimers; - private static string FilePath => Path.Combine( + /// Where the tests keep the settings file (a scratch path); null means the rynthoracle.json in RynthCore's %APPDATA% folder. + internal static string? PathOverride; + + internal static string FilePath => PathOverride ?? Path.Combine( Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "RynthCore", "rynthoracle.json"); + /// The names this version reads and writes; any other value in the file is kept as it was. + private static readonly string[] KnownNames = + { + "readQuestsAtLogin", "hideOwnQuestReplies", "checkQuestListDaily", "lastQuestListCheck", "autoShowVoidWindow", + "mainWindowOpen", "questTimersOpen", "alertTimers", "alertAllTimers", "tabName", + }; + // "conquestAutoDeposit" moved to RynthConquest (2026-10-20), which takes it over from this file once; + // it is kept here (as any value this version doesn't use) until then. + + /// + /// Values in the file this version doesn't use (a newer version's, or a setting that moved to + /// another plugin, which reads it from here once), written back unchanged so a save never loses them. + /// + private readonly System.Collections.Generic.List<(string Name, string Raw)> _kept = new(); + public void Load() { try @@ -45,13 +61,15 @@ internal sealed class OracleSettings using var doc = JsonDocument.Parse(File.ReadAllText(FilePath)); JsonElement r = doc.RootElement; if (r.ValueKind != JsonValueKind.Object) return; + _kept.Clear(); + foreach (JsonProperty p in r.EnumerateObject()) + if (Array.IndexOf(KnownNames, p.Name) < 0 && !_kept.Exists(k => k.Name == p.Name)) _kept.Add((p.Name, p.Value.GetRawText())); ReadQuestsAtLogin = Bool(r, "readQuestsAtLogin", ReadQuestsAtLogin); HideOwnQuestReplies = Bool(r, "hideOwnQuestReplies", HideOwnQuestReplies); CheckQuestListDaily = Bool(r, "checkQuestListDaily", CheckQuestListDaily); AutoShowVoidWindow = Bool(r, "autoShowVoidWindow", AutoShowVoidWindow); MainWindowOpen = Bool(r, "mainWindowOpen", MainWindowOpen); QuestTimersOpen = Bool(r, "questTimersOpen", QuestTimersOpen); - ConquestAutoDeposit = Bool(r, "conquestAutoDeposit", ConquestAutoDeposit); AlertTimers = Bool(r, "alertTimers", AlertTimers); AlertAllTimers = Bool(r, "alertAllTimers", AlertAllTimers); if (r.TryGetProperty("tabName", out JsonElement t) && t.ValueKind == JsonValueKind.String) TabName = t.GetString() ?? TabName; @@ -78,11 +96,12 @@ internal sealed class OracleSettings sb.Append(" \"autoShowVoidWindow\": ").Append(AutoShowVoidWindow ? "true" : "false").Append(",\n"); sb.Append(" \"mainWindowOpen\": ").Append(MainWindowOpen ? "true" : "false").Append(",\n"); sb.Append(" \"questTimersOpen\": ").Append(QuestTimersOpen ? "true" : "false").Append(",\n"); - sb.Append(" \"conquestAutoDeposit\": ").Append(ConquestAutoDeposit ? "true" : "false").Append(",\n"); sb.Append(" \"alertTimers\": ").Append(AlertTimers ? "true" : "false").Append(",\n"); sb.Append(" \"alertAllTimers\": ").Append(AlertAllTimers ? "true" : "false").Append(",\n"); - sb.Append(" \"tabName\": \"").Append(JsonEncodedText.Encode(TabName).ToString()).Append("\"\n"); - sb.Append("}\n"); + sb.Append(" \"tabName\": \"").Append(JsonEncodedText.Encode(TabName).ToString()).Append('"'); + foreach ((string name, string raw) in _kept) + sb.Append(",\n \"").Append(JsonEncodedText.Encode(name).ToString()).Append("\": ").Append(raw); + sb.Append("\n}\n"); Directory.CreateDirectory(Path.GetDirectoryName(FilePath)!); string tmp = FilePath + ".tmp"; File.WriteAllText(tmp, sb.ToString()); diff --git a/Plugins/RynthCore.Plugin.RynthOracle/PluginExports.cs b/Plugins/RynthCore.Plugin.RynthOracle/PluginExports.cs index 1babccf..c73efa6 100644 --- a/Plugins/RynthCore.Plugin.RynthOracle/PluginExports.cs +++ b/Plugins/RynthCore.Plugin.RynthOracle/PluginExports.cs @@ -38,7 +38,7 @@ public static unsafe class PluginExports public static IntPtr GetVersion() { // Keep in step with RynthOraclePlugin.Version (a u8 literal can't be built from a const string). - try { return LiteralPointer("0.2.2"u8); } + try { return LiteralPointer("0.3.0"u8); } catch { return IntPtr.Zero; } } diff --git a/Plugins/RynthCore.Plugin.RynthOracle/Resources/dynstamps.csv b/Plugins/RynthCore.Plugin.RynthOracle/Resources/dynstamps.csv new file mode 100644 index 0000000..6691ea9 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthOracle/Resources/dynstamps.csv @@ -0,0 +1,244 @@ +Area,Place,Npc,Reward,Stamp,Note +"Facility Hub","Folthid Cellar","Raxanza Folthid","O-Yoroi Leggings","Dynamic_1_Aq2hMsFmW!","" +"Facility Hub","Folthid Cellar","Felscuda","Healing Rabbit Pie","Dynamic_1_&9jiyTB!","8.8S, 53.1E" +"Facility Hub","Folthid Cellar","Mi Krau-Li","examines your Parchment","Dynamic_1_WAuFukcRLoL5!","" +"Looking Around","","Le-Ai Rea","Blue Molly","Dynamic_1_XH!!nh#^NaRp!","75.9S 57.3E" +"Looking Around","Frost Haven","Robert","Greater Celdon Shadow Sleeves","Dynamic_1_HLq&!","" +"Looking Around","Frost Haven","Elijah","Homemade Stout","Dynamic_1_MpBeVDU!","" +"Looking Around","Frost Haven","Emma","Frost Slingshot","Dynamic_1_bEt6H5ECwGb2!","" +"Looking Around","Frost Haven","Chef Pleist","Stone Mace","Dynamic_1_HgaUKA#hxa!","" +"Looking Around","Frost Haven","The Mayor","Fried Egg","Dynamic_1_MRfxp5!g!","" +"Looking Around","Frost Haven","Numb","Perfect Coruscating Isparian Mace","Dynamic_1_z8LpGZpe4rq!","" +"Looking Around","Land Bridge Staging Complex","Director's Majordomo","Spitter Trochanter Metamorphi","Dynamic_1_FZYLYrAW1Zb!","" +"Looking Around","Frost Haven","Mossy Chamber","Broken Virindi","Dynamic_1_ANND","" +"Looking Around","Freebooter","Jusad the Collector","Renegade Atlatl of the Mountains","Dynamic_1_!mqkm9M!","" +"Looking Around","Lum Seer","Shade of Lady Adja","Frost Board with Nail","Dynamic_1_ps6iG^P!ndH!","" +"Looking Around","Frost Haven","Ka'hiri","Hearty Spiced Applesauce","Dynamic_1_s5MAzDcP9!","" +"Looking Around","Frost Haven","Liam of Gelid","Composite Crossbow with Handle","Dynamic_1_7cv3O^MTLLKzs&!","" +"Looking Around","84.1N, 44.1E","Aerlinthe Node Golem","Silifi of Crimson Stars","Dynamic_1_D6YxLUyUIW!","84.1N, 44.1E" +"Looking Around","62.0N, 18.0E","Esper Node Golem","Composite Bow with Handle","Dynamic_1_LE5V8SVHG!","62.0N, 18.0E" +"Looking Around","93.8N, 67.4W","Halaetan Node Golem","Slashing Longbow","Dynamic_1_QfLhcZJ64Hkold!","93.8N, 67.4W" +"Looking Around","64.8S, 59.3E","Linvak Node Golem","Greater Celdon Shadow Girth","Dynamic_1_V8&t5$!","64.8S, 59.3E" +"Looking Around","Ulgrim Island","Ulgrim the Unappreciated","Applesauce","Dynamic_1_x!zs79y!","" +"Looking Around","Fake Niffis Crate Quest","Chef Jonus","Fish","Dynamic_1_j&T!ZrQwKvo!","" +"Looking Around","Frost Haven","Larnia","Acid Hand Axe","Dynamic_1_88P$YBwEl!","" +"Looking Around","Tanada Chamber of Scroll / Fire","Tanada Han-Tu","Hearty Ice Cream","Dynamic_1_STjY86!0Iu8x!","" +"Looking Around","Frost Haven","Tanada Hido","Acid Mace","Dynamic_1_3ZhBEF!","" +"Looking Around","Frost Haven","Tanada Shouka","Pouch of Dried Meat","Dynamic_1_YgClBFy!","" +"Looking Around","Gerent's Compound at 87.2S, 17.5W","Representative of the Singularity","Fish","Dynamic_1_qkU0b^i!","87.2S, 17.5W" +"Odd Stamps","93.2N, 48.2W in the Shattered Outlands","Arialle du Bellenesse","Healing Holtburger","Dynamic_1_ADm5RsrDGCbT!","93.2N, 48.2W" +"Odd Stamps","Crater","Silencia's Magma Golem","Slicing Royal Atlatl","Dynamic_1_fR730X5VsPULE5!","" +"Odd Stamps","Colosseum","Master Arbitrator","Palenqual's Tewhate","Dynamic_1_XnFt&!","" +"Odd Stamps","","Colosseum Ticket Vendor","Silifi of Crimson Stars","Dynamic_1_luguukhgZg!","" +"Odd Stamps","Beach Fort","Suzuhara Sheshumi","Silifi of Crimson Stars","Dynamic_1_n5u2imCs!","" +"Odd Stamps","Obsidian Plains","Varetha","Major Smoldering Atlan Bow","Dynamic_1_P1&xxk5!","44.3S, 62.5W" +"Odd Stamps","Crystal Crag","Oorjit","Perfect Shimmering Isparian Bow","Dynamic_1_lPn&BaZ!","" +"Odd Stamps","","Jyotsana","Cragstone Farms Mac&Cheese","Dynamic_1_YCGJJ7cA!","" +"Odd Stamps","","Tokashi Ando","Perfect Dissolving Isparian Crossbow","Dynamic_1_R#HIf!","" +"Odd Stamps","Ries Woron's Story","Thrungus","Expired Stamina Draught","Dynamic_1_eMJVhyPzaa$aGn!","" +"Odd Stamps","Mite Maze","Roderick","Apple Pie","Dynamic_1_#C^p&w0gV$$!","" +"Odd Stamps","Sawato","Ssavish","Composite Bow with Handle","Dynamic_1_NMlDXfx2t!","" +"Odd Stamps","dryreach rescue","Dansha-Ki","Composite Bow with Handle","Dynamic_1_FnXoHWS&kaM!","" +"Odd Stamps","Seat of Knorr","Arikas, Warden of Knorr","Hearty Healing Rabbit Noodle","Dynamic_1_aWOWTc30f4","" +"Odd Stamps","Swamp Garden","Terese","Diforsa Bracers","Dynamic_1_PTy0kqqTLP1Dn^!","" +"Odd Stamps","Dark Isle","Tyrina of Arwic","Major Shadow Gauntlets","Dynamic_1_zJNxGBc!","84.7n 58.7e" +"Odd Stamps","Dark Isle","Francois di Terli","Habraeloi","Dynamic_1_3!Og!","" +"Odd Stamps 2","Aun Settlement 82.7N 21.2E.","Aun Tikakhe","Good Chilling Isparian Mace","Dynamic_1_hafO$cQvbkg!","82.7N 21.2E" +"Odd Stamps 2","","Aun Saritea","Health Tonic","Dynamic_1_7yW17JvMHKu!","" +"Odd Stamps 2","","Aun Aulakhe","Mana Rabbit Pie","Dynamic_1_5xE2TM!","" +"Odd Stamps 2","Lost Wish Cottages (Arwic) 42.6n 62.4e","Lartorus","Pants","Dynamic_1_$GB72K!","42.6n 62.4e" +"Odd Stamps 2","Catacombs of Opposition","Ripper","Gladiatorial Tunic","Dynamic_1_69Rjbany2pKD!","" +"Odd Stamps 2","","Rat Nose","Fine Atlan Staff","Dynamic_1_eBlku!","" +"Odd Stamps 2","","Nanoc, Basher of Bugs","Mana Potion","Dynamic_1_XCTiy!","" +"Odd Stamps 2","","Narg","Iron Rusted Mace","Dynamic_1_S!AhI!","" +"Odd Stamps 2","","Scout Luzumin Abigwei","Alduressa Helm","Dynamic_1_NFf5!","" +"Odd Stamps 2","","Teela","Orange Molly","Dynamic_1_Bl#Y!","" +"Odd Stamps 2","","Scout Tel al-Arat","Envoy's Heaume","Dynamic_1_AJ3Wm9Bk!","" +"Odd Stamps 2","","Pincer Danta","Olthoi Sollerets","Dynamic_1_VezOOBWbn43KU!!","" +"Odd Stamps 2","Vissidal","Merwart Pelagurg","Superior Smoldering Atlan Staff","Dynamic_1_DOIC1!","" +"Odd Stamps 2","Vissidal","Merwart Urglurg","Butter Knife of Slaying","Dynamic_1_&!iRR#RrhnGA!","" +"Odd Stamps 2","Vissidal","Dayla Bint Kazm","Hearty Healing Chicken Pie","Dynamic_1_nDAXG!","" +"Odd Stamps 2","Vissidal","Peng-Ya","Major Dissolving Isparian Crossbow","Dynamic_1_sx^9H^&Mnqp!","" +"Odd Stamps 2","Vissidal","Colista Fluress","Lesser Amuli Shadow Leggings","Dynamic_1_Ej!Zz!","" +"Odd Stamps 2","99.7S 96.7W","Surloshen Realaidain","Hammer of Lightning","Dynamic_1_tiiFC!","99.7S 96.7W" +"Odd Stamps 2","Silyiun - 89.1N 47.6W","Fiun Gaya","Enhanced Shadow Gauntlets","Dynamic_1_hev0!","89.1N 47.6W" +"Odd Stamps 2","Hermit - Thrungus Hole","Hermit","Scored Amuli Leggings","Dynamic_1_rDBG!","" +"Odd Stamps 2","93.2N 48.2W - Eastwatch","Commander Rylane di Cinghalle","Acid Crossbow","Dynamic_1_pZpx41&!","93.2N 48.2W" +"Odd Stamps 2","32.0N, 43.2W - Virindi Crafters","Crafter of Arbelests","Healing Carrot Soup","Dynamic_1_L3Hb3O!","32.0N, 43.2W" +"Odd Stamps 2","32.0N, 43.2W - Virindi Crafters","Crafter of Fists","Platemail Breastplate","Dynamic_1_xj&USOHNL9K&!","32.0N, 43.2W" +"Odd Stamps 2","32.0N, 43.2W - Virindi Crafters","Crafter of Bows","Tasty Stout","Dynamic_1_hw2LNdjT6!","32.0N, 43.2W" +"Odd Stamps 2","32.0N, 43.2W - Virindi Crafters","Crafter of Atlatls","Composite Crossbow with Handle","Dynamic_1_P6!!","32.0N, 43.2W" +"Odd Stamps 2","32.0N, 43.2W - Virindi Crafters","Crafter of Axes","Three Eyed Guppy","Dynamic_1_xX^IHjOo##J$8E!","32.0N, 43.2W" +"Odd Stamps 2","32.0N, 43.2W - Virindi Crafters","Crafter of Blades","Flaming Weeping Dagger","Dynamic_1_iFuvP!","32.0N, 43.2W" +"Odd Stamps 2","32.0N, 43.2W - Virindi Crafters","Crafter of Staves","Composite Crossbow","Dynamic_1_J$JV&VKf!","32.0N, 43.2W" +"Odd Stamps 2","32.0N, 43.2W - Virindi Crafters","Crafter of Orbs","Health Tincture","Dynamic_1_S&JMdWiBDy!","32.0N, 43.2W" +"Odd Stamps 2","32.0N, 43.2W - Virindi Crafters","Crafter of Maces","Wooden Scarecrow Guise","Dynamic_1_^pTx!","32.0N, 43.2W" +"Odd Stamps 2","32.0N, 43.2W - Virindi Crafters","Crafter of Knives","Scalemail Hauberk","Dynamic_1_6ZR$k^$Srwc3g!","32.0N, 43.2W" +"Odd Stamps 2","83.4S 97.2E - Ithaenc","Abbess Zik'Lir","Hearty Fish Noodle","Dynamic_1_jmCfm1p5a!","83.4S 97.2E" +"Odd Stamps 2","72.8N,25.0W - Stonehold nearby","Lord Pyrovor","Enhanced Shadow Greaves","Dynamic_1_Tw$7Zwmutan!","72.8N,25.0W" +"Odd Stamps 2","VoD Encampment","Guard Alfric","Bowl of Rice","Dynamic_1_LZkvsu4Ln2$h!","" +"Odd Stamps 2","VoD Encampment","Guard Taziq","Blackfire Shadow Sollerets","Dynamic_1_t9uxr!","" +"Odd Stamps 2","VoD Encampment","Guard Q'alia","Ancient Relic Gauntlets","Dynamic_1_m1KeUXELMuH!","" +"Odd Stamps 2","VoD Encampment","Guard Li","Frost Hatchet","Dynamic_1_XgrV$!","" +"Odd Stamps 2","77.7S 97.0E Ithaenc","Shah-hi","Katar","Dynamic_1_G3N9HSXlowLT$!","77.7S 97.0E" +"Odd Stamps 2","Releasing the Light - Reward Room","Calitoth","Fish","Dynamic_1_mu^91#T!","" +"Odd Stamps 2","VoD Encampment","Guardian of the Forbidden","Princely Runed Dart Flinger","Dynamic_1_#BELoT72Ib!","Small Creepy Statue" +"Odd Stamps 2","Shattered Outlands 94.0n 45.9w","Torgash","examines your Parchment","Dynamic_1_S","94.0n 45.9w" +"Odd Stamps 2","Hoshino Must Die last room","Spirit of Bist'elle","Enhanced Shadow Breastplate","Dynamic_1_b!","" +"Bandit Castle","","Karwin, the Lunatic","Chainmail Pauldrons","Dynamic_1_HIlMkY!","" +"Bandit Castle","","Kiriel Shadowborn","Healing Apple Pie","Dynamic_1_WBzVFJpFUzHkC!","" +"Bandit Castle","","Jourgensson","Hearty Healing Mushroom Pie","Dynamic_1_$W&Pl4!","" +"Bandit Castle","","Gillian the Poacher","Peppermint Ice Cream","Dynamic_1_5oLp!","" +"Bandit Castle","","Alison Dulane","Amuli Shadow Leggings","Dynamic_1_079u9!","" +"Bandit Castle","","Arianna the Adept","Expired Stamina Draught","Dynamic_1_hZIsyYE!!OmcQ!","" +"Bandit Castle","","Shanrek the Forger","Sparring Shirt","Dynamic_1_fbcmDRC!","" +"Bandit Castle","","Neela Nashua","Perfect Dissolving Isparian Spear","Dynamic_1_4tXQFu&&o!","" +"Bandit Castle","","Gwillim, the Apprentice","Lightning Flanged Mace","Dynamic_1_is#X6rBaprU!","" +"Bur","","Drogur","Frost Yari","Dynamic_1_KS8e32dtk7t!","" +"Bur","","Collector Golem","Upper Exoskeleton Metamorphi","Dynamic_1_4xdYA1QvaiDf^!","" +"Bur","","Kuurak","Hearty Healing Chicken Noodle","Dynamic_1_Zapx!","" +"Bur","","Furgal","Spitter Thorax Metamorphi","Dynamic_1_4rk&MTz!","" +"Bur","","Tibik","Gear Crossbow","Dynamic_1_!Ce^d!","" +"Bur","","Nimeruuk","Greater Celdon Shadow Sleeves","Dynamic_1_zIX1Sf6FJt!","" +"Bur","","Kurket","Acidic Rejuvenation","Dynamic_1_snVaz#0Ze3R#4M!","" +"Bur","","Brogosh","Lugian Morning Star","Dynamic_1_$9YdvC2jYTxWZ!","" +"Bur","","Mohor","Quality Isparian Crossbow","Dynamic_1_qpXiWqwBTN4!","" +"Bur","","Kushuk","Silifi of Crimson Stars","Dynamic_1_3ISBG!","" +"Bur","","Borsh","Health Tonic","Dynamic_1_Jh4!","" +"Bur","","Kuuru","Electric Compound Bow","Dynamic_1_vNktko1!","" +"Bur","","Torgluuk, High Shaman of Kor-Gursha","Stout","Dynamic_1_2yxpXSMY!","" +"Bur","","Scout Leader Tmauruk","Hood","Dynamic_1_fEiU!","" +"Bur","","Gruuk'lar","Rynthid Tentacle Dagger","Dynamic_1_xFipmT1!","" +"Gear Knight","Inner Sea Gearknight Invasion","Lieutenant Micham","Dabus","Dynamic_1_CQxkFJvoJrVx!","" +"Gear Knight","Inner Sea Gearknight Invasion","Sir Oakley","Composite Crossbow with Handle","Dynamic_1_lh9wOaXR0!","" +"Gear Knight","Inner Sea Gearknight Invasion","Lieutenant Faen","Blunt Bow","Dynamic_1_Vz#gp!","" +"Gear Knight","Inner Sea Gearknight Invasion","Sir Stavitor","Red Tea","Dynamic_1_ogt05i!","" +"Gear Knight","Inner Sea Gearknight Invasion","Dame Alistra","Superb Flaming Isparian Claw","Dynamic_1_y!","" +"Gear Knight","Direland Gearknight Invasion","Sir Yanov","Major Shadow Greaves","Dynamic_1_BlAckAuHU#!","" +"Gear Knight","Direland Gearknight Invasion","Sir Durnstad","Silifi of Crimson Stars","Dynamic_1_#Dfd!","" +"Gear Knight","Direland Gearknight Invasion","Squire Tylaen","Good Coruscating Isparian Atlatl","Dynamic_1_i1Cxg8Bt!","" +"Gear Knight","Direland Gearknight Invasion","Dame Trielle","Frost Yari","Dynamic_1_h^MdsKZ$6SSD!","" +"Gear Knight","Direland Gearknight Invasion","T'ing Douzen","Panaq","Dynamic_1_p0BEy$e!","" +"Gear Knight","Atamarr Tasks Dungeon","Bronze Gauntlet Knight-Commander","Frost Greataxe","Dynamic_1_REv&biyDw!","" +"Gear Knight","Direland Gearknight Invasion","Copper Cog Craftsmaster","Greater Amuli Leggings of Frost","Dynamic_1_4uls5J!","" +"Wai Jhou","","Kreavon","Skeleton Fish","Dynamic_1_KrPl9N5!","" +"Wai Jhou","","Aun Teverea","Singularity Crossbow","Dynamic_1_Y9wg!RfKHoyL!","" +"Wai Jhou","","Nona","Fish","Dynamic_1_JrzQr8U!","" +"Wai Jhou","","Zho Heishan","Bandit Dagger","Dynamic_1_Abm8qK2!","" +"Wai Jhou","","Sarkin Killcrane","Shadow Tassets","Dynamic_1_mb7NAtZEdBaz!","" +"Wai Jhou","","Riordin Nightbane","Hafted Serpent Spear","Dynamic_1_cCzQdsl5JxLC!","" +"Wai Jhou","","Lacarra Avanthi","Shou-jen Shozoku Trousers","Dynamic_1_ip&NsyQ!","" +"Wai Jhou","","Xanda Har","Gold Fish","Dynamic_1_1CiKW8^x^$!","" +"Rynthid","","Lohrn","Shreth Hide Shoes","Dynamic_1_cS!mivYZ^b!cAA!","" +"Rynthid","","Rhys","Plate Leggings","Dynamic_1_A!!","" +"Rynthid","","Morgethais","Silifi of Crimson Stars","Dynamic_1_wDTf#!","" +"Rynthid","","Geilla","Audetaunga's Korua of the Mountains","Dynamic_1_&dNG5U4!","" +"Rynthid","","Rinne Gorber","Brilliant Celdon Leggings","Dynamic_1_ln!Lx!","" +"Rynthid","","Aun Ol'tra","Small Beer","Dynamic_1_&^3Hve4JXH^!","" +"Rynthid","","Ranulf","Prismatic Celdon Sleeves","Dynamic_1_8n2l!","" +"Rynthid","","Sylvanus","Ursuin Hide Coat","Dynamic_1_veaD!","" +"Rynthid","","Marcus","Fish","Dynamic_1_bpNCu!rsf45Fk!","" +"Rynthid","","Ilte Krongal","Hearty Mana Rabbit Noodle","Dynamic_1_AusVgDl!","" +"Rynthid","","The Bringer of Light","Peppermint Hot Chocolate","Dynamic_1_LrpV!62!","" +"Paradox Camp","Paradox Olthoi Camp","Ethan Wintermaine","Superb Flaming Isparian Bow","Dynamic_1_PPtO6!7dB!","" +"Paradox Camp","","Adrien Swiftblade","Oak Stormwood Crossbow","Dynamic_1_R^1Uv!J8k!","" +"Paradox Camp","","Alicia Swiftblade","Badlands Siraluun Dress","Dynamic_1_G0Rn1lOZKj7C!","" +"Paradox Camp","","Tomihino","Dart Flinger","Dynamic_1_!$cc!","" +"Paradox Camp","North Olthoi Burrow","Peda's Assistant","examines your Parchment","Dynamic_1_3ddaHUzi!","" +"Paradox Camp","North Olthoi Burrow","Peda","examines your Parchment","Dynamic_1_1R9O85L$b!","" +"Paradox Camp","North Olthoi Burrow","Crusher","examines your Parchment","Dynamic_1_a&Z2!","" +"Paradox Camp","North Olthoi Burrow","Deena","examines your Parchment","Dynamic_1_cIZV2uDB6B!","" +"Paradox Camp","North Olthoi Burrow","Mac","examines your Parchment","Dynamic_1_5x^G2$X9!","" +"Paradox Camp","North Olthoi Burrow","Swift-Eye","examines your Parchment","Dynamic_1_o$yT7al7ZTxv!","" +"Paradox Camp","North Olthoi Burrow","Sasha","examines your Parchment","Dynamic_1_CvzZIz!","" +"Paradox Camp","North Olthoi Burrow","Dead-Eye","examines your Parchment","Dynamic_1_fP9y!","" +"Paradox Camp","North Olthoi Burrow","Lash","examines your Parchment","Dynamic_1_AniHdl4wtIuF0!","" +"Paradox Camp","North Olthoi Burrow","Long-Shot","examines your Parchment","Dynamic_1_jJ^yEFc#m^M!","" +"Graveyard","","Renata","Singularity Spear","Dynamic_1_1fDZO3!","" +"Graveyard","","Yoite","Composite Bow with Handle","Dynamic_1_OG6jdId!","" +"Graveyard","","Gadi","Scored Celdon Girth","Dynamic_1_ELgh#!","" +"Graveyard","","Aethelswith","Leather Helm","Dynamic_1_cF!","" +"Graveyard","","Mhoire Soldier","Superb Isparian Bow","Dynamic_1_VgB#WcZOIA!","North Soldier - Opposite side of bunker" +"Graveyard","","Mhoire Soldier","Hafted Gromnie Banner with Crest","Dynamic_1_z$DX!","South Soldier - Opposite side of bunker" +"Graveyard","","Apep-tek the Tolerant","Spectacular Lager","Dynamic_1_Y55^MqgC!","Above ground, outside bunker 65.3w 44.0w" +"Graveyard","","Laylana","Stiletto","Dynamic_1_&SRgbH!","Above ground, outside bunker 65.2s 44.3w" +"Graveyard","","Lo Shoen","Amateur Explorer Pants","Dynamic_1_102!pkgn8wAYSe!","Floating Platform - Level 50 req" +"Graveyard","","Slubbley","Healing Cake","Dynamic_1_mDaEh7!","" +"Graveyard","","Jailer","Good Shimmering Isparian Bow","Dynamic_1_2Hm6DL!","NE bunker aboveground 64.9s 44.1w" +"Graveyard","","Kousu Temo","Fried Mushroom Rice Dough","Dynamic_1_QUXbn6!","EW Initiation guy, 64.2s 44.0w" +"Graveyard","","Candrus Steady-Hand","Academy Mana Potion","Dynamic_1_BKq6N6nXoR!","CH Initiation guy, 65.8s 45.3w" +"Graveyard","","Ancient Stones","Bandit Flaming Jambiya","Dynamic_1_xL!g4ZoCuv!H","Pile of stones at 66.5s 44.7w" +"Graveyard","Mhoire Castle - Great Hall","Ancient Throne","Taiaha","Dynamic_1_&y4ettwcivZ5Nm!","" +"Graveyard","Mhoire Castle - Great Hall","Shade of Antemy","Left Peg Leg","Dynamic_1_CphV&!","" +"Graveyard","Mhoire Castle - Great Hall","Shade of Fordroth","Perfect Chilling Isparian Atlatl","Dynamic_1_M0u7js^$E!","" +"Graveyard","Mhoire Castle - Great Hall","Shade of Terelev","Silifi of Crimson Stars","Dynamic_1_XPvw!","" +"Graveyard","Mhoire Castle - Great Hall","Guliant","Celdon Girth of Acid","Dynamic_1_aCEEdQil42!","" +"Neftet","","T'ing Setsuko","Flaming Broad Sword","Dynamic_1_JfmjJmY0O8r!","" +"Neftet","","Nephthys","Red Tea","Dynamic_1_mnJCjm5QR$s&!","" +"Neftet","","Fahneph","Gear Crossbow","Dynamic_1_owGS9WGJ1Q!","" +"Neftet","","Nekshla","Mana Pumpkin Pie","Dynamic_1_AAQ1#!","" +"Neftet","","Sir Hassim bin Tamarek","Enhanced Shadow Greaves","Dynamic_1_r7zID$U!","" +"Neftet","","Sir Adarl","Bobo's Stout","Dynamic_1_SoBgM6JPckOY9!","" +"Neftet","","Sir Ibreh bin Kassim","Expired Mana Tincture","Dynamic_1_aVMuY!","" +"Neftet","","Sir Daeglan","Quality Coruscating Isparian Crossbow","Dynamic_1_n!","" +"Neftet","","Bemeth the Gatherer","Lesser Koujia Breastplate of Acid","Dynamic_1_bda1WYoI!","" +"Neftet","","Hammah al Rundik","Olthoi Greaves","Dynamic_1_9v^POv6ADt3r!","" +"Neftet","22.2S 8.7E","Kaltus","Composite Bow with Handle","Dynamic_1_xWYS3fqIjPN!","22.2S 8.7E Not Dangerous run" +"Frozen Valley","","Sir Donovan","Pickled Egg","Dynamic_1_ypu2L!","" +"Frozen Valley","","Sir Learth","Royal Cabbage","Dynamic_1_xpAJDzm$!","" +"Frozen Valley","","Lady Daenerah","Acid Spadone","Dynamic_1_$SDp1uWx8wq$!","" +"Frozen Valley","","Gregoria, Gurog Destroyer","Chocolate Gromnie","Dynamic_1_!vr&1c1Ug1XI!","" +"Frozen Valley","","Hunter","Hearty Healing Chicken Pie","Dynamic_1_Sy!9l0FAJFI!","" +"Frozen Valley","","Leilah","Lightning Silifi","Dynamic_1_uyoL!","" +"Frozen Valley","","Halvor","Noble Quarterstaff","Dynamic_1_LfLac!","" +"Frozen Valley","","Kumiko","Expired Health Potion","Dynamic_1_TB!q!","" +"Frozen Valley","","Archmage Ichihiri","Arbalest","Dynamic_1_HzvCs4B2!","" +"Hoshino Tent","","Sergeant Trebuus","Soldier Pincer Metamorphi","Dynamic_1_GQIb1mF!","" +"Hoshino Tent","","Sergeant Freng","Lightning War Axe","Dynamic_1_wVJm&#Lpz7AQ#F","" +"Hoshino Tent","","Aun Kirtal","Arena Bow","Dynamic_1_V9ffGx!","" +"Hoshino Tent","","Lieutenant Aurin","Enhanced Smoldering Atlan Sword","Dynamic_1_4qlVcAWbM!","" +"Hoshino Tent","","Lord Eorlinde","Major Shadow Gauntlets","Dynamic_1_zkzTna!","" +"Hoshino Tent","","Griffon","Mana Elixir","Dynamic_1_b4^F&M1^uG!","" +"Hoshino Tent","","Hanamoto Aki'ko","Lightning Nekode","Dynamic_1_3Qlg!","" +"Hoshino Tent","","Corporal Irashi","Lesser Koujia Shadow Leggings","Dynamic_1_2DBoreKEH!","" +"Hoshino Tent","","Lieutenant Takamaki","Silifi of Crimson Stars","Dynamic_1_#hzL!","" +"Hoshino Tent","","Lieutenant Roothe","Fried Rabbit","Dynamic_1_XuH!z7l!","" +"Viridian Rise","","Brellegia","Greater Celdon Breastplate of Acid","Dynamic_1_mCyu9F!","Requires Viridian Rise Recall Gem" +"Viridian Rise","","Summercrown","Tachi","Dynamic_1_R8H6nh!","" +"Viridian Rise","","Aangesilus","Slashing Compound Bow","Dynamic_1_2LJyvGJL!","" +"Viridian Rise","","Dridge","Greater Amuli Leggings of Flame","Dynamic_1_LP3Ee7tH!","" +"Viridian Rise","","Kervim'telek","Ursuin Hide Coat","Dynamic_1_E5$S!","" +"Viridian Rise","","Swift","Fried Chicken","Dynamic_1_hYVV!","" +"Ayan","","Aludi al-Jaladh","Seasoned Explorer Gauntlets","Dynamic_1_7$I7bC!","" +"Ayan","","Aun Javhalrea, the Game Warden","Frost Ono","Dynamic_1_UdRA9W!","" +"Ayan","","Aun Khekierea","Rich Mocha","Dynamic_1_Yt1uiSkCgK!","" +"Ayan","","Aun Aukherea","Chocolate Cookie","Dynamic_1_G$iqi763E!","" +"Ayan","","Shuthoth","Silifi of Crimson Stars","Dynamic_1_CkuPj0IwP!","" +"Ayan","","Yuan Hanzu","Acid Hatchet","Dynamic_1_t^CiJAt2TBz17!","" +"Ayan","","Joku Shunja","Dho Life Apprentice Robe","Dynamic_1_&X4EDhy!","" +"Ayan","","Aaminah","Upgraded Marksman's Robe","Dynamic_1_YlHC^cbS!","" +"Ayan","","Anfram Mellow","Ulgrim's Bunny Slippers","Dynamic_1_$MJj0ytiSy0CKN!","" +"Ayan","","Alishia bint Aldan","Lightning Hatchet","Dynamic_1_87z&&Ok2o&jo!","" +"Ayan","","Vierana du Canamorra","Fine Shadow Atlan Mace","Dynamic_1_qtZdY0C!ae!","" +"Ayan","","Qurakh al-Taal","Hearty Mana Beef Stew","Dynamic_1_Ug2snTqb44!","" +"Ayan","","Laedron the Geomancer","Fine Stinging Atlan Spear","Dynamic_1_2lXQdqHWxPU!","" +"Ayan","","Rohula bint Ludun","Arena Staff","Dynamic_1_SjjPqyCHNigY!","" +"Ayan","","Guard Winterborn","Silifi of Crimson Stars","Dynamic_1_!fzudXFZV0Je3!","" +"Ayan","","Ennio di Cinghalle","Perfect Chilling Isparian Claw","Dynamic_1_fYP!","" +"Ayan","","Lydda","Pathwarden Scale Hauberk","Dynamic_1_neYBz15!","" +"Ayan","","Gaston Shadowbound","Major Shadow Tassets","Dynamic_1_jdMT!","" +"Ayan","","Harkwull the Discreet","Quality Flaming Isparian Crossbow","Dynamic_1_Bq7Brhg!","" +"Ayan","","Tanami Kei","Souldrinker","Dynamic_1_en!","" +"Ayan","","Lamorda Loschi","Major Shadow Sollerets","Dynamic_1_2xn4LwsUdh!","" +"Ayan","","Soju Bo-Ki","Composite Crossbow with Handle","Dynamic_1_ADDKG!","" +"Ayan","","Hoshar ibn Jalaq","High Balance Testing Coat","Dynamic_1_bZ4bc!","" +"Ayan","","Guard Bey","Tasty Stout","Dynamic_1_&!4f5YlXZ!","" +"Ayan","","Ishaq the Philosopher","Enhanced Skeletal Atlatl","Dynamic_1_H3UNETkRXTX!","" +"Candeth Keep","","Morathe gives you","Superb Isparian Atlatl","Dynamic_1_g9M7bV3z3#S!","" +"Candeth Keep","","Aun Autuorea gives you","Singularity Katar","Dynamic_1_5kEI0!","" +"Candeth Keep","","Talira Dain","Composite Bow","Dynamic_1_5i1z1Mb!","No text about being given item, it just shows up in backpack" +"Candeth Keep","","Dalius Kendmar gives you","Undead Guise","Dynamic_1_YFrw!","" +"Candeth Keep","","Grania the Bold gives you","Composite Crossbow with Handle","Dynamic_1_DaevbVP!","" +"Candeth Keep","","Yukara Miko the Collector","Acid Longbow","Dynamic_1_F1r^qTQ!","" +"Candeth Keep","","Ryukai Hiro","Good Olthoi Pauldrons","Dynamic_1_HeucrAy6c!","" +"Candeth Keep","","Garaena the Emissary","Seasoned Explorer Arbalest","Dynamic_1_es^0FY!","Aerlinthe Portal NPC" diff --git a/Plugins/RynthCore.Plugin.RynthOracle/Resources/legendary.csv b/Plugins/RynthCore.Plugin.RynthOracle/Resources/legendary.csv new file mode 100644 index 0000000..3a34ee6 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthOracle/Resources/legendary.csv @@ -0,0 +1,41 @@ +Group,Quest,CommonName,Luminance,Flags,Url,Note,Video +"Graveyard","Count Phainor's Amulet","",10000,"graverobbercompleted_0213","https://acportalstorm.com/wiki/Count_Phainor's_Amulet","Not too long, but long enough that its noot wworth 10k to do daily, but easy to do once in a while to get to 30 quests.","https://youtu.be/JRmFOlC-EFw" +"Graveyard","Mhoire Castle","",15000,"cleansingthethronewaiting_1209","https://acportalstorm.com/wiki/Castle_of_Lord_Mhoire_Quest","DON'T RECOMMEND: Don't hand this in, do it and keep your Oubliette flag open. You need to only flag once in the 3 towers and then you can skip straight to the boss daily if you like (I wouldn't, but I'd do it to get to 30). Flagging is easy if you use a flame rare for the SE/SW towers UPDATE: this was bugged for me, it does lock you out of the castle and you need to re-do the flag each time to get in. This is more of a pain to use it now, but the only way to get to Oubliette","https://youtu.be/2ww40h-MUIE" +"Graveyard","Oubliette of Mhoire Castle Quest","Oubliette",30000,"pickeduptokenoublietteboss_0112;startedoublietteboss_0112","https://acportalstorm.com/wiki/Oubliette_of_Mhoire_Castle_Quest","Time consuming but once you're flagged you can run it right after defeating the shade of Lord R in Mhoire castle, just need to collect so many of those stupid portal gems. UPDATE: Don't hand in Shade of Lord R for Mhoire castle and you can skip all that flagging and just run this each time, I recommend that, have to do Mhoire castle just the first time if done that way","https://youtu.be/HmskwQDBel0" +"Rynthid","Defeating the Curator of Torment","RTW",90000,"rtwcompleted_1013","https://acportalstorm.com/wiki/Defeating_the_Curator_of_Torment","Done by the server daily at 8:30 PM EST. Also done like 30 more times throughout the day, just join in, or learn how to open and do it yourself :D","https://youtu.be/uqkV3clTne8" +"Rynthid","Fear Factory Quest","",12000,"fearfactoryreleased_0813","https://acportalstorm.com/wiki/Fear_Factory_Quest","Small lum, so I wouldn't run it daily since its a bit out of the way, but its super easy. Run through rynthid talking to 5 shadows in a neat dungeon. One of the more unique dungeons.","https://youtu.be/rWa_8pngbWc" +"Rynthid","Rynthid Foundry Quest","",10000,"changinggearscompleted_0813","https://acportalstorm.com/wiki/Rynthid_Foundry_Quest","Not worth 10k Lum, but soloable. Dont' alert the guards in the first 2 rooms, then destroy the door once you're through the first door you can run through and hand out your 3 oils in a linear path","https://youtu.be/bZEBCl9vztk" +"Rynthid","Seed of Power","",15000,"visitors4completed_0713","https://acportalstorm.com/wiki/Seed_of_Power","Pain in the ass, 4 dungeons. Run through hitting switches, or doing jumps and finally following the lightning on the floor in a tedius walk through room. (There is a skip for this, search discord for Nan's youtube video showing the skip of the last room)","" +"Rynthid","Rynthid Foothold","Rynthid Recall",27500,"genesiscompleted_0813","https://acportalstorm.com/wiki/Rynthid_Foothold","Rynth recall. If you want to solo it, bring a lightning rare and its simplified","" +"Rynthid","Shroud of Emotion","",20000,"spiritedcompleted_0813","https://acportalstorm.com/wiki/Shroud_of_Emotion","Gives a great necklace, a bit too long to be a daily quest. Can easily be solo'd if you're able to navigate rynthid Virindi, if not you can easily get through with 1-2 friends.","https://youtu.be/n-75FEZXp-w" +"Rynthid","Rynthid Training","",20000,"rynthidtrainingcompleted_1013","https://acportalstorm.com/wiki/Rynthid_Training","Incredibly easy, though a bit buggy and you may need to reset from time to time, hopefully it gets fixed. Either way, Easy as hell to run.","https://youtu.be/oMRiCPELW5g" +"Rynthid","Lugian Assault","LA",20000,"lugianassaultcompleted_0913","https://acportalstorm.com/wiki/Lugian_Assault","Followed by Curator daily, also easy to solo.","https://youtu.be/BCqrQS2mloI" +"Rynthid","End of Days","EoD",15000,"eodcompleted_1013","https://acportalstorm.com/wiki/End_of_Days","Followed by Lugian Assault daily, also easy to solo.","https://youtu.be/Pnw9QcFm_Ag" +"Hoshino","Save Karul","",20000,"deconstructioncompleted_0213","https://acportalstorm.com/wiki/Save_Karul","Hosh quest, short dungeon, boss fight has a lot of tanky friends but with enough melee D they dont' really hit you. Bring a friend to make this fight go quicker.","https://youtu.be/U5GczhliqKg" +"Hoshino","Ninja Academy","",15000,"ninjaacademyfinished_0812","https://acportalstorm.com/wiki/Ninja_Academy","More Hosh, this one I feel needed at least 1 other person, can be solo'd but the enemies hit so hard and the last room has a bit if you run too quickly through to it as it locks you in.","https://youtu.be/HfPZj2SUNss" +"Hoshino","Tanada Intercept and Slaughter","",30000,"tanadaslaughterfinished_0912","https://acportalstorm.com/wiki/Tanada_Intercept","This is two quests but it only counts as 1, each give 15k lum each. One is collecting 6 items in the dungeon and the other is defeating the boss at the end of the dungeon, so do them together. Part of the Ninja academy quest chain and for some reason is easier than part 1","https://youtu.be/6MHFjofk55Y" +"Hoshino","Nanjou Stockade","",15000,"nanjoustockadefinished_1012","https://acportalstorm.com/wiki/Nanjou_Stockade","Third part of the quest chain, still easier than part 1, lol. Just do them all together but I probably wouldn't do these daily but to get to 30.. yes","https://youtu.be/XjrU-tdHhXg" +"Hoshino","Hoshino Must Die","HMD",100000,"defeathoshinokeicompleted_0113","https://acportalstorm.com/wiki/Defeat_Hoshino_Kei","Best done with a large group, don't see this run enough.","" +"Hoshino","Hoshino Fortress Infiltration","HFI",48000,"hoshinotowercomplete_0812","https://acportalstorm.com/wiki/Hoshino_Fortress_Infiltration","Would love to see this done daily but it definitely needs a group. Okay people can solo this, but its better off with a group. Update: There is a nice wall jump skip you can see an ATW youtube video showing this, makes it easier to solo.","" +"Frozen Valley","Halt Dericost Ritual Quest","Halt",40000,"ritualtimecompleted_0411","https://acportalstorm.com/wiki/Halt_Dericost_Ritual_Quest","UPDATE: Been seeing this run more often lately, flag for this quest and its an easy 40k lum and a good check on the john quests. Some people like to do this daily, I've only run it once at this point. Did it with 3 people, seemed like a solid number to do it with, the boss wave hits hard (4th wave)","https://youtu.be/AKRt1mST5zc" +"Frozen Valley","Deewain's Dark Cavern","",30000,"deewaincompleted0211;deewainlegkeypickuptimer","https://acportalstorm.com/wiki/Deewain's_Dark_Cavern","Another good daily you should be doing if you're not learn the maze and the jumps and you can be through it quick for some nice lum.","https://youtu.be/PWfd9Hz7Yes" +"Frozen Valley","Bloodstone Investigation","BS3",45000,"bloodstonefactorycompleted_0211","https://acportalstorm.com/wiki/Bloodstone_Investigation","Hoard bs3s in your inventory and do this one daily, best source of lum, a bit harder than the previous quests but easily soloable.","https://youtu.be/pdos-PebuiM" +"Frozen Valley","Geraine's Study","",30000,"geraineslibrarycompleted0312","https://acportalstorm.com/wiki/Mhoire_Infiltration","I'd put this further down the list but its so convientent to do right after bs3, the exit of bs3 brings you right to study, getting the pages and the symbols are a pain and Geraine takes a while to go down. Bring a friend to make it tolerable","https://youtu.be/HzfzkEAP71M" +"Frozen Valley","Gurog Creation","",10000,"gurogcreationcompleted_1110;journalnoteturninwait","https://acportalstorm.com/wiki/Gurog_Creation","Really easy, would be up higher if it was better than 10k lum, not worth the time to do daily but easy to throw in next time you're in FV and looking to get up to 30 quests.","https://youtu.be/46oPIQKfWdE" +"Neftet","First Sister","Bulb of Mornings",21000,"firstsistercompleted_1012","https://acportalstorm.com/wiki/Harvesting_the_Bulb_of_Mornings","Do all 3 sister quests solo, as they each require you to pick up 10-15 items and hand to a bulb. First sisters, beware the reedsharks, they hit hard. Don't take them lightly.","https://youtu.be/VBYojr1vbns" +"Neftet","Slave Master Quest","",30000,"neftetfreehatsheputwait;findmumiyahdevicewait","https://acportalstorm.com/wiki/Slave_Master_Quest","Soloable for sure, but I don't like this quest. Using the scrying rod is stupid, and it makes you do it twice. It also makes you clear out the entire dungeon worth of enemies to proceed, no skipping fights, bah","" +"Neftet","Janthef's Release","Escape",20000,"escapecompleted_0213","https://acportalstorm.com/wiki/Janthef's_Release","Neftet recall, talk to NPC. Another daily, just be careful of the void statues.","https://youtu.be/Sx-10_oSt2o" +"Neftet","Foundry of Izexi Quest","",15000,"foundryofizexicompleted_1212","https://acportalstorm.com/wiki/Foundry_of_Izexi_Quest","Newly added quest, worthy of being daily I might move this up the list with some more practice. 2 crystals to progress through the dungeon, just be careful of the spirits spamming war, don't get careless like me :D Update: I moved this below Janthef, do them together while at Neftet, might be worth doing daily just less lum than janthef","https://youtu.be/AF0XrmVtr9M" +"Neftet","Four Corners of Dereth","",20000,"fourcornerscompleted_1113","https://acportalstorm.com/wiki/Four_Corners_of_Dereth","UPDATE: I moved this up the list. Tge first four dungeons is a flag for the final part in Neftet, do it once then you can do a fairly quick quest for 20k Lum. Not the fastest 20k lum quest but its 100% worth being one of your 30 now. Only reason its so low is it takes time, 4 dungeons on the corners of the map and then another dungeon with a boss room at the end. If you don't like jumping puzzles, you might skip this. Recommend doing this quest at least once though, its a fun one just long. First 4 dungeons are easy, last dungeon picks up the difficulty a little but all soloable","https://youtu.be/qtklyqjjHC8" +"Random Locations","Third Sister","Bulb of Twilight",21000,"thirdsistercompleted_1212","https://acportalstorm.com/wiki/Harvesting_the_Bulb_of_Twilight","Needs to spawn more ore, be careful of the war spam in the ore collecting area. Not too bad, do it alone.","https://youtu.be/NTiCEE07MYI" +"Random Locations","Second Sister","Bulb of Harvests",21000,"secondsistercompleted_1112","https://acportalstorm.com/wiki/Harvesting_the_Bulb_of_Harvests","Do this to unlock the 3rd sister, and do it as part of your 30 if you have high enough jump (600+) to do it each time. If not, use a jump rare the first time to unlock sister 3 and skip in the future.","https://youtu.be/MFLDhvg5WVQ" +"Random Locations","Releasing the Light","",25000,"blessedcavecompleted_0912","https://acportalstorm.com/wiki/Releasing_the_Light","Out of the way quest, wouldn't run this daily. Extra 5k lum if you grab the book from an easy jump puzzle. Easy enough to be in the top 30. First quest in the 3 sister quest chain, follow up with 3 sisters.","https://youtu.be/qpRIxvvFy4M" +"Random Locations","Dream Reaver Investigation","DRI",20000,"btmcompleted_0513","https://acportalstorm.com/wiki/Dream_Reaver_Investigation","A good daily, a lot of people wait until someone collects the keys then tags along. I did that too, but then I learned the keys and they're super simple, good daily quest.","https://youtu.be/phB-O5AQTQM" +"Random Locations","Purging the Corruption","Purge",20000,"jtmcompleted_0613","https://acportalstorm.com/wiki/Purging_the_Corruption","Another good daily to do, a bit out of the way. Tie to tumerok caves on an alt and have a candeth portal (or get the recall) for quick turn in and it becomes a good daily","https://youtu.be/-eI7A5jBgG0" +"Random Locations","Rescuing Mouf P","Mouf",17500,"moufreward","https://acportalstorm.com/wiki/Rescuing_Mouf_P","One of the first legendary quests you probably learned and most people can do with their eyes closed.","https://youtu.be/eqfBYpXbG7o" +"Random Locations","Liberation of Uziz","",20000,"abductedcompleted_0313","https://acportalstorm.com/wiki/Liberation_of_Uziz","Another daily many people do, if you don't next time you see someone liberating uziz, tag along its quick and easy.","https://youtu.be/K8o_yoxqGyg" +"Random Locations","Lost Lore","",18000,"lostlorepagecompleted_0712","https://acportalstorm.com/wiki/Lost_Lore","This is really easy, just a bit out of the way in my opinion. Honestly could be a decent daily.","https://youtu.be/bO1nOM00Unk" +"Random Locations","Serpent Burial Grounds Quest","",18000,"serpentburialgroundsdone","https://acportalstorm.com/wiki/Serpent_Burial_Grounds_Quest","The dungeon is quick to get to, easy to navigate and the boss packs a mean punch. Bring someone who can debuff the boss and tugak his sclavus swarm, that'd be nice. The sclavus have high melee D and the boss hurts, debuff that sword. I recommend 2-3 people though it could be solo'd . UPDATE- I solo'd this, debuff his sword and its a pain in the ass but doable, took too long though solo.","https://youtu.be/h-NAwcVrrIQ" +"Random Locations","Empyrean Rescue Quest","",35000,"empyreanrescuecompleted_1010;erqlegkeypickuptimer","https://acportalstorm.com/wiki/Empyrean_Rescue_Quest","The longest part of this was finding the portal in the first dungeon, once you find it and go through to the last dungeon, you can tie to the end and skip most of this quest, but you still have to deal with triangles of death and a boss that will instant kill you. Not TERRIBLe but I still don't care much for it","" +"Random Locations","Geraine's Hosts","Hosts",70000,"gerainesbodiescompleted0412","https://acportalstorm.com/wiki/Geraine%27s_Hosts","I wanted to put this above slave master because fuck slave master, but collecting all 7 Geraine's books takes sooo long. I want to confirm you need all 7 and not just the first 1-4 hand in to get credit UPDATE: You only need to hand in books 1-4 for this to count, still time consuming","" +"Random Locations","Hive Queen Assault","",40000,"idoqcompleted_0413","https://acportalstorm.com/wiki/Hive_Queen_Assault","Way too time consuming, not hard but dropping 5 forks is long enough as it is. One of last one's I'd do if ever.","https://youtu.be/bafe1w3NQUQ" diff --git a/Plugins/RynthCore.Plugin.RynthOracle/RynthCore.Plugin.RynthOracle.csproj b/Plugins/RynthCore.Plugin.RynthOracle/RynthCore.Plugin.RynthOracle.csproj index b3fbe8b..450dfd0 100644 --- a/Plugins/RynthCore.Plugin.RynthOracle/RynthCore.Plugin.RynthOracle.csproj +++ b/Plugins/RynthCore.Plugin.RynthOracle/RynthCore.Plugin.RynthOracle.csproj @@ -23,7 +23,7 @@ 66 - Quests, character, titles and leaderboards. + Quests (with the Legendary, marker, Dynamic Stamp and Temple guardian trackers), character and titles. @@ -44,7 +44,10 @@ - + + + + @@ -52,6 +55,10 @@ + + + diff --git a/Plugins/RynthCore.Plugin.RynthOracle/RynthOraclePlugin.cs b/Plugins/RynthCore.Plugin.RynthOracle/RynthOraclePlugin.cs index 60b8190..541ea02 100644 --- a/Plugins/RynthCore.Plugin.RynthOracle/RynthOraclePlugin.cs +++ b/Plugins/RynthCore.Plugin.RynthOracle/RynthOraclePlugin.cs @@ -18,8 +18,8 @@ namespace RynthCore.Plugin.RynthOracle; /// public sealed class RynthOraclePlugin : RynthPluginBase { - // Previous release: 0.2.1. - public const string Version = "0.2.2"; + // Previous release: 0.2.2. + public const string Version = "0.3.0"; private const long QuestReadDelayMs = 6000; // after login, before the hidden /myquests private const long CharacterReadMs = 1000; @@ -41,15 +41,18 @@ public sealed class RynthOraclePlugin : RynthPluginBase private long _loginMs; private long _nextCharacterReadMs; private long _nextCharacterExtrasMs; + private string _charmsJson = ""; + private long _nextBreedingMs; + private string _breedingJson = ""; + private long _nextGuardianMs; + private string _guardianJson = ""; private bool _voidAutoDecided; private bool _dailyCheckStarted; - private int _seenFlagRevision = -1, _seenCatalogRevision = -1, _seenVoidRevision = -1; + private int _seenFlagRevision = -1, _seenCatalogRevision = -1, _seenVoidRevision = -1, _seenIltRevision = -1; // RynthCore's server list (ServerStateClient.Revision) last applied to the server identity. private int _seenServerStateRevision = -1; private bool _noUiLogged; private string? _catalogTag; // the server tag the catalog and server data were loaded for - private bool _conquestLoginRead; - private long _lastDepositBlock = -1; private int _titleCount = -2; private uint _titleCurrent; @@ -63,6 +66,11 @@ public sealed class RynthOraclePlugin : RynthPluginBase _c.ReloadQuestList = ReloadQuestList; _c.Send = cmd => _c.InWorld && Host.InvokeChatParser(cmd); _c.RunCommand = cmd => _c.InWorld && Host.InvokeChatParser(cmd); + _c.ToggleCharm = ToggleCharm; + _c.BreedingCommand = BreedingCommand; + _c.GuardianCommand = GuardianCommand; + _c.UbGiveAvailable = UbGiveAvailable; + _c.SendNav = line => Host.HasSendPluginCommand && Host.SendPluginCommand("RynthNav", "rnav", line); _ui.Log = msg => Host.Log(msg); _mainView = new OracleView(_c); @@ -118,13 +126,15 @@ public sealed class RynthOraclePlugin : RynthPluginBase _c.Flags.Clear(); _c.Void.Clear(); _c.Server.Reset(); + _c.Ilt.Clear(); + _c.Ilt.Poll(Host, Environment.TickCount64); _c.ServerState.Clear(); _c.ServerState.Poll(Host, Environment.TickCount64, force: true); _seenServerStateRevision = _c.ServerState.Revision; - _c.Server.Refresh(Host, Host.GetPlayerId(), _c.ServerState.State); + _c.VoidDotScale = VoidScaleFrom(_c.ServerState.ProfileJson); + _c.Server.Refresh(Host, Host.GetPlayerId(), _c.Ilt.Profile.Ilt, _c.ServerState.State); _catalogTag = null; ApplyServer(); - _conquestLoginRead = false; _titleCount = -2; _c.TitlesKnown = false; _c.EarnedTitles.Clear(); @@ -159,26 +169,47 @@ public sealed class RynthOraclePlugin : RynthPluginBase _c.Timers.Reset(); _c.Flags.Clear(); _c.Void.Clear(); - _c.Conquest.Clear(); - _c.Boards.Clear(); _c.Server.Reset(); + _c.VoidDotScale = 1.0; + _c.Ilt.Clear(); _c.ServerState.Clear(); _c.TitlesKnown = false; _c.EarnedTitles.Clear(); ClearCharacterExtras(); } - /// Forgets the Character tab's session (login, logout): the next character's comes fresh. + /// Forgets the Character tab's charms and session and the ILT readers' data (login, logout): the next character's come fresh. private void ClearCharacterExtras() { + _c.Charms = Shared.IltCharmsView.None; + _charmsJson = ""; + _c.CharmMessage = ""; + _c.Breeding = Shared.IltBreedingView.None; + _breedingJson = ""; + _c.BreedingMessage = ""; + _c.Guardian = Shared.IltGuardianView.None; + _guardianJson = ""; + _c.GuardianRevision++; + _c.GuardianMessage = ""; + _c.UbGiveMissing = false; _c.Session = default; _c.SessionKnown = false; _c.AiSession.Reset(); } + /// The Character tab's Toggle: RynthILT checks the id is one of the player's charms and uses it. + private bool ToggleCharm(uint id) + { + bool ok = _c.InWorld && _c.IltData.ToggleCharm(Host, Environment.TickCount64, id); + _c.CharmMessage = ok ? "Toggled; the status updates in a moment." : "RynthILT didn't take that (not carried any more, or RynthILT isn't loaded)."; + _nextCharacterExtrasMs = Environment.TickCount64 + 1000; // re-read soon so the new state shows + if (_main != null) _main.NeedsPass = true; + return ok; + } + /// - /// While the Character tab is on screen: RynthAi's session, every . - /// Nothing is read with the window closed or on another tab. + /// While the Character tab is on screen: RynthILT's charms JSON and RynthAi's session, every + /// . Nothing is read with the window closed or on another tab. /// private void ReadCharacterExtras(long now) { @@ -186,6 +217,13 @@ public sealed class RynthOraclePlugin : RynthPluginBase if (now < _nextCharacterExtrasMs) return; _nextCharacterExtrasMs = now + CharacterExtrasReadMs; + string json = _c.IltData.ReadCharms(Host, now); + if (!string.Equals(json, _charmsJson, StringComparison.Ordinal)) + { + _charmsJson = json; + _c.Charms = Shared.IltCharmsView.Parse(json); + _main.NeedsPass = true; + } bool known = _c.AiSession.TryGet(Host, now, out Shared.SessionStatsV1 s); if (known != _c.SessionKnown || known && (s.Xp != _c.Session.Xp || s.Lum != _c.Session.Lum || s.Kills != _c.Session.Kills)) _main.NeedsPass = true; @@ -193,12 +231,86 @@ public sealed class RynthOraclePlugin : RynthPluginBase _c.Session = known ? s : default; } + /// The Pet Breeding tab's buttons: a verb for RynthILT's tracker, then a quick re-read. + private bool BreedingCommand(string verb) + { + long now = Environment.TickCount64; + bool ok = _c.InWorld && _c.IltData.PetBreedingCommand(Host, now, verb); + _c.BreedingMessage = ok ? "Sent to RynthILT; the tab updates in a moment." : "RynthILT didn't take that (not loaded, or older than 0.3.1)."; + _nextBreedingMs = now + 800; + if (_main != null) _main.NeedsPass = true; + return ok; + } + + /// + /// While the Pet Breeding tab is on screen: RynthILT's breeding JSON every + /// (reading it keeps RynthILT's tracker scanning). Nothing is read with the window closed or on another tab. + /// + private void ReadBreeding(long now) + { + if (_main == null || _mainView == null || !_main.Visible || _mainView.Tab != OracleView.TabBreeding) return; + if (now < _nextBreedingMs) return; + _nextBreedingMs = now + CharacterExtrasReadMs; + string json = _c.IltData.ReadPetBreeding(Host, now); + if (string.Equals(json, _breedingJson, StringComparison.Ordinal)) return; + _breedingJson = json; + _c.Breeding = Shared.IltBreedingView.Parse(json); + _main.NeedsPass = true; + } + + /// The Quests tab's guardian controls: a verb for RynthILT's guardians, then a quick re-read. + private bool GuardianCommand(string verb) + { + long now = Environment.TickCount64; + bool ok = _c.InWorld && _c.IltData.GuardianCommand(Host, now, verb); + _c.GuardianMessage = ok ? "" : "RynthILT didn't take that (not loaded, or older than 0.3.3)."; + _nextGuardianMs = now + 400; + if (_main != null) _main.NeedsPass = true; + return ok; + } + + /// + /// While the Quests tab is on screen on Infinite Leaftide: RynthILT's Temple guardian JSON every + /// (the guardian rows, switches and last answer). Nothing is + /// read with the window closed, on another tab, or on another server. + /// + private void ReadGuardian(long now) + { + if (_main == null || _mainView == null || !_main.Visible || _mainView.Tab != OracleView.TabQuests) return; + if (!_c.Server.Is(ServerTags.InfiniteLeaftide)) return; + if (now < _nextGuardianMs) return; + _nextGuardianMs = now + CharacterExtrasReadMs; + string json = _c.IltData.ReadGuardian(Host, now); + if (string.Equals(json, _guardianJson, StringComparison.Ordinal)) return; + _guardianJson = json; + _c.Guardian = Shared.IltGuardianView.Parse(json); + _c.GuardianRevision++; + _main.NeedsPass = true; + } + + /// + /// The Give Parchment button's gate: the "/ub give" verb lives in RynthAi, so RynthAi must answer + /// on its hub interface, and must not have rejected the verb already. + /// + private bool UbGiveAvailable() + => _c.InWorld && !_c.UbGiveMissing && Host.HasInvokeChatParser && _c.AiSession.IsLoaded(Host, Environment.TickCount64); + + /// Opens the Quests tab on the trackers: one kind (/ro legendary, /ro dynamic ...) or all of them (null). + private void ShowTrackers(QuestKind? kind) + { + _mainView?.ShowTrackers(kind); + if (_main != null) { _main.Visible = true; _main.NeedsPass = true; } + _nextGuardianMs = 0; // read at once + } + /// Shows the main window on a tab (another plugin's link, or a /ro tab command). private void ShowTab(string tab) { if (_mainView != null) _mainView.Tab = tab; if (_main != null) { _main.Visible = true; _main.NeedsPass = true; } if (tab == OracleView.TabCharacter) _nextCharacterExtrasMs = 0; // read at once + if (tab == OracleView.TabBreeding) _nextBreedingMs = 0; + if (tab == OracleView.TabQuests) _nextGuardianMs = 0; } /// @@ -214,8 +326,6 @@ public sealed class RynthOraclePlugin : RynthPluginBase try { _c.Catalog.Load(tag, msg => Host.Log(msg)); } catch (Exception ex) { Host.Log($"[RynthOracle] Couldn't load the quest list: {ex.Message}"); } _c.Catalog.SyncDiscoveries(_c.Flags); - _c.Conquest.Clear(); - _c.Boards.Clear(); string pack = _c.Catalog.PackServer.Length > 0 ? $" + {_c.Catalog.ServerCount} {_c.Catalog.PackServer}" : ""; Host.Log($"[RynthOracle] Server: {(tag.Length > 0 ? tag : "no server-specific features")} ({_c.Server.Source}); {_c.Catalog.RetailCount} retail quests{pack}."); if (_main != null) _main.NeedsPass = true; @@ -237,6 +347,9 @@ public sealed class RynthOraclePlugin : RynthPluginBase long now = Environment.TickCount64; string line = text.TrimEnd('\r', '\n'); + // RynthAi's reply to a "/ub give" it doesn't have: the Give Parchment button turns itself off. + if (_c.NoteChatLineForGive(line, now) && _main != null) _main.NeedsPass = true; + MyQuestsLine kind = _c.Flags.OnChatLine(line, now); if (kind != MyQuestsLine.None) { @@ -247,29 +360,24 @@ public sealed class RynthOraclePlugin : RynthPluginBase } if (!_c.InWorld) return; - // Server-specific replies: each parser only runs on its own server. - bool ours; - if (_c.Server.Is(ServerTags.Conquest) && _c.Conquest.OnChatLine(line, now, out ours)) - { - if (ours && _c.Settings.HideOwnQuestReplies) eat = 1; - if (_main != null) _main.NeedsPass = true; - return; - } - if (_c.Server.Is(ServerTags.Aelrynth) && _c.Boards.OnChatLine(line, now, out ours)) - { - if (ours && _c.Settings.HideOwnQuestReplies) eat = 1; - if (_main != null) _main.NeedsPass = true; - return; - } - - double scale = _c.Server.Is(ServerTags.Conquest) - ? _c.Conquest.VoidDurationMultiplier(_c.Character.Int(Host, IntArchmagesEndurance)) - : 1.0; - _c.Void.OnChatLine(line.Trim(), now, ResolveTarget, () => _c.Character.HasEnchantment(SpellIds.SurgeOfDestruction), scale); + // A server's own command replies (Conquest's /b, Aelrynth's /top, ...) are its server plugin's. + // A server's own Void DoT duration rule comes from its plugin's profile (RynthConquest's for + // Conquest); 1 everywhere else (VoidScaleFrom). + _c.Void.OnChatLine(line.Trim(), now, ResolveTarget, () => _c.Character.HasEnchantment(SpellIds.SurgeOfDestruction), _c.VoidDotScale); } - /// PropertyInt AugmentationIncreasedSpellDuration (Archmage's Endurance), sent at login. - private const uint IntArchmagesEndurance = 238; + /// The server profile value RynthOracle's Void timers apply ("RynthServer.Profile" values). + internal const string VoidDotScaleKey = "voidDotDurationScale"; + + /// + /// The active server's Void DoT duration multiplier, from its plugin's profile: a number from 1 to + /// 10 (anything else, or none, is 1). Re-read whenever RynthCore's server state or the profile changes. + /// + internal static double VoidScaleFrom(string? profileJson) + { + double v = RynthCore.Plugin.Shared.ServerProfileView.Value(profileJson, VoidDotScaleKey, 1.0); + return v >= 1.0 && v <= 10.0 ? v : 1.0; + } /// The selected target's id when its name matches (RynthCore has no spell-cast event for plugins). private uint ResolveTarget(string name) @@ -320,11 +428,52 @@ public sealed class RynthOraclePlugin : RynthPluginBase break; case "character": case "char": - // The Character tab: the character overview and RynthAi's session (the generic part of - // the Mini Remote's old Character tab; Infinite Leaftide's charms stay RynthILT's). + case "charms": + case "charm": + // The Character tab: the character overview, RynthAi's session and, on Infinite Leaftide, + // RynthILT's charms (the Mini Remote's Charms tab stays as well). // RynthAi, RynthILT and RynthCore's menus link here; it shows, never toggles off. ShowTab(OracleView.TabCharacter); break; + case "legendary": + case "legend": + case "john": + // John's 30 Legendary Key quests: the Quests tab's Legendary rows. + ShowTrackers(QuestKind.Legendary); + break; + case "markers": + case "marker": + // The 100 exploration markers: the Quests tab's marker rows (the old Markers tab). + ShowTrackers(QuestKind.Marker); + break; + case "trackers": + // Every tracker this server has: Legendary, markers, and on Infinite Leaftide stamps and guardians. + ShowTrackers(null); + break; + case "dynamic": + case "dyn": + case "dyno": + case "stamps": + case "guardian": + case "guardians": + // Infinite Leaftide's trackers: Dynamic Stamps and RynthILT's Temple guardians. + bool guardians = arg is "guardian" or "guardians"; + if (!_c.Server.Is(ServerTags.InfiniteLeaftide)) + { + _c.Print((guardians ? "The Temple guardians are" : "Dynamic stamps are") + + " an Infinite Leaftide quest line; this server isn't recognised as Infinite Leaftide."); + ShowTrackers(null); + } + else ShowTrackers(guardians ? QuestKind.Guardian : QuestKind.Dynamic); + break; + case "breeding": + case "breed": + case "pets": + // The Pet Breeding tab (Infinite Leaftide only; the Mini Remote's Pets > Breeding is the same tracker). + if (!_c.Server.Is(ServerTags.InfiniteLeaftide)) + _c.Print("Pet breeding is an Infinite Leaftide feature; this server isn't recognised as Infinite Leaftide."); + ShowTab(OracleView.TabBreeding); + break; case "skills": case "skill": // The Skills tab: RynthCore's skills panel (raise and train) inside this window. @@ -347,20 +496,25 @@ public sealed class RynthOraclePlugin : RynthPluginBase + $"{_c.Flags.Flags.Count} quest flags read, {_c.Catalog.RetailCount} retail quests{pack}, {_c.Void.Dots.Count} Void spells tracked{titles}."); break; case "about": - // The About tab (settings, the server RynthCore says this is). + case "features": + // The About tab (settings, the server RynthCore says this is, RynthILT's server features). _c.Print("Based on Oracle of Dereth by Advis Eveldan - thank you! github.com/advis61/OracleOfDereth (MIT)"); ShowTab(OracleView.TabAbout); break; default: - _c.Print("Commands: /ro (window), /ro character (Character tab: status, session), " + _c.Print("Commands: /ro (window), /ro character (Character tab: status, session, charms), " + "/ro skills|attributes|progress (those tabs), /ro void (Void window), " - + "/ro timers (Quest Timers window), /ro fellowship (Fellowship tab), /ro quests (read quest flags), /ro status, " - + "/ro about (About tab: settings, server)"); + + "/ro timers (Quest Timers window), /ro fellowship (Fellowship tab), /ro breeding (Pet Breeding tab, Infinite Leaftide), " + + "/ro trackers (Quests tab, trackers only), /ro legendary (John's 30 key quests), /ro markers, " + + "/ro dynamic and /ro guardians (Infinite Leaftide: NPC stamps, Temple guardians), " + + "/ro quests (read quest flags), /ro status, " + + "/ro about (About tab: settings, server features)"); break; } - if (arg is "" or "void" or "timers" or "timer" or "fellowship" or "fellow" or "fship" or "character" or "char" + if (arg is "" or "void" or "timers" or "timer" or "fellowship" or "fellow" or "fship" or "character" or "char" or "charms" or "charm" or "skills" or "skill" or "attributes" or "attrs" or "attribute" or "vitals" or "progress" or "progression" - or "about" && !Host.HasUi && !_noUiLogged) + or "breeding" or "breed" or "pets" or "legendary" or "legend" or "john" or "markers" or "marker" or "trackers" + or "dynamic" or "dyn" or "dyno" or "stamps" or "guardian" or "guardians" or "about" or "features" && !Host.HasUi && !_noUiLogged) { _noUiLogged = true; _c.Print("This RynthCore engine can't show plugin windows (it needs script windows, API v71, with ImGui on). /ro status still works."); @@ -371,8 +525,15 @@ public sealed class RynthOraclePlugin : RynthPluginBase private bool RequestQuests() { if (!_c.InWorld) return false; - bool sent = _c.Flags.Request(cmd => Host.InvokeChatParser(cmd), Environment.TickCount64); - if (!sent) Host.Log("[RynthOracle] /myquests was sent moments ago; waiting for that reply."); + long now = Environment.TickCount64; + bool sent = _c.Flags.Request(cmd => Host.InvokeChatParser(cmd), now); + if (!sent) + { + int wait = _c.Flags.ThrottleSecondsLeft(now); + Host.Log(wait > 0 + ? $"[RynthOracle] The server answers one /myquests a minute; try again in {wait}s (the flags shown are kept)." + : "[RynthOracle] /myquests was sent moments ago; waiting for that reply."); + } if (_main != null) _main.NeedsPass = true; return sent; } @@ -410,7 +571,9 @@ public sealed class RynthOraclePlugin : RynthPluginBase long now = Environment.TickCount64; _c.ServerState.Poll(Host, now, force: true); _seenServerStateRevision = _c.ServerState.Revision; - _c.Server.Refresh(Host, _c.Character.PlayerId != 0 ? _c.Character.PlayerId : Host.GetPlayerId(), _c.ServerState.State); + _c.VoidDotScale = VoidScaleFrom(_c.ServerState.ProfileJson); + _c.Ilt.Poll(Host, now); + _c.Server.Refresh(Host, _c.Character.PlayerId != 0 ? _c.Character.PlayerId : Host.GetPlayerId(), _c.Ilt.Profile.Ilt, _c.ServerState.State); try { _c.Catalog.Load(_c.Server.Tag, msg => Host.Log(msg)); } catch (Exception ex) { Host.Log($"[RynthOracle] Couldn't load the quest list: {ex.Message}"); } _c.Catalog.SyncDiscoveries(_c.Flags); @@ -456,6 +619,11 @@ public sealed class RynthOraclePlugin : RynthPluginBase private void TickData(long now) { _c.Flags.Tick(now); + if (_c.Flags.LastPartialReply is { } partial) + { + _c.Flags.LastPartialReply = null; + Host.Log($"[RynthOracle] /myquests reply looked cut short ({partial.Got} lines, {partial.Had} flags held): merged it instead of replacing the list."); + } if (_c.Flags.Revision != _seenFlagRevision) { _seenFlagRevision = _c.Flags.Revision; @@ -491,14 +659,25 @@ public sealed class RynthOraclePlugin : RynthPluginBase if (!_c.InWorld) return; + // RynthILT's profile (every 2 s): which features the server has, the /qb list. + _c.Ilt.Poll(Host, now); + if (_c.Ilt.Revision != _seenIltRevision) + { + _seenIltRevision = _c.Ilt.Revision; + if (_main != null) _main.NeedsPass = true; + } + ReadCharacterExtras(now); + ReadBreeding(now); + ReadGuardian(now); // RynthCore's server list (every 2 s): a new pick or override applies now, not at the next character read. _c.ServerState.Poll(Host, now); if (_c.ServerState.Revision != _seenServerStateRevision) { _seenServerStateRevision = _c.ServerState.Revision; - _c.Server.Refresh(Host, _c.Character.PlayerId != 0 ? _c.Character.PlayerId : Host.GetPlayerId(), _c.ServerState.State); + _c.VoidDotScale = VoidScaleFrom(_c.ServerState.ProfileJson); + _c.Server.Refresh(Host, _c.Character.PlayerId != 0 ? _c.Character.PlayerId : Host.GetPlayerId(), _c.Ilt.Profile.Ilt, _c.ServerState.State); ApplyServer(); if (_main != null) _main.NeedsPass = true; } @@ -524,12 +703,11 @@ public sealed class RynthOraclePlugin : RynthPluginBase _nextCharacterReadMs = now + CharacterReadMs; _c.Character.Read(Host); _c.Void.RemoveExpired(now); - _c.Server.Refresh(Host, _c.Character.PlayerId, _c.ServerState.State); + _c.Server.Refresh(Host, _c.Character.PlayerId, _c.Ilt.Profile.Ilt, _c.ServerState.State); ApplyServer(); LoadQuestBook(now); AnnounceTimers(); ReadTitles(); - TickConquest(now); if (!_voidAutoDecided && _c.Character.Valid) { _voidAutoDecided = true; @@ -589,28 +767,6 @@ public sealed class RynthOraclePlugin : RynthPluginBase if (_main != null) _main.NeedsPass = true; } - /// ConquestAC only: read the advanced augs once after login (void DoT timing uses them), and the auto-deposit. - private void TickConquest(long now) - { - if (!_c.Server.Is(ServerTags.Conquest)) return; - if (!_conquestLoginRead && now - _loginMs > QuestReadDelayMs + 4000) - { - _conquestLoginRead = true; - Host.InvokeChatParser(_c.Conquest.RequestAugs(now)); - } - if (_c.Settings.ConquestAutoDeposit) - { - DateTime local = DateTime.Now; - long block = local.Ticks / TimeSpan.TicksPerMinute / 10; - if (local.Minute % 10 == 0 && block != _lastDepositBlock) - { - _lastDepositBlock = block; - Host.InvokeChatParser(_c.Conquest.AutoDeposit(now)); - _c.Print("Auto-deposited to the bank."); - } - } - } - private void RecordWindows(long now) { if (_main != null && _mainView != null) diff --git a/Plugins/RynthCore.Plugin.RynthOracle/THIRD_PARTY_NOTICES.md b/Plugins/RynthCore.Plugin.RynthOracle/THIRD_PARTY_NOTICES.md index dbe1d8e..9a1d499 100644 --- a/Plugins/RynthCore.Plugin.RynthOracle/THIRD_PARTY_NOTICES.md +++ b/Plugins/RynthCore.Plugin.RynthOracle/THIRD_PARTY_NOTICES.md @@ -18,7 +18,7 @@ What came from upstream: - The quest, augmentation, aug-gem quest, society quest, title and exploration marker lists in `Resources\` (`quests.csv`, `augmentations.csv`, `augquests.csv`, `society.csv`, - `titles.csv`, `markers.csv`, `customquests.csv`), copied unchanged, except that the + `titles.csv`, `markers.csv`), copied unchanged, except that the master quest list is split by its own Server column into `quests.csv` (every retail quest), `quests.conquest.csv` and `quests.levistras.csv` (each server's own rows, loaded only on that server); the lines themselves are untouched. `quests.csv` is Oracle of Dereth's curator-maintained master quest list; @@ -27,9 +27,11 @@ What came from upstream: file carries no licence of its own, so it is treated as part of the MIT-licensed repository. - The logic of the ported features (quest flag parsing and status rules, luminance costs, society ranks and ribbon limits, the status summary, exploration markers, Void - damage-over-time timers, and the ConquestAC features: bank, advanced and enlightenment - augmentations, XP bonuses and levels past 275, the fellowship list, the /top boards), - rewritten for RynthCore. Ported files say so in their header. + damage-over-time timers), rewritten for RynthCore. Ported files say so in their header. +- Upstream's ConquestAC features (bank and auto-deposit, advanced and enlightenment + augmentations, XP bonuses and levels past 275, the fellowship list, the /top boards, + `customquests.csv`) were part of RynthOracle until 2026-10-20 and are now in RynthConquest, + the Conquest server plugin (its own THIRD_PARTY_NOTICES.md). --- diff --git a/Plugins/RynthCore.Plugin.RynthOracle/Views/AboutTab.cs b/Plugins/RynthCore.Plugin.RynthOracle/Views/AboutTab.cs index 7af7c22..fa013b4 100644 --- a/Plugins/RynthCore.Plugin.RynthOracle/Views/AboutTab.cs +++ b/Plugins/RynthCore.Plugin.RynthOracle/Views/AboutTab.cs @@ -19,7 +19,7 @@ internal sealed partial class OracleView w.Checkbox("Read quest flags when you log in", "o.readlogin", s.ReadQuestsAtLogin, v => { s.ReadQuestsAtLogin = v; s.Save(); }); w.Tooltip("Sends /myquests once after login so the quest pages have data."); w.Checkbox("Hide the replies to RynthOracle's own requests", "o.hide", s.HideOwnQuestReplies, v => { s.HideOwnQuestReplies = v; s.Save(); }); - w.Tooltip("/myquests, and on their servers /b, /augs, /top and the like. A command you type yourself always shows its reply."); + w.Tooltip("/myquests. A command you type yourself always shows its reply."); w.Checkbox("Show the Void window for characters with Void Magic", "o.void", s.AutoShowVoidWindow, v => { s.AutoShowVoidWindow = v; s.Save(); }); w.Checkbox("Say in chat when a quest timer comes up", "o.alert", s.AlertTimers, v => { s.AlertTimers = v; s.Save(); }); w.Tooltip("Watches the quests you track (the * on the Quests tab) and prints a line the moment a cooldown ends."); @@ -29,7 +29,9 @@ internal sealed partial class OracleView w.SeparatorText("Server"); ServerIdentity sv = _c.Server; - w.Text(sv.Tag.Length > 0 ? $"{sv.Tag}: its own pages and quest pack are on." : "No server-specific pages here (retail features only)."); + w.Text(sv.Tag.Length == 0 ? "No server-specific pages here (retail features only)." + : sv.Is(ServerTags.InfiniteLeaftide) ? $"{sv.Tag}: its own pages are on (stamps and guardians on the Quests tab, Pet Breeding)." + : $"{sv.Tag}: its own pages and quest pack are on."); w.TextDisabled($"How it was decided: {sv.Source}"); // RynthCore's server list (API v86) and the active server's settings from the plugin that owns it. RynthCore.Plugin.Shared.ServerStateClient st = _c.ServerState; @@ -48,6 +50,8 @@ internal sealed partial class OracleView w.TextDisabled($"This engine is API v{_c.Host.Version}; v86 lets RynthOracle follow RynthCore's server pick and overrides."); if (_c.Host.Version < 75) w.TextDisabled($"This engine is API v{_c.Host.Version}; v75 adds a surer server check and the titles you hold."); + DrawServerFeatures(w); + w.SeparatorText("Quest list"); QuestCatalog cat = _c.Catalog; w.Text($"{cat.RetailCount} retail quests from the {cat.Source}" + @@ -66,17 +70,79 @@ internal sealed partial class OracleView w.SeparatorText("Commands"); w.BulletText("/ro open or close this window"); - w.BulletText("/ro character the Character tab (status, session)"); + w.BulletText("/ro character the Character tab (status, session, charms)"); w.BulletText("/ro skills the Skills tab (raise and train); /ro attributes, /ro progress likewise"); w.BulletText("/ro timers open or close the Quest Timers window"); w.BulletText("/ro fellowship the Fellowship tab"); - w.BulletText("/ro about this tab (settings, server)"); + w.BulletText("/ro trackers the Quests tab, trackers only (Legendary, markers, and on ILT stamps and guardians)"); + w.BulletText("/ro legendary John's Legendary Key quests: have, missing, repeat timers"); + w.BulletText("/ro markers the 100 exploration markers: found and still to find"); + if (_c.Server.Is(Data.ServerTags.InfiniteLeaftide)) + { + w.BulletText("/ro dynamic Infinite Leaftide Dynamic Stamps: NPC stamps you have and are missing"); + w.BulletText("/ro guardians the Temple guardians: riddle answers, auto hand-in, buy if missing, turn-ins"); + w.BulletText("/ro breeding the Pet Breeding tab (when the server has pet breeding)"); + } + w.BulletText("/ro about this tab (settings, server, server features)"); w.BulletText("/ro void open or close the Void window"); w.BulletText("/ro quests read your quest flags now"); w.BulletText("/ro help list the commands in chat"); w.TextDisabled("A server quest pack can be replaced without a rebuild: put quests..csv in %APPDATA%\\RynthCore\\RynthOracle\\packs."); } + /// + /// "Server features": the Leaftide feature list RynthILT keeps (sent in its "RynthILT.Server" + /// profile), drawn group by group in RynthILT's order with each feature's state and where it + /// lives. Nothing here is hard-coded: a newer RynthILT adds features without an Oracle update. + /// + private void DrawServerFeatures(UiWindow w) + { + IltServerProfile p = _c.Ilt.Profile; + if (!p.Available) + { + if (_c.Server.Is(ServerTags.InfiniteLeaftide)) + { + w.SeparatorText("Server features"); + w.TextDisabled("Load RynthILT to list the Infinite Leaftide features here."); + } + return; + } + if (p.Features.Count == 0) return; + + w.SeparatorText("Server features"); + string checkedText = p.CheckedUtc == DateTime.MinValue ? "not checked yet" : $"checked {p.CheckedUtc.ToLocalTime():yyyy-MM-dd HH:mm}"; + w.TextDisabled(p.Ilt + ? $"From RynthILT ({(p.World.Length > 0 ? p.World : "this world")}, {checkedText}{(p.Forced ? ", forced on" : "")})." + : "From RynthILT: this isn't an Infinite Leaftide world, so no Leaftide feature is claimed."); + + // Groups in the order RynthILT lists them; one table per group. + var groups = new System.Collections.Generic.List(); + foreach (IltFeature f in p.Features) + if (!groups.Exists(g => string.Equals(g, f.Group, StringComparison.OrdinalIgnoreCase))) groups.Add(f.Group); + + int on = 0; + foreach (IltFeature f in p.Features) if (f.State == RynthCore.Plugin.Shared.RynthIltServer.StateOn) on++; + w.TextDisabled($"{on} of {p.Features.Count} on."); + + foreach (string group in groups) + { + if (!w.CollapsingHeader(group.Length > 0 ? group : "Other", "o.feat.h." + group)) continue; + foreach (IltFeature f in p.InGroup(group)) + { + uint color = f.State switch + { + RynthCore.Plugin.Shared.RynthIltServer.StateOn => UiColors.Green, + RynthCore.Plugin.Shared.RynthIltServer.StateOff => UiColors.Red, + _ => UiColors.Yellow, + }; + w.TextColored(color, $"[{IltServerProfile.StateText(f.State)}]"); + w.SameLine(); + w.Text(f.Label); + if (f.Where.Length > 0) w.Tooltip("Where: " + f.Where); + } + } + } + private void StartQuestListCheck() { _c.Settings.LastQuestListCheckUtc = DateTime.UtcNow; diff --git a/Plugins/RynthCore.Plugin.RynthOracle/Views/BoardsTab.cs b/Plugins/RynthCore.Plugin.RynthOracle/Views/BoardsTab.cs deleted file mode 100644 index 60e1c75..0000000 --- a/Plugins/RynthCore.Plugin.RynthOracle/Views/BoardsTab.cs +++ /dev/null @@ -1,152 +0,0 @@ -// Ported from Oracle of Dereth by Advis Eveldan (advis61), MIT (the ConquestAC part). See THIRD_PARTY_NOTICES.md. -using System; -using RynthCore.Plugin.RynthOracle.Data; -using RynthCore.Plugin.RynthOracle.Ui; - -namespace RynthCore.Plugin.RynthOracle.Views; - -/// -/// Leaderboards, server-specific: ConquestAC's /top boards (upstream's Top Players tab), or -/// Aelrynth's /top boards and /trial dungeon records. Each server's view only exists on that -/// server (tab tags in OracleView), since both servers answer /top in different shapes. -/// -internal sealed partial class OracleView -{ - private int _conquestBoard; - private int _aelrynthView; // 0 boards, 1 me, 2 trials - private string _aelrynthBoardArg = ""; - private string _trialArg = ""; - - private void DrawBoards(UiWindow w) - { - if (_c.Server.Is(ServerTags.Conquest)) DrawConquestBoards(w); - else if (_c.Server.Is(ServerTags.Aelrynth)) DrawAelrynthBoards(w); - } - - private void DrawConquestBoards(UiWindow w) - { - ConquestData cq = _c.Conquest; - _conquestBoard = Math.Clamp(_conquestBoard, 0, cq.Boards.Count - 1); - for (int i = 0; i < cq.Boards.Count; i++) - { - int index = i; - if (i > 0) w.SameLine(); - w.ToggleButton(cq.Boards[i].Label, "cb.tab." + i, i == _conquestBoard, () => _conquestBoard = index, small: true); - } - ConquestBoard b = cq.Boards[_conquestBoard]; - w.TextDisabled(b.UpdatedUtc == DateTime.MinValue ? "not read yet" : $"read at {b.UpdatedUtc.ToLocalTime():HH:mm}"); - if (b.You != null) w.Text($"You: #{b.You.Rank} with {b.You.Value}"); - DrawRows(w, "cb.rows", b.Rows); - } - - private static void DrawRows(UiWindow w, string id, System.Collections.Generic.List rows) - { - w.BeginChild(id, 0f, 0f, border: true); - w.TextDisabled("Rank"); - w.SameLine(60f); - w.TextDisabled("Name"); - w.SameLine(280f); - w.TextDisabled("Value"); - foreach (BoardRow r in rows) - { - w.Text(r.Rank.ToString()); - w.SameLine(60f); - if (r.IsYou) w.TextColored(UiColors.Gold, Cut(r.Name, 30)); - else w.Text(Cut(r.Name, 30)); - w.SameLine(280f); - w.Text(r.Value); - if (r.Extra.Length > 0) { w.SameLine(420f); w.TextDisabled(Cut(r.Extra, 40)); } - } - if (rows.Count == 0) w.TextDisabled("Nothing read yet. Press Refresh."); - w.EndChild(); - } - - private void DrawAelrynthBoards(UiWindow w) - { - AelrynthBoards a = _c.Boards; - w.ToggleButton("Boards", "ab.v0", _aelrynthView == 0, () => _aelrynthView = 0, small: true); - w.SameLine(); - w.ToggleButton("Me", "ab.v1", _aelrynthView == 1, () => _aelrynthView = 1, small: true); - w.SameLine(); - w.ToggleButton("Trials", "ab.v2", _aelrynthView == 2, () => _aelrynthView = 2, small: true); - if (a.LastError.Length > 0) w.TextColored(UiColors.Red, a.LastError); - - if (_aelrynthView == 1) - { - w.BeginChild("ab.melist", 0f, 0f, border: true); - foreach (AelrynthStanding s in a.Standings) - { - w.Text(Cut(s.Title, 34)); - w.SameLine(260f); - w.Text(s.Rank > 0 ? $"#{s.Rank} of {s.Of}" : "-"); - if (s.Value.Length > 0) { w.SameLine(380f); w.Text(s.Value); } - } - if (a.Standings.Count == 0) w.TextDisabled("Nothing read yet. Press Refresh."); - w.EndChild(); - return; - } - - if (_aelrynthView == 2) - { - w.InputText("Dungeon", "ab.trialarg", _trialArg, 48, s => _trialArg = s); - w.SameLine(); - w.Button("Top 10", "ab.trialtop", () => { if (_trialArg.Trim().Length > 0) _c.Send(a.RequestTrial(_trialArg, _c.NowMs)); }); - w.BeginChild("ab.triallist", 0f, 0f, border: true); - foreach (TrialDungeon d in a.Trials) - { - TrialDungeon row = d; - w.Selectable($"{d.Name} ({d.Landblock})", "ab.t." + d.Landblock, false, - () => { _trialArg = row.Name; _c.Send(a.RequestTrial(row.Name, _c.NowMs)); }); - w.Tooltip("Click for this dungeon's top 10."); - w.TextDisabled(" record:"); w.SameLine(90f); w.TextWrapped(d.Record); - w.TextDisabled(" you:"); w.SameLine(90f); w.Text(d.You); - w.TextDisabled(" this week:"); w.SameLine(90f); w.Text(d.Week); - } - foreach (string line in a.TrialLines) if (!line.StartsWith("Trials - ", StringComparison.Ordinal)) w.TextWrapped(line); - if (a.TrialBoardTitle.Length > 0) - { - w.SeparatorText(a.TrialBoardTitle); - foreach (BoardRow r in a.TrialRows) - { - w.Text($"{r.Rank,2}. {r.Value}"); - w.SameLine(90f); - w.Text(Cut(r.Name, 28)); - w.SameLine(300f); - w.TextDisabled(Cut(r.Extra, 40)); - } - foreach (string n in a.TrialNotes) w.TextWrapped(n); - } - if (a.Trials.Count == 0 && a.TrialBoardTitle.Length == 0) w.TextDisabled("Nothing read yet. Press Refresh."); - w.EndChild(); - return; - } - - w.Button("All boards", "ab.all", () => _c.Send(a.RequestTop("", _c.NowMs))); - w.Tooltip("Sends /top: every board's leader."); - w.SameLine(); - w.InputText("Board", "ab.arg", _aelrynthBoardArg, 32, s => _aelrynthBoardArg = s); - w.SameLine(); - w.Button("Top 10", "ab.board", () => { if (_aelrynthBoardArg.Trim().Length > 0) _c.Send(a.RequestTop(_aelrynthBoardArg, _c.NowMs)); }); - if (a.OverviewNote.Length > 0) w.TextDisabled(a.OverviewNote); - - if (a.BoardTitle.Length > 0) - { - w.SeparatorText($"{a.BoardTitle} ({a.BoardNote})"); - if (a.BoardYou.Length > 0) w.TextColored(UiColors.Gold, a.BoardYou); - DrawRows(w, "ab.rows", a.BoardRows); - return; - } - w.BeginChild("ab.overview", 0f, 0f, border: true); - foreach (AelrynthBoardSummary s in a.Overview) - { - AelrynthBoardSummary row = s; - w.Selectable(Cut(s.Title, 30), "ab.o." + s.Key, false, () => { _aelrynthBoardArg = row.Key; _c.Send(a.RequestTop(row.Key, _c.NowMs)); }, 230f); - w.Tooltip($"/top {s.Key}"); - w.SameLine(240f); - w.Text(Cut(s.Leader, 24)); - if (s.Value.Length > 0) { w.SameLine(430f); w.Text(s.Value); } - } - if (a.Overview.Count == 0) w.TextDisabled("Nothing read yet. Press All boards."); - w.EndChild(); - } -} diff --git a/Plugins/RynthCore.Plugin.RynthOracle/Views/CharacterTab.cs b/Plugins/RynthCore.Plugin.RynthOracle/Views/CharacterTab.cs index c5fe314..d8eca34 100644 --- a/Plugins/RynthCore.Plugin.RynthOracle/Views/CharacterTab.cs +++ b/Plugins/RynthCore.Plugin.RynthOracle/Views/CharacterTab.cs @@ -9,8 +9,8 @@ namespace RynthCore.Plugin.RynthOracle.Views; /// /// Character: level and experience, luminance, the status summary (upstream's Status HUD: buff, /// house, beer, page and rare timers, key skills, aetheria surges), RynthAi's session (the generic -/// part of the Mini Remote's old Character tab, moved here 2026-10-13) and the full buff list. -/// Infinite Leaftide's charms stay RynthILT's (its Charms tab in the Mini Remote). +/// part of the Mini Remote's old Character tab, moved here 2026-10-13), on Infinite Leaftide RynthILT's +/// charms (a second place for them: the Mini Remote's Charms tab stays) and the full buff list. /// internal sealed partial class OracleView { @@ -57,6 +57,7 @@ internal sealed partial class OracleView Field(w, "Summoning", SkillText(c.Summoning), 300f, 400f); DrawSession(w); + DrawCharms(w); var list = new List(c.Enchantments); list.Sort((a, b) => a.Remaining.CompareTo(b.Remaining)); @@ -105,6 +106,97 @@ internal sealed partial class OracleView private static string RateText(double perHour) => perHour > 0 ? TimeText.Number((long)Math.Round(perHour)) : "0"; + /// + /// "Charms": RynthILT's Infinite Leaftide charm list (the Mini Remote's Charms tab shows the same + /// one), with a Toggle for each carried charm and Guardian Hand. Nothing is listed here: RynthILT + /// sends the list, so a charm it learns about shows up without an Oracle update. + /// + private void DrawCharms(UiWindow w) + { + Shared.IltCharmsView v = _c.Charms; + if (!v.Loaded) + { + if (_c.Server.Is(ServerTags.InfiniteLeaftide)) + { + w.SeparatorText("Charms"); + w.TextDisabled("Load RynthILT to list your Infinite Leaftide charms here."); + } + return; + } + if (!v.Available) return; // not an ILT world: no charms + + w.SeparatorText("Charms"); + w.TextDisabled($"{v.Acquired} acquired, {v.Active} on (from RynthILT{(v.World.Length > 0 ? ", " + v.World : "")})."); + if (_c.CharmMessage.Length > 0) w.TextDisabled(_c.CharmMessage); + + if (w.CollapsingHeader($"Charms ({v.Charms.Count})", "c.charms", defaultOpen: true)) + { + if (v.Charms.Count == 0) w.TextDisabled("RynthILT hasn't listed any charms yet."); + for (int i = 0; i < v.Charms.Count; i++) + { + Shared.IltCharmRow r = v.Charms[i]; + CharmState(w, r.Active); + w.SameLine(50f); + if (r.Carried) w.Text(Cut(r.Name, 30)); + else w.TextDisabled(Cut(r.Name, 30)); + if (r.Effect.Length > 0) w.Tooltip(r.Effect); + w.SameLine(270f); + w.TextDisabled(r.MaxTier > 0 ? $"T{r.Tier}/{r.MaxTier}" : r.Tier > 0 ? $"T{r.Tier}" : "-"); + w.SameLine(330f); + w.TextDisabled(AcquiredText(r)); + if (r.Server == "off") + { + w.SameLine(430f); + w.TextColored(UiColors.Red, "server off"); + } + if (r.Carried && r.ToggleId != 0) + { + w.SameLine(510f); + uint id = r.ToggleId; + w.SmallButton("Toggle", "c.charm." + i, () => _c.ToggleCharm(id)); + } + } + } + + if (v.Hands.Count > 0 && w.CollapsingHeader($"Guardian Hands ({v.Hands.Count})", "c.hands", defaultOpen: true)) + { + for (int i = 0; i < v.Hands.Count; i++) + { + Shared.IltHandRow h = v.Hands[i]; + CharmState(w, h.Active); + w.SameLine(50f); + w.Text(Cut(h.Name, 30)); + if (h.Server == "off") + { + w.SameLine(430f); + w.TextColored(UiColors.Red, "server off"); + } + w.SameLine(510f); + uint id = h.Id; + w.SmallButton("Toggle", "c.hand." + i, () => _c.ToggleCharm(id)); + } + } + } + + /// ON in green, OFF in red, "?" in grey (status not read yet). + private static void CharmState(UiWindow w, string active) + { + switch (active) + { + case "on": w.TextColored(UiColors.Green, "ON"); break; + case "off": w.TextColored(UiColors.Red, "OFF"); break; + default: w.TextColored(UiColors.Grey, "?"); break; + } + } + + /// Carried (with the count), stored (seen on this character before) or not acquired. + internal static string AcquiredText(Shared.IltCharmRow r) => r.Acquired switch + { + "carried" => r.Count > 1 ? $"carried x{r.Count}" : "carried", + "seen" => r.LastSeen.Length > 0 ? "seen " + r.LastSeen : "seen", + _ => "not acquired", + }; + /// /// The buff timer: the soonest-ending long (over 15 minutes) buff that isn't a beer, a debuff /// or one of the not-really-buffs, with how many there are (upstream's rule). diff --git a/Plugins/RynthCore.Plugin.RynthOracle/Views/ConquestTab.cs b/Plugins/RynthCore.Plugin.RynthOracle/Views/ConquestTab.cs deleted file mode 100644 index 1964c09..0000000 --- a/Plugins/RynthCore.Plugin.RynthOracle/Views/ConquestTab.cs +++ /dev/null @@ -1,204 +0,0 @@ -// Ported from Oracle of Dereth by Advis Eveldan (advis61), MIT. See THIRD_PARTY_NOTICES.md. -using System; -using System.Linq; -using RynthCore.Plugin.RynthOracle.Data; -using RynthCore.Plugin.RynthOracle.Ui; - -namespace RynthCore.Plugin.RynthOracle.Views; - -/// -/// ConquestAC (tag Conquest; the tab only exists there): bank balances and bank commands, advanced -/// and enlightenment augmentations, levels past 275 and the XP bonus breakdown, fellowships looking -/// for members, and the server's custom quest worklist. Upstream's Bank, Conquest Augs, Conquest XP, -/// Fship and Custom tabs. -/// -internal sealed partial class OracleView -{ - private static readonly string[] ConquestViews = { "Bank", "Augs", "Enlightenment", "Experience", "Fellowships", "Custom quests" }; - private int _conquestView; - private int _withdrawIndex = ConquestData.DefaultWithdraw, _transferIndex = ConquestData.DefaultTransfer; - private string _withdrawAmount = "", _transferAmount = "", _transferTarget = ""; - private int _fshipSort; - - private void DrawConquest(UiWindow w) - { - for (int i = 0; i < ConquestViews.Length; i++) - { - int index = i; - if (i > 0) w.SameLine(); - w.ToggleButton(ConquestViews[i], "cq.v." + i, i == _conquestView, () => _conquestView = index, small: true); - } - switch (_conquestView) - { - case 0: DrawConquestBank(w); break; - case 1: DrawConquestAugs(w); break; - case 2: DrawConquestEnl(w); break; - case 3: DrawConquestXp(w); break; - case 4: DrawConquestFships(w); break; - default: DrawConquestCustom(w); break; - } - } - - private static string ReadAt(DateTime utc) => utc == DateTime.MinValue ? "not read yet" : $"read at {utc.ToLocalTime():HH:mm}"; - - private void DrawConquestBank(UiWindow w) - { - ConquestData cq = _c.Conquest; - w.TextDisabled(ReadAt(cq.BankUtc)); - foreach (NamedValue b in cq.Bank.OrderBy(b => b.Name, StringComparer.OrdinalIgnoreCase)) - { - w.TextDisabled(Cut(b.Name, 34)); - w.SameLine(260f); - w.Text(b.Value); - } - if (cq.Bank.Count == 0) w.TextDisabled("No balances read yet."); - - w.SeparatorText("Deposit"); - w.Button("Deposit everything", "cq.bank.deposit", () => _c.Send("/bank deposit")); - w.Tooltip("Sends /bank deposit."); - w.Checkbox("Deposit by itself every ten minutes", "cq.bank.auto", _c.Settings.ConquestAutoDeposit, - v => { _c.Settings.ConquestAutoDeposit = v; _c.Settings.Save(); }); - w.Tooltip("At :00, :10, :20 ... while you're logged in on ConquestAC. Its reply is hidden."); - - w.SeparatorText("Withdraw"); - string[] wl = ConquestData.Withdrawable.Select(c => c.Label).ToArray(); - w.Combo("Currency", "cq.bank.wcur", _withdrawIndex, wl, i => _withdrawIndex = Math.Clamp(i, 0, wl.Length - 1)); - w.InputText("Amount", "cq.bank.wamt", _withdrawAmount, 16, s => _withdrawAmount = s); - w.Button("Withdraw", "cq.bank.withdraw", () => - { - string? cmd = ConquestData.WithdrawCommand(ConquestData.Withdrawable[_withdrawIndex], _withdrawAmount); - if (cmd == null) _c.Print("Withdraw: type a whole number above 0."); - else _c.Send(cmd); - }); - - w.SeparatorText("Transfer to a character"); - string[] tl = ConquestData.Transferable.Select(c => c.Label).ToArray(); - w.Combo("Currency##t", "cq.bank.tcur", _transferIndex, tl, i => _transferIndex = Math.Clamp(i, 0, tl.Length - 1)); - w.InputText("Amount##t", "cq.bank.tamt", _transferAmount, 16, s => _transferAmount = s); - w.InputText("Character", "cq.bank.tgt", _transferTarget, 40, s => _transferTarget = s); - w.Button("Transfer", "cq.bank.transfer", () => - { - string? cmd = ConquestData.TransferCommand(ConquestData.Transferable[_transferIndex], _transferAmount, _transferTarget); - if (cmd == null) _c.Print("Transfer: type a whole number above 0 (MMD notes: at most 1,000) and a character name."); - else _c.Send(cmd); - }); - } - - private void DrawConquestAugs(UiWindow w) - { - ConquestData cq = _c.Conquest; - w.TextDisabled($"{ReadAt(cq.AugsUtc)}, {cq.AugTotal} in total"); - w.TextDisabled("Aug"); w.SameLine(120f); w.TextDisabled("Have"); w.SameLine(170f); w.TextDisabled("Next costs"); w.SameLine(330f); w.TextDisabled("Effect now"); - foreach (ConquestAug a in cq.Augs) - { - w.Text(a.Name); - w.SameLine(120f); - w.Text(a.Count.ToString()); - w.SameLine(170f); - w.Text(a.NextCostText()); - w.SameLine(330f); - w.TextDisabled(Cut(a.Effect(), 48)); - w.Tooltip(a.Effect()); - } - } - - private void DrawConquestEnl(UiWindow w) - { - ConquestData cq = _c.Conquest; - w.TextDisabled(ReadAt(cq.EnlUtc)); - foreach (NamedValue a in cq.EnlAugs) - { - w.Text(Cut(a.Name, 26)); - w.SameLine(200f); - w.Text(a.Value); - w.SameLine(360f); - w.TextDisabled(ConquestData.EnlCost(a.Name)); - } - if (cq.EnlAugs.Count == 0) w.TextDisabled("Nothing read yet. Press Refresh."); - } - - private void DrawConquestXp(UiWindow w) - { - ConquestData cq = _c.Conquest; - CharacterSnapshot ch = _c.Character; - int level = ch.Level; - w.SeparatorText($"Level {level}"); - if (level >= ConquestData.MaxLevel) w.Text("Maximum level."); - else - { - long start = level >= 276 ? ConquestData.XpForLevel(level) : 0; - long next = level >= 275 ? ConquestData.XpForLevel(level + 1) : 0; - if (next > 0) - { - long toNext = Math.Max(0, next - ch.TotalXp); - long begin = level == 275 ? 191_226_310_247 : start; - float frac = next > begin ? (float)Math.Clamp((double)(ch.TotalXp - begin) / (next - begin), 0, 1) : 1f; - w.ProgressBar(frac, -1f, 0f, $"{TimeText.Number(toNext)} to level {level + 1}"); - } - else - { - (long toNext, float frac) = ch.LevelProgress(); - w.ProgressBar(frac, -1f, 0f, $"{TimeText.Number(toNext)} to level {level + 1}"); - } - long toMax = Math.Max(0, ConquestData.XpForLevel(ConquestData.MaxLevel) - ch.TotalXp); - w.TextDisabled($"{TimeText.Number(toMax)} to level {ConquestData.MaxLevel}"); - } - int target = ch.Enlightenment + 1; - w.SeparatorText($"Enlightenment {ch.Enlightenment}"); - w.Text($"Next costs {TimeText.Number(ConquestData.EnlCoinCost(target))} coins and {(ConquestData.EnlLuminanceCost(target) / 1_000_000.0):0.##}M luminance"); - - w.SeparatorText("Experience bonuses"); - w.TextDisabled(ReadAt(cq.BonusUtc)); - foreach (NamedValue b in cq.Bonuses) - { - w.TextDisabled(b.Name); - w.SameLine(200f); - w.Text(b.Value.Length > 0 ? b.Value : "-"); - } - } - - private void DrawConquestFships(UiWindow w) - { - ConquestData cq = _c.Conquest; - w.TextDisabled($"{ReadAt(cq.FshipUtc)}, {cq.Fellowships.Count} looking for members"); - w.Combo("Sort", "cq.fship.sort", _fshipSort, new[] { "Name", "Leader", "Most members", "Location" }, i => _fshipSort = i); - var list = _fshipSort switch - { - 1 => cq.Fellowships.OrderBy(f => f.Leader, StringComparer.OrdinalIgnoreCase), - 2 => cq.Fellowships.OrderByDescending(f => f.MemberCount), - 3 => cq.Fellowships.OrderBy(f => f.Location, StringComparer.OrdinalIgnoreCase), - _ => cq.Fellowships.OrderBy(f => f.Name, StringComparer.OrdinalIgnoreCase), - }; - w.BeginChild("cq.fship.list", 0f, 0f, border: true); - foreach (ConquestFellowship f in list) - { - w.Text(Cut(f.Name, 26)); - w.SameLine(200f); - w.Text(Cut(f.Leader, 20)); - w.SameLine(350f); - w.Text(f.Members); - if (f.Location.Length > 0) { w.SameLine(410f); w.TextDisabled(Cut(f.Location, 26)); } - } - if (cq.Fellowships.Count == 0) w.TextDisabled("None read yet. Press Refresh."); - w.EndChild(); - } - - private void DrawConquestCustom(UiWindow w) - { - DateTime now = _c.UtcNow; - bool any = false; - foreach (CustomQuest q in CustomQuestList.For(_c.Server)) - { - any = true; - DoneMark(w, q.IsComplete(_c.Flags, now)); - w.SameLine(50f); - CustomQuest row = q; - string status = q.Status(_c.Flags, now); - w.Selectable(Cut(q.Name, 34), "cq.cust." + q.Flag, false, () => PrintEntry(row.Name, row.Flag, status, row.Hint, row.Url), 280f); - w.SameLine(340f); - w.Text(status); - } - if (!any) w.TextDisabled("No custom quests listed for this server."); - if (_c.Flags.LastReadUtc == DateTime.MinValue) w.TextDisabled("Read your quest flags (Quests tab) for their status."); - } -} diff --git a/Plugins/RynthCore.Plugin.RynthOracle/Views/DynamicStampsTab.cs b/Plugins/RynthCore.Plugin.RynthOracle/Views/DynamicStampsTab.cs new file mode 100644 index 0000000..be3bd52 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthOracle/Views/DynamicStampsTab.cs @@ -0,0 +1,214 @@ +using System; +using System.Collections.Generic; +using RynthCore.Plugin.RynthOracle.Data; +using RynthCore.Plugin.RynthOracle.Ui; + +namespace RynthCore.Plugin.RynthOracle.Views; + +/// +/// Dynamic Stamps (Infinite Leaftide only): the NPC hand-ins that put a "Dynamic_N_..." flag on +/// the character, read from /myquests. They are rows of the Quests tab's merged list (QuestsTab.cs: +/// DYN rows, the Show filter's area picker). What is here is the opened stamp's box (RynthNav, the +/// Parchment hand-in, chat), the read after a hand-in, and the RynthNav sender every row kind +/// shares. The list follows the players' "ExtraDyn" sheet (dynstamps.csv). +/// +/// Give Parchment sends RynthAi's "/ub give 1 <parchment> to <npc>". That verb belongs to +/// RynthAi, so the button is disabled (with a tooltip saying why) when RynthAi isn't loaded or has +/// answered "Unrecognized /ub command" to it. +/// +internal sealed partial class OracleView +{ + // The stamp clicked last: the box below the list offers RynthNav's auto nav to it. + private DynamicStamp? _dynNav; + private bool _dynNavDone; + private string _dynNavStatus = ""; + // The Parchment waiting for Yes: handing it over is the one thing here that can't be taken back. + private string _giveConfirm = ""; + + /// + /// The destination box (the click's pop-up): the stamp, where RynthNav will take you, and Go (plan + /// and walk the route: portals, recalls and dungeon entrances included), Arrow, Chat and Close. + /// + private void DrawDynamicNavBox(UiWindow w) + { + DynamicStamp? s = _dynNav; + if (s == null) return; + List targets = s.NavCandidates(); + w.SeparatorText("Navigate to " + Cut(s.Label, 40)); + w.TextDisabled(targets.Count == 0 + ? "No place, coordinates or area to go to for this stamp." + : "Where: " + Cut(string.Join(" or ", targets), 90)); + if (targets.Count > 0) + { + w.Button("Go (auto nav)", "dy.nav.go", () => SendNav("go", s)); + w.Tooltip("RynthNav plans the route (walking, portals, recalls, the dungeon's entrance) and walks it."); + w.SameLine(); + w.Button("Arrow", "dy.nav.arrow", () => SendNav("arrow", s)); + w.Tooltip("Only point RynthNav's arrow at it."); + w.SameLine(); + } + w.Button("Chat", "dy.nav.chat", () => PrintStamp(s, _dynNavDone)); + w.SameLine(); + w.Button("Close", "dy.nav.close", () => { _dynNav = null; _dynNavStatus = ""; _selKey = ""; _giveConfirm = ""; }); + + // The hand-in: a Parchment from your packs to the stamp's NPC (RynthAi's /ub give). + if (s.Npc.Length > 0) + { + string? parchment = CarriedParchment(); + if (parchment != null) + { + string? why = GiveUnavailableReason(); + if (why == null && _giveConfirm == parchment) + { + // Asked first: the Parchment leaves the pack and doesn't come back. + w.TextColored(UiColors.Red, $"Give one {Cut(parchment, 30)} to {Cut(s.Npc, 30)}? It leaves your pack for good."); + w.SmallButton("Yes, give it", "dy.nav.give.yes", () => { _giveConfirm = ""; GiveParchment(s, parchment); }); + w.SameLine(); + w.SmallButton("Cancel", "dy.nav.give.no", () => _giveConfirm = ""); + } + else if (why == null) + { + w.Button("Give " + Cut(parchment, 24), "dy.nav.give", () => _giveConfirm = parchment); + w.Tooltip($"Hands one {parchment} to {s.Npc} (it asks first). Stand near them (or Go first): AC walks you the last bit."); + } + else + { + // Greyed text in place of the button, so it can't be clicked into a command nobody answers. + w.TextDisabled("[Give " + Cut(parchment, 24) + "]"); + w.Tooltip(why); + } + } + else + w.TextDisabled("No Parchment in your packs to give " + Cut(s.Npc, 30) + "."); + } + if (_dynNavStatus.Length > 0) w.TextDisabled(_dynNavStatus); + } + + // A /myquests read this long after a Parchment hand-in (the walk there and the NPC's answer), so + // the new stamp shows as had; 0 = none due. + private const long HandInRefreshMs = 8000; + private long _dynRefreshAt; + + /// The read after a hand-in, when it is due: now, or when the server's once-a-minute wait ends. + private void RefreshAfterHandIn(QuestFlagStore flags) + { + if (_dynRefreshAt == 0 || _c.NowMs < _dynRefreshAt) return; + if (flags.Loading) return; + int wait = flags.ThrottleSecondsLeft(_c.NowMs); + if (wait > 0) { _dynRefreshAt = _c.NowMs + wait * 1000L; return; } + _dynRefreshAt = 0; + _c.RequestQuests(); + } + + // Packs scanned for a Parchment at most this often (the box draws every frame). + private const long ParchmentScanMs = 1500; + private long _parchmentScanAt; + private string? _parchmentName; + + /// + /// The name of a Parchment you carry (the main pack and its side packs), or null. Any item + /// whose name has "Parchment" in it; read again every . + /// + private string? CarriedParchment() + { + if (_c.ParchmentFinder != null) return _c.ParchmentFinder(); + if (_c.NowMs - _parchmentScanAt < ParchmentScanMs && _parchmentScanAt != 0) return _parchmentName; + _parchmentScanAt = _c.NowMs == 0 ? 1 : _c.NowMs; + _parchmentName = null; + RynthCore.PluginSdk.RynthCoreHost host = _c.Host; // a struct: an empty one (the offline tests) reports nothing carried + uint me = _c.Character.PlayerId; + if (!_c.InWorld || me == 0 || !host.HasGetContainerContents) return null; + var buf = new uint[512]; + var packs = new List { me }; + for (int p = 0; p < packs.Count && p < 16; p++) + { + int n = Math.Min(host.GetContainerContents(packs[p], buf), buf.Length); + for (int i = 0; i < n; i++) + { + uint id = buf[i]; + if (!host.TryGetObjectName(id, out string name)) continue; + if (name.IndexOf("Parchment", StringComparison.OrdinalIgnoreCase) >= 0) { _parchmentName = name; return name; } + // A side pack in the main pack: look inside it too (only one level deep, as AC packs go). + if (p == 0) packs.Add(id); + } + } + return null; + } + + /// Why Give Parchment can't be used now (for its tooltip); null when it can. + private string? GiveUnavailableReason() + { + if (_c.UbGiveMissing) + return "The loaded RynthAi has no \"/ub give\" (it answered \"Unrecognized /ub command\"). Update RynthAi, or hand the Parchment over yourself."; + if (!_c.UbGiveAvailable()) + return "Needs RynthAi: the hand-in is RynthAi's \"/ub give\". It isn't loaded (or you aren't logged in), so give the Parchment to the NPC yourself."; + return null; + } + + /// A name made safe to put inside a chat command: no control characters. + private static string ForCommand(string name) + { + var sb = new System.Text.StringBuilder(name.Length); + foreach (char ch in name) if (ch >= ' ' && ch != '\u007f') sb.Append(ch); + return sb.ToString().Trim(); + } + + /// "/ub give 1 <parchment> to <npc>": RynthAi finds the NPC by name and hands it over. + private void GiveParchment(DynamicStamp s, string parchment) + { + if (!_c.InWorld) { _dynNavStatus = "Log in first."; return; } + string? why = GiveUnavailableReason(); + if (why != null) { _dynNavStatus = why; return; } + _c.UbGiveSentMs = _c.NowMs; // a "Unrecognized /ub command" in the next moments turns the button off + bool sent = _c.RunCommand($"/ub give 1 {ForCommand(parchment)} to {ForCommand(s.Npc)}"); + _parchmentScanAt = 0; // read the packs again after the give + // The stamp is a quest flag: read /myquests again once the NPC has had time to answer. + if (sent) _dynRefreshAt = _c.NowMs + HandInRefreshMs; + _dynNavStatus = sent + ? $"Giving {parchment} to {s.Npc} (RynthAi does the give; it says so in chat if {s.Npc} isn't in sight)." + : "Could not send the give."; + } + + /// Clicking a row: select it and ask RynthNav for the route (shown in chat and its overlay). + private void SelectDynamicStamp(DynamicStamp s, bool done) + { + _dynNav = s; + _dynNavDone = done; + _dynNavStatus = ""; + _giveConfirm = ""; + if (s.NavCandidates().Count > 0) SendNav("route", s); + } + + /// "/rnav <verb> a || b || c" to RynthNav (it takes the first candidate on its map). + private void SendNav(string verb, DynamicStamp s) + { + List targets = s.NavCandidates(); + if (targets.Count == 0) return; + _dynNavStatus = SendRynthNav(verb, targets); + } + + /// + /// "/rnav <verb> a || b || c" to RynthNav (go walks the route, route plans it in chat, arrow + /// points at it; RynthNav takes the first candidate on its map). What to tell the player. + /// Shared by every row kind of the Quests tab. + /// + private string SendRynthNav(string verb, IReadOnlyList targets) + { + if (targets.Count == 0) return ""; + if (!_c.InWorld) return "Log in first."; + bool sent = _c.SendNav(verb + " " + string.Join(" || ", targets)); + return !sent ? "RynthNav isn't loaded (it plans and walks the route)." + : verb == "go" ? "RynthNav is planning the route and walking it (its chat lines say how)." + : verb == "arrow" ? "RynthNav's arrow points at it." + : "RynthNav's route is in chat. Go walks it."; + } + + /// Chat: the NPC, its stamp and whether this character has it, where, the reward and + /// any coordinates (RynthChat makes those a RynthNav arrow link). + private void PrintStamp(DynamicStamp s, bool done) + { + string where = s.Place.Length > 0 ? $"{s.Area}, {s.Place}" : s.Area; + string details = $"{where}" + (s.Reward.Length > 0 ? $" - gives {s.Reward}" : "") + (s.Note.Length > 0 ? $" - {s.Note}" : ""); + PrintEntry(s.Label, s.Stamp, done ? "have" : "missing", details, ""); + } +} diff --git a/Plugins/RynthCore.Plugin.RynthOracle/Views/LegendaryTab.cs b/Plugins/RynthCore.Plugin.RynthOracle/Views/LegendaryTab.cs new file mode 100644 index 0000000..1c8dce2 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthOracle/Views/LegendaryTab.cs @@ -0,0 +1,18 @@ +using RynthCore.Plugin.RynthOracle.Data; + +namespace RynthCore.Plugin.RynthOracle.Views; + +/// +/// Legendary Key quests (John in Arwic counts 30 for his reward): rows of the Quests tab's merged +/// list since 2026-10-18 (QuestsTab.cs: LEG rows, John's counter in the trackers' status). The list +/// and notes follow the "Arwic John Route" sheet (legendary.csv). What is left here is the chat print. +/// +internal sealed partial class OracleView +{ + /// Chat: the quest, its flags and status, the sheet's notes, wiki and video links. + private void PrintLegendary(LegendaryQuest q, string status) + { + PrintEntry(q.Label, string.Join(", ", q.Flags), status, q.Note, q.Url); + if (q.Video.Length > 0) _c.Print("Video: " + q.Video); + } +} diff --git a/Plugins/RynthCore.Plugin.RynthOracle/Views/MarkersTab.cs b/Plugins/RynthCore.Plugin.RynthOracle/Views/MarkersTab.cs index 6f9f836..57fdd0b 100644 --- a/Plugins/RynthCore.Plugin.RynthOracle/Views/MarkersTab.cs +++ b/Plugins/RynthCore.Plugin.RynthOracle/Views/MarkersTab.cs @@ -1,61 +1,15 @@ // Ported from Oracle of Dereth by Advis Eveldan (advis61), MIT. See THIRD_PARTY_NOTICES.md. -using System; using RynthCore.Plugin.RynthOracle.Data; -using RynthCore.Plugin.RynthOracle.Ui; namespace RynthCore.Plugin.RynthOracle.Views; -/// Markers: which of the 100 exploration markers you've found, and the next one to run to. +/// +/// The 100 exploration markers: rows of the Quests tab's merged list (QuestsTab.cs: MRK rows, the +/// markers found and the next one in the trackers' status, "Not done" for the ones still to find). +/// What is left here is the chat print a click on a marker row (or its Print button) gives. +/// internal sealed partial class OracleView { - private const int MarkerPageSize = 50; - private bool _markersMissingOnly; - private int _markerPage; - - private void DrawMarkers(UiWindow w) - { - QuestFlagStore flags = _c.Flags; - if (flags.LastReadUtc == DateTime.MinValue) - w.TextDisabled("Quest flags not read yet (Quests tab, Refresh)."); - - int found = 0; - Marker? next = null; - foreach (Marker m in MarkerList.All) - { - if (m.IsFound(flags)) found++; - else next ??= m; - } - w.ProgressBar(MarkerList.All.Count > 0 ? (float)found / MarkerList.All.Count : 0f, -1f, 0f, $"{found} / {MarkerList.All.Count} markers found"); - if (next != null) - { - Marker n = next; - w.TextDisabled("Next:"); - w.SameLine(); - w.Selectable($"#{next.Number} {next.Name} ({next.Location})", "m.next", false, () => PrintMarker(n)); - w.Tooltip("Prints the directions in chat."); - } - w.Checkbox("Only the ones still to find", "m.missing", _markersMissingOnly, v => { _markersMissingOnly = v; _markerPage = 0; }); - - var rows = new System.Collections.Generic.List(); - foreach (Marker m in MarkerList.All) - if (!_markersMissingOnly || !m.IsFound(flags)) rows.Add(m); - _markerPage = Pager(w, "m.page", _markerPage, rows.Count, MarkerPageSize, p => _markerPage = p); - - w.BeginChild("m.list", 0f, 0f, border: true); - int start = _markerPage * MarkerPageSize; - for (int i = start; i < rows.Count && i < start + MarkerPageSize; i++) - { - Marker m = rows[i]; - DoneMark(w, m.IsFound(flags)); - w.SameLine(50f); - Marker row = m; - w.Selectable(Cut($"#{m.Number} {m.Name}", 38), "m.r." + m.Number, false, () => PrintMarker(row), 300f); - w.SameLine(360f); - w.TextDisabled(Cut(m.Location, 24)); - } - w.EndChild(); - } - private void PrintMarker(Marker m) => PrintEntry($"Marker {m.Number}: {m.Name}", "", m.IsFound(_c.Flags) ? "found" : "", m.Hint, m.Url); } diff --git a/Plugins/RynthCore.Plugin.RynthOracle/Views/OracleView.cs b/Plugins/RynthCore.Plugin.RynthOracle/Views/OracleView.cs index 46c3242..9f216cc 100644 --- a/Plugins/RynthCore.Plugin.RynthOracle/Views/OracleView.cs +++ b/Plugins/RynthCore.Plugin.RynthOracle/Views/OracleView.cs @@ -12,8 +12,11 @@ internal sealed partial class OracleView public const string TabQuests = "Quests", TabCharacter = "Character", TabSkills = "Skills", TabAttributes = "Attributes", TabProgress = "Progress", TabAugs = "Augs", TabSociety = "Society", - TabMarkers = "Markers", TabTitles = "Titles", TabVoid = "Void", TabFellowship = "Fellowship", - TabBoards = "Leaderboards", TabConquest = "Conquest", TabAbout = "About"; + TabTitles = "Titles", TabVoid = "Void", TabFellowship = "Fellowship", + TabBreeding = "Pet Breeding", TabAbout = "About"; + // The Markers tab (and the Legendary and Dynamic Stamps trackers and RynthILT's Temple guardians) + // are rows of the Quests tab: QuestsTab.cs, ShowTrackers, /ro markers. A saved tab name of the old + // Markers tab falls back to Quests (see Tab). /// /// A tab: shown where any of its server tags matches the server; no tags = everywhere (retail). @@ -51,17 +54,17 @@ internal sealed partial class OracleView () => "Re-reads your character from the game and sends /myquests for the gem timers."), new(TabSociety, any, DrawSociety, true, RefreshCharacterAndQuests, () => "Re-reads your society standing from the game and sends /myquests for today's ribbons and quest timers."), - new(TabMarkers, any, DrawMarkers, false, () => RefreshQuests(), - () => "Sends /myquests: the markers you found are in your quest flags."), new(TabTitles, any, DrawTitles, false, RefreshTitles, () => "Re-reads the titles you hold from the game."), new(TabVoid, any, DrawVoid, true, RefreshVoid, () => "Re-reads your buffs from the game and drops the spell timers that ran out."), new(TabFellowship, any, DrawFellowship, false, RefreshFellowship, () => "Re-reads the fellowship and its members from the game."), - // Server-specific: each parser and its commands only exist on its own server. - new(TabBoards, new[] { Data.ServerTags.Conquest, Data.ServerTags.Aelrynth }, DrawBoards, false, RefreshBoards, BoardsHelp), - new(TabConquest, new[] { Data.ServerTags.Conquest }, DrawConquest, true, RefreshConquest, ConquestHelp), + // A server's own pages are its server plugin's since 2026-10-20: Conquest's (bank, augs, + // boards, ...) RynthConquest's, Aelrynth's leaderboards and Trials RynthAelrynth's. + // Infinite Leaftide only, and only while the server has pet breeding (BreedingOffered). + new(TabBreeding, new[] { Data.ServerTags.InfiniteLeaftide }, DrawBreeding, false, RefreshBreeding, + () => "Asks RynthILT to appraise every essence again (charges, rest timers, bond, growth)."), new(TabAbout, any, DrawAbout, false, RefreshAbout, () => "Loads the quest list and server pack from their files again and asks RynthCore which server this is."), }; @@ -69,11 +72,24 @@ internal sealed partial class OracleView private bool Visible(TabDef t) { + if (t.Name == TabBreeding && !BreedingOffered()) return false; if (t.Servers.Length == 0) return true; foreach (string s in t.Servers) if (_c.Server.Is(s)) return true; return false; } + /// + /// The Pet Breeding tab is offered on an Infinite Leaftide world unless RynthILT's profile says + /// the server has pet breeding switched off (a feature it doesn't know yet counts as on). + /// + internal bool BreedingOffered() + { + if (!_c.Server.Is(Data.ServerTags.InfiniteLeaftide)) return false; + foreach (Data.IltFeature f in _c.Ilt.Profile.Features) + if (f.Key == "pet_breeding") return f.State != RynthCore.Plugin.Shared.RynthIltServer.StateOff; + return true; + } + /// The selected tab's name; a tab not available on this server falls back to Quests. public string Tab { diff --git a/Plugins/RynthCore.Plugin.RynthOracle/Views/PetBreedingTab.cs b/Plugins/RynthCore.Plugin.RynthOracle/Views/PetBreedingTab.cs new file mode 100644 index 0000000..9b67599 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthOracle/Views/PetBreedingTab.cs @@ -0,0 +1,202 @@ +using System; +using System.Collections.Generic; +using System.Globalization; +using RynthCore.Plugin.RynthOracle.Ui; +using RynthCore.Plugin.Shared; + +namespace RynthCore.Plugin.RynthOracle.Views; + +/// +/// "Pet Breeding" (Infinite Leaftide, and only where the server has pet breeding on): RynthILT's +/// breeding tracker, the same one as RynthAi's Mini Remote Pets > Breeding tab (which stays). RynthILT +/// reads the essences, learns the server's rules and runs the actions; this tab draws its JSON +/// ("RynthILT.Data" GetPetBreedingJson) and sends its verbs back. Dance and supply uses ask here +/// first (RynthILT doesn't ask again). The page's Refresh button is the Refresh row every page has. +/// +internal sealed partial class OracleView +{ + /// Essence rows drawn at most (each is about eight ops; the window's op budget is shared). + private const int BreedingMaxRows = 40; + + /// The breeding verb waiting for Yes / No, with its question ("" = none). + private string _breedConfirmVerb = "", _breedConfirmText = ""; + /// The essence the supplies are used on (index into the essence list). + private int _breedTarget; + + private void DrawBreeding(UiWindow w) + { + IltBreedingView v = _c.Breeding; + w.SeparatorText("Pet Breeding"); + if (!v.Loaded) + { + w.TextDisabled(_c.IltData.Connected && !_c.IltData.PetBreedingSupported + ? "This RynthILT is older than 0.3.1 and has no breeding tracker; update RynthILT." + : "Load RynthILT (0.3.1 or later) to track pet breeding here. Reading..."); + return; + } + + uint col = v.Enabled == "off" ? UiColors.Red : v.Enabled == "on" ? UiColors.Green : UiColors.Yellow; + w.TextColored(col, v.Enabled switch + { + "off" => "Pet breeding is off on this server.", + "on" => $"Pet breeding: on. Breeding room: {v.Room}.", + _ => "Pet breeding: not confirmed yet (Diagnostics in the breeding room checks).", + }); + if (v.Bond == "off") w.TextColored(UiColors.Yellow, "Pet bond is off here, so bond can't reach the breeding minimum."); + + w.SmallButton("Diagnostics", "br.debug", () => _c.BreedingCommand(IltBreedingView.DebugVerb())); + w.Tooltip("@breed-debug: whether you're in the breeding room, your pet, partners nearby."); + w.SameLine(); + w.SmallButton("Dance", "br.dance", () => AskBreeding(IltBreedingView.DanceVerb(), + "Dance now? If your partner dances in time with both pets summoned in the same room, the breed happens.")); + w.Tooltip("@dance: both owners must dance within a few seconds."); + w.SameLine(); + w.SmallButton("Mini Remote", "br.remote", () => _c.RunCommand("/ra hub open breeding")); + w.Tooltip("RynthAi's Mini Remote, Pets > Breeding (the same tracker, with the pair planner)."); + + if (_breedConfirmVerb.Length > 0) + { + w.TextColored(UiColors.Gold, _breedConfirmText); + string verb = _breedConfirmVerb; + w.SmallButton("Yes", "br.yes", () => { _breedConfirmVerb = ""; _c.BreedingCommand(verb); }); + w.SameLine(); + w.SmallButton("No", "br.no", () => _breedConfirmVerb = ""); + } + if (v.Message.Length > 0) w.TextDisabled(v.Message); + else if (_c.BreedingMessage.Length > 0) w.TextDisabled(_c.BreedingMessage); + if (v.FreeSlots == 0) w.TextColored(UiColors.Yellow, "Your main pack is full: as the dam's owner you couldn't receive the baby."); + + DrawBreedEssences(w, v); + DrawBreedPairs(w, v); + DrawBreedSupplies(w, v); + DrawBreedRules(w, v); + DrawBreedEvents(w, v); + } + + /// Holds a verb until the player clicks Yes. + private void AskBreeding(string verb, string question) + { + _breedConfirmVerb = verb; + _breedConfirmText = question; + } + + private void DrawBreedEssences(UiWindow w, IltBreedingView v) + { + int ready = 0; + foreach (IltBreedEssenceRow e in v.Essences) if (e.Ready) ready++; + if (!w.CollapsingHeader($"Essences ({ready} ready of {v.Essences.Count})", "br.ess", defaultOpen: true)) return; + if (v.Essences.Count == 0) { w.TextDisabled("No combat pet essences in your pack."); return; } + for (int i = 0; i < v.Essences.Count && i < BreedingMaxRows; i++) + { + IltBreedEssenceRow e = v.Essences[i]; + w.TextColored(e.Ready ? UiColors.Green : e.Problems.Count > 0 && e.ReadyIn > 0 ? UiColors.Yellow : UiColors.Grey, Cut(e.Status, 22)); + w.SameLine(170f); + w.Text(Cut(e.Name, 32)); + w.Tooltip(BreedTooltip(e)); + w.SameLine(410f); + w.TextDisabled($"{(e.Male ? "M" : "F")} T{(e.Tier > 0 ? e.Tier.ToString(CultureInfo.InvariantCulture) : "?")} B{e.Bond} " + + $"Mut {e.Mutations}{(e.PotencyMutations > 0 ? "+" + e.PotencyMutations + "p" : "")}"); + } + if (v.Essences.Count > BreedingMaxRows) w.TextDisabled($"... and {v.Essences.Count - BreedingMaxRows} more (see the Mini Remote)."); + } + + private static string BreedTooltip(IltBreedEssenceRow e) + { + var lines = new List { $"{e.Name}: {(e.Male ? "stud" : "dam")}, tier {e.Tier}, bond {e.Bond}" }; + if (e.Male) lines.Add($"Charges {e.Charges}/{e.ChargesMax}"); + if (e.Juvenile) lines.Add($"Growing: {e.Stage}, {Math.Max(0, e.KillsRequired - e.Kills)} kills to Adult"); + if (e.Boosters.Count > 0) lines.Add("Boosters: " + string.Join(", ", e.Boosters)); + foreach (string p in e.Problems) lines.Add("- " + p); + return string.Join("\n", lines); + } + + private static void DrawBreedPairs(UiWindow w, IltBreedingView v) + { + if (v.Pairs.Count == 0) return; + if (!w.CollapsingHeader($"Ready pairs ({v.Pairs.Count})", "br.pairs", defaultOpen: true)) return; + w.TextDisabled("Stat mutation odds; fewer inherited mutations keep the odds up. Each owner dances with their own pet."); + for (int i = 0; i < v.Pairs.Count; i++) + { + IltBreedPairRow p = v.Pairs[i]; + w.Text($"{Cut(p.Stud, 26)} x {Cut(p.Dam, 26)}"); + w.SameLine(400f); + w.TextDisabled($"{Pct(p.ChanceWorst)}-{Pct(p.ChanceBest)}, inherits {p.InheritMin}-{p.InheritMax}"); + } + } + + private void DrawBreedSupplies(UiWindow w, IltBreedingView v) + { + long carried = 0; + foreach (IltBreedSupplyRow s in v.Supplies) carried += s.Count; + if (!w.CollapsingHeader($"Supplies ({carried} carried)", "br.sup", defaultOpen: false)) return; + w.TextDisabled("Ivo sells these at the Seedy Motel. Boosters are spent by the essence's next breed."); + + IltBreedEssenceRow? target = null; + if (v.Essences.Count > 0) + { + var names = new List(v.Essences.Count); + foreach (IltBreedEssenceRow e in v.Essences) names.Add(Cut(e.Name, 34)); + int index = Math.Clamp(_breedTarget, 0, v.Essences.Count - 1); + w.Combo("Use on", "br.target", index, names, i => _breedTarget = i); + target = v.Essences[index]; + } + + for (int i = 0; i < v.Supplies.Count; i++) + { + IltBreedSupplyRow s = v.Supplies[i]; + w.TextColored(s.Count > 0 ? UiColors.Green : UiColors.Grey, $"{s.Count,3} {s.Name}"); + w.Tooltip(s.Price > 0 ? $"{s.Effect}\nIvo's price: {Price(s.Price)} pyreals" : s.Effect); + if (!s.Apply || s.Count <= 0 || target == null) continue; + w.SameLine(330f); + if (System.Linq.Enumerable.Contains(s.Targets, target.Id)) + { + string verb = IltBreedingView.ApplyVerb(s.Key, target.Id); + string q = $"Use {s.Name} on {target.Name}? {s.Effect}"; + w.SmallButton("Use", "br.use." + i, () => AskBreeding(verb, q)); + } + else w.TextDisabled("-"); + } + } + + private static void DrawBreedRules(UiWindow w, IltBreedingView v) + { + if (!w.CollapsingHeader("Server rules", "br.rules", defaultOpen: false)) return; + w.TextDisabled("Values this server showed win over the ILT profile, which wins over ACE's defaults."); + foreach (IltBreedRuleRow r in v.Rules) + { + w.Text(r.Label); + if (r.Help.Length > 0) w.Tooltip(r.Help); + w.SameLine(230f); + w.Text(r.Value); + w.SameLine(310f); + w.TextColored(r.Source == "seen on server" ? UiColors.Green : UiColors.Grey, r.Source); + } + if (v.Debug is { } d) + { + w.Separator(); + w.TextDisabled($"Last diagnostics ({d.When} UTC):"); + if (d.Location.Length > 0) w.BulletText("You: " + d.Location); + if (d.Match.Length > 0) w.BulletText(d.Match == "valid" ? "In the breeding room" : "Not in the breeding room"); + if (d.Pet.Length > 0) w.BulletText("Pet: " + d.Pet + (d.Sex.Length > 0 ? " (" + d.Sex + ")" : "")); + if (d.Partners >= 0) w.BulletText($"Partners nearby: {d.Partners}"); + } + } + + private static void DrawBreedEvents(UiWindow w, IltBreedingView v) + { + if (!w.CollapsingHeader($"Recent events ({v.Events.Count})", "br.events", defaultOpen: false)) return; + if (v.Events.Count == 0) w.TextDisabled("Nothing yet: rituals, births, growth and charges land here."); + foreach (IltBreedEventRow e in v.Events) + { + w.TextDisabled(e.When); + w.SameLine(130f); + w.TextWrapped(e.Text); + } + } + + private static string Pct(double v) => (v * 100).ToString("0.#", CultureInfo.InvariantCulture) + "%"; + + private static string Price(long p) => p >= 1_000_000 + ? (p / 1_000_000.0).ToString("0.##", CultureInfo.InvariantCulture) + "M" + : p.ToString("N0", CultureInfo.InvariantCulture); +} diff --git a/Plugins/RynthCore.Plugin.RynthOracle/Views/QuestsTab.cs b/Plugins/RynthCore.Plugin.RynthOracle/Views/QuestsTab.cs index 859baa1..09bfe76 100644 --- a/Plugins/RynthCore.Plugin.RynthOracle/Views/QuestsTab.cs +++ b/Plugins/RynthCore.Plugin.RynthOracle/Views/QuestsTab.cs @@ -1,25 +1,42 @@ // Ported from Oracle of Dereth by Advis Eveldan (advis61), MIT. See THIRD_PARTY_NOTICES.md. -// Tracking, kill tasks and rewards merged in from RynthAi's Mini Remote Quests tab and -// UtilityBelt ILT's quest tracker (2026-10-13). Infinite Leaftide's quest bonus list (/qb) stays -// RynthILT's (the Quests section it draws in the Mini Remote). +// Tracking, kill tasks, rewards and the quest bonus list merged in from RynthAi's Mini Remote +// Quests tab and UtilityBelt ILT's quest tracker (2026-10-13). The Legendary, Markers and Dynamic +// Stamps tabs and RynthILT's Temple guardians merged in as tracker rows (SilentKelpie's PR 12, +// RynthOracle 0.6.0, ported by hand onto this lineage). using System; using System.Collections.Generic; using RynthCore.Plugin.RynthOracle.Data; using RynthCore.Plugin.RynthOracle.Ui; +using RynthCore.Plugin.Shared; namespace RynthCore.Plugin.RynthOracle.Views; /// -/// Quests: every flag the character holds, cross-referenced with the master quest list, in one -/// searchable, sortable, paged list (upstream's Quest Flags tab). The * column tracks a quest in -/// the Quest Timers window; clicking a quest opens it below the list, with its notes and the -/// rewards editor (UtilityBelt ILT's). +/// What a row of the merged Quests list is. Every kind but Quest is a tracker: Legendary Key quests +/// and exploration markers everywhere, Dynamic Stamps and the Temple guardians on Infinite Leaftide. +/// +internal enum QuestKind { Quest, Legendary, Marker, Dynamic, Guardian } + +/// +/// Quests: every flag the character holds, cross-referenced with the master quest list, plus the +/// trackers (Legendary Key quests, exploration markers, Dynamic Stamps, Temple guardians), in one +/// searchable, sortable, paged list. Each kind shows only on the servers it belongs to, and +/// "Trackers only" narrows the list to the trackers with their status above it. The * column tracks +/// a quest in the Quest Timers window (a favourite); clicking a row opens it below the list: a +/// quest's notes and rewards editor, a tracker's details, and RynthNav's Go / Route / Arrow for any +/// coordinates in its notes. A click on a quest or a marker also prints its texts in chat. On +/// Infinite Leaftide the quest bonus list (/qb, read by RynthILT) follows. /// internal sealed partial class OracleView { private const int QuestPageSize = 40; + private const int QbShownMax = 150; // per /qb list on one pass (the rest: narrow with Search) private const float QuestListHeightWithPanel = 300f; private static readonly string[] QuestSorts = { "Flag", "Name", "Done first", "Not done first", "Ready soonest", "Most solves" }; + /// The kinds' names in order (the Show filter). + private static readonly string[] KindNames = { "Quests", "Legendary", "Markers", "Dynamic Stamps", "Guardians" }; + /// The guardians' last answer is offered for this long (RynthILT's Mini Remote line does the same). + private const long GuardianAnswerShownSec = 600; // The reward editor's fields, in QuestReward order (two percentages, then counts). private static readonly string[] RewardLabels = @@ -27,21 +44,79 @@ internal sealed partial class OracleView private string _questSearch = ""; private bool _qDone, _qNotDone, _qRepeatable, _qOneTime, _qNew, _qServer, _qTracked, _qKill; + // Trackers only: the list keeps only tracker rows, with the trackers' status above it. + private bool _qTrackers; + // The Show filter: one kind, or null for every kind this server has. + private QuestKind? _qKind; private int _questSort; private int _questPage; + private int _dynArea; // 0 = all areas, else DynamicStampList.Areas[n - 1] (Show: Dynamic Stamps) - private readonly List _questRows = new(); + private readonly List _questRows = new(); private string _questKey = ""; private long _questBuiltMs; - // The quest opened below the list, and its reward editor's text (kept while typing). + // The row opened below the list: a quest (_questSel), a Dynamic Stamp (_dynNav) or another tracker (_selKey). + private QuestKind _selKind; + private string _selKey = ""; private string _questSel = ""; private readonly string[] _rewardEdit = new string[RewardLabels.Length]; private string _rewardMsg = ""; + /// One row of the merged list: its kind, a unique key, and the entry it shows. + private sealed class QuestRow + { + public QuestKind Kind; + /// Unique across kinds: the quest flag, or "lg:", "mk:", "dy:", "gd:" and the tracker's own key. + public string Key = ""; + public string Label = ""; + /// The tracker's group: a Legendary area, a marker's location, a stamp's area, a guardian's NPC. + public string Group = ""; + /// Its place in its own list (the default order of tracker rows). + public int Order; + public bool Done; + public Quest? Q; + public LegendaryQuest? L; + public Marker? M; + public DynamicStamp? D; + public IltGuardianRow? G; + } + + /// + /// The kinds this server shows: quests, Legendary quests and markers everywhere; Dynamic Stamps + /// and the Temple guardians only on Infinite Leaftide. Internal for the tests. + /// + internal List AvailableKinds() + { + var kinds = new List { QuestKind.Quest, QuestKind.Legendary, QuestKind.Marker }; + if (_c.Server.Is(ServerTags.InfiniteLeaftide)) + { + kinds.Add(QuestKind.Dynamic); + kinds.Add(QuestKind.Guardian); + } + return kinds; + } + + /// A kind is listed: this server has it, the Show filter allows it, and Trackers only doesn't hide it. + private bool KindListed(QuestKind k, List kinds) + => kinds.Contains(k) && (_qKind == null || _qKind == k) && !(_qTrackers && k == QuestKind.Quest); + + /// + /// Opens the Quests tab on the trackers: one kind (/ro legendary, /ro dynamic, /ro markers, + /// /ro guardians) or all of them (null). The old tabs' commands land here. + /// + public void ShowTrackers(QuestKind? kind) + { + _qTrackers = kind != QuestKind.Quest; + _qKind = kind; + _questPage = 0; + Tab = TabQuests; + } + private void DrawQuests(UiWindow w) { QuestFlagStore flags = _c.Flags; + RefreshAfterHandIn(flags); if (flags.ServerDisabled) w.TextColored(UiColors.Red, "This server has /myquests turned off, so quest flags can't be read."); else if (flags.Loading) @@ -50,6 +125,9 @@ internal sealed partial class OracleView w.TextDisabled("Quest flags not read yet. Press Refresh, or type /myquests."); else w.Text($"{flags.Flags.Count} quest flags on this character, read at {flags.LastReadUtc.ToLocalTime():HH:mm}."); + int throttleLeft = flags.ThrottleSecondsLeft(_c.NowMs); + if (throttleLeft > 0 && !flags.Loading) + w.TextDisabled($"The server answers one /myquests a minute: Refresh works again in {throttleLeft}s."); bool timersShown = _c.QuestTimersWindowVisible(); w.Button(timersShown ? "Hide quest timers" : "Show quest timers", "q.timers", () => _c.SetQuestTimersWindow(!timersShown)); @@ -60,9 +138,15 @@ internal sealed partial class OracleView ? $"{cat.RetailCount} retail quests + {cat.ServerCount} {cat.PackServer} quests" : $"{cat.RetailCount} retail quests"); + // A Show filter left on a kind this server doesn't have (another server's character): all kinds. + List kinds = AvailableKinds(); + if (_qKind is QuestKind chosen && !kinds.Contains(chosen)) _qKind = null; + bool ilt = kinds.Contains(QuestKind.Dynamic); + w.InputText("Search", "q.search", _questSearch, 64, s => { _questSearch = s; _questPage = 0; }); - w.Tooltip("Words to find in the quest's flag or name, e.g. \"kill task\". "); + w.Tooltip("Words to find in a row: a quest's flag or name; a tracker's NPC, place, area, reward or notes. Also filters the quest bonus list."); w.Checkbox("Done", "q.done", _qDone, v => { _qDone = v; _questPage = 0; }); + w.Tooltip("Done quests; Legendary quests and stamps you have, markers found, guardians on cooldown."); w.SameLine(); w.Checkbox("Not done", "q.notdone", _qNotDone, v => { _qNotDone = v; _questPage = 0; }); w.SameLine(); @@ -83,18 +167,49 @@ internal sealed partial class OracleView w.Checkbox(_c.Catalog.PackServer + " only", "q.server", _qServer, v => { _qServer = v; _questPage = 0; }); w.Tooltip($"Quests only {_c.Catalog.PackServer} has."); } + + w.Checkbox("Trackers only", "q.trackers", _qTrackers, v => + { + _qTrackers = v; + if (v && _qKind == QuestKind.Quest) _qKind = null; + _questPage = 0; + }); + w.Tooltip("Only the trackers, with their status above the list: Legendary Key quests, exploration markers" + + (ilt ? ", Dynamic Stamps and the Temple guardians." : ".") + + (ilt ? "" : "\nDynamic Stamps and the Temple guardians show on Infinite Leaftide.")); + w.SameLine(); + var kindItems = new List(kinds.Count + 1) { "Everything" }; + foreach (QuestKind k in kinds) kindItems.Add(KindNames[(int)k]); + int kindIndex = _qKind is QuestKind sel ? kinds.IndexOf(sel) + 1 : 0; + w.Combo("Show", "q.kind", kindIndex, kindItems, i => + { + _qKind = i <= 0 || i > kinds.Count ? null : kinds[i - 1]; + if (_qKind == QuestKind.Quest) _qTrackers = false; + _questPage = 0; + }); + w.Tooltip("One kind of row, or everything this server has."); + if (_qKind == QuestKind.Dynamic) + { + w.SameLine(); + var areaItems = new List(DynamicStampList.Areas.Count + 1) { "All areas" }; + areaItems.AddRange(DynamicStampList.Areas); + w.Combo("##dyarea", "dy.area", Math.Clamp(_dynArea, 0, areaItems.Count - 1), areaItems, v => { _dynArea = v; _questPage = 0; }); + } w.Combo("Sort", "q.sort", _questSort, QuestSorts, i => { _questSort = Math.Clamp(i, 0, QuestSorts.Length - 1); _questPage = 0; }); - List rows = QuestRows(); + if (_qTrackers || _qKind is QuestKind k2 && k2 != QuestKind.Quest) DrawTrackerSummary(w, kinds); + + List rows = QuestRows(kinds); w.Text($"{rows.Count} shown"); w.SameLine(160f); _questPage = Pager(w, "q.page", _questPage, rows.Count, QuestPageSize, p => _questPage = p); - // A fixed-height list when the opened quest follows it; else it fills the page. - bool selected = _questSel.Length > 0; - w.BeginChild("q.list", 0f, selected ? QuestListHeightWithPanel : 0f, border: true); + // A fixed-height list when something follows it (the opened row, the /qb list); else it fills the page. + IltQuestBonusList? qb = ilt && !_qTrackers ? _c.Ilt.Profile.QuestBonus : null; + bool selected = HasSelection(); + w.BeginChild("q.list", 0f, selected || qb != null ? QuestListHeightWithPanel : 0f, border: true); w.TextDisabled("*"); - w.Tooltip("Track: list the quest in the Quest Timers window."); + w.Tooltip("Track: list the quest in the Quest Timers window. Trackers show their kind here instead (LEG, MRK, DYN, GRD)."); w.SameLine(28f); w.TextDisabled("Done"); w.SameLine(72f); @@ -105,26 +220,38 @@ internal sealed partial class OracleView w.TextDisabled("Solves"); w.SameLine(530f); w.TextDisabled("Rewards"); - w.Tooltip("What you recorded for the quest (click it to edit): %XP, %Lum, Coins, Trinkets, Medallions, Yellow/Red/Blue powder, MMDs (D), at Level."); + w.Tooltip("What you recorded for a quest (click it to edit): %XP, %Lum, Coins, Trinkets, Medallions, Yellow/Red/Blue powder, MMDs (D), at Level.\n" + + "Trackers: a Legendary quest's luminance, a marker's location, a stamp's area, a guardian's next turn-in."); DateTime now = _c.UtcNow; bool canTrack = _c.Book.Loaded; int start = _questPage * QuestPageSize; for (int i = start; i < rows.Count && i < start + QuestPageSize; i++) + DrawQuestRow(w, rows[i], flags, now, canTrack); + if (rows.Count == 0) + w.TextDisabled(_qTracked ? "No tracked quests match. Tick * on a quest to track it." : "No rows match."); + w.EndChild(); + + if (selected) DrawSelection(w); + if (qb != null) DrawQuestBonus(w, qb); + } + + /// One list row: a quest (track, done, timer, solves, rewards) or a tracker (kind, status, its own columns). + private void DrawQuestRow(UiWindow w, QuestRow r, QuestFlagStore flags, DateTime now, bool canTrack) + { + if (r.Kind == QuestKind.Quest) { - Quest q = rows[i]; + Quest q = r.Q!; string flag = q.Flag; bool tracked = _c.Book.IsTracked(flag); w.ToggleButton("*", "q.t." + flag, tracked, () => { if (canTrack) _c.Book.ToggleTracked(flag); }, small: true); w.SameLine(28f); - bool done = q.IsComplete(flags); - DoneMark(w, done); + DoneMark(w, r.Done); w.SameLine(72f); - Quest row = q; - w.Selectable(Cut(q.Label, 44), "q.r." + flag, flag == _questSel, () => SelectQuest(row), 290f); + w.Selectable(Cut(q.Label, 44), "q.r." + flag, IsSelected(r), () => SelectRow(r), 290f); w.Tooltip(flag + "\nClick: opens it below and prints its texts in chat."); w.SameLine(370f); - TimerText(w, q, flags, now, done); + TimerText(w, q, flags, now, r.Done); string solves = q.SolvesText(flags); if (solves.Length > 0) { @@ -138,11 +265,99 @@ internal sealed partial class OracleView w.Text(Cut(reward, 18)); if (reward.Length > 18) w.Tooltip(reward); } + return; } - if (rows.Count == 0) w.TextDisabled(_qTracked ? "No tracked quests match. Tick * on a quest to track it." : "No quests match."); - w.EndChild(); - if (selected) DrawSelectedQuest(w); + // A tracker: its kind tag where the * is, then its mark, label and columns. + w.TextColored(UiColors.Gold, r.Kind switch + { + QuestKind.Legendary => "LEG", + QuestKind.Marker => "MRK", + QuestKind.Dynamic => "DYN", + _ => "GRD", + }); + w.SameLine(28f); + TrackerMark(w, r); + w.SameLine(72f); + w.Selectable(Cut(r.Label, 44), "q.r." + r.Key, IsSelected(r), () => SelectRow(r), 290f); + string tip = TrackerTooltip(r); + if (tip.Length > 0) w.Tooltip(Cut(tip, 300)); + switch (r.Kind) + { + case QuestKind.Legendary: + { + LegendaryQuest l = r.L!; + TimeSpan? left = l.TimeLeft(flags, now); + w.SameLine(370f); + if (left == null) w.TextColored(UiColors.Grey, "not done"); + else if (left.Value <= TimeSpan.Zero) w.TextColored(UiColors.Green, "ready"); + else w.TextColored(UiColors.Yellow, TimeText.Friendly(left.Value)); + if (l.Luminance > 0) + { + w.SameLine(530f); + w.TextDisabled(TimeText.Number(l.Luminance) + " lum"); + } + break; + } + case QuestKind.Guardian: + { + IltGuardianRow g = r.G!; + w.SameLine(370f); + w.TextColored(g.Ready ? UiColors.Green : g.Status == "Unknown" ? UiColors.Grey : UiColors.Yellow, Cut(g.Status, 14)); + w.SameLine(470f); + w.Text("#" + g.Count); + if (g.Eta.Length > 0) + { + w.SameLine(530f); + w.TextDisabled(Cut(g.Eta, 18)); + } + break; + } + default: + // Markers and stamps: where they are. + if (r.Group.Length > 0) + { + w.SameLine(530f); + w.TextDisabled(Cut(r.Group, 18)); + } + break; + } + } + + /// A tracker's done column: have / need, found / --, or a guardian's ready / wait. + private static void TrackerMark(UiWindow w, QuestRow r) + { + switch (r.Kind) + { + case QuestKind.Marker: + DoneMark(w, r.Done); + break; + case QuestKind.Guardian: + // Done = turned in and on cooldown; not done = a turn-in is ready (or unknown). + w.TextColored(r.Done ? UiColors.Yellow : UiColors.Green, r.Done ? "wait" : "ready"); + break; + default: + w.TextColored(r.Done ? UiColors.Green : UiColors.Red, r.Done ? "have" : "need"); + break; + } + } + + /// A tracker row's hover text: its notes, hint or where it comes from. + private static string TrackerTooltip(QuestRow r) => r.Kind switch + { + QuestKind.Legendary => r.L!.Note.Length > 0 ? $"{r.Group}: {r.L.Note}" : r.Group, + QuestKind.Marker => r.M!.Hint, + QuestKind.Dynamic => string.Join(" - ", Parts(r.D!.Area, r.D.Place, r.D.Reward.Length > 0 ? "gives " + r.D.Reward : "", r.D.Note)), + QuestKind.Guardian => $"{r.G!.Npc}: {(r.G.Exact ? "from /myquests (exact)" : "from /qb wait stamps (count and timer are estimates)")}", + _ => "", + }; + + /// The non-empty strings, in order. + private static List Parts(params string[] items) + { + var list = new List(items.Length); + foreach (string s in items) if (!string.IsNullOrWhiteSpace(s)) list.Add(s); + return list; } /// The timer column: "ready" (green once done), a countdown, "N left" (yellow) or done (grey). @@ -158,21 +373,341 @@ internal sealed partial class OracleView } } - // ── The opened quest and its rewards ────────────────────────────────── + // ── Tracker status (above the list in Trackers only / one tracker kind) ── /// - /// A click opens the quest below the list (a second click closes it) and, as upstream's list - /// does, prints its texts in chat: the info and hint, the wiki link and the flag's history. + /// The trackers' status (what each old tab showed at its top), for the kinds the Show filter + /// lists: John's Legendary counter, markers found and the next one, stamps had, and the Temple + /// guardians' switches, last answer and hand-in. /// - private void SelectQuest(Quest q) + private void DrawTrackerSummary(UiWindow w, List kinds) + { + QuestFlagStore flags = _c.Flags; + bool Shows(QuestKind k) => kinds.Contains(k) && (_qKind == null || _qKind == k); + + if (Shows(QuestKind.Legendary)) + { + DateTime now = _c.UtcNow; + int have = 0, ready = 0; + foreach (LegendaryQuest q in LegendaryList.All) + { + TimeSpan? left = q.TimeLeft(flags, now); + if (left == null) continue; + have++; + if (left.Value <= TimeSpan.Zero) ready++; + } + // John's own counter when the server has it; it counts every key quest, not just these. + int? john = LegendaryList.JohnCount(flags); + int shown = john ?? have; + w.ProgressBar(Math.Min(1f, (float)shown / LegendaryList.JohnTarget), -1f, 0f, + john != null + ? $"John: {john} / {LegendaryList.JohnTarget} legendary quests ({ready} ready to run again)" + : $"{have} / {LegendaryList.JohnTarget} toward John, {ready} ready to run again"); + w.Tooltip("John in Arwic (33.6N 56.7E) rewards 30 different Legendary Key quests: 500,000 luminance and a 25-use Legendary Key.\n" + + "Bar: his counter (legendaryquestcounter_0913) when /myquests has it, else the Legendary quests you've done."); + } + + if (Shows(QuestKind.Marker)) + { + int found = 0; + Marker? next = null; + foreach (Marker m in MarkerList.All) + { + if (m.IsFound(flags)) found++; + else next ??= m; + } + w.ProgressBar(MarkerList.All.Count > 0 ? (float)found / MarkerList.All.Count : 0f, -1f, 0f, $"{found} / {MarkerList.All.Count} markers found"); + if (next != null) + { + Marker n = next; + w.TextDisabled("Next marker:"); + w.SameLine(); + w.Selectable($"#{next.Number} {next.Name} ({next.Location})", "m.next", false, () => SelectRow(MarkerRow(n, flags, 0))); + w.Tooltip("Opens it below the list (directions, RynthNav) and prints the directions in chat."); + } + } + + if (Shows(QuestKind.Dynamic)) + { + List all = DynamicStampList.All; + int have = 0; + foreach (DynamicStamp s in all) if (s.Have(flags)) have++; + int unlisted = DynamicStampList.Unlisted(flags).Count; + w.ProgressBar(all.Count == 0 ? 0f : (float)have / all.Count, -1f, 0f, + $"{have} / {all.Count} listed Dynamic stamps" + (unlisted > 0 ? $" (+{unlisted} not in the list)" : "")); + w.Tooltip("Dynamic stamps are one-time quest flags (Dynamic_1_...) from handing items to NPCs on Infinite Leaftide.\n" + + "List: the players' ExtraDyn sheet. Click a stamp for RynthNav's route to it and the Parchment hand-in." + + (unlisted > 0 ? "\nStamps not in the sheet show as quests with Not in list." : "")); + } + + if (Shows(QuestKind.Guardian)) DrawGuardianControls(w); + } + + /// + /// The Temple guardians' controls (RynthILT's Guardian window): chat detection, auto hand-in and + /// buy-if-missing, which run inside RynthILT; the last answer with Hand in / Stop; and a refresh. + /// + private void DrawGuardianControls(UiWindow w) + { + IltGuardianView g = _c.Guardian; + if (!g.Loaded) + { + w.TextDisabled(_c.IltData.Connected + ? "Temple guardians: this RynthILT is older than 0.3.3 (no guardian data for Oracle)." + : "Temple guardians: RynthILT isn't loaded (it runs the riddles, hand-ins and turn-in tracker)."); + return; + } + int ready = 0; + foreach (IltGuardianRow r in g.Rows) if (r.Ready) ready++; + w.TextColored(UiColors.Gold, "Temple guardians"); + w.SameLine(); + w.TextDisabled($"{ready} of {g.Rows.Count} attribute turn-ins ready" + + (g.SyncedUtc == DateTime.MinValue ? ", /qb not read this session" : $", /qb read {g.SyncedUtc.ToLocalTime():HH:mm}")); + w.SameLine(); + w.SmallButton("Refresh", "gd.refresh", () => _c.GuardianCommand(IltGuardianView.RefreshVerb())); + w.Tooltip("RynthILT re-reads /myquests and /qb list for the turn-ins (the server allows each once a minute)."); + + w.Checkbox("Detect from chat", "gd.chat", g.Chat, v => _c.GuardianCommand(IltGuardianView.SwitchVerb("chat", v))); + w.Tooltip("Translate the guardians' tells as they arrive and show the answer here."); + w.SameLine(); + w.Checkbox("Auto hand-in", "gd.auto", g.Auto, v => _c.GuardianCommand(IltGuardianView.SwitchVerb("auto", v))); + w.Tooltip("After a chat answer, RynthILT gives one of the item to the guardian automatically."); + w.SameLine(); + w.Checkbox("Buy if missing", "gd.buy", g.Buy, v => _c.GuardianCommand(IltGuardianView.SwitchVerb("buy", v))); + w.Tooltip("Temple guardian: when you carry none, RynthILT buys one from the open or nearest vendor first."); + + bool recent = g.Answer.Length > 0 && g.AnswerAgeSec >= 0 && g.AnswerAgeSec < GuardianAnswerShownSec; + if (recent || g.Running) + { + w.TextColored(UiColors.Green, g.Answer); + if (g.Heard.Length > 0) w.Tooltip("Heard: " + Cut(g.Heard, 300)); + w.SameLine(); + w.TextDisabled("-> " + g.Npc); + w.SameLine(); + if (g.Running) w.SmallButton("Stop", "gd.stop", () => _c.GuardianCommand(IltGuardianView.StopVerb())); + else w.SmallButton("Hand in", "gd.handin", () => _c.GuardianCommand(IltGuardianView.HandInVerb())); + } + else w.TextDisabled("No guardian answer yet."); + w.TextDisabled("Hand-in: " + g.Status + (_c.GuardianMessage.Length > 0 ? " - " + _c.GuardianMessage : "")); + } + + // ── The opened row ────────────────────────────────────────────────────── + + /// Something is opened below the list. + private bool HasSelection() => _selKind switch + { + QuestKind.Quest => _questSel.Length > 0, + QuestKind.Dynamic => _dynNav != null, + _ => _selKey.Length > 0, + }; + + private bool IsSelected(QuestRow r) => r.Kind switch + { + QuestKind.Quest => _selKind == QuestKind.Quest && r.Q!.Flag == _questSel, + QuestKind.Dynamic => _selKind == QuestKind.Dynamic && ReferenceEquals(r.D, _dynNav), + _ => _selKind == r.Kind && _selKey == r.Key, + }; + + /// + /// Clicking a row opens it below the list (a second click closes it). As before, a click on a + /// quest prints its texts in chat (the info and hint, the wiki link and the flag's history) and + /// a click on a marker prints its directions. A Dynamic Stamp also asks RynthNav for the route + /// at once, as its tab did. + /// + private void SelectRow(QuestRow r) + { + if (r.Kind == QuestKind.Quest) _c.PrintQuest(r.Q!); + else if (r.Kind == QuestKind.Marker) PrintMarker(r.M!); + + bool same = IsSelected(r); + _questSel = ""; + _dynNav = null; + _selKey = ""; + _questStopIdx = 0; + _questNavStatus = ""; + if (same) return; + _selKind = r.Kind; + switch (r.Kind) + { + case QuestKind.Quest: + OpenQuest(r.Q!); + break; + case QuestKind.Dynamic: + _selKey = r.Key; + SelectDynamicStamp(r.D!, r.Done); + break; + default: + _selKey = r.Key; + break; + } + } + + /// Opens a quest below the list with its reward editor. + private void OpenQuest(Quest q) { - _c.PrintQuest(q); - if (_questSel == q.Flag) { _questSel = ""; return; } _questSel = q.Flag; _rewardMsg = ""; LoadRewardEdit(q.Flag); } + /// The opened row's panel: a quest, a Dynamic Stamp's nav box, a Legendary quest, a marker or a guardian. + private void DrawSelection(UiWindow w) + { + switch (_selKind) + { + case QuestKind.Quest: + DrawSelectedQuest(w); + break; + case QuestKind.Dynamic: + DrawDynamicNavBox(w); + break; + case QuestKind.Legendary: + LegendaryQuest? l = LegendaryList.All.Find(x => "lg:" + x.Name == _selKey); + if (l != null) DrawSelectedLegendary(w, l); + break; + case QuestKind.Marker: + Marker? m = MarkerList.All.Find(x => "mk:" + x.Number == _selKey); + if (m != null) DrawSelectedMarker(w, m); + break; + case QuestKind.Guardian: + IltGuardianRow? g = null; + foreach (IltGuardianRow r in _c.Guardian.Rows) + if ("gd:" + r.Attribute == _selKey) { g = r; break; } + DrawSelectedGuardian(w, g); + break; + } + } + + private void DrawSelectedLegendary(UiWindow w, LegendaryQuest l) + { + QuestFlagStore flags = _c.Flags; + string status = l.Status(flags, _c.UtcNow); + w.SeparatorText(Cut(l.Label, 60)); + w.TextDisabled("Area"); + w.SameLine(90f); + w.Text(l.Group); + w.TextDisabled("Flags"); + w.SameLine(90f); + w.Text(Cut(string.Join(", ", l.Flags), 70)); + w.TextDisabled("Status"); + w.SameLine(90f); + w.TextColored(status == "missing" ? UiColors.Red : status == "ready" ? UiColors.Green : UiColors.Yellow, status); + if (l.Luminance > 0) + { + w.SameLine(260f); + w.TextDisabled(TimeText.Number(l.Luminance) + " luminance"); + } + if (l.Note.Length > 0) w.TextWrapped(Cut(l.Note, 600)); + DrawGoTo(w, StopsFor("lg:" + l.Name, () => NavTargets.Stops(l.Note))); + w.Button("Print in chat", "lg.sel.print", () => PrintLegendary(l, status)); + w.Tooltip("The quest, its flags and status, the notes, wiki and video links."); + w.SameLine(); + w.Button("Close", "lg.sel.close", () => _selKey = ""); + } + + private void DrawSelectedMarker(UiWindow w, Marker m) + { + bool found = m.IsFound(_c.Flags); + w.SeparatorText(Cut($"Marker {m.Number}: {m.Name}", 60)); + w.TextDisabled("Location"); + w.SameLine(90f); + w.Text(m.Location); + w.TextDisabled("Status"); + w.SameLine(90f); + w.TextColored(found ? UiColors.Green : UiColors.Grey, found ? "found" : "not found yet"); + if (m.Hint.Length > 0) w.TextWrapped(Cut(m.Hint, 600)); + // Coordinates in the directions, else the location's name for RynthNav's Atlas. + DrawGoTo(w, StopsFor("mk:" + m.Number, () => + { + List stops = NavTargets.Stops(m.Hint); + if (stops.Count == 0 && m.Location.Length > 0) stops.Add(NavTargets.Place(m.Location)); + return stops; + })); + w.Button("Print in chat", "m.sel.print", () => PrintMarker(m)); + w.SameLine(); + w.Button("Close", "m.sel.close", () => _selKey = ""); + } + + private void DrawSelectedGuardian(UiWindow w, IltGuardianRow? g) + { + if (g != null) + { + w.SeparatorText("Temple guardian: " + g.Attribute); + w.TextDisabled("NPC"); + w.SameLine(90f); + w.Text(g.Npc); + w.TextDisabled("Turn-ins"); + w.SameLine(90f); + w.Text(g.Count.ToString()); + w.TextDisabled("Status"); + w.SameLine(90f); + w.TextColored(g.Ready ? UiColors.Green : g.Status == "Unknown" ? UiColors.Grey : UiColors.Yellow, g.Status); + if (g.Eta.Length > 0) + { + w.SameLine(260f); + w.TextDisabled("Next: " + g.Eta); + } + w.TextDisabled(g.Exact ? "From /myquests (exact)." : $"From /qb wait stamps: the count and timer are estimates (cooldown taken as {_c.Guardian.CooldownHours} h)."); + } + else w.SeparatorText("Temple guardians"); + DrawGuardianControls(w); + w.Button("Close", "gd.sel.close", () => _selKey = ""); + } + + // ── Go to: the coordinates in the opened row's text, through RynthNav ── + + private string _questStopsFor = ""; + private List _questStops = new(); + private int _questStopIdx; + private string _questNavStatus = ""; + + /// The opened row's stops, worked out once per row (). + private List StopsFor(string key, Func> build) + { + if (_questStopsFor != key) + { + _questStopsFor = key; + _questStops = build(); + } + return _questStops; + } + + /// + /// Go to: one place is shown with Go / Route / Arrow; several get a picker first (picking one + /// plans its route, as clicking a Dynamic Stamp does). Nothing without any. + /// + private void DrawGoTo(UiWindow w, List stops) + { + if (stops.Count == 0) return; + _questStopIdx = Math.Clamp(_questStopIdx, 0, stops.Count - 1); + w.SeparatorText(stops.Count == 1 ? "Go to" : $"Go to ({stops.Count} places in these notes)"); + if (stops.Count == 1) + w.Text(Cut(stops[0].Display, 80)); + else + { + var items = new List(stops.Count); + for (int i = 0; i < stops.Count; i++) items.Add($"{i + 1}. {Cut(stops[i].Display, 70)}"); + w.Combo("##q.nav.pick", "q.nav.pick", _questStopIdx, items, i => + { + _questStopIdx = Math.Clamp(i, 0, stops.Count - 1); + _questNavStatus = SendRynthNav("route", new[] { stops[_questStopIdx].Target }); + }); + w.Tooltip("The places the notes give coordinates for, in their order. Picking one plans RynthNav's route to it."); + } + NavTargets.Stop stop = stops[_questStopIdx]; + w.Button("Go (auto nav)", "q.nav.go", () => _questNavStatus = SendRynthNav("go", new[] { stop.Target })); + w.Tooltip("RynthNav plans the route (walking, portals, recalls, a dungeon's entrance) and walks it."); + w.SameLine(); + w.Button("Route", "q.nav.route", () => _questNavStatus = SendRynthNav("route", new[] { stop.Target })); + w.Tooltip("Only plan it: RynthNav prints the steps in chat."); + w.SameLine(); + w.Button("Arrow", "q.nav.arrow", () => _questNavStatus = SendRynthNav("arrow", new[] { stop.Target })); + w.Tooltip("Only point RynthNav's arrow at it."); + if (_questNavStatus.Length > 0) w.TextDisabled(_questNavStatus); + } + + // ── The opened quest and its rewards ────────────────────────────────── + /// Fills the editor from what is recorded (blank fields for zero). private void LoadRewardEdit(string flag) { @@ -202,6 +737,7 @@ internal sealed partial class OracleView } string details = q.Details(); if (details.Length > 0) w.TextWrapped(Cut(details, 600)); + DrawGoTo(w, StopsFor("q:" + q.Flag, () => NavTargets.Stops(q.Info + " - " + q.Hint))); bool loaded = _c.Book.Loaded; bool tracked = _c.Book.IsTracked(q.Flag); @@ -274,13 +810,61 @@ internal sealed partial class OracleView _rewardMsg = r.IsEmpty ? "Cleared." : "Saved: " + r.ShortSummary(); } + // ── Quest bonus (/qb, Infinite Leaftide through RynthILT) ────────────── + + private void DrawQuestBonus(UiWindow w, IltQuestBonusList qb) + { + string count = qb.Count >= 0 ? $" - count {TimeText.Number(qb.Count)}" : ""; + if (!w.CollapsingHeader($"Quest bonus (/qb){count}", "q.qb")) return; + if (qb.Disabled) + { + w.TextDisabled("/qb is turned off on this server."); + return; + } + w.Button("Load /qb list", "q.qb.load", () => + { + if (!_c.Send("/ilt qb")) _c.Print("Log in first."); + }); + w.Tooltip("RynthILT asks the server for your quest bonus list (the server allows once a minute)."); + w.SameLine(); + w.TextDisabled(qb.Generation == 0 && qb.Status == "not loaded" ? "Not loaded yet this session." : qb.Status); + + string[] terms = _questSearch.Split(' ', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries); + QbList(w, "Incomplete", "q.qb.todo", qb.Incomplete, terms, UiColors.Yellow); + QbList(w, "Completed", "q.qb.done", qb.Completed, terms, UiColors.Green); + } + + private static void QbList(UiWindow w, string label, string id, IReadOnlyList items, string[] terms, uint color) + { + var shown = new List(); + foreach (string s in items) + if (MatchesAll(s, terms)) shown.Add(s); + string counts = terms.Length > 0 ? $"{shown.Count} of {items.Count}" : items.Count.ToString(); + if (!w.CollapsingHeader($"{label} ({counts})", id)) return; + for (int i = 0; i < shown.Count && i < QbShownMax; i++) w.TextColored(color, shown[i]); + if (shown.Count > QbShownMax) w.TextDisabled($"... and {shown.Count - QbShownMax} more. Narrow them with Search."); + if (shown.Count == 0) w.TextDisabled(items.Count == 0 ? "None." : "None match the search."); + } + + /// Every search word is in (any case); no words = everything matches. + private static bool MatchesAll(string hay, string[] terms) + { + foreach (string t in terms) + if (hay.IndexOf(t, StringComparison.OrdinalIgnoreCase) < 0) return false; + return true; + } + // ── Rows ────────────────────────────────────────────────────────────── - /// The filtered, sorted rows; rebuilt when the filter or data changed (or every 5 s for timers). - private List QuestRows() + /// + /// The filtered, sorted rows of every listed kind; rebuilt when the filter or data changed (or + /// every 5 s for the timer sort). + /// + private List QuestRows(List kinds) { string key = $"{_questSearch}|{_qDone}{_qNotDone}{_qRepeatable}{_qOneTime}{_qNew}{_qServer}{_qTracked}{_qKill}|{_questSort}" - + $"|{_c.Flags.Revision}|{_c.Catalog.Revision}|{(_qTracked ? _c.Book.Revision : 0)}"; + + $"|{_qTrackers}|{_qKind}|{_dynArea}|{string.Join(",", kinds)}" + + $"|{_c.Flags.Revision}|{_c.Catalog.Revision}|{(_qTracked ? _c.Book.Revision : 0)}|{_c.GuardianRevision}"; bool timeSorted = _questSort == 4; if (key == _questKey && (!timeSorted || _c.NowMs - _questBuiltMs < 5000)) return _questRows; _questKey = key; @@ -289,53 +873,138 @@ internal sealed partial class OracleView QuestFlagStore flags = _c.Flags; string[] terms = _questSearch.Split(' ', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries); _questRows.Clear(); - foreach (Quest q in _c.Catalog.Quests) + + // The Dynamic stamps the list matched: shown as stamp rows, not again as unknown quest flags. + var stampFlags = new HashSet(StringComparer.OrdinalIgnoreCase); + if (kinds.Contains(QuestKind.Dynamic)) + foreach (DynamicStamp s in DynamicStampList.All) + if (s.MatchedFlag(flags) is string f) stampFlags.Add(f); + + if (KindListed(QuestKind.Quest, kinds)) { - if (_qNew && !q.IsNew) continue; - if (_qServer && q.Server.Length == 0) continue; - if (_qTracked && !_c.Book.IsTracked(q.Flag)) continue; - if (_qKill && !(flags.TryGet(q.Flag, out QuestFlag kf) && QuestTimer.IsKillTask(kf))) continue; - if (_qDone != _qNotDone && q.IsComplete(flags) != _qDone) continue; - if (_qRepeatable != _qOneTime && q.IsRepeatable(flags) != _qRepeatable) continue; - if (terms.Length > 0) + foreach (Quest q in _c.Catalog.Quests) { - string hay = q.Flag + " " + q.DisplayName; - bool all = true; - foreach (string t in terms) - if (hay.IndexOf(t, StringComparison.OrdinalIgnoreCase) < 0) { all = false; break; } - if (!all) continue; + if (q.IsNew && stampFlags.Contains(q.Flag)) continue; + if (_qNew && !q.IsNew) continue; + if (_qServer && q.Server.Length == 0) continue; + if (_qTracked && !_c.Book.IsTracked(q.Flag)) continue; + if (_qKill && !(flags.TryGet(q.Flag, out QuestFlag kf) && QuestTimer.IsKillTask(kf))) continue; + bool done = q.IsComplete(flags); + if (_qDone != _qNotDone && done != _qDone) continue; + if (_qRepeatable != _qOneTime && q.IsRepeatable(flags) != _qRepeatable) continue; + if (!MatchesAll(q.Flag + " " + q.DisplayName, terms)) continue; + _questRows.Add(new QuestRow { Kind = QuestKind.Quest, Key = q.Flag, Label = q.DisplayName, Done = done, Q = q }); } - _questRows.Add(q); + } + + // The quest-only filters (not in the list, server pack, kill tasks) leave the trackers out. + if (!_qNew && !_qServer && !_qKill) + { + if (KindListed(QuestKind.Legendary, kinds)) + for (int i = 0; i < LegendaryList.All.Count; i++) + { + LegendaryQuest l = LegendaryList.All[i]; + var r = new QuestRow { Kind = QuestKind.Legendary, Key = "lg:" + l.Name, Label = l.Label, Group = l.Group, Order = i, Done = l.Have(flags), L = l }; + bool tracked = l.Flags.Length > 0 && _c.Book.IsTracked(l.Flags[0]); + if (KeepTracker(r, repeatable: true, tracked, $"{l.Label} {l.Group} {l.Note} {string.Join(" ", l.Flags)}", terms)) _questRows.Add(r); + } + + if (KindListed(QuestKind.Marker, kinds)) + for (int i = 0; i < MarkerList.All.Count; i++) + { + QuestRow r = MarkerRow(MarkerList.All[i], flags, i); + if (KeepTracker(r, repeatable: false, tracked: false, $"{r.Label} {r.M!.Location} {r.M.Hint}", terms)) _questRows.Add(r); + } + + if (KindListed(QuestKind.Dynamic, kinds)) + for (int i = 0; i < DynamicStampList.All.Count; i++) + { + DynamicStamp s = DynamicStampList.All[i]; + if (_dynArea > 0 && (_dynArea > DynamicStampList.Areas.Count || DynamicStampList.Areas[_dynArea - 1] != s.Area)) continue; + var r = new QuestRow { Kind = QuestKind.Dynamic, Key = "dy:" + s.Stamp, Label = s.Label, Group = s.Area, Order = i, Done = s.Have(flags), D = s }; + if (KeepTracker(r, repeatable: false, tracked: false, $"{s.Npc} {s.Place} {s.Reward} {s.Area} {s.Stamp} {s.Note}", terms)) _questRows.Add(r); + } + + if (KindListed(QuestKind.Guardian, kinds)) + for (int i = 0; i < _c.Guardian.Rows.Count; i++) + { + IltGuardianRow g = _c.Guardian.Rows[i]; + var r = new QuestRow { Kind = QuestKind.Guardian, Key = "gd:" + g.Attribute, Label = g.Attribute + " (" + g.Npc + ")", Group = g.Npc, Order = i, Done = !g.Ready, G = g }; + if (KeepTracker(r, repeatable: true, tracked: false, $"{g.Attribute} {g.Npc} {g.Status}", terms)) _questRows.Add(r); + } } DateTime now = _c.UtcNow; - Comparison byFlag = (a, b) => string.CompareOrdinal(a.Flag, b.Flag); switch (_questSort) { case 1: - _questRows.Sort((a, b) => Then(string.Compare(a.DisplayName, b.DisplayName, StringComparison.OrdinalIgnoreCase), a, b)); + _questRows.Sort((a, b) => Then(string.Compare(a.Label, b.Label, StringComparison.OrdinalIgnoreCase), a, b)); break; case 2: - _questRows.Sort((a, b) => Then(b.IsComplete(flags).CompareTo(a.IsComplete(flags)), a, b)); + _questRows.Sort((a, b) => Then(b.Done.CompareTo(a.Done), a, b)); break; case 3: - _questRows.Sort((a, b) => Then(a.IsComplete(flags).CompareTo(b.IsComplete(flags)), a, b)); + _questRows.Sort((a, b) => Then(a.Done.CompareTo(b.Done), a, b)); break; case 4: - _questRows.Sort((a, b) => Then(ReadyKey(a, flags, now).CompareTo(ReadyKey(b, flags, now)), a, b)); + _questRows.Sort((a, b) => Then(RowReadyKey(a, flags, now).CompareTo(RowReadyKey(b, flags, now)), a, b)); break; case 5: - _questRows.Sort((a, b) => Then(Solves(b, flags).CompareTo(Solves(a, flags)), a, b)); + _questRows.Sort((a, b) => Then(RowSolves(b, flags).CompareTo(RowSolves(a, flags)), a, b)); break; default: - _questRows.Sort(byFlag); + _questRows.Sort((a, b) => Then(0, a, b)); break; } return _questRows; - static int Then(int c, Quest a, Quest b) => c != 0 ? c : string.CompareOrdinal(a.Flag, b.Flag); + // Ties: by kind (quests first), then quests by flag and trackers in their own list's order. + static int Then(int c, QuestRow a, QuestRow b) + { + if (c != 0) return c; + if (a.Kind != b.Kind) return a.Kind.CompareTo(b.Kind); + return a.Kind == QuestKind.Quest ? string.CompareOrdinal(a.Key, b.Key) : a.Order.CompareTo(b.Order); + } } + /// A marker's row (the list, and the summary's "Next marker"). + private static QuestRow MarkerRow(Marker m, QuestFlagStore flags, int order) + => new() { Kind = QuestKind.Marker, Key = "mk:" + m.Number, Label = $"#{m.Number} {m.Name}", Group = m.Location, Order = order, Done = m.IsFound(flags), M = m }; + + /// The filters a tracker row answers to: Tracked, Done / Not done, Repeatable / One-time and Search. + private bool KeepTracker(QuestRow r, bool repeatable, bool tracked, string hay, string[] terms) + { + if (_qTracked && !tracked) return false; + if (_qDone != _qNotDone && r.Done != _qDone) return false; + if (_qRepeatable != _qOneTime && repeatable != _qRepeatable) return false; + return MatchesAll(hay, terms); + } + + /// Ready soonest: held repeatable quests and Legendary quests by time left, ready guardians first; the rest after. + private static double RowReadyKey(QuestRow r, QuestFlagStore flags, DateTime now) + { + switch (r.Kind) + { + case QuestKind.Quest: + return ReadyKey(r.Q!, flags, now); + case QuestKind.Legendary: + TimeSpan? left = r.L!.TimeLeft(flags, now); + return left == null ? double.MaxValue : Math.Max(0, left.Value.TotalSeconds); + case QuestKind.Guardian: + return r.G!.Ready ? 0 : double.MaxValue; + default: + return double.MaxValue; + } + } + + /// Most solves: a repeatable quest's solves, a guardian's turn-ins. + private static int RowSolves(QuestRow r, QuestFlagStore flags) => r.Kind switch + { + QuestKind.Quest => Solves(r.Q!, flags), + QuestKind.Guardian => r.G!.Count, + _ => 0, + }; + /// Held repeatables by time left (ready ones first); everything else after them. private static double ReadyKey(Quest q, QuestFlagStore flags, DateTime now) => flags.TryGet(q.Flag, out _) && (q.IsRepeatable(flags) || flags.TryGet(q.Flag, out QuestFlag f) && QuestTimer.IsKillTask(f)) diff --git a/Plugins/RynthCore.Plugin.RynthOracle/Views/RefreshBar.cs b/Plugins/RynthCore.Plugin.RynthOracle/Views/RefreshBar.cs index 57f0686..f7ef119 100644 --- a/Plugins/RynthCore.Plugin.RynthOracle/Views/RefreshBar.cs +++ b/Plugins/RynthCore.Plugin.RynthOracle/Views/RefreshBar.cs @@ -8,7 +8,7 @@ namespace RynthCore.Plugin.RynthOracle.Views; /// /// The Refresh button every page of the Oracle window starts with, and the status line beside it. /// What "refresh" means depends on where a page's data comes from: -/// - data the server owns (quest flags, ConquestAC's bank and boards, Aelrynth's /top and /trial) +/// - data the server owns (the quest flags) /// is asked for again with the same command the page always used, and the line waits for the /// reply; /// - data read from the game client (level, buffs, titles, fellowship) is re-read at once instead @@ -33,13 +33,8 @@ internal sealed partial class OracleView private DateTime _refreshAtUtc, _refreshDoneUtc; private readonly Dictionary _refreshSent = new(); - /// The tab, plus the sub-page a tab has (Conquest's views, the boards), so a status line stays with its own page. - private string RefreshScope(string tab) => tab switch - { - TabConquest => tab + _conquestView, - TabBoards => tab + _aelrynthView + _conquestBoard, - _ => tab, - }; + /// The page a status line belongs to (each tab is one page). + private static string RefreshScope(string tab) => tab; private void DrawRefreshRow(UiWindow w, TabDef def) { @@ -90,16 +85,6 @@ internal sealed partial class OracleView private const string TooSoon = "That was just asked for; wait a few seconds before asking again."; - /// Sends one chat command (the page's own) and waits for to change. - private RefreshResult Ask(string key, Func state, Func command) - { - if (CoolingDown(key)) return new RefreshResult(TooSoon); - long before = state(); - string cmd = command(); - if (!_c.Send(cmd)) return new RefreshResult($"Couldn't send {cmd} (not in the world)."); - return new RefreshResult($"Sent {cmd}.", () => state() != before); - } - /// /myquests (refused for 5 s after the last one); the line waits for the new flags. private RefreshResult RefreshQuests(string before = "") { @@ -107,6 +92,8 @@ internal sealed partial class OracleView int rev = f.Revision; if (_c.RequestQuests()) return new RefreshResult(before + "Asked the server for your quest flags (/myquests).", () => f.Revision != rev); if (f.Loading) return new RefreshResult(before + "Your quest flags are already being read.", () => f.Revision != rev); + int wait = f.ThrottleSecondsLeft(_c.NowMs); + if (wait > 0) return new RefreshResult(before + $"The server answers one /myquests a minute; try again in {wait}s (the flags shown are kept)."); return new RefreshResult(before + "Your quest flags were asked for a moment ago; wait a few seconds before asking again."); } @@ -137,6 +124,16 @@ internal sealed partial class OracleView return new RefreshResult("Re-read your buffs and dropped the spell timers that ran out. Timers on targets are learned from your casts."); } + /// The Pet Breeding tab: RynthILT appraises every essence again; the line waits for the new snapshot. + private RefreshResult RefreshBreeding() + { + if (CoolingDown("breeding")) return new RefreshResult(TooSoon); + object before = _c.Breeding; + if (!_c.BreedingCommand(RynthCore.Plugin.Shared.IltBreedingView.RefreshVerb())) + return new RefreshResult("RynthILT didn't take that (not loaded, or older than 0.3.1)."); + return new RefreshResult("Asked RynthILT to appraise your essences again.", () => !ReferenceEquals(_c.Breeding, before)); + } + private RefreshResult RefreshFellowship() { _c.Fellowship.Invalidate(); @@ -151,63 +148,4 @@ internal sealed partial class OracleView string pack = cat.PackServer.Length > 0 ? $" + {cat.ServerCount} {cat.PackServer}" : ""; return new RefreshResult($"Reloaded the quest list ({cat.RetailCount} retail{pack}) and asked RynthCore which server this is."); } - - private RefreshResult RefreshBoards() - { - if (_c.Server.Is(ServerTags.Conquest)) - { - ConquestData cq = _c.Conquest; - ConquestBoard b = cq.Boards[Math.Clamp(_conquestBoard, 0, cq.Boards.Count - 1)]; - return Ask("board" + b.Key, () => b.UpdatedUtc.Ticks, () => cq.RequestBoard(b, _c.NowMs)); - } - AelrynthBoards a = _c.Boards; - return _aelrynthView switch - { - 1 => Ask("top me", () => a.Revision, () => a.RequestTop("me", _c.NowMs)), - 2 => Ask("trial", () => a.Revision, () => a.RequestTrial("", _c.NowMs)), - _ => Ask("top " + _aelrynthBoardArg, () => a.Revision, - () => a.RequestTop(a.BoardTitle.Length > 0 ? _aelrynthBoardArg : "", _c.NowMs)), - }; - } - - private string BoardsHelp() - { - if (_c.Server.Is(ServerTags.Conquest)) - { - ConquestBoard b = _c.Conquest.Boards[Math.Clamp(_conquestBoard, 0, _c.Conquest.Boards.Count - 1)]; - return $"Sends {b.Command} and reads the reply."; - } - return _aelrynthView switch - { - 1 => "Sends /top me and reads the reply.", - 2 => "Sends /trial and reads the dungeon list.", - _ => "Sends /top (every board's leader), or asks again for the board that is open.", - }; - } - - private RefreshResult RefreshConquest() - { - ConquestData cq = _c.Conquest; - switch (_conquestView) - { - case 0: return Ask("bank", () => cq.BankUtc.Ticks, () => cq.RequestBank(_c.NowMs)); - case 1: return Ask("augs", () => cq.AugsUtc.Ticks, () => cq.RequestAugs(_c.NowMs)); - case 2: return Ask("enl", () => cq.EnlUtc.Ticks, () => cq.RequestEnl(_c.NowMs)); - case 3: - _c.RereadCharacter(); - return Ask("bonus", () => cq.BonusUtc.Ticks, () => cq.RequestBonus(_c.NowMs)); - case 4: return Ask("fship", () => cq.FshipUtc.Ticks, () => cq.RequestFships(_c.NowMs)); - default: return RefreshQuests(); - } - } - - private string ConquestHelp() => _conquestView switch - { - 0 => "Sends /b and reads your balances.", - 1 => "Sends /augs and reads your advanced augmentations.", - 2 => "Sends /enl augs and reads your enlightenment augmentations.", - 3 => "Re-reads your level, and sends /bonus for the experience bonuses.", - 4 => "Sends /fship list and reads the fellowships looking for members.", - _ => "Sends /myquests: the custom quests' status comes from your quest flags.", - }; } diff --git a/Plugins/Shared/EngineServerState.cs b/Plugins/Shared/EngineServerState.cs index 6e3515b..d478d65 100644 --- a/Plugins/Shared/EngineServerState.cs +++ b/Plugins/Shared/EngineServerState.cs @@ -187,6 +187,31 @@ internal sealed record ServerProfileView(string Id, string Name, string Plugin, } } + /// + /// A live number from the profile's "values" (a server plugin's ServerPackPlugin.SetProfileValue, + /// e.g. "voidDotDurationScale"), or when the profile, the value or a + /// finite number isn't there (an older plugin, another server, a server without the rule). + /// + public static double Value(string? json, string key, double fallback) + { + if (string.IsNullOrWhiteSpace(json) || string.IsNullOrEmpty(key)) return fallback; + try + { + using JsonDocument doc = JsonDocument.Parse(json); + JsonElement root = doc.RootElement; + if (root.ValueKind != JsonValueKind.Object + || !root.TryGetProperty("values", out JsonElement values) || values.ValueKind != JsonValueKind.Object + || !values.TryGetProperty(key, out JsonElement v) || v.ValueKind != JsonValueKind.Number + || !v.TryGetDouble(out double d) || !double.IsFinite(d)) + return fallback; + return d; + } + catch (JsonException) + { + return fallback; + } + } + /// One plain-ASCII line for a status report ("PvE, ACE; botting forbidden - ..."). public string Summary() { @@ -211,6 +236,55 @@ internal sealed record ServerProfileView(string Id, string Name, string Plugin, /// "afterCap": applied last, only once the item's tink slots are full. /// "stackGroup": rows in one group share per item ("" = none). /// "stackCap": the group's combined cap per item. +/// +/// Which jewelry is a trinket on the active server (the profile's "trinkets": name words and words +/// that rule a name out again). (no server, or one without trinkets): nothing is. +/// +internal sealed record ServerTrinketRule(IReadOnlyList Names, IReadOnlyList Except) +{ + public static readonly ServerTrinketRule None = new(Array.Empty(), Array.Empty()); + + /// True when holds one of the words and none of the exceptions. + public bool IsTrinket(string? name) + { + string n = name ?? string.Empty; + if (n.Length == 0 || Names.Count == 0) return false; + foreach (string x in Except) + if (x.Length > 0 && n.Contains(x, StringComparison.OrdinalIgnoreCase)) return false; + foreach (string w in Names) + if (w.Length > 0 && n.Contains(w, StringComparison.OrdinalIgnoreCase)) return true; + return false; + } + + /// The profile's rule, read leniently: without one (or for unusable text). + public static ServerTrinketRule Parse(string? json) + { + if (string.IsNullOrWhiteSpace(json)) return None; + try + { + using JsonDocument doc = JsonDocument.Parse(json); + if (doc.RootElement.ValueKind != JsonValueKind.Object + || !doc.RootElement.TryGetProperty("trinkets", out JsonElement t) || t.ValueKind != JsonValueKind.Object) + return None; + var names = Words(t, "names"); + return names.Count == 0 ? None : new ServerTrinketRule(names, Words(t, "except")); + } + catch (JsonException) + { + return None; + } + } + + private static List Words(JsonElement e, string name) + { + var list = new List(); + if (!e.TryGetProperty(name, out JsonElement a) || a.ValueKind != JsonValueKind.Array) return list; + foreach (JsonElement w in a.EnumerateArray()) + if (w.ValueKind == JsonValueKind.String && w.GetString() is { Length: > 0 and <= 64 } s) list.Add(s.Trim()); + return list; + } +} + internal sealed record ServerSalvageView(string Bench, int Material, string Kind, string Effect, bool UsesTinkSlot, string NameMatch, int AppliedInt = 0, bool Prepared = false, int Order = 0, bool AfterCap = false, string StackGroup = "", int StackCap = 0) diff --git a/Plugins/Shared/PetCaptureLines.cs b/Plugins/Shared/PetCaptureLines.cs index e70109d..72777e7 100644 --- a/Plugins/Shared/PetCaptureLines.cs +++ b/Plugins/Shared/PetCaptureLines.cs @@ -1,9 +1,9 @@ // PetCaptureLines.cs - The chat lines that mean an ACECustom siphon-lens capture worked. // -// One list for both plugins (linked source): RynthAi's Pets tab reads them to time its auto-capture -// (success -> short cooldown), and RynthILT's Vaulted Dungeons keeper counts a capture as a kill for -// its "Kill Client" timer (a hunter who captures instead of killing is not idle). They are the -// MonsterCapture success replies the Pets tab already matched; nothing new is guessed here. +// RynthILT's (linked source): its siphon auto-capture (IltPetAutomation, RynthAi's Pets tab's until +// 2026-10-20) reads them to time the next lens (success -> short cooldown), and its Vaulted Dungeons +// keeper counts a capture as a kill for its "Kill Client" timer (a hunter who captures instead of +// killing is not idle). They are the MonsterCapture success replies; nothing new is guessed here. using System; namespace RynthCore.Plugin.Shared; diff --git a/Plugins/Shared/RynthAiHubApi.cs b/Plugins/Shared/RynthAiHubApi.cs index bc5680f..062a90c 100644 --- a/Plugins/Shared/RynthAiHubApi.cs +++ b/Plugins/Shared/RynthAiHubApi.cs @@ -4,8 +4,10 @@ // borrows from RynthAi. The Mini Remote that hosts the ILT tabs, the /myquests // tracker (the Temple attribute tracker reads its flags), spell names (the dispel // keeper), VTank loot-profile matching (equipment suits) and the VTank .usd -// importer (which edits RynthAi's own rules; drawn in RynthILT's Gear tab), and the -// Mini Remote's session stats (the Character tab's rates count the same session). +// importer (which edits RynthAi's own rules; drawn in RynthILT's Gear tab), the +// Mini Remote's session stats (the ILT rates count the same session), and since +// 2026-10-20 combat's generic back-away (the Empyrean Handler's ring) and the loot +// rules' wield counters (the T11 counters RynthILT reads from /aug). // Compiled into both plugins (linked source), so the layout can't drift. // // Rules: as RynthILT.Hub (Shared/RynthIltHubApi.cs): append-only, UTF-8 strings, @@ -26,6 +28,18 @@ public static class RynthAiHub /// RenderSection: the VTank .usd settings importer (RynthAi's monster / weapon / consumable rules). public const string SectionVTankImport = "vtank-import"; + + // BackAwayFrom results. + /// The back-jump started; attacks wait until it settles. + public const int BackAwayStarted = 1; + /// Not now: RynthAi's macro isn't running with combat on, it is backing away already, or it isn't logged in. + public const int BackAwayNotNow = 0; + /// The character is outside the radius: nothing done. + public const int BackAwayOutside = 2; + /// The object (or the player) has no position. + public const int BackAwayUnknownObject = 3; + /// In range, but the jump didn't start. + public const int BackAwayJumpRefused = -1; } /// One /myquests flag as RynthAi's quest tracker has it. Blittable. @@ -176,9 +190,37 @@ public unsafe struct RynthAiHubApiV1 public static int VaultedDungeonsEnabledOffset => (int)BaseStructSize + sizeof(nint); /// - /// VaultedDungeonsEnabled(): 1 when RynthAi's "Vaulted Dungeons" setting (Settings > Navigation) is - /// on. That setting is the master switch of RynthILT's Vaulted Dungeons keeper and lives only in - /// RynthAi; 0 (off) is also the answer before login and after shutdown. Any thread. + /// VaultedDungeonsEnabled(): obsolete since 2026-10-20, kept because the table is append-only. The + /// Vaulted Dungeons master switch is RynthILT's own setting now (RynthILT 0.4+ reads its state, and + /// RynthAi mirrors it for the engine through RynthILT.Hub GetSetting / SetSetting). RynthAi answers + /// the value its profile still carries (what RynthILT copied once), so an older RynthILT keeps + /// working; 0 before login and after shutdown. Any thread. /// public delegate* unmanaged[Cdecl] VaultedDungeonsEnabled; + + // ── Appended 2026-10-20 (check with Has before calling) ───────────────── + + /// The byte offset of (for ): right after VaultedDungeonsEnabled. + public static int BackAwayFromOffset => (int)BaseStructSize + 2 * sizeof(nint); + + /// + /// BackAwayFrom(objectId, radiusYards, holdMs): a server plugin's "get out of this radius now" (RynthILT: + /// the Empyrean Handler's lethal ring). RynthAi faces the object, run-back jumps away from it (holdMs = + /// the jump's charge, 100-3000) and holds its attacks until the jump settles, then re-engages the same + /// target; the radius is at least the player's Ring Range. Only while RynthAi's macro runs with combat + /// on. Returns and the other BackAway* results. Pump thread. + /// + public delegate* unmanaged[Cdecl] BackAwayFrom; + + /// The byte offset of (for ): right after BackAwayFrom. + public static int SetPlayerCounterOffset => (int)BaseStructSize + 3 * sizeof(nint); + + /// + /// SetPlayerCounter(propertyId, value): a player counter the server doesn't send at login and the + /// loot rules' wield gates compare against (the T11 "Can Wield" key: Item Augmentations 9008, Triune + /// Weave 50000, the school charms 50001-50004). The server plugin reads them (RynthILT: ACECustom's + /// "/aug" reply, with its item-aug override applied) and reports each; value < 0 = unknown again. + /// 1 = taken, 0 = not such a counter. Any thread. + /// + public delegate* unmanaged[Cdecl] SetPlayerCounter; } diff --git a/Plugins/Shared/RynthAiSessionClient.cs b/Plugins/Shared/RynthAiSessionClient.cs index 2728e90..6c5224b 100644 --- a/Plugins/Shared/RynthAiSessionClient.cs +++ b/Plugins/Shared/RynthAiSessionClient.cs @@ -28,6 +28,9 @@ public sealed unsafe class RynthAiSessionClient /// RynthAi answered with its hub table (last lookup). public bool Connected => _table != null && _table->Version >= 1; + /// RynthAi is loaded and answers on its hub interface now (looked up again every few seconds while it is missing). + public bool IsLoaded(RynthCoreHost host, long now) => Table(host, now) != null; + /// Forget the table; the next call looks it up again (login, logout). public void Reset() { diff --git a/Plugins/Shared/RynthIltDataApi.cs b/Plugins/Shared/RynthIltDataApi.cs index fa34804..84601ee 100644 --- a/Plugins/Shared/RynthIltDataApi.cs +++ b/Plugins/Shared/RynthIltDataApi.cs @@ -1,8 +1,9 @@ // ============================================================================ // RynthSuite - Plugins/Shared/RynthIltDataApi.cs // The "RynthILT.Data" interface: the Infinite Leaftide data RynthILT's Mini Remote Charms -// and Banking tabs show, for other plugins to draw (SilentKelpie's RynthOracle Character -// tab and RynthInventory Global Inventory "Banking" tab read it; neither is in this tree yet): +// and Banking tabs show, for other plugins to draw (RynthOracle's Character tab charms, +// Pet Breeding tab and Quests tab guardians, and RynthInventory's Global Inventory "Banking" tab +// read it; the Mini Remote's own tabs keep working beside them): // - the registry charms and Guardian Hands (GetCharmsJson, ToggleCharm); // - the bank balances of every character RynthILT has seen on this server, and // deposits, withdrawals, transfers and balance reads (GetBankJson, BankCommand); @@ -48,8 +49,8 @@ // The reader confirms a transfer with the player before sending it (RynthILT doesn't ask again). // // Version 2 (RynthILT 0.3.1) appends GetPetBreedingJson and PetBreedingCommand: the data of the -// pet breeding tracker RynthILT draws in the Mini Remote's Pets > Breeding sub-tab (no plugin in -// this tree reads it yet). Readers still query version 1 and accept a version-1 table, so charms +// pet breeding tracker RynthILT draws in the Mini Remote's Pets > Breeding sub-tab (RynthOracle's +// Pet Breeding tab reads it too). Readers still query version 1 and accept a version-1 table, so charms // and the bank keep working with an older RynthILT; they use the breeding functions only when // the table says Version >= 2 and is that big (HasPetBreeding). // @@ -69,6 +70,19 @@ // "sex": "...", "partners": 1 } } // PetBreedingCommand verbs (ASCII): refresh | debug | dance | apply // The reader confirms "apply" and "dance" with the player first (RynthILT doesn't ask again). +// +// Version 3 (RynthILT 0.2.20) appends GetGuardianJson and GuardianCommand (the Temple guardians +// on RynthOracle's Quests tab). Readers use them only when Version >= 3 and the table is that big +// (HasGuardian); a version-2 table still answers charms, the bank and breeding (V2Size). +// +// GetGuardianJson payload (IltGuardian.BuildJson; read leniently): +// { "available": true, "world": "...", "chat": true, "auto": false, "buy": true, "cooldownHours": 20, +// "answer": "Pyreal", "npc": "Guardian of ...", "answerAgeSec": 42 (-1 none yet), "heard": "...", +// "running": false, "status": "idle", "synced": "2026-10-18T19:05:00Z" ("" /qb not read), +// "rows": [ { "attribute": "Strength", "npc": "...", "count": 3, "status": "Ready", "eta": "", +// "ready": true, "exact": true } ] } exact = from /myquests (else /qb estimates) +// GuardianCommand verbs (ASCII): handin | stop | refresh | chat on|off | auto on|off | buy on|off +// Auto hand-in and buying a missing Temple item run inside RynthILT whatever the reader shows. // ============================================================================ using System; @@ -85,7 +99,7 @@ namespace RynthCore.Plugin.Shared; public unsafe struct RynthIltDataApiV1 { public const string InterfaceName = "RynthILT.Data"; - public const uint InterfaceVersion = 2; + public const uint InterfaceVersion = 3; /// The size of a version-1 table (everything before GetPetBreedingJson) on this platform. public static uint V1Size @@ -97,6 +111,16 @@ public unsafe struct RynthIltDataApiV1 } } + /// The size of a version-2 table (everything before GetGuardianJson) on this platform. + public static uint V2Size + { + get + { + RynthIltDataApiV1 t = default; + return (uint)((byte*)&t.GetGuardianJson - (byte*)&t); + } + } + public uint Version; // InterfaceVersion of the table RynthILT filled; 0 once it has shut down public uint StructSize; // sizeof(RynthIltDataApiV1) as RynthILT built it @@ -125,6 +149,14 @@ public unsafe struct RynthIltDataApiV1 /// PetBreedingCommand(utf8 verb line): queues a breeding verb (header above). 1 = queued, 0 = refused. public delegate* unmanaged[Cdecl] PetBreedingCommand; + + // ── Version 3 ─────────────────────────────────────────────────────────── + + /// GetGuardianJson(buffer, capacity): the Temple guardian JSON, same contract as GetCharmsJson. + public delegate* unmanaged[Cdecl] GetGuardianJson; + + /// GuardianCommand(utf8 verb line): queues a guardian verb (header above). 1 = queued, 0 = refused. + public delegate* unmanaged[Cdecl] GuardianCommand; } /// @@ -183,7 +215,33 @@ public sealed unsafe class RynthIltDataClient } private static bool HasPetBreeding(RynthIltDataApiV1* t) - => t != null && t->Version >= 2 && t->StructSize >= (uint)sizeof(RynthIltDataApiV1); + => t != null && t->Version >= 2 && t->StructSize >= RynthIltDataApiV1.V2Size; + + /// The Temple guardian JSON now ("" without a RynthILT that has it, version 3). + public string ReadGuardian(RynthCoreHost host, long now) + { + RynthIltDataApiV1* t = Table(host, now); + return !HasGuardian(t) || t->GetGuardianJson == null ? "" : Read(t->GetGuardianJson); + } + + /// The loaded RynthILT has the guardian functions (table version 3 or later). + public bool GuardianSupported => HasGuardian(_table); + + /// Queues a guardian verb line (see the header). False without RynthILT or when it refused. + public bool GuardianCommand(RynthCoreHost host, long now, string verbLine) + { + RynthIltDataApiV1* t = Table(host, now); + if (!HasGuardian(t) || t->GuardianCommand == null || string.IsNullOrWhiteSpace(verbLine)) return false; + byte[] bytes = Encoding.UTF8.GetBytes(verbLine + "\0"); + try + { + fixed (byte* p = bytes) return t->GuardianCommand(p) == 1; + } + catch { return false; } + } + + private static bool HasGuardian(RynthIltDataApiV1* t) + => t != null && t->Version >= 3 && t->StructSize >= (uint)sizeof(RynthIltDataApiV1); /// Asks RynthILT to use a carried charm. False without RynthILT or when it refused. public bool ToggleCharm(RynthCoreHost host, long now, uint objectId) @@ -548,6 +606,88 @@ public sealed class IltBreedingView => string.Join(' ', "apply", (supplyKey ?? "").Trim(), essenceId.ToString(CultureInfo.InvariantCulture)); } +/// One Temple attribute turn-in from the guardian JSON. +public sealed record IltGuardianRow(string Attribute, string Npc, int Count, string Status, string Eta, bool Ready, bool Exact); + +/// The Temple guardian JSON parsed. without RynthILT; every field read leniently. +public sealed class IltGuardianView +{ + public static readonly IltGuardianView None = new(); + + /// RynthILT answered. + public bool Loaded { get; private init; } + public bool Available { get; private init; } + public string World { get; private init; } = ""; + /// Translate the guardians' tells as they arrive. + public bool Chat { get; private init; } + /// Give the answer item to the guardian automatically after a chat answer. + public bool Auto { get; private init; } + /// Buy a missing Temple item from the nearest vendor first. + public bool Buy { get; private init; } + public int CooldownHours { get; private init; } + public string Answer { get; private init; } = ""; + public string Npc { get; private init; } = ""; + /// Seconds since the last answer (-1 none yet). + public long AnswerAgeSec { get; private init; } = -1; + public string Heard { get; private init; } = ""; + /// A hand-in is running. + public bool Running { get; private init; } + public string Status { get; private init; } = ""; + /// When /qb was last read (MinValue never). + public DateTime SyncedUtc { get; private init; } = DateTime.MinValue; + public IReadOnlyList Rows { get; private init; } = Array.Empty(); + + public static IltGuardianView Parse(string? json) + { + if (string.IsNullOrWhiteSpace(json)) return None; + try + { + using JsonDocument doc = JsonDocument.Parse(json); + JsonElement root = doc.RootElement; + if (root.ValueKind != JsonValueKind.Object) return None; + var rows = new List(); + foreach (JsonElement r in IltJson.Array(root, "rows")) + { + string attr = IltJson.Str(r, "attribute"); + if (attr.Length == 0) continue; + rows.Add(new IltGuardianRow(attr, IltJson.Str(r, "npc"), (int)IltJson.Long(r, "count"), IltJson.Str(r, "status"), + IltJson.Str(r, "eta"), IltJson.Bool(r, "ready"), IltJson.Bool(r, "exact"))); + } + DateTime synced = DateTime.MinValue; + string when = IltJson.Str(root, "synced"); + if (when.Length > 0 + && DateTime.TryParse(when, CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal | DateTimeStyles.AssumeUniversal, out DateTime t)) + synced = t; + return new IltGuardianView + { + Loaded = true, + Available = IltJson.Bool(root, "available"), + World = IltJson.Str(root, "world"), + Chat = IltJson.Bool(root, "chat"), + Auto = IltJson.Bool(root, "auto"), + Buy = IltJson.Bool(root, "buy"), + CooldownHours = (int)IltJson.Long(root, "cooldownHours"), + Answer = IltJson.Str(root, "answer"), + Npc = IltJson.Str(root, "npc"), + AnswerAgeSec = IltJson.Long(root, "answerAgeSec", -1), + Heard = IltJson.Str(root, "heard"), + Running = IltJson.Bool(root, "running"), + Status = IltJson.Str(root, "status"), + SyncedUtc = synced, + Rows = rows, + }; + } + catch (JsonException) { return None; } + } + + /// The guardian verb lines (header of this file); pure so the tests check them. + public static string HandInVerb() => "handin"; + public static string StopVerb() => "stop"; + public static string RefreshVerb() => "refresh"; + /// "chat on", "auto off", "buy on": is chat, auto or buy. + public static string SwitchVerb(string name, bool on) => (name ?? "").Trim().ToLowerInvariant() + (on ? " on" : " off"); +} + /// Lenient JSON field reads shared by the views above. internal static class IltJson { diff --git a/Plugins/Shared/RynthIltHubApi.cs b/Plugins/Shared/RynthIltHubApi.cs index 5fff5fa..cdd3e9a 100644 --- a/Plugins/Shared/RynthIltHubApi.cs +++ b/Plugins/Shared/RynthIltHubApi.cs @@ -1,10 +1,14 @@ // ============================================================================ // RynthSuite - Plugins/Shared/RynthIltHubApi.cs -// The "RynthILT.Hub" interface: RynthILT's Infinite Leaftide features as RynthAi's -// Mini Remote shows them. The Mini Remote stays RynthAi's (its window, tab bar, -// Remote tab, Quests and Pets tabs); RynthILT supplies the ILT tabs (Character, -// Banking, Gear, Charms, Games), a few ILT sections drawn inside RynthAi's -// surfaces, the server's ILT feature bits and the "/ra hub ..." ILT verbs. +// The "RynthILT.Hub" interface: a server plugin's features as RynthAi's Mini +// Remote shows them (RynthILT's Infinite Leaftide ones; any server plugin may serve +// the same layout as "RynthServer.Hub", which RynthAi asks the active server's owner +// for first). The Mini Remote stays RynthAi's (its window, tab bar, Remote, Pets and +// Crafting tabs) and knows no server's content: the plugin supplies its tabs and the +// Pets tab's sub-tabs, its sections drawn inside RynthAi's surfaces (Remote, Pets, +// Options, menu), its feature bits, texts and mirrored settings, its "/ra" verbs and +// the pet summon-from-empty gate. Field names say ILT for history; the meaning is +// "the plugin's server" (IsIltWorld, GetForceIlt). // Compiled into both plugins (linked source), so the layout can't drift. // // Rules (as the RynthAi.* interfaces, Shared/RynthAiScriptApi.cs): @@ -48,13 +52,48 @@ public static class RynthIltHub public const string SectionPetLogs = "pets-logs"; /// /// Pets tab, Breeding sub-tab: the pet breeding tracker, the sub-tab's whole body (RynthILT 0.3.1+; - /// older copies draw nothing). RynthAi shows the sub-tab on an ILT world unless FeaturePetBreeding is off. + /// older copies draw nothing). Since 2026-10-20 RynthAi shows it because GetSubTabs(TabParentPets) + /// lists it (RynthILT: an ILT world unless FeaturePetBreeding is off); older RynthAi decided itself. /// public const string SectionPetBreeding = "pets-breeding"; + /// + /// Pets tab, under the roster: the ACECustom pet charms (Summon Essence Refill and its "summon from + /// empty" opt-in, Universal Summoning Mastery, the casting supplies warning). RynthILT 2026-10-20+; + /// it was RynthAi's. Draws its own leading separator; nothing off ILT. + /// + public const string SectionPetCharms = "pets-charms"; + /// Pets tab, under the charms: ACECustom siphon-lens auto-capture (switch, lens, status). As SectionPetCharms. + public const string SectionPetCapture = "pets-capture"; + + /// GetSubTabs parent: RynthAi's Pets tab (its first sub-tab, the roster, is RynthAi's own). + public const string TabParentPets = "pets"; + + /// + /// GetSetting / SetSetting key: the Vaulted Dungeons keeper's master switch (0 off, 1 on; RynthILT's + /// per-character setting since 2026-10-20, RynthAi's profile's before). RynthAi mirrors it into the + /// engine's Settings > Navigation row; -1 (no row) off ILT. + /// + public const string SettingVaultedDungeons = "vaulted-dungeons"; /// Mini Remote menu, under Infinite Leaftide: why no ILT feature is on, the Force-ILT override, Refresh. public const string SectionIltStatus = "ilt-status"; /// Mini Remote menu without RynthCore's server list: RynthILT's own Infinite Leaftide items. public const string SectionServerMenu = "server-menu"; + /// + /// Remote tab, Stats section, under RynthAi's per-hour lines: the server's own session rates (RynthILT: + /// Enlightened Coins and pyreals per hour). RynthILT 2026-10-20+; RynthAi drew them from GetRates before. + /// + public const string SectionRemoteStats = "remote-stats"; + /// + /// The Remote tab's Options popup, under RynthAi's own section switches: the server's Remote sections' + /// switches (RynthILT: Bank, Guardian answer; saved by RynthILT, which then draws or skips SectionRemoteBank / + /// SectionRemoteGuardian). RynthILT 2026-10-20+; they were RynthAi's huds.json flags. + /// + public const string SectionRemoteOptions = "remote-options"; + + /// GetText id: the tail RynthAi adds to its one-line session report ("" or ", Coins 1.2k/h, Pyr 4.5m/h"). + public const string TextSessionReport = "session-report"; + /// GetText id: the RynthCore server id this plugin's tabs and menu entries belong to ("ilt"). + public const string TextServerId = "server-id"; /// Feature keys RynthAi reads (GetFeature). public const string FeatureQuests = "quests"; @@ -88,6 +127,37 @@ public unsafe struct RynthIltHubApiV1 public const string InterfaceName = "RynthILT.Hub"; public const uint InterfaceVersion = 1; + /// + /// The same table under a server-neutral name (2026-10-20): RynthAi asks the engine's active server's + /// owner plugin for it first, so any server plugin can offer the Mini Remote tabs, sections and verbs + /// in this layout. RynthILT serves both names. + /// + public const string NeutralInterfaceName = "RynthServer.Hub"; + + /// + /// The table's size up to and including Command, as every RynthILT since the interface's first + /// release fills it. Readers check StructSize against this (not sizeof, which grows as functions + /// are appended) and check for the appended functions with . + /// + public static uint BaseStructSize => (uint)(2 * sizeof(uint) + 9 * sizeof(nint)); + + /// Whether a table RynthILT built is big enough to hold the function at . + public static bool Has(RynthIltHubApiV1* t, int offset) => t != null && t->StructSize >= (uint)(offset + sizeof(nint)); + + /// Byte offset of the n-th function appended after the base table (0 = AllowSummonOnEmpty). + private static int Appended(int n) => (int)BaseStructSize + n * sizeof(nint); + + /// Offset of (for ). + public static int AllowSummonOnEmptyOffset => Appended(0); + /// Offset of . + public static int GetSubTabsOffset => Appended(1); + /// Offset of . + public static int GetSettingOffset => Appended(2); + /// Offset of . + public static int SetSettingOffset => Appended(3); + /// Offset of . + public static int GetTextOffset => Appended(4); + public uint Version; // InterfaceVersion of the table RynthILT filled; 0 once it has shut down public uint StructSize; // sizeof(RynthIltHubApiV1) as RynthILT built it @@ -124,4 +194,38 @@ public unsafe struct RynthIltHubApiV1 /// 1 = handled, 0 = not an ILT verb. Pump thread. /// public delegate* unmanaged[Cdecl] Command; + + // ── Appended 2026-10-20 (check with Has before calling) ───────────────── + + /// + /// AllowSummonOnEmpty(): 1 when a pet may be summoned from an EMPTY essence because the server + /// refills it (ACECustom's Summon Essence Refill charm is on, the player opted in, and the server + /// confirmed the feature). RynthAi's PetManager hook asks this; 0 off ILT and whenever unsure (an + /// unknown state never spends pyreals). Cached by RynthILT's tick. Any thread. + /// + public delegate* unmanaged[Cdecl] AllowSummonOnEmpty; + + /// + /// GetSubTabs(parent, tabs, capacity): the sub-tabs RynthILT adds to one of RynthAi's tabs + /// (parent RynthIltHub.TabParentPets: the Pets tab's Breeding). Each tab's Id is a section id + /// drawn with RenderSection; Width / Height are 0 (the parent's size). Writes up to capacity, + /// returns how many (tabs null: the count); 0 off ILT or for an unknown parent. Render thread. + /// + public delegate* unmanaged[Cdecl] GetSubTabs; + + /// + /// GetSetting(key): one of the server plugin's settings that another plugin shows (RynthIltHub.Setting*; + /// RynthAi mirrors them into the engine's Settings window). The value, or -1 when the plugin has no + /// such setting to offer now (unknown key, before login, off ILT). Any thread. + /// + public delegate* unmanaged[Cdecl] GetSetting; + + /// SetSetting(key, value): changes that setting (saved by RynthILT); 1 = taken, 0 = not ours / not now. Any thread. + public delegate* unmanaged[Cdecl] SetSetting; + + /// + /// GetText(id, buffer, capacity): a short text RynthAi shows (RynthIltHub.Text*), UTF-8, truncated to + /// capacity. Returns its length; 0 for nothing (unknown id, off ILT). Any thread. + /// + public delegate* unmanaged[Cdecl] GetText; } diff --git a/Plugins/Shared/RynthIltServerApi.cs b/Plugins/Shared/RynthIltServerApi.cs new file mode 100644 index 0000000..a485b5e --- /dev/null +++ b/Plugins/Shared/RynthIltServerApi.cs @@ -0,0 +1,74 @@ +// ============================================================================ +// RynthSuite - Plugins/Shared/RynthIltServerApi.cs +// The "RynthILT.Server" interface: what RynthILT knows about the Infinite Leaftide +// server, for any plugin that wants it without drawing RynthILT's UI (RynthOracle's +// Fellowship tab, for one). One call hands out a JSON snapshot: whether this is an +// ILT world, every Leaftide feature RynthILT supports with the server's state for it, +// and the server's fellowship rules. +// Separate from "RynthILT.Hub" (RynthIltHubApi.cs) so that interface, which RynthAi asks +// for at an exact version, never has to change for this. +// Compiled into RynthILT and its readers (linked source), so the layout can't drift. +// +// Rules (as the other shared interfaces): +// - Append-only: new functions go at the end, and Version goes up. +// - Strings are UTF-8, NUL-terminated. The JSON itself is plain ASCII. +// - Every function returns safely (no exception crosses the boundary). +// - The table is allocated once per loaded copy of RynthILT and never freed; shutdown +// sets Version to 0, and a reader re-queries (host GetPluginInterface) when it sees that. +// +// GetProfileJson payload (every field may be missing on an older RynthILT; read leniently): +// { +// "ilt": true, // ILT world (its world list, or the character's override) +// "world": "InfiniteLeaftide", // the world name the server announced ("" before login) +// "forced": false, // "Treat this world as ILT" is on +// "source": "probe", // where the feature bits came from ("ilt-features", "probe", "") +// "checked": "2026-10-13T21:25:37Z", // last server-options check (UTC), "" = never +// "features": [ { "key": "bank", "label": "Banking", "group": "Character", +// "state": 1, "where": "Mini Remote > Banking tab" }, ... ], +// // state: 1 on, 0 off, -1 not known yet +// "fellowship": { "maxMembers": 29, "zoneShare": 1, "blackjack": 0, "luminanceShare": 1 }, +// "questBonus": { "disabled": false, "generation": 2, "count": 41, "status": "12 completed, 3 incomplete", +// "completed": [ "flag", ... ], "incomplete": [ "flag", ... ] } +// // the /qb list; ILT worlds only (generation 0 = not loaded yet) +// } +// ============================================================================ + +using System.Runtime.InteropServices; + +namespace RynthCore.Plugin.Shared; + +/// Constants of the "RynthILT.Server" interface. +public static class RynthIltServer +{ + /// The providing plugin's display name. + public const string PluginName = "RynthILT"; + + /// Feature state in the profile JSON: the server reports it on. + public const int StateOn = 1; + /// Feature state: the server reports it off. + public const int StateOff = 0; + /// Feature state: not known yet (not checked, not an ILT world, or no RynthILT). + public const int StateUnknown = -1; + + /// A retail fellowship's member limit (what a reader assumes without RynthILT). + public const int RetailFellowshipMax = 9; +} + +[StructLayout(LayoutKind.Sequential)] +public unsafe struct RynthIltServerApiV1 +{ + public const string InterfaceName = "RynthILT.Server"; + public const uint InterfaceVersion = 1; + + public uint Version; // InterfaceVersion of the table RynthILT filled; 0 once it has shut down + public uint StructSize; // sizeof(RynthIltServerApiV1) as RynthILT built it + + /// + /// GetProfileJson(buffer, capacity): writes the profile JSON (UTF-8, NUL-terminated) into + /// buffer when it fits, and returns its length in bytes without the NUL. A return value of + /// capacity or more means nothing was written: call again with a bigger buffer. 0 = nothing + /// to report (RynthILT shutting down). Any thread (it hands out a snapshot RynthILT's pump + /// rebuilds about once a second). + /// + public delegate* unmanaged[Cdecl] GetProfileJson; +} diff --git a/Plugins/Shared/RynthServerProfileApi.cs b/Plugins/Shared/RynthServerProfileApi.cs index 6ea3375..51cfe46 100644 --- a/Plugins/Shared/RynthServerProfileApi.cs +++ b/Plugins/Shared/RynthServerProfileApi.cs @@ -40,7 +40,10 @@ // "afterCap": true, // last, only once the item's tink slots are full // "stackGroup": "x", "stackCap": 10 // rows of one group share this cap per item // } ], -// "discord": "", "website": "", "wiki": "", "source": "" +// "discord": "", "website": "", "wiki": "", "source": "", +// "values": { // live numbers for this character on this server ({} when none; +// "voidDotDurationScale": 1.35 // ServerProfileView.Value reads one): RynthConquest's Void DoT +// } // duration rule, which RynthOracle's Void timers apply // } // ============================================================================ diff --git a/Plugins/Shared/ServerPack/ServerChatRequest.cs b/Plugins/Shared/ServerPack/ServerChatRequest.cs new file mode 100644 index 0000000..4bd477e --- /dev/null +++ b/Plugins/Shared/ServerPack/ServerChatRequest.cs @@ -0,0 +1,23 @@ +// ServerChatRequest.cs - "the server plugin just sent this command": a short time window in which the +// command's reply counts as the plugin's own, so the server's code (ServerPackPlugin.ServerChatText) +// can hide replies to its own requests and still show the same command typed by hand. A time window, +// as RynthOracle has always done it (ported from Oracle of Dereth by Advis Eveldan, MIT): these replies +// carry nothing tying them to the request. Each reply line extends it, so a long reply stays ours to its end. +// Pure: RynthServerPack.Tests covers it. +namespace RynthCore.Plugin.ServerPack; + +internal sealed class ServerChatRequest +{ + public const long WindowMs = 5000; + private long _untilMs; + + public void Sent(long nowMs) => _untilMs = nowMs + WindowMs; + public void Clear() => _untilMs = 0; + public bool Awaiting(long nowMs) => nowMs < _untilMs; + + /// A reply line arrived: keep the window open a little longer. + public void Extend(long nowMs) + { + if (Awaiting(nowMs)) _untilMs = nowMs + 2000 > _untilMs ? nowMs + 2000 : _untilMs; + } +} diff --git a/Plugins/Shared/ServerPack/ServerPackExports.cs b/Plugins/Shared/ServerPack/ServerPackExports.cs index deaed4f..4b98af7 100644 --- a/Plugins/Shared/ServerPack/ServerPackExports.cs +++ b/Plugins/Shared/ServerPack/ServerPackExports.cs @@ -67,6 +67,10 @@ public static unsafe class ServerPackExports [UnmanagedCallersOnly(EntryPoint = "RynthPluginOnChatBarEnter", CallConvs = new[] { typeof(CallConvCdecl) })] public static void OnChatBarEnter(IntPtr textUtf16, IntPtr eatFlag) => Runtime.OnChatBarEnter(textUtf16, eatFlag); + // Incoming chat, for the server's own code (ServerPackPlugin.ServerChatText). Pump thread. + [UnmanagedCallersOnly(EntryPoint = "RynthPluginOnChatWindowText", CallConvs = new[] { typeof(CallConvCdecl) })] + public static void OnChatWindowText(IntPtr textUtf16, int chatType, IntPtr eatFlag) => Runtime.OnChatWindowText(textUtf16, chatType, eatFlag); + /// The standalone server card ("/rserver"). Render thread. [UnmanagedCallersOnly(EntryPoint = "RynthPluginRender", CallConvs = new[] { typeof(CallConvCdecl) })] public static void Render() @@ -95,8 +99,8 @@ public static unsafe class ServerPackExports /// /// RynthCore's Mini Remote sections: "section:server-<id>" (":popout" added in a popped-out - /// window) draws the server card into the engine's current window. 1 = drawn, 0 = not ready or - /// not ours. + /// window) draws the server card into the engine's current window, "section:server-<id>.<page>" + /// one of the server's own pages (ServerPackPages). 1 = drawn, 0 = not ready or not ours. /// [UnmanagedCallersOnly(EntryPoint = "RynthPluginRenderEmbed", CallConvs = new[] { typeof(CallConvCdecl) })] public static int RenderEmbed(byte* surface, float width, float height, float* wantWidth, float* wantHeight) @@ -106,9 +110,18 @@ public static unsafe class ServerPackExports if (surface == null) return 0; string name = Marshal.PtrToStringUTF8((IntPtr)surface) ?? string.Empty; if (name.EndsWith(":popout", StringComparison.Ordinal)) name = name[..^":popout".Length]; - if (!name.Equals(ServerPackPlugin.SettingsSurface, StringComparison.Ordinal)) return 0; var plugin = Runtime.Plugin; - if (plugin == null || !plugin.RenderEmbeddedCard(out float wantH)) return 0; + if (plugin == null) return 0; + float wantH; + if (name.Equals(ServerPackPlugin.SettingsSurface, StringComparison.Ordinal)) + { + if (!plugin.RenderEmbeddedCard(out wantH)) return 0; + } + else + { + string? page = ServerPackPages.PageIdOf(name, RynthPluginInfo.ServerId); + if (page == null || !plugin.RenderEmbeddedPage(page, out wantH)) return 0; + } if (wantWidth != null) *wantWidth = width; if (wantHeight != null) *wantHeight = wantH; return 1; diff --git a/Plugins/Shared/ServerPack/ServerPackInfo.cs b/Plugins/Shared/ServerPack/ServerPackInfo.cs index cb0a0f6..b7a6d8f 100644 --- a/Plugins/Shared/ServerPack/ServerPackInfo.cs +++ b/Plugins/Shared/ServerPack/ServerPackInfo.cs @@ -78,6 +78,13 @@ internal sealed class ServerPackInfo public ServerCommand[] Commands { get; init; } = Array.Empty(); /// The server's own tinkering salvage (only recipes known to exist); empty = none defined. public ServerSalvage[] Salvage { get; init; } = Array.Empty(); + /// + /// Jewelry that is a trinket on this server (the Crafting tab's Trinkets bench, not Jewelry): name + /// words, case-insensitive, and words that rule a name out again ("top" but not "topaz"). Empty: + /// the server has no trinkets (retail: every jewelry piece is Jewelry). + /// + public string[] TrinketNames { get; init; } = Array.Empty(); + public string[] TrinketExcept { get; init; } = Array.Empty(); /// "3 accounts", "3 active characters", ...; empty when not published. public string AccountLimit { get; init; } = string.Empty; public BottingPolicy Botting { get; init; } = BottingPolicy.Unknown; diff --git a/Plugins/Shared/ServerPack/ServerPackInterface.cs b/Plugins/Shared/ServerPack/ServerPackInterface.cs index 339b749..1d84a47 100644 --- a/Plugins/Shared/ServerPack/ServerPackInterface.cs +++ b/Plugins/Shared/ServerPack/ServerPackInterface.cs @@ -6,6 +6,7 @@ // unloaded); after Release() it reports Version 0 and GetProfileJson answers 0. Before the plugin is // up, or between characters, the profile still describes the server (active false, no world). using System; +using System.Collections.Generic; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Text; @@ -20,7 +21,7 @@ internal static unsafe class ServerPackInterface private static volatile bool _released; /// The last JSON handed out, and what it was built for (rebuilt only when that changes). - private sealed record Snapshot(bool Active, string World, string Json); + private sealed record Snapshot(bool Active, string World, int ValuesRevision, string Json); private static Snapshot? _last; /// The table for (, ), or 0 when it isn't ours. @@ -52,10 +53,14 @@ internal static unsafe class ServerPackInterface ServerPackInfo info = plugin?.Info ?? ServerPackPlugin.StaticInfo; bool active = plugin?.Active ?? false; string world = plugin?.World ?? string.Empty; + int valuesRevision = plugin?.ProfileValues.Revision ?? -1; Snapshot? last = Volatile.Read(ref _last); - if (last != null && last.Active == active && last.World == world) return last.Json; - string json = ServerPackProfile.BuildJson(info, RynthPluginInfo.Name, RynthPluginInfo.Version, active, world); - Volatile.Write(ref _last, new Snapshot(active, world, json)); + if (last != null && last.Active == active && last.World == world && last.ValuesRevision == valuesRevision) return last.Json; + KeyValuePair[] values = plugin != null + ? plugin.ProfileValues.Snapshot(out valuesRevision) + : Array.Empty>(); + string json = ServerPackProfile.BuildJson(info, RynthPluginInfo.Name, RynthPluginInfo.Version, active, world, values); + Volatile.Write(ref _last, new Snapshot(active, world, valuesRevision, json)); return json; } diff --git a/Plugins/Shared/ServerPack/ServerPackModel.cs b/Plugins/Shared/ServerPack/ServerPackModel.cs index 7d8b951..b38ad05 100644 --- a/Plugins/Shared/ServerPack/ServerPackModel.cs +++ b/Plugins/Shared/ServerPack/ServerPackModel.cs @@ -12,6 +12,7 @@ // with a single reference write, so the render thread always reads a whole one. // Pure (no host calls): RynthServerPack.Tests covers it. using System; +using System.Collections.Generic; using System.Text; using System.Threading; @@ -163,8 +164,10 @@ internal sealed class ServerPackModel /// card in the shared "Server" section, shown only while that server is active (detected or /// forced in RynthCore Options > Diagnostics). The card left the Char section on 2026-10-13: that /// section is Session Stats now, session stats only. + /// (ServerPackPages, already validated) are the server's own views: + /// primary views of the same section, so each gets a sub-tab there, also only on that server. /// - public static string BuildSectionsJson(ServerPackInfo info, string pluginName) + public static string BuildSectionsJson(ServerPackInfo info, string pluginName, IReadOnlyList? pages = null) { var sb = new StringBuilder(512); sb.Append("{\"version\":1,\"servers\":[{\"id\":").Append(Q(info.Id)).Append(",\"name\":").Append(Q(info.Name)); @@ -180,7 +183,22 @@ internal sealed class ServerPackModel sb.Append(",\"primary\":false,\"height\":320,\"enabled\":true,\"tooltip\":"); sb.Append(Q("What is known about " + info.Name + ": rules, account limits, botting policy, links and setup (" + pluginName + "; also /rserver).")); - sb.Append(",\"order\":130}]}"); + sb.Append(",\"order\":130}"); + if (pages != null) + { + for (int i = 0; i < pages.Count; i++) + { + ServerPage p = pages[i]; + sb.Append(",{\"section\":").Append(Q(SectionId)); + sb.Append(",\"server\":").Append(Q(info.Id)); + sb.Append(",\"label\":").Append(Q(p.Label)); + sb.Append(",\"surface\":").Append(Q(ServerPackPages.SurfaceFor(info.Id, p.Id))); + sb.Append(",\"primary\":true,\"width\":").Append(ServerPackPages.Width).Append(",\"height\":").Append(ServerPackPages.Height); + sb.Append(",\"enabled\":true,\"tooltip\":").Append(Q(p.Tooltip.Length > 0 ? p.Tooltip : p.Label + " (" + pluginName + ")")); + sb.Append(",\"order\":").Append(100 + i).Append('}'); + } + } + sb.Append("]}"); return sb.ToString(); } diff --git a/Plugins/Shared/ServerPack/ServerPackPages.cs b/Plugins/Shared/ServerPack/ServerPackPages.cs new file mode 100644 index 0000000..a45f327 --- /dev/null +++ b/Plugins/Shared/ServerPack/ServerPackPages.cs @@ -0,0 +1,86 @@ +// ServerPackPages.cs - Pages a server plugin adds beside its server card (RynthConquest's Conquest and +// Leaderboards pages, RynthAelrynth's Leaderboards, ...). +// +// A server's own features need somewhere to show. The ServerPackPlugin.ServerPages hook lists them +// once, at construction; the shared code then +// * declares each one in the sections manifest as a primary view of the shared "Server" section, +// shown only while this plugin's server is active (contribution "server": ), so RynthCore's +// Mini Remote gives it a sub-tab next to the server card; +// * draws it through RynthPluginRenderEmbed under the surface "section:server-." +// (":popout" added in a popped-out window), into the engine's current window and context; +// * shows the same pages as tabs of the standalone "/rserver" window, after the card. +// Draw runs on the render thread: a page reads its state under its own lock and queues anything it +// sends for the plugin tick (ServerPackPlugin.RunOnTick). +// Pure (no ImGui, no host calls): RynthServerPack.Tests covers it. +using System; +using System.Collections.Generic; + +namespace RynthCore.Plugin.ServerPack; + +/// +/// One page a server plugin adds. is 1-16 of a-z, 0-9 and '-' (part of the +/// surface name); draws the body into the current ImGui window (render thread). +/// +internal sealed record ServerPage(string Id, string Label, string Tooltip, Action Draw); + +internal static class ServerPackPages +{ + /// At most this many pages per plugin (the Mini Remote shows them as one row of tabs). + public const int MaxPages = 6; + /// The longest page id (keeps "section:server-<32-char id>.<page>" under the engine's 64). + public const int MaxIdLength = 16; + /// The engine caps contribution labels at 48 characters. + public const int MaxLabelLength = 48; + /// Page views open at this size in the Mini Remote (it fits the window to the view). + public const int Width = 540, Height = 520; + + /// True for a page id: 1-16 of a-z, 0-9 and '-'. + public static bool IsValidId(string? id) + { + if (string.IsNullOrEmpty(id) || id.Length > MaxIdLength) return false; + foreach (char c in id) + if (!(c is >= 'a' and <= 'z' || c is >= '0' and <= '9' || c == '-')) return false; + return true; + } + + /// "section:server-conquest.bank": the page's surface. + public static string SurfaceFor(string serverId, string pageId) => ServerPackModel.SurfaceFor(serverId) + "." + pageId; + + /// + /// The page id a surface names for this server ("section:server-conquest.bank" -> "bank"), or + /// null for the card, another server's surface or anything else. ":popout" is ignored. + /// + public static string? PageIdOf(string? surface, string serverId) + { + if (string.IsNullOrEmpty(surface)) return null; + string name = surface.EndsWith(":popout", StringComparison.Ordinal) ? surface[..^":popout".Length] : surface; + string prefix = ServerPackModel.SurfaceFor(serverId) + "."; + if (!name.StartsWith(prefix, StringComparison.Ordinal)) return null; + string id = name[prefix.Length..]; + return IsValidId(id) ? id : null; + } + + /// + /// The pages kept from what a plugin listed: valid, unique ids, a label, at most + /// ; each one dropped is reported to . + /// + public static List Validate(IEnumerable? pages, Action? log = null) + { + var kept = new List(); + if (pages == null) return kept; + foreach (ServerPage p in pages) + { + if (p == null) continue; + string why = !IsValidId(p.Id) ? "its id isn't 1-16 of a-z, 0-9 and '-'" + : string.IsNullOrWhiteSpace(p.Label) ? "it has no label" + : p.Draw == null ? "it has nothing to draw" + : kept.Exists(k => k.Id == p.Id) ? "another page has its id" + : kept.Count >= MaxPages ? $"a plugin has at most {MaxPages} pages" + : string.Empty; + if (why.Length > 0) { log?.Invoke($"Page '{p.Id}' left out: {why}."); continue; } + string label = p.Label.Trim(); + kept.Add(p with { Label = label.Length <= MaxLabelLength ? label : label[..MaxLabelLength], Tooltip = p.Tooltip ?? string.Empty }); + } + return kept; + } +} diff --git a/Plugins/Shared/ServerPack/ServerPackPlugin.cs b/Plugins/Shared/ServerPack/ServerPackPlugin.cs index 598d76e..754ded7 100644 --- a/Plugins/Shared/ServerPack/ServerPackPlugin.cs +++ b/Plugins/Shared/ServerPack/ServerPackPlugin.cs @@ -14,11 +14,33 @@ // Server-specific features: add files to the server's project implementing the partial hooks below // (ServerLoginComplete, ServerTick, ServerChatCommand, ...). Unimplemented hooks compile away. // -// Threads: OnTick, login/logout and the engine's export calls run on the plugin pump. OnChatBarEnter -// runs on AC's main thread, so it only queues. The card draws on the render thread (OnRender, -// RynthPluginRenderEmbed) and queues its commands for the tick. +// What the shared code gives a server's own features (added 2026-10-20, when RynthOracle's and +// RynthInventory's Conquest and Aelrynth features moved into RynthConquest and RynthAelrynth, so a +// shared plugin carries nothing for one server): +// ServerPages(list) pages of its own (ServerPackPages.cs): sub-tabs of the Mini Remote's +// Server section, only while its server is active, and tabs of the +// /rserver window. Draw runs on the render thread. +// ServerChatText(...) every incoming chat line (pump thread), to read the server's replies +// and hide the ones answering the plugin's own requests (eat). +// ServerChatBar(text) every line sent through the chat bar (AC's thread: note it only), +// to tell the player's typed command from the plugin's own. +// Settings the plugin's own settings file (ServerPackSettings.cs), loaded before +// ServerInitialize; MigrateOnce imports a setting from its old home. +// SetProfileValue(key, n) a live number in its "RynthServer.Profile" ("values"), for other +// plugins that apply a server rule without knowing the server. +// ServerCommandVerbs(list) its own "/rserver " words, handled in ServerChatCommand. +// RunOnTick(action) work for the next tick (a page's button, on the render thread). +// Send(command) a chat command as if typed (pump thread, logged in only); +// LogTagged(text) the engine log, "[RynthConquest] ..."; ChatLine(text) the chat window. +// The tick, chat and command hooks only run while a character is logged in; each +// should check Active itself, since the plugin can be loaded for a world that isn't its server. +// +// Threads: OnTick, login/logout, chat lines and the engine's export calls run on the plugin pump. +// OnChatBarEnter runs on AC's main thread, so it only queues. The card and the pages draw on the +// render thread (OnRender, RynthPluginRenderEmbed) and queue their commands for the tick. using System; using System.Collections.Concurrent; +using System.Collections.Generic; using System.Runtime.InteropServices; using ImGuiNET; using RynthCore.PluginCore; @@ -40,10 +62,19 @@ public sealed partial class ServerPackPlugin : RynthPluginBase private readonly ServerPackModel _model; private readonly ServerPackUi _ui; private readonly string _sectionsJson; + // The server's own pages (ServerPages), validated; what was left out is logged at Initialize. + private readonly List _pages; + private readonly List _pageNotes = new(); + private readonly ServerPackSettings _settings = new(ServerPackSettings.DefaultPath(RynthPluginInfo.Name)); + private readonly ServerProfileValues _profileValues = new(); // RynthCore commands from the card (render thread), run on the next tick. private readonly ConcurrentQueue _engineCommands = new(); // "/rserver ..." lines from OnChatBarEnter, run on the next tick. private readonly ConcurrentQueue _commands = new(); + // The server code's work for the tick (RunOnTick: its pages' buttons). + private readonly ConcurrentQueue _tickActions = new(); + // The server's own "/rserver" verbs (ServerCommandVerbs). + private readonly HashSet _serverVerbs = new(StringComparer.OrdinalIgnoreCase); private volatile bool _loginComplete; private volatile string? _world; private bool _wasActive; @@ -52,8 +83,14 @@ public sealed partial class ServerPackPlugin : RynthPluginBase { ServerPackInfo info = ServerData.Create(); _model = new ServerPackModel(info); - _ui = new ServerPackUi(_model, RynthPluginInfo.Name + " " + Marshal.PtrToStringAnsi(VersionPointer), () => _world); - _sectionsJson = ServerPackModel.BuildSectionsJson(info, RynthPluginInfo.Name); + var pages = new List(); + ServerPages(pages); + _pages = ServerPackPages.Validate(pages, _pageNotes.Add); + var verbs = new List(); + ServerCommandVerbs(verbs); + foreach (string v in verbs) if (!string.IsNullOrWhiteSpace(v)) _serverVerbs.Add(v.Trim()); + _ui = new ServerPackUi(_model, RynthPluginInfo.Name + " " + Marshal.PtrToStringAnsi(VersionPointer), () => _world, _pages); + _sectionsJson = ServerPackModel.BuildSectionsJson(info, RynthPluginInfo.Name, _pages); } internal ServerPackInfo Info => _model.Info; @@ -79,8 +116,52 @@ public sealed partial class ServerPackPlugin : RynthPluginBase partial void ServerTick(bool active); /// "/rserver <verb> ..." verbs the shared code doesn't know; set handled to stop the help text. partial void ServerChatCommand(string[] parts, ref bool handled); + /// + /// The server's own "/rserver" verbs (lower case), so "/rserver vault" reaches ServerChatCommand + /// instead of being read as another server's id. Called once, from the constructor. + /// + partial void ServerCommandVerbs(List verbs); /// Extra lines for "/rserver info". partial void ServerInfoLines(Action line); + /// The server's own pages (ServerPackPages.cs). Called once, from the constructor (no Host yet). + partial void ServerPages(List pages); + /// + /// An incoming chat line (pump thread, logged in only): set to keep it out of + /// the chat window (it comes in true when an earlier plugin already ate it). + /// + partial void ServerChatText(string text, int chatType, ref bool eat); + /// + /// A line sent through the chat bar, typed or another plugin's command (trimmed), before + /// "/rserver" is looked at. AC's main thread: only note it (interlocked state or a queue). + /// + partial void ServerChatBar(string text); + + // ── What the server's own code uses ────────────────────────────────── + + /// The plugin's settings file (loaded before ServerInitialize). Pump thread. + internal ServerPackSettings Settings => _settings; + + /// The live numbers of the profile ("values"). Any thread. + internal ServerProfileValues ProfileValues => _profileValues; + + /// The pages this plugin draws. + internal IReadOnlyList Pages => _pages; + + /// Publishes a live number in the "RynthServer.Profile" JSON ("values"). Any thread. + internal void SetProfileValue(string key, double value) => _profileValues.Set(key, value); + + /// Runs on the next tick while logged in (dropped at logout). Any thread. + internal void RunOnTick(Action action) + { + if (action != null) _tickActions.Enqueue(action); + } + + /// Sends a chat command as if typed; false when nothing went out. Pump thread. + internal bool Send(string command) + => _loginComplete && !string.IsNullOrWhiteSpace(command) && Host.HasInvokeChatParser && Host.InvokeChatParser(command); + + /// The plugin's log, tagged with its name. + internal void LogTagged(string message) => Host.Log($"[{RynthPluginInfo.Name}] {message}"); public override int Initialize() { @@ -89,6 +170,9 @@ public sealed partial class ServerPackPlugin : RynthPluginBase // Mini Remote's included), never a second copy of ImGui (ImGuiNativeBinding.cs). Found and fixed // by SilentKelpie (rynth PR #12); re-implemented here. RynthCore.Plugin.Shared.ImGuiNativeBinding.Ensure(msg => Host.Log($"[{RynthPluginInfo.Name}] {msg}")); + foreach (string note in _pageNotes) LogTagged(note); + _settings.Load(); + if (_settings.LastError.Length > 0) LogTagged($"Settings ({_settings.FilePath}) not read: {_settings.LastError}; using defaults."); ServerInitialize(); return 0; } @@ -108,7 +192,9 @@ public sealed partial class ServerPackPlugin : RynthPluginBase _world = null; while (_commands.TryDequeue(out _)) { } while (_engineCommands.TryDequeue(out _)) { } + while (_tickActions.TryDequeue(out _)) { } _model.Clear(); + _profileValues.Clear(); ServerLogout(); } @@ -124,6 +210,11 @@ public sealed partial class ServerPackPlugin : RynthPluginBase if (!Host.HasInvokeChatParser || !Host.InvokeChatParser(command)) ChatLine($"[{RynthPluginInfo.Name}] RynthCore didn't take: " + command); } + while (_tickActions.TryDequeue(out Action? action)) + { + try { action(); } + catch (Exception ex) { LogTagged($"A queued action failed: {ex.GetType().Name}: {ex.Message}"); } + } bool active = Active; if (active && !_wasActive && Info.Botting == BottingPolicy.Forbidden) @@ -173,7 +264,20 @@ public sealed partial class ServerPackPlugin : RynthPluginBase /// into the engine's current window and context (popped-out windows have their own). /// is the height it used. False until login. Render thread. /// - internal bool RenderEmbeddedCard(out float wantHeight) + internal bool RenderEmbeddedCard(out float wantHeight) => RenderEmbedded(_ui.RenderBody, "Server card", out wantHeight); + + /// + /// RynthPluginRenderEmbed "section:server-<id>.<page>": one of the server's pages + /// (ServerPages) in RynthCore's Mini Remote. False for a page this plugin doesn't have, or before login. + /// + internal bool RenderEmbeddedPage(string pageId, out float wantHeight) + { + wantHeight = 0; + ServerPage? page = _pages.Find(p => p.Id == pageId); + return page != null && RenderEmbedded(page.Draw, "Page " + page.Label, out wantHeight); + } + + private bool RenderEmbedded(Action draw, string what, out float wantHeight) { wantHeight = 0; if (!_loginComplete) return false; @@ -184,24 +288,36 @@ public sealed partial class ServerPackPlugin : RynthPluginBase try { float startY = ImGui.GetCursorPosY(); - _ui.RenderBody(); + draw(); wantHeight = MathF.Max(40f, ImGui.GetCursorPosY() - startY + 4f); return true; } catch (Exception ex) { - Host.Log($"[{RynthPluginInfo.Name}] Server card failed: {ex.Message}"); + Host.Log($"[{RynthPluginInfo.Name}] {what} failed: {ex.Message}"); return false; } finally { ImGui.SetCurrentContext(previous); } } + // ── Chat ───────────────────────────────────────────────────────────── + + /// Incoming chat (pump thread): the server's own code reads it (ServerChatText). + public override void OnChatWindowText(string? text, int chatType, ref int eat) + { + if (!_loginComplete || string.IsNullOrEmpty(text)) return; + bool eaten = eat != 0; + ServerChatText(text, chatType, ref eaten); + if (eaten) eat = 1; + } + // ── Commands ───────────────────────────────────────────────────────── public override void OnChatBarEnter(string? text, ref int eat) { if (!_loginComplete || string.IsNullOrEmpty(text)) return; string trimmed = text.Trim(); + ServerChatBar(trimmed); if (!trimmed.Equals(ChatCommand, StringComparison.OrdinalIgnoreCase) && !trimmed.StartsWith(ChatCommand + " ", StringComparison.OrdinalIgnoreCase)) return; @@ -216,8 +332,9 @@ public sealed partial class ServerPackPlugin : RynthPluginBase _commands.Enqueue(parts); } - private static bool IsVerb(string word) => - word.ToLowerInvariant() is "show" or "hide" or "toggle" or "info" or "help" or "on" or "off" or "auto"; + private bool IsVerb(string word) => + word.ToLowerInvariant() is "show" or "hide" or "toggle" or "info" or "help" or "on" or "off" or "auto" + || _serverVerbs.Contains(word); /// Drops the server id: "/rserver coldeve info" -> "/rserver info". private static string[] Shift(string[] parts) diff --git a/Plugins/Shared/ServerPack/ServerPackProfile.cs b/Plugins/Shared/ServerPack/ServerPackProfile.cs index e3c3a70..700c431 100644 --- a/Plugins/Shared/ServerPack/ServerPackProfile.cs +++ b/Plugins/Shared/ServerPack/ServerPackProfile.cs @@ -9,10 +9,90 @@ // The JSON is plain ASCII (anything else is \u-escaped), so a reader can show it in the AC client. // Pure (no host calls): RynthServerPack.Tests covers it. using System; +using System.Collections.Generic; +using System.Globalization; using System.Text; namespace RynthCore.Plugin.ServerPack; +/// +/// Live numbers a server plugin publishes in its profile ("values"), for other plugins that apply a +/// server rule without knowing the server: e.g. RynthConquest's "voidDotDurationScale" (how much +/// longer this character's Void damage-over-time lasts there), which RynthOracle's Void timers use. +/// Set from the server's own code (ServerPackPlugin.SetProfileValue), read by the profile interface +/// on any thread; goes up on every change, so the JSON is rebuilt only then. +/// +internal sealed class ServerProfileValues +{ + private readonly object _gate = new(); + private readonly List> _values = new(); + private volatile int _revision; + + /// Goes up whenever a value changes. + public int Revision => _revision; + + /// 1-48 of letters, digits, '.', '_' and '-'. + public static bool IsValidKey(string? key) + { + if (string.IsNullOrEmpty(key) || key.Length > 48) return false; + foreach (char c in key) + if (!(char.IsAsciiLetterOrDigit(c) || c is '.' or '_' or '-')) return false; + return true; + } + + /// Sets (or adds) a value; false for a bad key or a number that isn't finite. Any thread. + public bool Set(string key, double value) + { + if (!IsValidKey(key) || !double.IsFinite(value)) return false; + lock (_gate) + { + int i = _values.FindIndex(v => v.Key == key); + if (i >= 0) + { + if (_values[i].Value.Equals(value)) return true; + _values[i] = new KeyValuePair(key, value); + } + else _values.Add(new KeyValuePair(key, value)); + _revision++; + } + return true; + } + + /// Drops one value (true when it was there). Any thread. + public bool Remove(string key) + { + lock (_gate) + { + int i = _values.FindIndex(v => v.Key == key); + if (i < 0) return false; + _values.RemoveAt(i); + _revision++; + return true; + } + } + + /// Drops every value (logout: the next character publishes its own). Any thread. + public void Clear() + { + lock (_gate) + { + if (_values.Count == 0) return; + _values.Clear(); + _revision++; + } + } + + /// A copy of the values and the revision it belongs to. Any thread. + public KeyValuePair[] Snapshot(out int revision) + { + lock (_gate) + { + revision = _revision; + return _values.ToArray(); + } + } +} + internal static class ServerPackProfile { /// The profile JSON's schema (RynthServerProfile.Schema). @@ -29,9 +109,11 @@ internal static class ServerPackProfile /// /// The profile for : is this plugin's verdict - /// (RynthCore's when it pushed one), the world name the client reports. + /// (RynthCore's when it pushed one), the world name the client reports, + /// the live numbers the server's own code published (ServerProfileValues). /// - public static string BuildJson(ServerPackInfo info, string pluginName, string pluginVersion, bool active, string? world) + public static string BuildJson(ServerPackInfo info, string pluginName, string pluginVersion, bool active, string? world, + IReadOnlyList>? values = null) { var sb = new StringBuilder(1024); sb.Append("{\"schema\":").Append(Schema); @@ -93,10 +175,35 @@ internal static class ServerPackProfile sb.Append('}'); } sb.Append(']'); + // Added within schema 1 (2026-10-20), only when the server has trinkets. + if (info.TrinketNames.Length > 0) + { + sb.Append(",\"trinkets\":{"); + sb.Append("\"names\":["); + for (int i = 0; i < info.TrinketNames.Length; i++) { if (i > 0) sb.Append(','); Str(sb, info.TrinketNames[i]); } + sb.Append("],\"except\":["); + for (int i = 0; i < info.TrinketExcept.Length; i++) { if (i > 0) sb.Append(','); Str(sb, info.TrinketExcept[i]); } + sb.Append("]}"); + } Field(sb, "discord", info.Discord); Field(sb, "website", info.Website); Field(sb, "wiki", info.Wiki); Field(sb, "source", info.Source); + // Added within schema 1: live numbers for this character on this server ({} when none). + sb.Append(",\"values\":{"); + if (values != null) + { + bool first = true; + foreach (KeyValuePair v in values) + { + if (!ServerProfileValues.IsValidKey(v.Key) || !double.IsFinite(v.Value)) continue; + if (!first) sb.Append(','); + first = false; + Str(sb, v.Key); + sb.Append(':').Append(v.Value.ToString("R", CultureInfo.InvariantCulture)); + } + } + sb.Append('}'); sb.Append('}'); return sb.ToString(); } diff --git a/Plugins/Shared/ServerPack/ServerPackRefresh.cs b/Plugins/Shared/ServerPack/ServerPackRefresh.cs new file mode 100644 index 0000000..3887d72 --- /dev/null +++ b/Plugins/Shared/ServerPack/ServerPackRefresh.cs @@ -0,0 +1,88 @@ +// ServerPackRefresh.cs - The Refresh button a server page starts with, and the status line beside it +// (as RynthOracle's pages have it): the page's own command is asked for again, refused for a few +// seconds after it went out (so the button can't spam the server), and the line waits for the reply +// ("Waiting...", then "Updated hh:mm:ss", or "No reply yet" after a while). +// Render thread: Draw runs inside the page's own lock; the page's refresh callback only decides and +// queues what to send (ServerPackPlugin.RunOnTick). +using System; +using System.Collections.Generic; +using System.Numerics; +using ImGuiNET; +using RynthCore.Plugin.Shared; + +namespace RynthCore.Plugin.ServerPack; + +/// What a Refresh did, and (when it asked the server) how to tell the reply has landed. +internal sealed record ServerRefreshResult(string What, Func? Done = null); + +internal sealed class ServerRefreshRow +{ + public const long CooldownMs = 3000; + public const long ReplyWaitMs = 15_000; + public const string TooSoon = "That was just asked for; wait a few seconds before asking again."; + + private static readonly Vector4 Yellow = new(0.95f, 0.85f, 0.35f, 1f); + private static readonly Vector4 Red = new(0.95f, 0.45f, 0.40f, 1f); + + private readonly Dictionary _sent = new(); + private string _scope = string.Empty, _what = string.Empty; + private Func? _done; + private bool _doneSeen; + private long _atMs; + private DateTime _atLocal, _doneLocal; + + /// The same request (by ) twice within is refused. + public bool CoolingDown(string key, long nowMs) + { + if (_sent.TryGetValue(key, out long t) && nowMs - t < CooldownMs) return true; + _sent[key] = nowMs; + return false; + } + + /// Forgets the status line and the cooldowns (logout). + public void Reset() + { + _sent.Clear(); + _scope = _what = string.Empty; + _done = null; + } + + /// + /// The row: Refresh (tooltip ) and, for the page that last refreshed + /// (), what happened. + /// + public void Draw(string scope, string help, Func refresh) + { + long now = Environment.TickCount64; + if (ImGui.SmallButton("Refresh##refresh_" + scope)) + { + ServerRefreshResult r; + try { r = refresh(); } + catch (Exception ex) { r = new ServerRefreshResult("Couldn't refresh: " + ex.Message); } + _scope = scope; + _what = r.What; + _done = r.Done; + _doneSeen = false; + _atMs = now; + _atLocal = DateTime.Now; + } + if (help.Length > 0 && ImGui.IsItemHovered()) SafeImGui.SetTooltip(help); + if (_scope != scope || _what.Length == 0) return; + + ImGui.SameLine(); + if (_done != null && !_doneSeen && _done()) + { + _doneSeen = true; + _doneLocal = DateTime.Now; + } + if (_done != null && !_doneSeen) + { + if (now - _atMs > ReplyWaitMs) SafeImGui.TextColored(Red, "No reply yet. Press Refresh to ask again."); + else SafeImGui.TextColored(Yellow, _what + " Waiting for the reply..."); + } + else if (_done != null) + SafeImGui.TextDisabled($"Updated {_doneLocal:HH:mm:ss}. {_what}"); + else + SafeImGui.TextDisabled($"Refreshed {_atLocal:HH:mm:ss}. {_what}"); + } +} diff --git a/Plugins/Shared/ServerPack/ServerPackSettings.cs b/Plugins/Shared/ServerPack/ServerPackSettings.cs new file mode 100644 index 0000000..0b9b1ac --- /dev/null +++ b/Plugins/Shared/ServerPack/ServerPackSettings.cs @@ -0,0 +1,158 @@ +// ServerPackSettings.cs - A server plugin's own settings file, %APPDATA%\RynthCore\.json +// (rynthconquest.json, ...), for the server's features (ServerPackPlugin.Settings). +// +// Flat named values (true/false, text), written by hand and read with JsonDocument: plugin types +// never go through System.Text.Json's serializer, which roots them across hot reloads. Values the +// plugin doesn't ask for are kept as they were written, so an older or newer copy of the plugin +// never drops another's. MigrateOnce imports settings that used to live elsewhere (another +// plugin's file) exactly once, and remembers that it did. +// Pure (file I/O only): RynthServerPack.Tests covers it. Pump thread only. +using System; +using System.Collections.Generic; +using System.IO; +using System.Text; +using System.Text.Json; + +namespace RynthCore.Plugin.ServerPack; + +internal sealed class ServerPackSettings +{ + // name -> the value's JSON text, in file order. + private readonly List> _values = new(); + + public ServerPackSettings(string path) => FilePath = path; + + /// %APPDATA%\RynthCore\<plugin name, lower case>.json. + public static string DefaultPath(string pluginName) => Path.Combine( + Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "RynthCore", pluginName.ToLowerInvariant() + ".json"); + + public string FilePath { get; } + + /// Why the last Load or Save failed ("" when it didn't). + public string LastError { get; private set; } = string.Empty; + + /// Reads the file; a missing or broken one means defaults (the next save rewrites it). + public void Load() + { + _values.Clear(); + LastError = string.Empty; + try + { + if (!File.Exists(FilePath)) return; + using JsonDocument doc = JsonDocument.Parse(File.ReadAllText(FilePath)); + if (doc.RootElement.ValueKind != JsonValueKind.Object) { LastError = "not a JSON object"; return; } + foreach (JsonProperty p in doc.RootElement.EnumerateObject()) + Put(p.Name, p.Value.GetRawText()); + } + catch (Exception ex) + { + _values.Clear(); + LastError = ex.Message; + } + } + + /// Writes the file (through a temporary file, so a crash never leaves half of one). False on failure. + public bool Save() + { + try + { + var sb = new StringBuilder("{\n"); + for (int i = 0; i < _values.Count; i++) + { + sb.Append(" ").Append(Quote(_values[i].Key)).Append(": ").Append(_values[i].Value); + sb.Append(i + 1 < _values.Count ? ",\n" : "\n"); + } + sb.Append("}\n"); + Directory.CreateDirectory(Path.GetDirectoryName(FilePath)!); + string tmp = FilePath + ".tmp"; + File.WriteAllText(tmp, sb.ToString()); + File.Move(tmp, FilePath, overwrite: true); + LastError = string.Empty; + return true; + } + catch (Exception ex) + { + LastError = ex.Message; + return false; + } + } + + public bool Has(string name) => Find(name) >= 0; + + public bool GetBool(string name, bool fallback) + { + int i = Find(name); + return i < 0 ? fallback : _values[i].Value switch { "true" => true, "false" => false, _ => fallback }; + } + + /// Sets a value; true when it changed (the caller saves). + public bool SetBool(string name, bool value) => Put(name, value ? "true" : "false"); + + public string GetString(string name, string fallback) + { + int i = Find(name); + if (i < 0) return fallback; + try + { + using JsonDocument doc = JsonDocument.Parse(_values[i].Value); + return doc.RootElement.ValueKind == JsonValueKind.String ? doc.RootElement.GetString() ?? fallback : fallback; + } + catch (JsonException) { return fallback; } + } + + public bool SetString(string name, string value) => Put(name, Quote(value ?? string.Empty)); + + /// + /// Runs once per settings file: unless is + /// already set, it runs, the marker is set and the file saved. True when it ran now. + /// + public bool MigrateOnce(string marker, Action migrate) + { + if (GetBool(marker, false)) return false; + migrate(this); + SetBool(marker, true); + Save(); + return true; + } + + /// + /// A true/false value from another JSON settings file (an old home of a moved setting), or null + /// when the file, the value or its type isn't there. Never throws. + /// + public static bool? ReadBoolFrom(string path, string name) + { + try + { + if (!File.Exists(path)) return null; + using JsonDocument doc = JsonDocument.Parse(File.ReadAllText(path)); + if (doc.RootElement.ValueKind != JsonValueKind.Object || !doc.RootElement.TryGetProperty(name, out JsonElement v)) return null; + return v.ValueKind switch { JsonValueKind.True => true, JsonValueKind.False => false, _ => null }; + } + catch + { + return null; + } + } + + private int Find(string name) + { + for (int i = 0; i < _values.Count; i++) + if (string.Equals(_values[i].Key, name, StringComparison.Ordinal)) return i; + return -1; + } + + private bool Put(string name, string json) + { + int i = Find(name); + if (i >= 0) + { + if (_values[i].Value == json) return false; + _values[i] = new KeyValuePair(name, json); + return true; + } + _values.Add(new KeyValuePair(name, json)); + return true; + } + + private static string Quote(string s) => "\"" + JsonEncodedText.Encode(s).ToString() + "\""; +} diff --git a/Plugins/Shared/ServerPack/ServerPackUi.cs b/Plugins/Shared/ServerPack/ServerPackUi.cs index 66ea2e9..7db36ba 100644 --- a/Plugins/Shared/ServerPack/ServerPackUi.cs +++ b/Plugins/Shared/ServerPack/ServerPackUi.cs @@ -7,6 +7,7 @@ // account limit, botting policy, its features), the commands it adds, its links, and how to set an // account up for it in the launcher. Render thread only. using System; +using System.Collections.Generic; using System.Numerics; using ImGuiNET; using RynthCore.Plugin.Shared; @@ -24,6 +25,7 @@ internal sealed class ServerPackUi private readonly string _pluginLabel; private readonly Func _world; private readonly string _windowTitle; + private readonly IReadOnlyList _pages; private string _status = string.Empty; /// The standalone window is open ("/rserver"). @@ -31,21 +33,42 @@ internal sealed class ServerPackUi /// "RynthColdeve 0.1.0", for the title and the card. /// The world name the client reports now (null when unknown). - public ServerPackUi(ServerPackModel model, string pluginLabel, Func world) + /// The server's own pages: tabs of the window after the card. + public ServerPackUi(ServerPackModel model, string pluginLabel, Func world, IReadOnlyList? pages = null) { _model = model; _pluginLabel = pluginLabel; _world = world; + _pages = pages ?? Array.Empty(); _windowTitle = model.Info.Name + " server (" + pluginLabel + ")##server_" + model.Info.Id; } - /// The standalone window, while open. + /// The standalone window, while open: the card, and the server's pages as tabs when it has some. public void RenderWindow() { if (!WindowOpen) return; - ImGui.SetNextWindowSize(new Vector2(460, 520), ImGuiCond.FirstUseEver); + ImGui.SetNextWindowSize(new Vector2(_pages.Count > 0 ? 560 : 460, 520), ImGuiCond.FirstUseEver); bool open = WindowOpen; - if (ImGui.Begin(_windowTitle, ref open)) RenderBody(); + if (ImGui.Begin(_windowTitle, ref open)) + { + if (_pages.Count == 0) RenderBody(); + else if (ImGui.BeginTabBar("##server_tabs_" + _model.Info.Id)) + { + if (ImGui.BeginTabItem("Server##card")) + { + RenderBody(); + ImGui.EndTabItem(); + } + foreach (ServerPage page in _pages) + { + if (!ImGui.BeginTabItem(page.Label + "##page_" + page.Id)) continue; + if (ImGui.BeginChild("##page_body_" + page.Id)) page.Draw(); + ImGui.EndChild(); + ImGui.EndTabItem(); + } + ImGui.EndTabBar(); + } + } ImGui.End(); WindowOpen = open; } diff --git a/Plugins/Shared/ServerPack/ServerPlugin.props b/Plugins/Shared/ServerPack/ServerPlugin.props index 406b133..0a65166 100644 --- a/Plugins/Shared/ServerPack/ServerPlugin.props +++ b/Plugins/Shared/ServerPack/ServerPlugin.props @@ -17,7 +17,8 @@ engine loads the plugin only for its server) and into RynthPluginInfo (the plugin's own use). Server-specific features go in the project as more files, through the partial hooks in - ServerPackPlugin.cs (ServerTick, ServerChatCommand, ...), so the shared code stays the same for all. + ServerPackPlugin.cs (ServerTick, ServerChatCommand, ServerChatText, ServerPages, ...), so the + shared code stays the same for all (the hooks and helpers are listed at the top of that file). --> net10.0-windows @@ -44,6 +45,11 @@ + + + + + diff --git a/Plugins/Shared/StorageFeed.cs b/Plugins/Shared/StorageFeed.cs new file mode 100644 index 0000000..15cc616 --- /dev/null +++ b/Plugins/Shared/StorageFeed.cs @@ -0,0 +1,153 @@ +// ============================================================================ +// RynthSuite - Plugins/Shared/StorageFeed.cs +// Storage the client is never shown, handed to RynthInventory by another plugin: a server plugin +// that can read a server-side store (RynthAelrynth reads Aelrynth's account vault with /mule-data) +// sends RynthInventory the whole record, and RynthInventory files it with the character's storage +// (searched, shown with icons and merged across characters like a container that was opened). +// RynthInventory knows nothing about the server: the sender decides what the store is and when to +// read it; without the sender (its server plugin not installed) nothing is asked and nothing is sent. +// +// Transport: the engine's plugin-command broker, SendPluginCommand("RynthInventory", "storage", +// json) -> RynthInventory's RynthPluginApplyRemoteCommand. The strings travel as ANSI, so the JSON +// is plain ASCII (anything else \u-escaped). Payload (version 1): +// { "v": 1, +// "id": 4278190080, // a stand-in container id, top byte 0xFF (never a real object's); +// // the same id replaces the earlier copy (per character file) +// "name": "Aelrynth vault", "label": "Account vault", +// "items": [ { "o": id, "w": wcid, "n": "name", "i": icon, "u": underlay, "v": overlay, +// "s": stack, "m": max stack, "y": item type }, ... ] } +// Compiled into RynthInventory (receiver) and the senders (linked source), so the format can't drift. +// Pure: RynthInventory.Tests and RynthServerPack.Tests cover it. +// ============================================================================ + +using System; +using System.Collections.Generic; +using System.Globalization; +using System.Text; +using System.Text.Json; + +namespace RynthCore.Plugin.Shared; + +/// One stored item, as a sender read it (the vault's "o", "w", "n", ... fields). +internal sealed record StorageFeedItem(uint Id, uint Wcid, string Name, uint Icon, uint Underlay, uint Overlay, + int Stack, int MaxStack, uint ItemType); + +/// A whole store: its stand-in id, its name and label, and everything in it. +internal sealed record StorageFeedRecord(uint Id, string Name, string Label, IReadOnlyList Items); + +internal static class StorageFeed +{ + /// The receiver, and the plugin command it answers. + public const string TargetPlugin = "RynthInventory"; + public const string Action = "storage"; + public const int Version = 1; + public const int MaxItems = 5000; + public const int MaxJsonLength = 4 * 1024 * 1024; + public const int MaxNameLength = 64; + + /// A stand-in container id: top byte 0xFF, where no object the client has seen lives. + public static bool IsStandInId(uint id) => id >> 24 == 0xFF; + + /// The payload for (plain ASCII). + public static string ToJson(StorageFeedRecord record) + { + var sb = new StringBuilder(64 + record.Items.Count * 120); + sb.Append("{\"v\":").Append(Version).Append(",\"id\":").Append(record.Id.ToString(CultureInfo.InvariantCulture)); + sb.Append(",\"name\":"); Str(sb, record.Name); + sb.Append(",\"label\":"); Str(sb, record.Label); + sb.Append(",\"items\":["); + for (int i = 0; i < record.Items.Count; i++) + { + StorageFeedItem it = record.Items[i]; + if (i > 0) sb.Append(','); + sb.Append("{\"o\":").Append(it.Id.ToString(CultureInfo.InvariantCulture)); + sb.Append(",\"w\":").Append(it.Wcid.ToString(CultureInfo.InvariantCulture)); + sb.Append(",\"n\":"); Str(sb, it.Name); + sb.Append(",\"i\":").Append(it.Icon.ToString(CultureInfo.InvariantCulture)); + sb.Append(",\"u\":").Append(it.Underlay.ToString(CultureInfo.InvariantCulture)); + sb.Append(",\"v\":").Append(it.Overlay.ToString(CultureInfo.InvariantCulture)); + sb.Append(",\"s\":").Append(it.Stack.ToString(CultureInfo.InvariantCulture)); + sb.Append(",\"m\":").Append(it.MaxStack.ToString(CultureInfo.InvariantCulture)); + sb.Append(",\"y\":").Append(it.ItemType.ToString(CultureInfo.InvariantCulture)); + sb.Append('}'); + } + sb.Append("]}"); + return sb.ToString(); + } + + /// + /// The record in a payload, or null (with the reason in ) for anything + /// unusable: not JSON, a newer version, an id that isn't a stand-in, no name, too many items. + /// Never throws. + /// + public static StorageFeedRecord? Parse(string? json, out string error) + { + error = string.Empty; + if (string.IsNullOrWhiteSpace(json)) { error = "empty"; return null; } + if (json.Length > MaxJsonLength) { error = "too large"; return null; } + try + { + using JsonDocument doc = JsonDocument.Parse(json); + JsonElement root = doc.RootElement; + if (root.ValueKind != JsonValueKind.Object) { error = "not a JSON object"; return null; } + int v = Int(root, "v", 0); + if (v < 1 || v > Version) { error = "version " + v; return null; } + uint id = UInt(root, "id"); + if (!IsStandInId(id)) { error = $"id 0x{id:X8} is not a stand-in (top byte 0xFF)"; return null; } + string name = Cap(Str(root, "name")); + if (name.Length == 0) { error = "no name"; return null; } + string label = Cap(Str(root, "label")); + var items = new List(); + if (root.TryGetProperty("items", out JsonElement list) && list.ValueKind == JsonValueKind.Array) + { + foreach (JsonElement e in list.EnumerateArray()) + { + if (e.ValueKind != JsonValueKind.Object) continue; + if (items.Count >= MaxItems) { error = $"more than {MaxItems} items"; return null; } + items.Add(new StorageFeedItem(UInt(e, "o"), UInt(e, "w"), Str(e, "n"), UInt(e, "i"), UInt(e, "u"), UInt(e, "v"), + Math.Max(1, Int(e, "s", 1)), Int(e, "m", 0), UInt(e, "y"))); + } + } + return new StorageFeedRecord(id, name, label.Length > 0 ? label : name, items); + } + catch (JsonException ex) + { + error = "bad JSON: " + ex.Message; + return null; + } + } + + private static string Cap(string s) + { + s = s.Trim(); + return s.Length <= MaxNameLength ? s : s[..MaxNameLength]; + } + + private static int Int(JsonElement e, string name, int fallback) => + e.TryGetProperty(name, out JsonElement v) && v.ValueKind == JsonValueKind.Number && v.TryGetInt32(out int i) ? i : fallback; + + private static uint UInt(JsonElement e, string name) => + e.TryGetProperty(name, out JsonElement v) && v.ValueKind == JsonValueKind.Number && v.TryGetUInt32(out uint u) ? u : 0u; + + private static string Str(JsonElement e, string name) => + e.TryGetProperty(name, out JsonElement v) && v.ValueKind == JsonValueKind.String ? v.GetString() ?? string.Empty : string.Empty; + + /// A JSON string literal in plain ASCII (control and non-ASCII characters \u-escaped). + private static void Str(StringBuilder sb, string? s) + { + sb.Append('"'); + foreach (char c in s ?? string.Empty) + { + switch (c) + { + case '"': sb.Append("\\\""); break; + case '\\': sb.Append("\\\\"); break; + default: + if (c < 0x20 || c > 0x7e) sb.Append("\\u").Append(((int)c).ToString("x4", CultureInfo.InvariantCulture)); + else sb.Append(c); + break; + } + } + sb.Append('"'); + } +} diff --git a/Shared/RynthCore.LootSdk/T11/T11PlayerAugs.cs b/Shared/RynthCore.LootSdk/T11/T11PlayerAugs.cs index bb1a6d4..b7d3012 100644 --- a/Shared/RynthCore.LootSdk/T11/T11PlayerAugs.cs +++ b/Shared/RynthCore.LootSdk/T11/T11PlayerAugs.cs @@ -49,6 +49,12 @@ public sealed class T11PlayerAugs } } + /// Forgets one counter (it reads as unknown again). + public void Forget(T11Counter counter) + { + lock (_gate) _counts.Remove(counter); + } + /// Forgets the "/aug" counts (logout). The manual override is kept. public void Clear() { diff --git a/Tools/RynthCore.AutoVendorTests/Program.cs b/Tools/RynthCore.AutoVendorTests/Program.cs index fb2833d..61e841e 100644 --- a/Tools/RynthCore.AutoVendorTests/Program.cs +++ b/Tools/RynthCore.AutoVendorTests/Program.cs @@ -391,6 +391,50 @@ internal static class Program var p5 = AutoVendorPlanner.PlanNext(v, none, new List(), Pack(0)); Eq(p5.Kind, PlanKind.Done, "nothing to do"); + // A split lands on another partial stack of the same item, so the planner never splits while one + // exists (Drakkon's Gold Peas looped split-wait-split, 2026-10-19). Peas: 25,000 each, max 100. + SellItem Pea(uint id, int stack) => new() { Id = id, Name = "Gold Pea", Value = 25_000 * stack, StackSize = stack, + Class = AcObjectClass.Misc, ItemType = 0x40000000, RuleName = "S: Peas", MaxStack = 100, Wcid = 9001 }; + // 88 free main slots: (88 - 2) * 25000 / 25000 = 86 peas fit. + var twoPartials = AutoVendorPlanner.PlanNext(v, none, new List { Pea(1, 100), Pea(2, 91), Pea(3, 88) }, Pack(0, free: 88)); + Eq(twoPartials.Kind, PlanKind.Merge, "two partials: merge first"); + Eq(twoPartials.SplitItem!.Id, 3u, "the smaller partial goes..."); + Eq(twoPartials.MergeTarget!.Id, 2u, "...onto the bigger one"); + + // Right after a split: the new stack (38) fits and is sold, never merged back onto the source (62). + var justSplit = AutoVendorPlanner.PlanNext(v, none, new List { Pea(1, 62), Pea(2, 38), Pea(3, 100) }, Pack(0, free: 40)); + Eq(justSplit.Kind, PlanKind.Sell, "the freshly split stack is sold..."); + Eq(justSplit.Sells.Single().Id, 2u, "...not merged back"); + var justSplit2 = AutoVendorPlanner.PlanNext(v, none, new List { Pea(1, 100), Pea(2, 62), Pea(3, 38) }, Pack(0, free: 40)); + Eq(justSplit2.Kind, PlanKind.Sell, "same with a full stack first"); + Eq(justSplit2.Sells.Single().Id, 3u, "the 38"); + + var onePartialFits = AutoVendorPlanner.PlanNext(v, none, new List { Pea(1, 100), Pea(2, 79) }, Pack(0, free: 88)); + Eq(onePartialFits.Kind, PlanKind.Sell, "one partial that fits: sold whole, no split"); + Eq(onePartialFits.Sells.Single().Id, 2u, "the partial"); + + var onePartialBig = AutoVendorPlanner.PlanNext(v, none, new List { Pea(1, 100), Pea(2, 95) }, Pack(0, free: 88)); + Eq(onePartialBig.Kind, PlanKind.Split, "one partial too big: split..."); + Eq(onePartialBig.SplitItem!.Id, 2u, "...from the partial itself (nothing else for it to join)"); + Eq(onePartialBig.SplitAmount, 86, "86 fit"); + + var allFull = AutoVendorPlanner.PlanNext(v, none, new List { Pea(1, 100), Pea(2, 100) }, Pack(0, free: 88)); + Eq(allFull.Kind, PlanKind.Split, "all full: plain split"); + Eq(allFull.SplitItem!.Id, 1u, "from the first"); + + var otherItem = new SellItem { Id = 5, Name = "Silver Pea", Value = 50, StackSize = 50, MaxStack = 100, Wcid = 9002, Class = AcObjectClass.Misc, ItemType = 0x40000000 }; + var notSame = AutoVendorPlanner.PlanNext(v, none, new List { Pea(1, 100), otherItem }, Pack(0, free: 88)); + Eq(notSame.Kind, PlanKind.Split, "another item's partial doesn't count"); + Eq(notSame.SplitItem!.Id, 1u, "gold split as asked"); + + // Stale stack values: a split leaves 100 peas' value on a small stack, a merge leaves a small value on a big one. + Eq(AutoVendorPlanner.MostCarriedUnit(new Dictionary { [25_000] = 800, [1_250_000] = 2, [3_000] = 100 }), 25_000, "most peas carry the true price"); + Eq(AutoVendorPlanner.MostCarriedUnit(new Dictionary { [25_000] = 50, [30_000] = 50 }), 30_000, "tie: the higher value"); + Eq(AutoVendorPlanner.MostCarriedUnit(new Dictionary()), 0, "nothing: 0 (no override)"); + + var unknownMax = AutoVendorPlanner.PlanNext(v, none, new List { S(1, "Gem", 100_000, stack: 100), S(2, "Gem", 50_000, stack: 50) }, Pack(0, free: 3)); + Eq(unknownMax.Kind, PlanKind.Split, "unknown max stack: the old plain split"); + // Payout estimate uses the vendor's buy rate (ACE floor(value * rate + 0.1)). var half = Vendor(buy: 0.5f); var p6 = AutoVendorPlanner.PlanNext(half, none, new List { S(1, "Salvage", 101) }, Pack(0)); diff --git a/Tools/RynthCore.RynthAiHostTests/Fakes/FakeHost.cs b/Tools/RynthCore.RynthAiHostTests/Fakes/FakeHost.cs index 5dfbb05..cea74b8 100644 --- a/Tools/RynthCore.RynthAiHostTests/Fakes/FakeHost.cs +++ b/Tools/RynthCore.RynthAiHostTests/Fakes/FakeHost.cs @@ -230,6 +230,16 @@ internal static unsafe class FakeHost public static bool UseOnCalls; /// Every UseObjectOn (source, target), in order (opt-in with ). public static readonly List<(uint Source, uint Target)> UsesOn = new(); + /// Opt-in (set before Create): the trade window and vendor calls (API v72 / v67). A vendor named + /// (id 0x70000001) is open; every trade action and vendor transaction is recorded. + public static bool TradeVendorCalls; + public static string VendorName = "Town Vendor"; + /// Trade actions in order: "accept", "decline", "reset", "close", "add:". + public static readonly List TradeActions = new(); + /// Every VendorSell: the vendor id and the item ids. + public static readonly List<(uint Vendor, uint[] Items)> VendorSells = new(); + /// Every VendorBuy: the vendor id and the (object, amount) entries. + public static readonly List<(uint Vendor, (uint Id, int Amount)[] Entries)> VendorBuys = new(); /// Opt-in: install SendPluginCommand (the engine's plugin-command broker, API v64). public static bool PluginCommandCalls; /// What SendPluginCommand answers: true = delivered (the target plugin is loaded). @@ -256,6 +266,10 @@ internal static unsafe class FakeHost public static Action? OnUseObject; /// Runs inside UseObjectOn, after it is recorded. public static Action? OnUseObjectOn; + /// Object id -> (health, max health) for GetTargetVitals (opt-in: installed when it has entries at Create()). + public static readonly Dictionary TargetVitals = new(); + /// Opt-in (set before Create): GetLiveObjectIds (API v69) lists every id in . + public static bool LiveObjectsCalls; // ANSI strings handed back to tested code stay alive for the whole run. private static readonly Dictionary _ansi = new(); @@ -301,10 +315,12 @@ internal static unsafe class FakeHost SelectedItem = 0; UseOnCalls = false; UsesOn.Clear(); PluginCommandCalls = false; PluginCommandDelivered = true; PluginCommands.Clear(); + TradeVendorCalls = false; TradeActions.Clear(); VendorSells.Clear(); VendorBuys.Clear(); CombatModeCalls = false; CombatModeRequests.Clear(); CombatModeRefuse = false; CombatModeRefusals = 0; BusyCalls = false; ForceResets = 0; BusyStateValue = 0; ObjectPropertiesCalls = false; PropertyRecord = null; PropertyQueries.Clear(); ObjectStates.Clear(); OnUseObject = null; OnUseObjectOn = null; + TargetVitals.Clear(); LiveObjectsCalls = false; } /// @@ -351,6 +367,7 @@ internal static unsafe class FakeHost api.GetObjectInstanceIdPropertyFn = (IntPtr)(delegate* unmanaged[Cdecl])&GetObjectInstanceIdProperty; api.SetAutoRunFn = (IntPtr)(delegate* unmanaged[Cdecl])&SetAutoRun; api.TurnToHeadingFn = (IntPtr)(delegate* unmanaged[Cdecl])&TurnToHeading; + api.GetPlayerHeadingFn = (IntPtr)(delegate* unmanaged[Cdecl])&GetPlayerHeading; api.JumpNonAutonomousFn = (IntPtr)(delegate* unmanaged[Cdecl])&JumpNonAutonomous; if (TapJumpCalls) api.TapJumpFn = (IntPtr)(delegate* unmanaged[Cdecl])&TapJump; @@ -402,6 +419,13 @@ internal static unsafe class FakeHost } if (CombatModeCalls) api.ChangeCombatModeFn = (IntPtr)(delegate* unmanaged[Cdecl])&ChangeCombatMode; + if (TargetVitals.Count > 0) + api.GetTargetVitalsFn = (IntPtr)(delegate* unmanaged[Cdecl])&GetTargetVitals; + if (LiveObjectsCalls) + { + api.Version = Math.Max(api.Version, 69u); + api.GetLiveObjectIdsFn = (IntPtr)(delegate* unmanaged[Cdecl])&GetLiveObjectIds; + } if (BusyCalls) { api.ForceResetBusyCountFn = (IntPtr)(delegate* unmanaged[Cdecl])&ForceResetBusyCount; @@ -409,6 +433,23 @@ internal static unsafe class FakeHost } if (UseOnCalls) api.UseObjectOnFn = (IntPtr)(delegate* unmanaged[Cdecl])&UseObjectOn; + if (TradeVendorCalls) + { + api.Version = Math.Max(api.Version, 82u); + api.GetVendorInfoFn = (IntPtr)(delegate* unmanaged[Cdecl])&GetVendorInfo; + api.GetVendorItemsFn = (IntPtr)(delegate* unmanaged[Cdecl])&GetVendorItems; + api.VendorBuyFn = (IntPtr)(delegate* unmanaged[Cdecl])&VendorBuy; + api.VendorSellFn = (IntPtr)(delegate* unmanaged[Cdecl])&VendorSell; + api.GetVendorTradeStatusFn = (IntPtr)(delegate* unmanaged[Cdecl])&GetVendorTradeStatus; + api.GetTradeStateFn = (IntPtr)(delegate* unmanaged[Cdecl])&GetTradeState; + api.GetTradeItemsFn = (IntPtr)(delegate* unmanaged[Cdecl])&GetTradeItems; + api.TradeOpenFn = (IntPtr)(delegate* unmanaged[Cdecl])&TradeOpen; + api.TradeAddFn = (IntPtr)(delegate* unmanaged[Cdecl])&TradeAdd; + api.TradeAcceptFn = (IntPtr)(delegate* unmanaged[Cdecl])&TradeAccept; + api.TradeDeclineFn = (IntPtr)(delegate* unmanaged[Cdecl])&TradeDecline; + api.TradeResetFn = (IntPtr)(delegate* unmanaged[Cdecl])&TradeReset; + api.TradeCloseFn = (IntPtr)(delegate* unmanaged[Cdecl])&TradeClose; + } if (WieldCalls) { api.Version = 73; @@ -630,6 +671,26 @@ internal static unsafe class FakeHost [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] private static int ObjectIsAttackable(uint id) => NotAttackable.Contains(id) ? 0 : 1; + [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] + private static int GetTargetVitals(uint id, uint* hp, uint* maxHp, uint* stam, uint* maxStam, uint* mana, uint* maxMana) + { + if (!TargetVitals.TryGetValue(id, out var v)) return 0; + *hp = v.Hp; *maxHp = v.MaxHp; *stam = 0; *maxStam = 0; *mana = 0; *maxMana = 0; + return 1; + } + + [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] + private static int GetLiveObjectIds(uint* buffer, int capacity) + { + int n = 0; + foreach (uint id in Names.Keys) + { + if (n < capacity) buffer[n] = id; + n++; + } + return n; + } + [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] private static int GetObjectIntProperty(uint id, uint key, int* v) { @@ -806,6 +867,16 @@ internal static unsafe class FakeHost [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] private static int TurnToHeading(float deg) { HeadingDeg = deg; Turns++; return 1; } + // What the engine's GetPlayerHeading really returns: 0 = East, counter-clockwise, i.e. + // 90 - the compass heading (Freya 2026-10-20: quaternion 13.9, GetPlayerHeading 76.1). + [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] + private static int GetPlayerHeading(float* deg) + { + if (!HasPose) return 0; + *deg = (float)(((90.0 - HeadingDeg) % 360.0 + 360.0) % 360.0); + return 1; + } + [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] private static int JumpNonAutonomous(float extent) { Jumps++; return 1; } @@ -817,6 +888,51 @@ internal static unsafe class FakeHost [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] private static int StopCompletely() { Stops++; Sent.Add("stop"); return 1; } [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] + private static int GetVendorInfo(VendorInfoNative* info) + { + *info = default; + info->VendorId = 0x70000001; + byte[] name = System.Text.Encoding.ASCII.GetBytes(VendorName); + for (int i = 0; i < name.Length && i < 63; i++) info->Name[i] = name[i]; + return 1; + } + [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] + private static int GetVendorItems(VendorItemNative* items, int max) => 0; + [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] + private static uint VendorBuy(uint vendor, VendorTradeEntryNative* entries, int count) + { + var list = new (uint, int)[count]; + for (int i = 0; i < count; i++) list[i] = (entries[i].ObjectId, entries[i].Amount); + VendorBuys.Add((vendor, list)); + return 1; + } + [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] + private static uint VendorSell(uint vendor, uint* ids, int count) + { + var list = new uint[count]; + for (int i = 0; i < count; i++) list[i] = ids[i]; + VendorSells.Add((vendor, list)); + return 1; + } + [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] + private static int GetVendorTradeStatus(VendorTradeStatusNative* status) => 0; + [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] + private static int GetTradeState(IntPtr state) => 0; + [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] + private static int GetTradeItems(int side, uint* buffer, int capacity) => 0; + [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] + private static int TradeOpen(uint target) { TradeActions.Add("open:" + target.ToString("X8")); return 1; } + [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] + private static int TradeAdd(uint item, uint slot) { TradeActions.Add("add:" + item.ToString("X8")); return 1; } + [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] + private static int TradeAccept() { TradeActions.Add("accept"); return 1; } + [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] + private static int TradeDecline() { TradeActions.Add("decline"); return 1; } + [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] + private static int TradeReset() { TradeActions.Add("reset"); return 1; } + [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] + private static int TradeClose() { TradeActions.Add("close"); return 1; } + [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] private static void ForceResetBusyCount() { ForceResets++; BusyStateValue = 0; } [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] private static int GetBusyState() => BusyStateValue; diff --git a/Tools/RynthCore.RynthAiHostTests/Fakes/FakeServerHub.cs b/Tools/RynthCore.RynthAiHostTests/Fakes/FakeServerHub.cs new file mode 100644 index 0000000..766661b --- /dev/null +++ b/Tools/RynthCore.RynthAiHostTests/Fakes/FakeServerHub.cs @@ -0,0 +1,168 @@ +using System; +using System.Collections.Generic; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using System.Text; +using RynthCore.Plugin.Shared; + +namespace RynthCore.RynthAiHostTests.Fakes; + +/// +/// A stand-in for a server plugin's "RynthILT.Hub" table (Plugins/Shared/RynthIltHubApi.cs), so the +/// tests can check what RynthAi does WITH a server plugin (RynthILT) as well as without one. Its +/// functions answer from the static state below; RynthAi's ServerHubClient takes the table through +/// UseTableForTests. The render functions draw nothing (no ImGui frame in the tests): they only +/// record which section was asked for. Reset() before each test that uses it. +/// +internal static unsafe class FakeServerHub +{ + /// IsIltWorld's answer. + public static bool Active; + /// GetFeature: key -> -1 / 0 / 1 (missing = -1). + public static readonly Dictionary Features = new(StringComparer.OrdinalIgnoreCase); + /// AllowSummonOnEmpty's answer. + public static bool AllowEmpty; + /// GetSubTabs(parent): parent -> (id, label) list. + public static readonly Dictionary> SubTabs = new(StringComparer.OrdinalIgnoreCase); + /// Command lines the plugin took, and which it takes (null = none). + public static readonly List Commands = new(); + public static Func? TakesCommand; + /// RenderSection ids asked for, and the ones that "draw" (return 1). + public static readonly List SectionsAsked = new(); + public static readonly HashSet SectionsDrawn = new(StringComparer.OrdinalIgnoreCase); + /// GetSetting / SetSetting: key -> value (missing = not offered, -1; SetSetting only takes known keys). + public static readonly Dictionary Settings = new(StringComparer.OrdinalIgnoreCase); + /// GetText: id -> text (missing = ""). + public static readonly Dictionary Texts = new(StringComparer.OrdinalIgnoreCase); + + private static RynthIltHubApiV1* _table; + + public static void Reset() + { + Active = false; + Features.Clear(); + AllowEmpty = false; + SubTabs.Clear(); + Commands.Clear(); + TakesCommand = null; + SectionsAsked.Clear(); + SectionsDrawn.Clear(); + Settings.Clear(); + Texts.Clear(); + } + + /// The table (allocated once, never freed: like the real one). + public static IntPtr Table + { + get + { + if (_table == null) + { + var t = (RynthIltHubApiV1*)NativeMemory.AllocZeroed((nuint)sizeof(RynthIltHubApiV1)); + t->StructSize = (uint)sizeof(RynthIltHubApiV1); + t->IsIltWorld = &IsIltWorld; + t->GetFeature = &GetFeature; + t->GetTabs = &GetTabs; + t->RenderTab = &RenderTab; + t->RenderSection = &RenderSection; + t->Command = &Command; + t->AllowSummonOnEmpty = &AllowSummonOnEmpty; + t->GetSubTabs = &GetSubTabs; + t->GetSetting = &GetSetting; + t->SetSetting = &SetSetting; + t->GetText = &GetText; + t->Version = RynthIltHubApiV1.InterfaceVersion; + _table = t; + } + return (IntPtr)_table; + } + } + + private static string? Utf8(byte* p) => p == null ? null : Marshal.PtrToStringUTF8((IntPtr)p); + + private static void Write(string s, byte* dest, int capacity) + { + byte[] b = Encoding.UTF8.GetBytes(s); + int n = Math.Min(b.Length, capacity - 1); + for (int i = 0; i < n; i++) dest[i] = b[i]; + dest[n] = 0; + } + + [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] + private static int IsIltWorld() => Active ? 1 : 0; + + [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] + private static int GetFeature(byte* key) + { + string? k = Utf8(key); + return k != null && Features.TryGetValue(k, out int v) ? v : -1; + } + + [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] + private static int GetTabs(IltTabV1* tabs, int capacity) => 0; + + [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] + private static int RenderTab(byte* id) => 0; + + [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] + private static int RenderSection(byte* id) + { + string s = Utf8(id) ?? string.Empty; + SectionsAsked.Add(s); + return SectionsDrawn.Contains(s) ? 1 : 0; + } + + [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] + private static int Command(byte* text) + { + string line = Utf8(text) ?? string.Empty; + if (TakesCommand?.Invoke(line) != true) return 0; + Commands.Add(line); + return 1; + } + + [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] + private static int GetSetting(byte* key) + { + string? k = Utf8(key); + return k != null && Settings.TryGetValue(k, out int v) ? v : -1; + } + + [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] + private static int SetSetting(byte* key, int value) + { + string? k = Utf8(key); + if (k == null || !Settings.ContainsKey(k)) return 0; + Settings[k] = value; + return 1; + } + + [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] + private static int GetText(byte* id, byte* buffer, int capacity) + { + string? k = Utf8(id); + if (k == null || !Texts.TryGetValue(k, out string? text) || text.Length == 0) return 0; + Write(text, buffer, capacity); + return Encoding.UTF8.GetByteCount(text); + } + + [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] + private static int AllowSummonOnEmpty() => AllowEmpty ? 1 : 0; + + [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] + private static int GetSubTabs(byte* parent, IltTabV1* tabs, int capacity) + { + string p = Utf8(parent) ?? string.Empty; + if (!SubTabs.TryGetValue(p, out var list)) return 0; + if (tabs != null) + for (int i = 0; i < list.Count && i < capacity; i++) + { + Write(list[i].Id, tabs[i].Id, 24); + Write(list[i].Label, tabs[i].Label, 32); + tabs[i].Width = 0; + tabs[i].Height = 0; + tabs[i].Flags = RynthIltHub.TabShown | RynthIltHub.TabAvailable; + } + return list.Count; + } +} diff --git a/Tools/RynthCore.RynthAiHostTests/Program.cs b/Tools/RynthCore.RynthAiHostTests/Program.cs index ec50861..3327fe6 100644 --- a/Tools/RynthCore.RynthAiHostTests/Program.cs +++ b/Tools/RynthCore.RynthAiHostTests/Program.cs @@ -92,13 +92,17 @@ internal static class Program TargetingTests.Register(runner); LootAddItemTests.Register(runner); GiveTests.Register(runner); + UbCompatTests.Register(runner); + MetaAuditTests.Register(runner); + MetaSampleCompatTests.Register(runner); IdRefusalTests.Register(runner); DungeonMapBakeTests.Register(runner); MonsterEditorTests.Register(runner); InstallPathsTests.Register(runner); PetRefillTests.Register(runner); AutoStackTests.Register(runner); - RingEvadeTests.Register(runner); + BackAwayTests.Register(runner); + ServerPluginForwardTests.Register(runner); IgnoreMonsterTests.Register(runner); WorldCacheTypedTests.Register(runner); NavOverlayTests.Register(runner); @@ -106,6 +110,7 @@ internal static class Program HazardEscapeTests.Register(runner); ManaStoneChoiceTests.Register(runner); CustomDebuffTests.Register(runner); + DebuffRenewTests.Register(runner); ProfileLoadTests.Register(runner); ActivityInterfaceTests.Register(runner); CastNoDamageTests.Register(runner); @@ -141,7 +146,8 @@ internal static class Program LauncherSwapTests.Register(runner); MissileCraftingTests.Register(runner); SelfRatingsTests.Register(runner); - IltClientLookupTests.Register(runner); + ServerHubClientLookupTests.Register(runner); + UbMtSafetyTests.Register(runner); return runner.Run("RynthAi host tests", args.Length > 0 ? args[0] : null); } } diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/BackAwayTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/BackAwayTests.cs new file mode 100644 index 0000000..3f58a10 --- /dev/null +++ b/Tools/RynthCore.RynthAiHostTests/Tests/BackAwayTests.cs @@ -0,0 +1,111 @@ +using System; +using RynthCore.Plugin.RynthAi; +using RynthCore.Plugin.RynthAi.LegacyUi; +using RynthCore.Plugin.Shared; +using RynthCore.RynthAiHostTests.Fakes; +using RynthCore.RynthAiTests.Harness; + +namespace RynthCore.RynthAiHostTests.Tests; + +// The back-away combat does on a server plugin's request (CombatManager.BackAwayFrom, RynthAi.Hub +// BackAwayFrom). It was the Empyrean Handler lethal-ring evade (Silentkelpie's PR 12) until 2026-10-20, +// when the Handler's detection and its setting went to RynthILT (Infinite Leaftide content); RynthAi +// keeps the generic part: face the object, back-jump, hold attacks until it settles. Gated: only while +// the macro is running with combat on, and only inside the radius (at least Ring Range). RynthAi alone +// never reacts to the Handler's line any more. +internal static class BackAwayTests +{ + private const uint Player = 0x50000D11; + private const uint Danger = 0x80300110; + private const uint Lb = 0xA9B40000; + private const string RingLine = "The handler briefly channels infused Empyrean hatred to release a lethal ring."; + + public static void Register(Runner r) + { + r.Add("back away: inside the radius with the macro running and combat on, one back-jump (and none while it runs)", Jumps); + r.Add("back away: not with the macro stopped or combat off", Gated); + r.Add("back away: outside the radius (Ring Range widens it), or an object without a position: no jump", NotThese); + r.Add("back away: RynthAi alone ignores the Empyrean Handler's ring line (RynthILT's now)", HandlerLineIgnored); + } + + private sealed class Rig + { + public readonly LegacyUiSettings S = new() { MonsterRange = 40, EnableCombat = true }; + public readonly CombatManager Combat; + public int Jumps; + public float Heading = -1; + public bool Busy; + + public Rig(float dangerYards, bool place = true) + { + FakeHost.Reset(); + FakeHost.Names[Player] = "Evader"; + FakeHost.Positions[Player] = (Lb | 0x1C, 96f, 96f, 0f); + FakeHost.PlayerPose = (Lb | 0x1C, 96f, 96f, 0f); + FakeHost.Names[Danger] = "Empyrean Handler"; + if (place) FakeHost.Positions[Danger] = (Lb | 0x1C, 96f, 96f + dangerYards, 0f); + FakeHost.ItemTypes[Danger] = 0x10; + var host = FakeHost.Create(Player); + var cache = FakeHost.MakeCache(host, Player, new[] { Danger }); + S.IsMacroRunning = true; + Combat = new CombatManager(host, S, cache); + Combat.SetPlayerId(Player); + Combat.ScanNearbyTargets(); + Combat.RequestBackJump = (h, ms) => { Jumps++; Heading = h; Busy = true; return true; }; + Combat.JumpBusy = () => Busy; + } + + public int Ask(double radius = 12, int holdMs = 750) => Combat.BackAwayFrom(unchecked((int)Danger), radius, holdMs, "test"); + } + + private static void Jumps() + { + var rig = new Rig(dangerYards: 5); + Check.Eq(rig.Ask(), RynthAiHub.BackAwayStarted, "5 yards inside 12: started"); + Check.Eq(rig.Jumps, 1, "one back-jump"); + Check.True(rig.Combat.BackAwayActive, "combat holds while it runs"); + Check.Eq(rig.Ask(), RynthAiHub.BackAwayNotNow, "a second request while backing away: not now"); + Check.Eq(rig.Jumps, 1, "still one jump"); + + var refused = new Rig(5); + refused.Combat.RequestBackJump = (_, _) => false; + Check.Eq(refused.Ask(), RynthAiHub.BackAwayJumpRefused, "the jumper refused: said so"); + Check.False(refused.Combat.BackAwayActive, "and combat isn't held"); + } + + private static void Gated() + { + var stopped = new Rig(5); + stopped.S.IsMacroRunning = false; + Check.Eq(stopped.Ask(), RynthAiHub.BackAwayNotNow, "macro stopped: not now"); + Check.Eq(stopped.Jumps, 0, "no jump"); + + var noCombat = new Rig(5); + noCombat.S.EnableCombat = false; + Check.Eq(noCombat.Ask(), RynthAiHub.BackAwayNotNow, "combat off: not now"); + Check.Eq(noCombat.Jumps, 0, "no jump"); + } + + private static void NotThese() + { + var far = new Rig(30); + Check.Eq(far.Ask(), RynthAiHub.BackAwayOutside, "30 yards away is outside 12"); + Check.Eq(far.Jumps, 0, "no jump"); + far.S.RingRange = 40; + Check.Eq(far.Ask(), RynthAiHub.BackAwayStarted, "Ring Range 40 widens the radius: 30 yards is inside"); + + var unknown = new Rig(5, place: false); + Check.Eq(unknown.Ask(), RynthAiHub.BackAwayUnknownObject, "no position for the object"); + Check.Eq(unknown.Jumps, 0, "no jump"); + } + + private static void HandlerLineIgnored() + { + var rig = new Rig(5); + rig.Combat.HandleChatForDamage(RingLine, 0x0C); + rig.Combat.HandleChatForDebuffs(RingLine); + Check.Eq(rig.Jumps, 0, "the ring line alone does nothing in RynthAi (no server plugin asked)"); + Check.False(rig.Combat.BackAwayActive, "and combat isn't held"); + Check.True(new LegacyUiSettings().HandlerRingEvade, "the old profile field still loads (on by default; unused, for RynthILT's import)"); + } +} diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/DebuffRenewTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/DebuffRenewTests.cs new file mode 100644 index 0000000..050622a --- /dev/null +++ b/Tools/RynthCore.RynthAiHostTests/Tests/DebuffRenewTests.cs @@ -0,0 +1,94 @@ +using System; +using RynthCore.Plugin.RynthAi; +using RynthCore.RynthAiTests.Harness; + +namespace RynthCore.RynthAiHostTests.Tests; + +// 2026-10-20: the Monsters tab's debuffs (custom ones too) were cast once per target and never +// again, so a long fight with a high-HP monster ran on without them once they wore off. A +// landed debuff is now timed by its spell's duration and cast again just before the end. +internal static class DebuffRenewTests +{ + private const int Mob = 0x7A001234, Other = 0x7A005678; + + public static void Register(Runner r) + { + r.Add("debuff renewal: spell durations come from the spell data (Imperil I 60 s, Incantation 300 s)", Durations); + r.Add("debuff renewal: a landed debuff is due again just before it wears off", RenewsBeforeEnd); + r.Add("debuff renewal: no duration casts once per target; three failures give up; a target switch keeps timers", OnceAndFailures); + r.Add("debuff renewal: a monster that goes takes its timers with it", ForgetTarget); + } + + private static void Durations() + { + Check.Eq(SpellDatabase.DurationSeconds(SpellDatabase.GetIdByName("Imperil Other I")), 60, "Imperil Other I lasts 60 s"); + Check.Eq(SpellDatabase.DurationSeconds(SpellDatabase.GetIdByName("Incantation of Imperil Other")), 300, "Incantation of Imperil Other 300 s"); + Check.Eq(SpellDatabase.DurationSeconds(SpellDatabase.GetIdByName("Corrosion VII")), 16, "a damage-over-time debuff (Corrosion VII) 16 s"); + Check.Eq(SpellDatabase.DurationSeconds(SpellDatabase.GetIdByName("Lifestone Recall")), 0, "a recall has none"); + Check.Eq(SpellDatabase.DurationSeconds(-1), 0, "an unknown id has none"); + } + + private static void RenewsBeforeEnd() + { + var t = new DebuffTimers(); + var now = new DateTime(2026, 10, 20, 20, 0, 0); + Check.False(t.IsOn(Mob, "Imperil", now), "nothing cast yet: due"); + t.Landed(Mob, "Imperil", 240, now); + Check.True(t.IsOn(Mob, "Imperil", now.AddSeconds(200)), "on at 200 s of 240"); + Check.True(t.IsOn(Mob, "Imperil", now.AddSeconds(234.9)), "still on 5 s before the end"); + Check.False(t.IsOn(Mob, "Imperil", now.AddSeconds(235)), "due 5 s before it wears off"); + Check.True(t.RenewAt(Mob, "Imperil") != null, "a renewal, not a first cast"); + Check.False(t.IsOn(Other, "Imperil", now), "another monster has its own"); + + // A short damage-over-time debuff renews a fifth of its length early, not 5 s. + t.Landed(Mob, "Custom:Corrosion", 16, now); + Check.True(t.IsOn(Mob, "Custom:Corrosion", now.AddSeconds(12.7)), "Corrosion on at 12.7 s"); + Check.False(t.IsOn(Mob, "Custom:Corrosion", now.AddSeconds(12.8)), "and due at 12.8 s of 16"); + + // The renewal lands: the timer starts over. + t.Landed(Mob, "Imperil", 240, now.AddSeconds(236)); + Check.True(t.IsOn(Mob, "Imperil", now.AddSeconds(400)), "renewed at 236 s: on until 471 s"); + Check.False(t.IsOn(Mob, "Imperil", now.AddSeconds(471)), "due again at 471 s"); + } + + private static void OnceAndFailures() + { + var t = new DebuffTimers(); + var now = new DateTime(2026, 10, 20, 20, 0, 0); + t.Landed(Mob, "Custom:Odd", 0, now); + Check.True(t.IsOn(Mob, "Custom:Odd", now.AddHours(1)), "no duration: never again on this target"); + Check.True(t.RenewAt(Mob, "Custom:Odd") == null, "and no timer"); + + Check.False(t.Failed(Mob, "Fester"), "first resist: try again"); + Check.False(t.Failed(Mob, "Fester"), "second: again"); + Check.False(t.IsOn(Mob, "Fester", now), "still due after two"); + Check.True(t.Failed(Mob, "Fester"), "third: given up"); + Check.True(t.IsOn(Mob, "Fester", now), "not cast at this target again"); + + t.Landed(Mob, "Yield", 240, now); + Check.False(t.Failed(Mob, "Yield"), "a renewal that fizzles once"); + t.Landed(Mob, "Yield", 240, now); + Check.Eq(t.Failures(Mob, "Yield"), 0, "landing clears the count: each renewal gets three tries"); + + // Fighting something else and coming back: the given-up and once-only marks start over, + // the timers stay (the monster still has the debuff). + t.NewTarget(now.AddSeconds(10)); + Check.False(t.IsOn(Mob, "Fester", now.AddSeconds(10)), "given up only for that engagement"); + Check.False(t.IsOn(Mob, "Custom:Odd", now.AddSeconds(10)), "once-only too"); + Check.True(t.IsOn(Mob, "Yield", now.AddSeconds(10)), "Yield's timer kept across the switch"); + t.NewTarget(now.AddSeconds(300)); + Check.Eq(t.TimerCount, 0, "a switch drops timers that fell due"); + } + + private static void ForgetTarget() + { + var t = new DebuffTimers(); + var now = new DateTime(2026, 10, 20, 20, 0, 0); + t.Landed(Mob, "Imperil", 240, now); + t.Landed(Mob, "Vuln:Fire", 240, now); + t.Landed(Other, "Imperil", 240, now); + t.Forget(Mob); + Check.Eq(t.TimerCount, 1, "the gone monster's two timers dropped"); + Check.True(t.IsOn(Other, "Imperil", now), "the other monster keeps its own"); + } +} diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/DoorTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/DoorTests.cs index 4f0a0a3..f3e0b5b 100644 --- a/Tools/RynthCore.RynthAiHostTests/Tests/DoorTests.cs +++ b/Tools/RynthCore.RynthAiHostTests/Tests/DoorTests.cs @@ -42,8 +42,37 @@ internal static class DoorTests r.Add("door: Only Doors On My Path - a door beside the way is left shut, one straight ahead is opened", PathOnlyAhead); r.Add("door: Only Doors On My Path - on a route the door on the next leg goes, not a nearer one beside it", PathOnlyRoute); r.Add("door: Only Doors On My Path - not a door past the range along the path, nor one behind the route's direction", PathOnlyRange); + r.Add("door: one created before its position was readable (just after a portal) is still found and opened", CreatedBeforePosition); } + /// + /// A dungeon's objects arrive while the character is still in portal space, often before their + /// position reads: such a door was filed as inventory and never seen by the door scans (Dargoth + /// Hera, Infested Mine, 2026-10-19: Open Doors on, a closed door on the route, no use at all). + /// + private static void CreatedBeforePosition() => With(() => + { + foreach (uint? itemType in new uint?[] { 0x80u, null }) // a readable item type, and none at all + { + var b = new Bot(); + MoveDoor(Door, 40f, 0f); // the rig's door far out of range + FakeHost.Names[Door2] = "Door"; + FakeHost.Bitfields[Door2] = BfDoor; + FakeHost.ObjectStates[Door2] = Closed; + if (itemType is uint t) FakeHost.ItemTypes[Door2] = t; + b.Cache.OnCreateObject(Door2); // no position yet + for (int i = 0; i < 12; i++) b.Cache.Tick(); // classified (and any retries spent) without one + Check.True(b.Cache.GetLandscapeObjects().Any(o => unchecked((uint)o.Id) == Door2), + $"a static door stays a world object without a position (item type {(itemType is null ? "unreadable" : "0x80")})"); + Check.False(b.Cache.GetInventory().Any(o => unchecked((uint)o.Id) == Door2), "never filed as inventory"); + + FakeHost.Positions[Door2] = (Me0.Cell, Me0.X + 2f, Me0.Y, Me0.Z); // the position comes in + b.Tick(); + b.Run(300); + Check.Eq(Uses(Door2), 1, "the door is used once it has a position"); + } + }); + // ── Rig ───────────────────────────────────────────────────────────────── private sealed class Bot diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/ExpressionTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/ExpressionTests.cs index 0a76b7a..c17710f 100644 --- a/Tools/RynthCore.RynthAiHostTests/Tests/ExpressionTests.cs +++ b/Tools/RynthCore.RynthAiHostTests/Tests/ExpressionTests.cs @@ -41,6 +41,7 @@ internal static class ExpressionTests r.Add("expr: control flow (iif, if, ifthen, exec) is lazy", ControlFlow); r.Add("expr: delayexec fires on the pump when due, in order", DelayExec); r.Add("expr: stopwatches", Stopwatches); + r.Add("expr: ub-IT's remaining functions answer (no-equivalent ones with ub-IT's empty values)", UbCompatFunctions); r.Add("expr: object type, options and unknown functions", TypesOptionsUnknown); r.Add("expr: RynthAi settings and meta state from expressions", SettingsAndState); r.Add("expr: character properties, skills, vitals through the host", CharacterFunctions); @@ -516,10 +517,14 @@ internal static class ExpressionTests var e = Engine(); long now = 5_000; e.TickMs = () => now; + // ub-IT: delayexec returns its id (1, 2, ...), which clearexec takes. Is(e, "delayexec[1000, `setvar[x, first]`]", "1"); - Is(e, "delayexec[1000, `setvar[x, second]`]", "1"); - Is(e, "delayexec[-50, `setvar[neg, 1]`]", "1"); - Is(e, "delayexec[soon, `setvar[bad, 1]`]", "1"); + Is(e, "delayexec[1000, `setvar[x, second]`]", "2"); + Is(e, "delayexec[-50, `setvar[neg, 1]`]", "3"); + Is(e, "delayexec[soon, `setvar[bad, 1]`]", "4"); + Is(e, "delayexec[1000, `setvar[cancelled, 1]`]", "5"); + Is(e, "clearexec[5]", "1"); + Is(e, "clearexec[5]", "0"); // already gone e.PumpDelayedExecs(); Is(e, "getvar[neg]", "1"); // negative delay: next pump Is(e, "getvar[bad]", "1"); // unreadable delay: next pump @@ -530,16 +535,76 @@ internal static class ExpressionTests now += 1; e.PumpDelayedExecs(); Is(e, "getvar[x]", "second"); // both fired, in the order scheduled + Is(e, "testvar[cancelled]", "0"); // the cleared one never ran // A delayexec scheduled by a firing one waits for a later pump. // (\` is an escaped backtick inside a backtick string.) - Is(e, "delayexec[0, `delayexec[0, \\`setvar[chain, 1]\\`]`]", "1"); + Is(e, "delayexec[0, `delayexec[0, \\`setvar[chain, 1]\\`]`]", "6"); e.PumpDelayedExecs(); Is(e, "testvar[chain]", "0"); e.PumpDelayedExecs(); Is(e, "getvar[chain]", "1"); } + private static void UbCompatFunctions() + { + FakeHost.Reset(); + var settings = new LegacyUiSettings(); + var e = Engine(FakeHost.Create(), settings); + + // enlightenmentmaterials: levels 6-150 cost (level - 5) tokens; 1-5 and 151+ none. + Is(e, "enlightenmentmaterials[0, 10]", "15"); // 1+2+3+4+5 + Is(e, "enlightenmentmaterials[149, 151]", "145"); // only 150 costs tokens + Is(e, "enlightenmentmaterials[160, 165]", "0"); + Is(e, "enlightenmentmaterials[10, 5]", "0"); + + // Macro state, casting, quests. + settings.IsMacroRunning = true; + Is(e, "vtmacroenabled[]", "1"); + settings.IsMacroRunning = false; + Is(e, "vtmacroenabled[]", "0"); + Is(e, "iscasting[]", "0"); + Is(e, "canrefreshquests[]", "1"); // no tracker: nothing throttles it + Is(e, "isrefreshingquestbonuses[]", "0"); + Is(e, "getcooldownexpiration[515]", "0"); + + // Corpses opened by this character come from the plugin's hook. + e.CorpseOpenedByMe = id => id == 0x50000123; + Is(e, "hascorpsebeenopenedbyme[0x50000123]", "1"); + Is(e, "hascorpsebeenopenedbyme[0x50000124]", "0"); + Is(e, "getcorpsesunopenedbyme[]", "[]"); // no cache, no corpses + + // Unknown or unreadable objects: ub-IT's -1 / 0. + Is(e, "wobjectgethealthvalue[0]", "-1"); + Is(e, "actiontrymove[0, 0]", "0"); + Is(e, "actiontrysplit[0, 5]", "0"); + Is(e, "actiontrydrop[0x50000123]", "0"); + + // spelldata of an unknown spell is an empty dictionary. + Is(e, "dictsize[spelldata[999999]]", "0"); + + // XP meter: starts at zero. + Is(e, "xpreset[]", "1"); + Is(e, "xptotal[]", "0"); + Is(e, "lumtotal[]", "0"); + Is(e, "xpavg[]", "0"); + Check.True(e.Evaluate("xpmeter[]").Contains("XP/hr"), "xpmeter[] is the meter text"); + + // No RynthAi equivalent: they answer so the expression keeps going. + Is(e, "statushud[kills, 5]", "1"); + Is(e, "statushudcolored[kills, 5, red]", "1"); + Is(e, "netclients[]", "[]"); + Is(e, "getcharacterindex[Bob]", "-1"); + Is(e, "setnextlogin[Bob]", "0"); + Is(e, "clearnextlogin[]", "1"); + Is(e, "uiviewexists[myview]", "0"); + Is(e, "uiviewvisible[myview]", "0"); + Is(e, "statushud[a, 1] && 7", "1"); // used inside a larger expression + + // A real typo is still an unknown function. + Is(e, "nosuchfunctionatall[]", ""); + } + private static void Stopwatches() { var e = Engine(); diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/GiveTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/GiveTests.cs index 7d89433..fe4a7d1 100644 --- a/Tools/RynthCore.RynthAiHostTests/Tests/GiveTests.cs +++ b/Tools/RynthCore.RynthAiHostTests/Tests/GiveTests.cs @@ -1,7 +1,9 @@ using System; +using System.IO; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; +using RynthCore.Loot; using RynthCore.Plugin.RynthAi; using RynthCore.Plugin.RynthAi.LegacyUi; using RynthCore.PluginCore; @@ -27,6 +29,11 @@ internal static class GiveTests r.Add("give: /ub give with a count hands over that many", UbGiveCount); r.Add("give: /mt give hands over only the first match", MtGivesFirst); r.Add("give: /ub givep matches part of the name", UbGivePartial); + r.Add("give: a meta's /ub give hands over every match too (it used to take /mt give's one)", MetaUbGivesAll); + r.Add("give: give-all never hands over RynthAi's own items, attuned or equipped ones", GiveAllSkipsProtected); + r.Add("give: a running meta's give-all also keeps what the loot profile keeps; a typed one does not", GiveAllLootKeepOnlyForMeta); + r.Add("give: give-all logs every stack it queues and caps one command at 500", GiveAllLogsAndCaps); + r.Add("give: a delayed /ub give keeps the standing of the line that queued it", DelayedGiveKeepsStanding); r.Add("give: the next give waits until the server took the last (it answers extra gives 'too busy')", WaitsForServer); r.Add("give: a whole stack to an NPC that takes one per give keeps giving until it is gone, one give per tick", NpcStackOneAtATime); r.Add("give: the answer and the next give share one tick (the interval is only a minimum gap between sends)", NextGiveSameTick); @@ -98,6 +105,8 @@ internal static class GiveTests public void Set(string f, object? v) => typeof(RynthAiPlugin).GetField(f, Any)!.SetValue(P, v); public object? Call(string m, params object?[] a) => typeof(RynthAiPlugin).GetMethod(m, Any)!.Invoke(P, a); + public int LogWith(string text) => FakeHost.Logs.Count(l => l.Contains(text, StringComparison.Ordinal)); + public int ChatWith(string text) => FakeHost.Chat.Count(c => c.Contains(text, StringComparison.Ordinal)); /// Runs the chat command, then drains the give queue. public void Run(string command) @@ -167,6 +176,134 @@ internal static class GiveTests Check.False(w.GivenItems.Contains(WornMote), "and never the worn one"); } + private static void MetaUbGivesAll() + { + var w = new World(); + w.S.IsMacroRunning = true; + w.S.EnableMeta = true; + w.Call("HandleMetaChatCommand", "/ub give Mana Mote to Town Crier"); + for (int i = 0; i < 20; i++) w.Call("DrainGiveQueue"); + Check.Eq(FakeHost.Gives.Count, 3, "all three carried Mana Motes, as typed"); + Check.False(FakeHost.Gives.Any(g => g.Item == WornMote), "and never the worn one"); + } + + private static void GiveAllSkipsProtected() + { + var w = new World(); + // Mote2 is on the Weapons list, Mote3 on the Consumables list: RynthAi is using them. + w.S.ItemRules.Add(new ItemRule { Id = unchecked((int)Mote2), Name = "Mana Mote" }); + w.S.ConsumableRules.Add(new ConsumableRule { Id = unchecked((int)Mote3), Name = "Mana Mote" }); + w.Run("/ub give Mana Mote to Town Crier"); + Check.Eq(FakeHost.Gives.Count, 1, "only the unprotected mote goes"); + Check.Eq(FakeHost.Gives[0].Item, Mote1, "that one"); + Check.Eq(w.LogWith("skipped 0x80281102 'Mana Mote': on RynthAi's Weapons list"), 1, "the Weapons-list skip is logged"); + Check.Eq(w.LogWith("skipped 0x80281103 'Mana Mote': on RynthAi's Consumables list"), 1, "and the Consumables-list one"); + Check.True(w.ChatWith("2 protected stack(s) skipped") == 1, "and the summary counts them"); + + // A monster rule's weapon is protected too. + var w2 = new World(); + w2.S.MonsterRules.Add(new MonsterRule { Name = "Drudge", WeaponId = unchecked((int)Mote1), OffhandId = unchecked((int)Mote2) }); + w2.Run("/ub give Mana Mote to Town Crier"); + Check.True(FakeHost.Gives.Count == 1 && FakeHost.Gives[0].Item == Mote3, "a monster rule's weapon and off hand stay"); + + // An attuned item can't be given, and isn't tried. + var w3 = new World(); + foreach (uint id in new[] { Mote1, Mote2, Mote3 }) FakeHost.Ints[(id, 114u)] = 1; + w3.Run("/ub give Mana Mote to Town Crier"); + Check.Eq(FakeHost.Gives.Count, 0, "attuned motes are not given"); + Check.True(w3.ChatWith("Nothing to give") == 1, "and it says why nothing was queued"); + } + + private static string KeepEverythingProfile() + { + string path = Path.Combine(Program.TempRoot, "give-keep-all.json"); + var p = new LootProfile { Name = "keep all" }; + p.Rules.Add(new LootRule { Name = "All", Action = LootAction.Keep }); + p.Save(path); + return path; + } + + private static void GiveAllLootKeepOnlyForMeta() + { + // Typed: the user asked for it; only the always-on protections apply. + var typed = new World(); + typed.S.CurrentLootPath = KeepEverythingProfile(); + typed.Run("/ub give Mana Mote to Town Crier"); + Check.Eq(FakeHost.Gives.Count, 3, "typed /ub give hands over what the loot profile keeps"); + + // From a running meta: what the loot profile keeps stays. + var meta = new World(); + meta.S.CurrentLootPath = KeepEverythingProfile(); + meta.S.IsMacroRunning = true; + meta.S.EnableMeta = true; + meta.Call("HandleMetaChatCommand", "/ub give Mana Mote to Town Crier"); + for (int i = 0; i < 20; i++) meta.Call("DrainGiveQueue"); + Check.Eq(FakeHost.Gives.Count, 0, "a meta's /ub give leaves what the loot profile keeps"); + Check.Eq(meta.LogWith("kept by the loot profile"), 3, "each skip is logged"); + Check.True(meta.ChatWith("Nothing to give") == 1, "and said"); + + // The same meta with the macro stopped is not a running meta: the typed rules apply. + var stopped = new World(); + stopped.S.CurrentLootPath = KeepEverythingProfile(); + stopped.S.IsMacroRunning = false; + stopped.Call("HandleMetaChatCommand", "/ub give Mana Mote to Town Crier"); + for (int i = 0; i < 20; i++) stopped.Call("DrainGiveQueue"); + Check.Eq(FakeHost.Gives.Count, 3, "without a running meta it is a plain give"); + } + + private static void GiveAllLogsAndCaps() + { + var w = new World(); + // 520 carried pebbles: more than one command may queue. + const int Pebbles = 520; + uint first = 0x80290000; + for (int i = 0; i < Pebbles; i++) + { + uint id = first + (uint)i; + FakeHost.Names[id] = "Pebble"; + FakeHost.Containers[id] = Player; + FakeHost.ItemTypes[id] = 0x80; + } + for (int i = 0; i < Pebbles; i++) w.Cache.OnCreateObject(first + (uint)i); + for (int i = 0; i < 6; i++) w.Cache.Tick(); // the cache classifies 250 objects a tick + w.Call("HandleUbCommand", "/ub give Pebble to Town Crier"); + var queue = (System.Collections.ICollection)typeof(RynthAiPlugin).GetField("_pendingGives", Any)!.GetValue(w.P)!; + Check.Eq(queue.Count, RynthAiPlugin.MaxGiveAllPerCommand, "one command queues at most 500"); + Check.Eq(w.LogWith("[Give] queued 0x"), RynthAiPlugin.MaxGiveAllPerCommand, "one log line per stack queued"); + Check.Eq(w.LogWith("the cap is 500"), 1, "the cap is logged"); + Check.True(w.ChatWith("capped at 500") == 1, "and said in chat"); + + // Below the cap nothing is cut. + var small = new World(); + small.Call("HandleUbCommand", "/ub give Mana Mote to Town Crier"); + var q2 = (System.Collections.ICollection)typeof(RynthAiPlugin).GetField("_pendingGives", Any)!.GetValue(small.P)!; + Check.Eq(q2.Count, 3, "three motes, three queued"); + Check.Eq(small.LogWith("the cap is"), 0, "no cap line"); + } + + private static void DelayedGiveKeepsStanding() + { + // A running meta that queues "/ub delay 0 /ub give ..." gives as a running meta when it fires, + // so the loot profile's Keep rules still protect; a typed delay does not. + var meta = new World(); + meta.S.CurrentLootPath = KeepEverythingProfile(); + meta.S.IsMacroRunning = true; + meta.S.EnableMeta = true; + meta.Call("HandleMetaChatCommand", "/ub delay 0 /ub give Mana Mote to Town Crier"); + meta.Call("TickDelayedCommands"); + for (int i = 0; i < 20; i++) meta.Call("DrainGiveQueue"); + Check.Eq(FakeHost.Gives.Count, 0, "the delayed line still counts as the meta's"); + + var typed = new World(); + typed.S.CurrentLootPath = KeepEverythingProfile(); + typed.S.IsMacroRunning = true; + typed.S.EnableMeta = true; + typed.Call("HandleUbCommand", "/ub delay 0 /ub give Mana Mote to Town Crier"); + typed.Call("TickDelayedCommands"); + for (int i = 0; i < 20; i++) typed.Call("DrainGiveQueue"); + Check.Eq(FakeHost.Gives.Count, 3, "a typed delay is a typed give"); + } + private static void UbGivePartial() { var w = new World(); diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/IltClientLookupTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/IltClientLookupTests.cs deleted file mode 100644 index e3c8390..0000000 --- a/Tools/RynthCore.RynthAiHostTests/Tests/IltClientLookupTests.cs +++ /dev/null @@ -1,39 +0,0 @@ -using RynthCore.Plugin.RynthAi.MiniRemote; -using RynthCore.RynthAiTests.Harness; - -namespace RynthCore.RynthAiHostTests.Tests; - -// RynthAi's lookup of RynthILT's "RynthILT.Hub" table (MiniRemote/IltClient.Tick). Until -// 0.5.60 the "never looked" sentinel was long.MinValue, "now - long.MinValue" overflowed to a -// negative number, the recheck gate always said "not due", and RynthAi never found RynthILT: -// no ILT tabs, sections or feature bits in the Mini Remote on Infinite Leaftide. -internal static class IltClientLookupTests -{ - public static void Register(Runner r) - { - r.Add("ILT client: the first Tick (and the first after Reset) looks RynthILT up", FirstLook); - r.Add("ILT client: a live table is kept until the recheck interval", LiveTableKept); - r.Add("ILT client: no table retries every interval; a shut-down table at once", RetryRules); - } - - private static void FirstLook() - { - // Any clock value, including the large tick counts of a long-running PC. - foreach (long now in new[] { 0L, 1_000L, 5_000_000L, long.MaxValue / 2 }) - Check.True(IltClient.LookupDue(checkedOnce: false, checkedAt: 0, now, haveTable: false, tableLive: false), - $"never looked: due at now={now}"); - } - - private static void LiveTableKept() - { - Check.False(IltClient.LookupDue(true, checkedAt: 10_000, now: 11_000, haveTable: true, tableLive: true), "live table within the interval"); - Check.True(IltClient.LookupDue(true, checkedAt: 10_000, now: 13_000, haveTable: true, tableLive: true), "live table after the interval"); - } - - private static void RetryRules() - { - Check.False(IltClient.LookupDue(true, checkedAt: 10_000, now: 12_999, haveTable: false, tableLive: false), "no table: waits the interval"); - Check.True(IltClient.LookupDue(true, checkedAt: 10_000, now: 13_000, haveTable: false, tableLive: false), "no table: looks again after it"); - Check.True(IltClient.LookupDue(true, checkedAt: 10_000, now: 10_001, haveTable: true, tableLive: false), "Version 0 (RynthILT shut down): looks again at once"); - } -} diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/ManaStoneChoiceTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/ManaStoneChoiceTests.cs index fd91b76..72f5be9 100644 --- a/Tools/RynthCore.RynthAiHostTests/Tests/ManaStoneChoiceTests.cs +++ b/Tools/RynthCore.RynthAiHostTests/Tests/ManaStoneChoiceTests.cs @@ -28,6 +28,7 @@ internal static class ManaStoneChoiceTests r.Add("mana charges: refill gear even when ManaStone rules name only other stones", ChargesIgnoreStoneRules); r.Add("mana stones: the server's 'low on Mana' refills gear whose read is stale-high", ServerLowRefills); r.Add("mana stones: worn gear is identified again, so a stale-high read follows the gear", GearReadRefreshed); + r.Add("mana stones: worn means worn per the tracker - a packed item with a stale wield record takes no appraisals, gear it says is worn gets refilled", WornPerTracker); r.Add("mana charges: overnight idle, the gear never runs dry (re-identify)", () => Overnight(identify: true)); r.Add("mana charges: overnight idle, the gear never runs dry (server warnings only)", () => Overnight(identify: false)); r.Add("mana tapping: one item at a time - the stone first, then one item, drained before the next", OneTapItemAtATime); @@ -140,6 +141,34 @@ internal static class ManaStoneChoiceTests Check.Eq(rig.OnPlayer.Count, 2, "full: back to the reads (90%)"); } + /// + /// The engine's equipment tracker decides what is worn. A robe moved to the pack keeps its old wield + /// record: it used to count as worn and take the pass's appraisal ("worn=41" for 20 worn, 2026-10-20). + /// A cloak whose own wield record reads 0 but the tracker says is worn is gear like any other. + /// + private static void WornPerTracker() + { + const uint Robe = 0x80400040, Cloak = 0x80400041; + using var rig = new Rig(tapping: false, new (uint, int?)[] { (ChargeA, 1000) }, stoneName: ManaCharge, maceMana: 4500, + before: ids => + { + FakeHost.Names[Robe] = "Old Robe"; + FakeHost.Containers[Robe] = Player; // in the pack... + FakeHost.Ints[(Robe, WieldedSlotKey)] = 0x200; // ...with a stale wield record, mana unread + FakeHost.Names[Cloak] = "Cloak"; + FakeHost.Wielders[Cloak] = Player; + FakeHost.Ints[(Cloak, MaxManaKey)] = 1000; + FakeHost.Ints[(Cloak, CurManaKey)] = 100; // 10%: needs a refill + ids.Add(Robe); ids.Add(Cloak); + FakeHost.EquippedCalls = true; // the tracker: mace and cloak are worn + FakeHost.Equipped[Mace] = 0x100000; + FakeHost.Equipped[Cloak] = 0x8000000; + }); + rig.Run(3000); + Check.Eq(FakeHost.IdRequests.Count(i => i == Robe), 0, "no appraisal spent on the packed robe"); + Check.Eq(rig.OnPlayer.Count, 1, "the cloak the tracker says is worn (10%) gets the charge"); + } + private static void GearReadRefreshed() { using var rig = new Rig(tapping: false, new (uint, int?)[] { (ChargeA, 1000) }, stoneName: ManaCharge, maceMana: 4500); @@ -229,7 +258,7 @@ internal static class ManaStoneChoiceTests /// The engine can identify objects (RequestId). public Rig(bool tapping, (uint Id, int? Mana)[] stones, bool ringToDrain = false, string stoneName = "Moderate Mana Stone", int maceMana = 0, bool identify = true, - bool ringArrived = true, bool contents = false) + bool ringArrived = true, bool contents = false, Action>? before = null) { FakeHost.Reset(); FakeHost.UseOnCalls = true; @@ -260,6 +289,7 @@ internal static class ManaStoneChoiceTests ids.Add(Ring); } + before?.Invoke(ids); // a test's own objects and host options, before the host exists var host = FakeHost.Create(Player); C = FakeHost.MakeCache(host, Player, ids); S = new LegacyUiSettings { EnableManaTapping = tapping, ManaTapMinMana = 100 }; diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/MetaAuditTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/MetaAuditTests.cs new file mode 100644 index 0000000..b9f1bed --- /dev/null +++ b/Tools/RynthCore.RynthAiHostTests/Tests/MetaAuditTests.cs @@ -0,0 +1,258 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Text; +using System.Text.RegularExpressions; +using RynthCore.Plugin.RynthAi; +using RynthCore.Plugin.RynthAi.LegacyUi; +using RynthCore.Plugin.RynthAi.Meta; +using RynthCore.PluginCore; +using RynthCore.RynthAiHostTests.Fakes; +using RynthCore.RynthAiTests.Harness; + +namespace RynthCore.RynthAiHostTests.Tests; + +// Opt-in audit (RYNTH_META_AUDIT=): what each meta asks of RynthAi - its chat +// commands through the real /vt /mt /ub dispatchers, its expression functions through the engine, +// its VTank options against the option map - and a report of what isn't supported. +internal static class MetaAuditTests +{ + private const BindingFlags Any = BindingFlags.Instance | BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public; + + public static void Register(Runner r) + { + string? dir = Environment.GetEnvironmentVariable("RYNTH_META_AUDIT"); + if (!string.IsNullOrEmpty(dir) && Directory.Exists(dir)) r.Add("audit: sample metas (RYNTH_META_AUDIT)", () => Run(dir)); + } + + private sealed class Found + { + public readonly SortedDictionary> Commands = new(StringComparer.OrdinalIgnoreCase); + public readonly SortedDictionary> Functions = new(StringComparer.OrdinalIgnoreCase); + public readonly SortedDictionary> Options = new(StringComparer.OrdinalIgnoreCase); + public readonly SortedDictionary> Kinds = new(StringComparer.OrdinalIgnoreCase); + public readonly SortedDictionary> States = new(StringComparer.OrdinalIgnoreCase); + public void Add(SortedDictionary> d, string key, string meta) + { + if (!d.TryGetValue(key, out var s)) d[key] = s = new SortedSet(StringComparer.OrdinalIgnoreCase); + s.Add(meta); + } + } + + private static readonly Regex FnRx = new(@"(?>(StringComparer.OrdinalIgnoreCase); + foreach (string path in Directory.GetFiles(dir, "*.met").OrderBy(p => p, StringComparer.OrdinalIgnoreCase)) + { + string meta = Path.GetFileName(path); + LoadedMeta m = MetFileParser.Load(path); + report.AppendLine($"## {meta}: {m.Rules.Count} rules, {m.EmbeddedNavs.Count} navs" + (m.Warnings.Count > 0 ? ", warnings: " + string.Join(" | ", m.Warnings) : "")); + var states = new HashSet(StringComparer.OrdinalIgnoreCase); + definedStates[meta] = states; + foreach (MetaRule rule in m.Rules) { states.Add(rule.State); Walk(rule, meta, f); } + } + + // Chat commands through the dispatchers. + var w = new PluginWorld(); + report.AppendLine("\n# Chat commands"); + foreach (var (cmd, metas) in f.Commands) + report.AppendLine($" [{Classify(cmd, w)}] {cmd} <- {string.Join(", ", metas)}"); + + // Expression functions through the engine. + report.AppendLine("\n# Expression functions not known to RynthAi"); + FakeHost.Reset(); + var host = FakeHost.Create(); + foreach (var (fn, metas) in f.Functions) + { + var e = new ExpressionEngine(host); + int logs = FakeHost.Logs.Count; + try { e.Evaluate(fn + "[]"); } catch { } + bool unknown = FakeHost.Logs.Skip(logs).Any(l => l.Contains("unknown expression function '" + fn, StringComparison.OrdinalIgnoreCase)); + if (unknown) report.AppendLine($" {fn} <- {string.Join(", ", metas)}"); + } + report.AppendLine(" (all functions used: " + string.Join(", ", f.Functions.Keys) + ")"); + + // VTank options against the option map / settings map / special options. + report.AppendLine("\n# VTank options"); + var mm = new MetaManager(new LegacyUiSettings(), host, new PlayerVitalsCache()); + var map = (Dictionary)typeof(MetaManager).GetField("VtOptionMap", Any)!.GetValue(null)!; + var special = typeof(MetaManager).GetMethod("IsSpecialVtOption", Any)!; + var settings = mm.Expressions.BuildSettingsMapPublic(); + var settingsCi = new HashSet(settings.Keys, StringComparer.OrdinalIgnoreCase); + foreach (var (opt, metas) in f.Options) + { + bool known = map.ContainsKey(opt) || settingsCi.Contains(opt) || (bool)special.Invoke(null, new object[] { opt })!; + report.AppendLine($" [{(known ? "ok" : "NOT MAPPED")}] {opt}{(map.TryGetValue(opt, out string? ra) ? " -> " + ra : "")} <- {string.Join(", ", metas)}"); + } + + // The same VTank values set two ways: '/vt opt set' and the vtsetsetting[] expression. + report.AppendLine("\n# /vt opt set vs vtsetsetting[] (VTank units in, RynthAi setting out)"); + foreach (var (opt, val) in new[] { ("AttackDistance", "0.025"), ("ApproachDistance", "0.0208333"), ("NavCloseStopRange", "0.00625"), ("PetCustomRange", "0.0625"), ("LootOnlyRareCorpses", "1") }) + { + var s1 = new LegacyUiSettings(); var m1 = new MetaManager(s1, host, new PlayerVitalsCache()); + m1.TryHandleVtCommand($"/vt opt set {opt} {val}"); + var s2 = new LegacyUiSettings(); var m2 = new MetaManager(s2, host, new PlayerVitalsCache()); + m2.Expressions.Evaluate($"vtsetsetting[{opt},`{val}`]"); + string Read(MetaManager mm2) => (string?)typeof(MetaManager).GetMethod("GetVtOption", Any)!.Invoke(mm2, new object[] { opt }) ?? "(null)"; + report.AppendLine($" {opt}={val}: /vt opt set -> {Read(m1)} vtsetsetting -> {Read(m2)} (MonsterRange {s1.MonsterRange} vs {s2.MonsterRange}, ApproachRange {s1.ApproachRange} vs {s2.ApproachRange}, CustomPetRange {s1.CustomPetRange} vs {s2.CustomPetRange})"); + } + + report.AppendLine("\n# Rule kinds used"); + foreach (var (k, metas) in f.Kinds) report.AppendLine($" {k} <- {string.Join(", ", metas)}"); + + report.AppendLine("\n# States set or called but not defined"); + foreach (var (st, metas) in f.States) + foreach (string meta in metas) + if (definedStates.TryGetValue(meta, out var defined) && !defined.Contains(st)) report.AppendLine($" {meta}: '{st}'"); + + string outPath = Path.Combine(Path.GetTempPath(), "meta_audit.txt"); + File.WriteAllText(outPath, report.ToString()); + Console.WriteLine(" audit report: " + outPath); + Check.True(true, "audit ran"); + } + + private static void Walk(MetaRule r, string meta, Found f) + { + f.Add(f.Kinds, "if " + r.Condition, meta); + if (r.Condition == MetaConditionType.Expression) Expr(r.ConditionData, meta, f); + foreach (MetaRule c in r.Children) WalkCondition(c, meta, f); + Action(r, meta, f); + } + + private static void WalkCondition(MetaRule c, string meta, Found f) + { + f.Add(f.Kinds, "if " + c.Condition, meta); + if (c.Condition == MetaConditionType.Expression) Expr(c.ConditionData, meta, f); + foreach (MetaRule cc in c.Children) WalkCondition(cc, meta, f); + } + + private static void Action(MetaRule r, string meta, Found f) + { + f.Add(f.Kinds, "do " + r.Action, meta); + string d = r.ActionData ?? ""; + switch (r.Action) + { + case MetaActionType.ChatCommand: + foreach (string line in d.Split('\n', StringSplitOptions.RemoveEmptyEntries)) + { + string cmd = line.Trim(); + f.Add(f.Commands, cmd, meta); + Match om = Regex.Match(cmd, @"^/vt\s+opt\s+(?:set|get)\s+(\S+)", RegexOptions.IgnoreCase); + if (om.Success) f.Add(f.Options, om.Groups[1].Value, meta); + } + break; + case MetaActionType.ExpressionAction: + case MetaActionType.ChatExpression: + Expr(d, meta, f); + break; + case MetaActionType.SetRAOption: + { string[] p = d.Split(';', 2); f.Add(f.Options, p[0].Trim(), meta); if (p.Length > 1) Expr(p[1], meta, f); } + break; + case MetaActionType.GetRAOption: + { string[] p = d.Split(';'); if (p.Length > 1) f.Add(f.Options, p[1].Trim(), meta); } + break; + case MetaActionType.SetMetaState: + case MetaActionType.CallMetaState: + f.Add(f.States, d.Split(';')[0].Trim(), meta); + if (r.CallReturnState.Length > 0) f.Add(f.States, r.CallReturnState, meta); + break; + } + foreach (MetaRule c in r.ActionChildren) Action(c, meta, f); + } + + private static void Expr(string? text, string meta, Found f) + { + if (string.IsNullOrWhiteSpace(text)) return; + foreach (Match m in FnRx.Matches(text)) f.Add(f.Functions, m.Groups[1].Value.ToLowerInvariant(), meta); + string plain = text.Replace("\\/", "/").Replace("\\", ""); + foreach (Match m in CmdInExprRx.Matches(plain)) f.Add(f.Commands, m.Value.Trim() + " (in an expression)", meta); + foreach (Match m in OptFnRx.Matches(text)) f.Add(f.Options, m.Groups[2].Value, meta); + Match setopt = Regex.Match(plain, @"/vt\s+opt\s+set\s+([A-Za-z0-9_]+)", RegexOptions.IgnoreCase); + if (setopt.Success) f.Add(f.Options, setopt.Groups[1].Value, meta); + } + + /// A RynthAi plugin wired enough to run its /mt and /ub dispatchers, plus a meta manager for /vt. + private sealed class PluginWorld + { + public readonly RynthAiPlugin P = new(); + public readonly MetaManager M; + public readonly HashSet RaVerbs; + + public PluginWorld() + { + FakeHost.Reset(); + FakeHost.PluginCommandCalls = true; + FakeHost.Create(playerId: 0x50000F99); + typeof(RynthPluginBase).GetMethod("Attach", Any)!.Invoke(P, new object[] { FakeHost.LastApi }); + var s = new LegacyUiSettings(); + var dash = (LegacyDashboardRenderer)RuntimeHelpers.GetUninitializedObject(typeof(LegacyDashboardRenderer)); + typeof(LegacyDashboardRenderer).GetField("_settings", Any)!.SetValue(dash, s); + Set("_dashboard", dash); + Set("_initialized", true); + Set("_loginComplete", true); + M = new MetaManager(s, FakeHost.Create(playerId: 0x50000F99), new PlayerVitalsCache()); + M.SetRaCommandHandler(_ => { }); + RaVerbs = ReadRaVerbs(); + } + + private void Set(string n, object? v) => typeof(RynthAiPlugin).GetField(n, Any)!.SetValue(P, v); + public bool Meta(string cmd) => (bool)typeof(RynthAiPlugin).GetMethod("HandleMetaChatCommand", Any)!.Invoke(P, new object[] { cmd })!; + + /// The /ra verbs: the case labels of DispatchRaCommand's switch (unknown ones are ignored silently). + private static HashSet ReadRaVerbs() + { + var verbs = new HashSet(StringComparer.OrdinalIgnoreCase); + string? root = AppContext.BaseDirectory; + while (root != null && !Directory.Exists(Path.Combine(root, "Plugins"))) root = Path.GetDirectoryName(root); + if (root == null) return verbs; + string src = File.ReadAllText(Path.Combine(root, "Plugins", "RynthCore.Plugin.RynthAi", "RynthAiPlugin.cs")); + int a = src.IndexOf("private void DispatchRaCommand(", StringComparison.Ordinal); + int b = a >= 0 ? src.IndexOf("\n }\n", a, StringComparison.Ordinal) : -1; + string body = a >= 0 ? src.Substring(a, (b > a ? b : src.Length) - a) : ""; + foreach (Match m in Regex.Matches(body, "case \"([a-z0-9_]+)\"")) verbs.Add(m.Groups[1].Value); + return verbs; + } + } + + private static string Classify(string cmd, PluginWorld w) + { + // A command an expression builds: its arguments only exist at run time, so only the + // verb was captured; running it bare says nothing. + if (cmd.EndsWith("(in an expression)", StringComparison.Ordinal)) return "built at run time (verb only)"; + string c = cmd.Trim(); + if (!c.StartsWith("/") && !c.StartsWith("@")) return "say (plain chat)"; + string[] parts = c.Split(' ', StringSplitOptions.RemoveEmptyEntries); + string prefix = parts[0].ToLowerInvariant(); + string verb = parts.Length > 1 ? parts[1].ToLowerInvariant() : ""; + try + { + switch (prefix) + { + case "/vt": + return w.M.TryHandleVtCommand(c) ? "vt ok" : "VT NOT HANDLED"; + case "/mt": + case "/ub": + int chat = FakeHost.Chat.Count; + bool ok = w.Meta(c); + bool noop = FakeHost.Chat.Skip(chat).Any(l => l.Contains("no RynthAi equivalent")); + if (prefix == "/ub" && (bool)typeof(RynthAiPlugin).GetMethod("IsUbRythaiCommand", Any)!.Invoke(null, new object[] { verb, parts.Length > 2 ? string.Join(" ", parts, 2, parts.Length - 2) : "" })!) + return "ub-Rythai"; + return !ok ? prefix.ToUpperInvariant().TrimStart('/') + " NOT HANDLED" : noop ? "accepted no-op" : prefix.TrimStart('/') + " ok"; + case "/ra": + return w.RaVerbs.Contains(verb) || verb.StartsWith("jump") ? "ra ok" : "RA verb not in DispatchRaCommand (may be a hotkey verb)"; + default: + return "game/server"; + } + } + catch (Exception ex) { return "THREW " + (ex.InnerException ?? ex).GetType().Name + ": " + (ex.InnerException ?? ex).Message; } + } +} diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/MetaSampleCompatTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/MetaSampleCompatTests.cs new file mode 100644 index 0000000..3176b98 --- /dev/null +++ b/Tools/RynthCore.RynthAiHostTests/Tests/MetaSampleCompatTests.cs @@ -0,0 +1,146 @@ +using System; +using System.Linq; +using System.Reflection; +using System.Runtime.CompilerServices; +using RynthCore.Plugin.RynthAi; +using RynthCore.Plugin.RynthAi.LegacyUi; +using RynthCore.Plugin.RynthAi.Meta; +using RynthCore.PluginCore; +using RynthCore.RynthAiHostTests.Fakes; +using RynthCore.RynthAiTests.Harness; + +namespace RynthCore.RynthAiHostTests.Tests; + +// What the sample metas (meta samples: PistolPete, S_Bulb/Caul/Colo/CountPhainor/Cows/Deewain, +// Willow; audited 2026-10-18 with MetaAuditTests) needed that RynthAi didn't do. +internal static class MetaSampleCompatTests +{ + private const BindingFlags Any = BindingFlags.Instance | BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public; + + public static void Register(Runner r) + { + r.Add("meta samples: vtsetsetting[] takes VTank distances like /vt opt set (6 yd, not the 50 yd default)", VtSetSettingDistances); + r.Add("meta samples: the options they set map to RynthAi settings (pet range, blacklist, rebuff, auto attack power)", MappedOptions); + r.Add("meta samples: /vt deletemonster is accepted", DeleteMonster); + r.Add("meta samples: /ub close corpse closes the open corpse", UbCloseCorpse); + r.Add("meta samples: /ub is evaluated (the /ub bc vtsetmetastate[] broadcast)", UbExpression); + r.Add("meta samples: /mt face and /ub face take decimals and coordinates, and hold nav while turning", Face); + } + + private static (LegacyUiSettings S, MetaManager M) Meta() + { + FakeHost.Reset(); + var s = new LegacyUiSettings(); + var m = new MetaManager(s, FakeHost.Create(), new PlayerVitalsCache()); + m.SetRaCommandHandler(_ => { }); + return (s, m); + } + + private static void VtSetSettingDistances() + { + var (s, m) = Meta(); + m.Expressions.Evaluate("vtsetsetting[AttackDistance,`0.025`]"); + Check.Eq(s.MonsterRange, 6, "vtsetsetting AttackDistance 0.025 = 6 yd (was left at 50)"); + m.Expressions.Evaluate("vtsetsetting[ApproachDistance,`0.0208333`]"); + Check.Eq(s.ApproachRange, 5, "ApproachDistance 0.0208333 = 5 yd"); + Check.Eq(m.Expressions.Evaluate("vtgetsetting[AttackDistance]"), "0.025", "vtgetsetting reads it back in VTank units"); + m.TryHandleVtCommand("/vt opt set AttackDistance 0.2166"); + Check.Eq(s.MonsterRange, 52, "/vt opt set the same way"); + m.Expressions.Evaluate("vtsetsetting[IdlePeaceMode,`1`]"); + Check.True(s.PeaceModeWhenIdle, "a bool through vtsetsetting"); + m.Expressions.Evaluate("rasetsetting[MonsterRange,`7`]"); + Check.Eq(s.MonsterRange, 7, "rasetsetting keeps RynthAi's own names and units"); + } + + private static void MappedOptions() + { + var (s, m) = Meta(); + m.Expressions.Evaluate("vtsetsetting[PetCustomRange,`0.0625`]"); + Check.Eq(s.CustomPetRange, 15, "PetCustomRange 0.0625 = 15 yd"); + m.Expressions.Evaluate("vtsetsetting[BlacklistMonsterTimeoutSeconds,`45`]"); + Check.Eq(s.BlacklistTimeoutSec, 45, "BlacklistMonsterTimeoutSeconds"); + m.TryHandleVtCommand("/vt opt set rebufftimeremainingseconds 4500"); + Check.Eq(s.RebuffSecondsRemaining, 4500, "rebufftimeremainingseconds (VTank's spelling)"); + + // AutoAttackPower: on = automatic (-1); off = the attack bar's value. + m.TryHandleVtCommand("/vt setattackbar .9"); + m.Expressions.Evaluate("vtsetsetting[AutoAttackPower,`1`]"); + Check.True(s.MeleeAttackPower == -1 && s.MissileAttackPower == -1, "AutoAttackPower on: automatic"); + Check.Eq(m.Expressions.Evaluate("vtgetsetting[AutoAttackPower]"), "true", "reads back on"); + m.TryHandleVtCommand("/vt opt set autoattackpower false"); + Check.True(s.MeleeAttackPower == 90 && s.MissileAttackPower == 90, "AutoAttackPower off: the bar's 90%"); + } + + private static void DeleteMonster() + { + var (_, m) = Meta(); + Check.True(m.TryHandleVtCommand("/vt deletemonster"), "/vt deletemonster handled (not sent to AC as unknown)"); + } + + private sealed class World + { + public readonly RynthAiPlugin P = new(); + public World(bool closeCalls = true) + { + FakeHost.Reset(); + FakeHost.CloseContainerCalls = closeCalls; + FakeHost.Create(playerId: 0x50000F31); + typeof(RynthPluginBase).GetMethod("Attach", Any)!.Invoke(P, new object[] { FakeHost.LastApi }); + var dash = (LegacyDashboardRenderer)RuntimeHelpers.GetUninitializedObject(typeof(LegacyDashboardRenderer)); + typeof(LegacyDashboardRenderer).GetField("_settings", Any)!.SetValue(dash, new LegacyUiSettings()); + Set("_dashboard", dash); + Set("_initialized", true); + Set("_loginComplete", true); + } + public void Set(string f, object? v) => typeof(RynthAiPlugin).GetField(f, Any)!.SetValue(P, v); + public bool Ub(string line) => (bool)typeof(RynthAiPlugin).GetMethod("HandleUbCommand", Any)!.Invoke(P, new object[] { line })!; + public bool Mt(string line) => (bool)typeof(RynthAiPlugin).GetMethod("HandleMtCommand", Any)!.Invoke(P, new object[] { line })!; + } + + private static void UbCloseCorpse() + { + var w = new World(); + Check.True(w.Ub("/ub close corpse"), "/ub close corpse handled with nothing open"); + Check.True(FakeHost.Chat.Any(c => c.Contains("No container is currently open")), "and says so, as ub-IT"); + FakeHost.GroundContainer = 0x80F00001; + w.Ub("/ub close corpse"); + Check.True(FakeHost.Closes.Contains(0x80F00001), "closes the open container"); + Check.False(FakeHost.Chat.Any(c => c.Contains("Unrecognized")), "never 'Unrecognized /ub command'"); + } + + private static void UbExpression() + { + var w = new World(); + Check.True(w.Ub("/ub vtsetmetastate[NavigatingToFlowerTwo]"), "/ub handled"); + Check.False(w.Ub("/ub notaverb x"), "a plain unknown verb is still unknown"); + } + + private static void Face() + { + var w = new World(); + // No jumper (not logged in fully): one plain turn. + Check.True(w.Mt("/mt face 135.5"), "/mt face 135.5 (decimal)"); + Check.True(Math.Abs(FakeHost.HeadingDeg - 135.5f) < 0.01f, "turned to 135.5"); + Check.True(w.Ub("/ub face 450"), "/ub face 450"); + Check.True(Math.Abs(FakeHost.HeadingDeg - 90f) < 0.01f, "450 wraps to 90"); + + // A coordinate: from 10N 10E, 20N 10E is due north and 10N 20E due east. + FakeHost.SetNavPosition(10, 10); + Check.True(w.Mt("/mt face 20N, 10E"), "/mt face "); + Check.True(FakeHost.HeadingDeg < 0.5f || FakeHost.HeadingDeg > 359.5f, "north is 0"); + Check.True(w.Ub("/ub face 10N 20E"), "/ub face (no comma)"); + Check.True(Math.Abs(FakeHost.HeadingDeg - 90f) < 0.5f, "east is 90"); + Check.False(w.Mt("/mt face somewhere"), "not a heading or a coordinate: not handled"); + + // With the jumper: nav is held while turning and given back once the heading is reached. + var s = new LegacyUiSettings { EnableNavigation = true }; + var jumper = new Jumper(FakeHost.Create(playerId: 0x50000F31), s, _ => { }); + w.Set("_jumper", jumper); + w.Mt("/mt face 200"); + Check.False(s.EnableNavigation, "nav held while turning"); + System.Threading.Thread.Sleep(120); + jumper.Tick(); + Check.True(s.EnableNavigation, "nav back once facing 200"); + Check.False(jumper.IsBusy, "and the jumper is free"); + } +} diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/MetaTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/MetaTests.cs index 49b5265..bf18530 100644 --- a/Tools/RynthCore.RynthAiHostTests/Tests/MetaTests.cs +++ b/Tools/RynthCore.RynthAiHostTests/Tests/MetaTests.cs @@ -45,6 +45,7 @@ internal static class MetaTests r.Add("meta: expression condition fails closed on errors", ExpressionCondition); r.Add("meta: need-to-buff with no buff manager, unknown condition types", NeedToBuffAndUnknown); r.Add("meta action: chat commands, /ra, /vt and /mt", ChatCommands); + r.Add("meta action: the /vt verbs and options the metas use that were missing (2026-10-17)", VtPortedVerbs); r.Add("meta action: SetMetaState, CallMetaState and ReturnFromCall", CallReturn); r.Add("meta action: All runs every child in order", AllAction); r.Add("meta action: embedded nav route", EmbeddedNav); @@ -915,6 +916,90 @@ internal static class MetaTests Check.Eq(reversed.S.ActiveNavIndex, 2, "index mirrored"); } + // /vt verbs and options found in ub-IT and the metas on disk (universalremote.met, SASocietyTasks.met, + // FoundryIzexi.met, DerethExploration (1).met) that RynthAi didn't handle. + private static void VtPortedVerbs() + { + FakeHost.Reset(); + FakeHost.TapJumpCalls = true; // the engine's tap jump, for /vt tapjump + var rig = new Rig(FakeHost.Create(), Player); + + // /vt e toggles the macro. Straight to the /vt handler: a meta doesn't run with the macro off. + rig.S.IsMacroRunning = false; + Check.True(rig.M.TryHandleVtCommand("/vt e") && rig.Ra.Contains("/ra start"), "/vt e with the macro off starts it"); + rig.S.IsMacroRunning = true; + Check.True(rig.M.TryHandleVtCommand("/vt e") && rig.Ra.Contains("/ra stop"), "/vt e with the macro on stops it"); + + // /vt jump heading shift holdms -> /ra jump[s] heading hold; /vt tapjump -> the engine's tap jump. + RunAction(rig, A.ChatCommand, "/vt jump 90 true 750"); + Check.True(rig.Ra.Contains("/ra jumps 90 750"), "/vt jump 90 true 750 -> /ra jumps 90 750"); + RunAction(rig, A.ChatCommand, "/vt jump 180 false 300"); + Check.True(rig.Ra.Contains("/ra jump 180 300"), "shift false -> /ra jump"); + int taps = FakeHost.TapJumps; + RunAction(rig, A.ChatCommand, "/vt tapjump"); + Check.Eq(FakeHost.TapJumps, taps + 1, "/vt tapjump"); + + // Settings profiles go to /ra settings; other /vt settings verbs are still swallowed. + RunAction(rig, A.ChatCommand, "/vt settings savechar Banes"); + Check.True(rig.Ra.Contains("/ra settings savechar Banes"), "/vt settings savechar"); + RunAction(rig, A.ChatCommand, "/vt settings loadchar Base Profile"); + Check.True(rig.Ra.Contains("/ra settings loadchar Base Profile"), "/vt settings loadchar keeps spaces"); + + // looting load = loot load; equipitemsfor -> /ra equipfor. + RunAction(rig, A.ChatCommand, "/vt looting load NoSuchProfile.utl"); + Check.True(FakeHost.Chat.Any(c => c.Contains("Loot profile not found: NoSuchProfile.utl")), "/vt looting load is handled as loot load"); + RunAction(rig, A.ChatCommand, "/vt equipitemsfor Pyre Skeleton"); + Check.True(rig.Ra.Contains("/ra equipfor Pyre Skeleton"), "/vt equipitemsfor -> /ra equipfor"); + + // Distances: VTank landblock units (x240) -> yards; a value over 1 is already yards. + RunAction(rig, A.ChatCommand, "/vt opt set attackdistance .01666"); + Check.Eq(rig.S.MonsterRange, 4, "attackdistance .01666 -> 4 yd (was dropped: an int setter refused the decimal)"); + RunAction(rig, A.ChatCommand, "/vt opt set attackrange 0.04166"); + Check.Eq(rig.S.MonsterRange, 10, "attackrange 0.04166 -> 10 yd"); + RunAction(rig, A.ChatCommand, "/vt opt set approachdistance 0.0175"); + Check.Eq(rig.S.ApproachRange, 4, "approachdistance 0.0175 -> 4 yd"); + RunAction(rig, A.ChatCommand, "/vt opt set dooropenrange 0.005"); + Check.Near(rig.S.OpenDoorRange, 1.2, 1e-3, "dooropenrange 0.005 -> 1.2 yd (was 0.005 yd)"); + RunAction(rig, A.ChatCommand, "/vt opt set ringdistance 0.025"); + Check.Eq(rig.S.RingRange, 6, "ringdistance 0.025 -> 6 yd"); + RunAction(rig, A.ChatCommand, "/vt opt set corpseapproachrange-max 0.05"); + Check.Near(rig.S.CorpseApproachRangeMax, 12, 1e-3, "corpseapproachrange-max 0.05 -> 12 yd"); + RunAction(rig, A.ChatCommand, "/vt opt set minimumringtargets 3"); + Check.Eq(rig.S.MinRingTargets, 3, "minimumringtargets"); + RunAction(rig, A.ChatCommand, "/vt opt set attackdistance 25"); + Check.Eq(rig.S.MonsterRange, 25, "a value over 1 is yards already"); + + // An option written as a verb (DerethExploration: /vt navclosestoprange 0.005). + RunAction(rig, A.ChatCommand, "/vt navclosestoprange 0.005"); + Check.Near(rig.S.FollowNavMin, 1.2, 1e-3, "/vt navclosestoprange 0.005 -> nav point reach 1.2 yd"); + RunAction(rig, A.ChatCommand, "/vt opt set navclosetoprange .00625"); + Check.Near(rig.S.FollowNavMin, 1.5, 1e-3, "the misspelt navclosetoprange too"); + + // Options whose value means something else in RynthAi. + RunAction(rig, A.ChatCommand, "/vt opt set defaultmeleeattackheight 3"); + Check.Eq(rig.S.MeleeAttackHeight, 2, "VTank height 3 (high) -> RynthAi 2"); + RunAction(rig, A.ChatCommand, "/vt opt set defaultmeleeattackheight 2"); + Check.Eq(rig.S.MeleeAttackHeight, 1, "VTank height 2 (medium) -> RynthAi 1"); + rig.S.LootOwnership = 0; + RunAction(rig, A.ChatCommand, "/vt opt set lootfellowcorpses true"); + Check.Eq(rig.S.LootOwnership, 1, "lootfellowcorpses -> fellowship kills"); + RunAction(rig, A.ChatCommand, "/vt opt set lootallcorpses true"); + Check.Eq(rig.S.LootOwnership, 2, "lootallcorpses -> all corpses"); + RunAction(rig, A.ChatCommand, "/vt opt set lootallcorpses false"); + Check.Eq(rig.S.LootOwnership, 0, "lootallcorpses false -> my kills"); + RunAction(rig, A.ChatCommand, "/vt opt set usearcs 3"); + Check.True(rig.S.UseArcs, "usearcs 3 -> on"); + RunAction(rig, A.ChatCommand, "/vt opt set usearcs 0"); + Check.False(rig.S.UseArcs, "usearcs 0 -> off"); + RunAction(rig, A.ChatCommand, "/vt opt set minimumhealkitsuccesschance 55"); + Check.Eq(rig.S.KitMinSuccessPct, 55, "minimumhealkitsuccesschance 55 %"); + RunAction(rig, A.ChatCommand, "/vt opt set minimumhealkitsuccesschance 0.8"); + Check.Eq(rig.S.KitMinSuccessPct, 80, "a fraction is scaled to a percent"); + RunAction(rig, A.ChatCommand, "/vt opt set defaultmeleeattackheight 3"); + RunAction(rig, A.ChatCommand, "/vt opt get defaultmeleeattackheight"); + Check.True(FakeHost.Chat.Any(c => c.Contains("defaultmeleeattackheight = 3")), "read back in VTank's own 1-3"); + } + private static void CallReturn() { var rig = new Rig(rules: new[] diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/MiniRemoteMoveTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/MiniRemoteMoveTests.cs index 141e278..a6e842a 100644 --- a/Tools/RynthCore.RynthAiHostTests/Tests/MiniRemoteMoveTests.cs +++ b/Tools/RynthCore.RynthAiHostTests/Tests/MiniRemoteMoveTests.cs @@ -21,9 +21,6 @@ internal static class MiniRemoteMoveTests { private const uint Player = 0x50000E01; - [System.Runtime.CompilerServices.UnsafeAccessor(System.Runtime.CompilerServices.UnsafeAccessorKind.Field, Name = "_selectBreeding")] - private static extern ref bool SelectBreedingPending(PetsTab pets); - private const string LegacyHubJson = """ { "Bank": { "Pyreals": 99 }, @@ -38,9 +35,11 @@ internal static class MiniRemoteMoveTests { r.Add("mini remote: Pets / Quests settings come over from ilt-hub.json once, which is never rewritten", LegacyState); r.Add("mini remote: without RynthILT there are no ILT tabs, bits or verbs", NoRynthIlt); - r.Add("mini remote: /ra hub|quests|pets stay RynthAi's; quest windows point to RynthOracle; ILT verbs say RynthILT is needed", Commands); + r.Add("mini remote: /ra hub|quests|pets stay RynthAi's; quest windows point to RynthOracle; other hub verbs are a server plugin's", Commands); r.Add("mini remote: the pyreal refill path never spends without RynthILT's confirmation", RefillNeedsIlt); - r.Add("vaulted dungeons: the master switch is off by default, saved with the profile, and an older engine's save leaves it alone", VaultedMasterSwitch); + r.Add("pets: ACECustom's charms, capture, refill gate and Breeding come from the server plugin (none without it)", PetsFromServerPlugin); + r.Add("mini remote: the session report's tail and the menu's server come from the server plugin", RemoteTextsFromServerPlugin); + r.Add("vaulted dungeons: the master switch is RynthILT's; RynthAi mirrors it for the engine row (none without RynthILT)", VaultedMasterSwitch); r.Add("profile: the old Server Features fields still round-trip (RynthILT migrates them)", LegacyProfileFields); r.Add("RynthAi.Hub: table, spell names, nothing before login", HubTable); } @@ -85,13 +84,16 @@ internal static class MiniRemoteMoveTests Check.False(fresh.Pet.HealingEnabled, "no files at all: defaults"); } - private static MiniRemoteController NewController(string folder, out RynthCoreHost host, out LegacyUiSettings settings) + private static MiniRemoteController NewController(string folder, out RynthCoreHost host, out LegacyUiSettings settings, bool serverPlugin = false) { FakeHost.Reset(); + FakeServerHub.Reset(); host = FakeHost.Create(Player); var s = new LegacyUiSettings(); settings = s; - var c = new MiniRemoteController(host, Folder(folder), () => null, () => s, () => null, () => { }, new IltClient(host)); + var client = new ServerHubClient(host); + if (serverPlugin) client.UseTableForTests(FakeServerHub.Table); + var c = new MiniRemoteController(host, Folder(folder), () => null, () => s, () => null, () => { }, client); string? lastTab = null; c.MiniRemoteCommand = mode => "[Mini Remote] remote " + mode; c.MiniRemoteTabCommand = (tab, mode) => { lastTab = tab + ":" + mode; return "tab " + lastTab; }; @@ -101,16 +103,18 @@ internal static class MiniRemoteMoveTests private static void NoRynthIlt() { var c = NewController("noilt", out var host, out _); - var ilt = c.Ilt; + var ilt = c.ServerHub; ilt.Tick(); Check.False(ilt.Loaded, "no RynthILT (no plugin interfaces on this host)"); - Check.False(ilt.IsIltWorld, "so never an ILT world"); + Check.False(ilt.ServerActive, "so never an ILT world"); Check.Eq(ilt.Feature(RynthIltHub.FeaturePetRefill), -1, "feature bits unknown"); Check.False(ilt.IsOff(RynthIltHub.FeatureQuests), "unknown is not off (/myquests still refreshes)"); Check.Eq(ilt.Tabs().Count, 0, "no ILT tabs"); Check.False(ilt.RenderSection(RynthIltHub.SectionQuestBonus), "no ILT sections"); Check.False(ilt.Command("hub bank"), "no ILT verbs taken"); - Check.False(ilt.TryGetRates(out _, out _), "no ILT rates"); + Check.Eq(ilt.Text(RynthIltHub.TextSessionReport), string.Empty, "no server rates in the session report"); + Check.Eq(ilt.Text(RynthIltHub.TextServerId), string.Empty, "no server of a plugin's in the menu"); + Check.Eq(ilt.Setting(RynthIltHub.SettingVaultedDungeons), -1, "no server setting offered"); Check.False(c.SkipLoginQuestRefresh, "the login /myquests refresh isn't skipped"); } @@ -128,19 +132,18 @@ internal static class MiniRemoteMoveTests Check.True(FakeHost.Chat.Any(x => x.Contains("tab pets:show")), "same tab"); FakeHost.Chat.Clear(); // The Pets tab's Breeding sub-tab is RynthILT's (Infinite Leaftide only): without RynthILT there is none. - Check.False(c.Pets.BreedingOffered, "no Breeding sub-tab without RynthILT"); + Check.Eq(c.Pets.SubTabs().Count, 0, "no Pets sub-tabs without a server plugin"); Check.True(c.HandleCommand("hub", new[] { "open", "breeding" }), "hub open breeding is answered"); - Check.True(FakeHost.Chat.Any(x => x.Contains(IltClient.NotLoaded)), "it says RynthILT is needed"); Check.False(FakeHost.Chat.Any(x => x.Contains("tab pets:")), "and opens nothing"); - Check.False(SelectBreedingPending(c.Pets), "no Breeding sub-tab request"); + Check.True(c.Pets.PendingSubTab == null, "no sub-tab request"); FakeHost.Chat.Clear(); Check.True(c.HandleCommand("hub", new[] { "tab", "Breed" }), "hub tab breed (the dashboard)"); Check.False(FakeHost.Chat.Any(), "tab switches quietly"); - Check.False(SelectBreedingPending(c.Pets), "still no Breeding sub-tab request without RynthILT"); + Check.True(c.Pets.PendingSubTab == null, "still no sub-tab request without a server plugin"); FakeHost.Chat.Clear(); Check.True(c.HandleCommand("hub", new[] { "bank" }), "hub bank is handled (answered)"); - Check.True(FakeHost.Chat.Any(x => x.Contains("RynthILT")), "it says the ILT verbs come with RynthILT"); - Check.True(FakeHost.Chat.Any(x => x.Contains("/ra hub open pets|crafting [show|hide|toggle] /ra hub open breeding")), "and lists what RynthAi still has"); + Check.True(FakeHost.Chat.Any(x => x.Contains("/ra hub open pets|crafting [show|hide|toggle]")), "with the help: what RynthAi has"); + Check.False(FakeHost.Chat.Any(x => x.Contains("RynthILT") || x.Contains("Leaftide")), "and nothing about ILT (a retail world's answer)"); FakeHost.Chat.Clear(); // The Quests tab moved to RynthOracle (2026-10-13): its verbs and tab names say so. Check.True(c.HandleCommand("hub", new[] { "open", "quests" }), "hub open quests is answered"); @@ -152,21 +155,73 @@ internal static class MiniRemoteMoveTests Check.True(c.HandleCommand("quests", Array.Empty()), "quests (refresh) stays RynthAi's"); Check.True(FakeHost.Chat.Any(x => x.Contains("Quest tracker not ready")), "the meta tracker's refresh (none in this test)"); FakeHost.Chat.Clear(); - Check.True(c.HandleCommand("guardian", new[] { "handin" }), "guardian is answered"); - Check.True(FakeHost.Chat.Any(x => x.Contains("RynthILT")), "with the RynthILT note"); - FakeHost.Chat.Clear(); - Check.True(c.HandleCommand("bountys", Array.Empty()), "the bountys spelling too"); + Check.False(c.HandleCommand("guardian", new[] { "handin" }), "guardian isn't the Mini Remote's (a server plugin's verb)"); + Check.False(c.HandleCommand("bountys", Array.Empty()), "nor bounty"); Check.False(c.HandleCommand("start", Array.Empty()), "other verbs aren't the Mini Remote's"); + Check.False(FakeHost.Chat.Any(), "and it says nothing about them"); + + // With a server plugin, a hub verb RynthAi doesn't have is the plugin's. + var ilt = NewController("cmds-ilt", out _, out _, serverPlugin: true); + FakeServerHub.TakesCommand = line => line.StartsWith("hub bank", StringComparison.Ordinal); + FakeHost.Chat.Clear(); + Check.True(ilt.HandleCommand("hub", new[] { "bank" }), "hub bank"); + Check.Eq(FakeServerHub.Commands.Count, 1, "went to the server plugin"); + Check.False(FakeHost.Chat.Any(), "RynthAi adds nothing (the plugin answers itself)"); } private static void RefillNeedsIlt() { var c = NewController("refill", out _, out _); - c.State.Pet.UsePyrealRefillPath = true; - FakeHost.Bools[(Player, MiniRemoteInventory.BoolPyrealRefillActive)] = true; // the server's player bool + c.State.Pet.UsePyrealRefillPath = true; // the old (obsolete) opt-in in miniremote.json + FakeHost.Bools[(Player, 9049)] = true; // ACECustom's refill player bool Check.False(c.Pets.AllowSummonOnEmpty(), "not an ILT world (no RynthILT): an empty essence is never summoned on pyreals"); } + /// + /// The Remote tab's server texts with a server plugin (2026-10-20): the session report's tail and the + /// server its menu entries belong to come from the plugin, as they are. + /// + private static void RemoteTextsFromServerPlugin() + { + var c = NewController("texts", out _, out _, serverPlugin: true); + Check.Eq(c.ServerHub.Text(RynthIltHub.TextSessionReport), string.Empty, "nothing until the plugin says something"); + FakeServerHub.Texts[RynthIltHub.TextSessionReport] = ", Coins 12/h, Pyr 3.4m/h"; + FakeServerHub.Texts[RynthIltHub.TextServerId] = "ilt"; + Check.Eq(c.ServerHub.Text(RynthIltHub.TextSessionReport), ", Coins 12/h, Pyr 3.4m/h", "the report's tail is the plugin's"); + Check.Eq(c.ServerHub.Text(RynthIltHub.TextServerId), "ilt", "and the server its menu entries belong to"); + } + + /// + /// The Pets tab with and without a server plugin (2026-10-20): ACECustom's pet charms, siphon + /// auto-capture, the summon-from-empty gate and the Breeding sub-tab are RynthILT's. Without it the + /// tab asks nothing of the kind; with it the gate is RynthILT's answer and its sub-tab opens by name. + /// + private static void PetsFromServerPlugin() + { + var plain = NewController("pets-plain", out _, out _); + Check.False(plain.ServerHub.Loaded, "no server plugin"); + Check.False(plain.Pets.AllowSummonOnEmpty(), "no summon from empty"); + Check.Eq(plain.Pets.FindSubTab("breeding"), null, "no Breeding"); + + var c = NewController("pets-ilt", out _, out _, serverPlugin: true); + FakeServerHub.Active = true; + Check.True(c.ServerHub.Loaded && c.ServerHub.ServerActive, "the fake RynthILT is there, on its world"); + Check.False(c.Pets.AllowSummonOnEmpty(), "RynthILT says no: no summon from empty"); + FakeServerHub.AllowEmpty = true; + Check.True(c.Pets.AllowSummonOnEmpty(), "RynthILT says yes (charm on, opted in, confirmed): summon from empty"); + Check.Eq(c.Pets.SubTabs().Count, 0, "no sub-tabs until RynthILT offers one"); + FakeServerHub.SubTabs[RynthIltHub.TabParentPets] = new() { (RynthIltHub.SectionPetBreeding, "Breeding") }; + Check.Eq(c.Pets.SubTabs().Count, 1, "RynthILT's Breeding sub-tab"); + Check.Eq(c.Pets.FindSubTab("breeding"), RynthIltHub.SectionPetBreeding, "found by its short id"); + Check.Eq(c.Pets.FindSubTab("Breed"), RynthIltHub.SectionPetBreeding, "and the 'breed' alias"); + Check.Eq(c.Pets.FindSubTab("roster"), null, "the roster isn't a server sub-tab"); + FakeHost.Chat.Clear(); + Check.True(c.HandleCommand("hub", new[] { "open", "breeding" }), "hub open breeding"); + Check.True(FakeHost.Chat.Any(x => x.Contains("tab pets:show")), "shows the Pets tab"); + Check.Eq(c.Pets.PendingSubTab, RynthIltHub.SectionPetBreeding, "on the Breeding sub-tab"); + Check.Eq(FakeServerHub.Commands.Count, 0, "RynthAi handled it itself (nothing forwarded)"); + } + private static void LegacyProfileFields() { var s = JsonSerializer.Deserialize("{\"FeatureServerNames\":[\"MyShard\"],\"ForceServerFeatures\":true}", @@ -179,19 +234,17 @@ internal static class MiniRemoteMoveTests } /// - /// "Vaulted Dungeons" (Settings > Navigation) is RynthILT's keeper's master switch and lives only in - /// RynthAi's profile: off for a new or older profile, round-tripped through the settings bridge, and - /// an engine that predates the row (it sends no such field) never flips it. + /// "Vaulted Dungeons" (the engine's Settings > Navigation row) is RynthILT's keeper master switch, and + /// since 2026-10-20 RynthILT's own setting (copied once from the profile, whose old field still loads + /// and is carried, unused). RynthAi only mirrors it: without a server plugin offering it the row gets + /// null (hidden) and a save changes nothing; with one, the row shows its value and a save goes to it. /// private static void VaultedMasterSwitch() { - Check.False(new LegacyUiSettings().EnableVaultedDungeons, "off by default"); - var oldProfile = JsonSerializer.Deserialize("{\"BoostNavPriority\":true}", RynthAiJsonContext.Default.LegacyUiSettings)!; - Check.False(oldProfile.EnableVaultedDungeons, "a profile saved before the switch existed has it off"); - - var on = new LegacyUiSettings { EnableVaultedDungeons = true }; - string json = JsonSerializer.Serialize(on, RynthAiJsonContext.Default.LegacyUiSettings); - Check.True(JsonSerializer.Deserialize(json, RynthAiJsonContext.Default.LegacyUiSettings)!.EnableVaultedDungeons, "saved with the profile"); + var oldProfile = JsonSerializer.Deserialize("{\"EnableVaultedDungeons\":true}", RynthAiJsonContext.Default.LegacyUiSettings)!; + Check.True(oldProfile.EnableVaultedDungeons, "an old profile's switch still loads (RynthILT copies it once)"); + string json = JsonSerializer.Serialize(oldProfile, RynthAiJsonContext.Default.LegacyUiSettings); + Check.True(json.Contains("\"EnableVaultedDungeons\": true"), "and is written back unchanged"); var s = new LegacyUiSettings(); var dash = (LegacyDashboardRenderer)System.Runtime.CompilerServices.RuntimeHelpers.GetUninitializedObject(typeof(LegacyDashboardRenderer)); @@ -200,15 +253,27 @@ internal static class MiniRemoteMoveTests typeof(LegacyDashboardRenderer).GetField("_advancedSettingsUi", flags)!.SetValue(dash, new LegacyAdvancedSettingsUi(s)); var sent = JsonSerializer.Deserialize(dash.BuildSettingsJson(), RynthAiJsonContext.Default.SettingsBridgePayload)!; - Check.True(sent.EnableVaultedDungeons == false, "the Settings face is sent the switch (off)"); + Check.True(sent.EnableVaultedDungeons == null, "no server plugin: the row is sent nothing (it hides)"); dash.ApplySettingsJson("{\"EnableVaultedDungeons\":true}"); - Check.True(s.EnableVaultedDungeons, "the Settings checkbox turns it on"); + Check.False(s.EnableVaultedDungeons, "and a save doesn't touch RynthAi's old field"); + + // A server plugin offering the switch (RynthILT, through the Mini Remote's server client). + FakeHost.Reset(); + FakeServerHub.Reset(); + var client = new ServerHubClient(FakeHost.Create(Player)); + client.UseTableForTests(FakeServerHub.Table); + dash.ServerSettingGet = key => client.Setting(key); + dash.ServerSettingSet = (key, value) => client.SetSetting(key, value); + sent = JsonSerializer.Deserialize(dash.BuildSettingsJson(), RynthAiJsonContext.Default.SettingsBridgePayload)!; + Check.True(sent.EnableVaultedDungeons == null, "RynthILT not offering it (off ILT): still hidden"); + FakeServerHub.Settings[RynthIltHub.SettingVaultedDungeons] = 0; + sent = JsonSerializer.Deserialize(dash.BuildSettingsJson(), RynthAiJsonContext.Default.SettingsBridgePayload)!; + Check.True(sent.EnableVaultedDungeons == false, "offered: the row shows RynthILT's value (off)"); + dash.ApplySettingsJson("{\"EnableVaultedDungeons\":true}"); + Check.Eq(FakeServerHub.Settings[RynthIltHub.SettingVaultedDungeons], 1, "the checkbox turns RynthILT's switch on"); dash.ApplySettingsJson("{\"NavRingThickness\":6}"); - Check.True(s.EnableVaultedDungeons, "an older engine's save (no such field) leaves it on"); - dash.ApplySettingsJson("{\"EnableVaultedDungeons\":false}"); - Check.False(s.EnableVaultedDungeons, "the checkbox turns it off"); - dash.ApplySettingsJson("{\"NavRingThickness\":6}"); - Check.False(s.EnableVaultedDungeons, "and an older engine's save leaves it off"); + Check.Eq(FakeServerHub.Settings[RynthIltHub.SettingVaultedDungeons], 1, "an older engine's save (no such field) leaves it alone"); + Check.False(s.EnableVaultedDungeons, "RynthAi's old field is never written"); } private static unsafe void HubTable() @@ -229,6 +294,14 @@ internal static class MiniRemoteMoveTests Check.Eq(t->MiniRemoteVisible(), 0, "no Mini Remote before login"); Check.True(t->VaultedDungeonsEnabled != null, "the Vaulted Dungeons master switch is served"); Check.Eq(t->VaultedDungeonsEnabled(), 0, "the master switch is off before login (and by default)"); + Check.True(RynthAiHubApiV1.Has(t, RynthAiHubApiV1.BackAwayFromOffset) && t->BackAwayFrom != null, "the back-away is served (appended 2026-10-20)"); + Check.Eq(t->BackAwayFrom(1, 12f, 750), RynthAiHub.BackAwayNotNow, "not now before login"); + Check.True(RynthAiHubApiV1.Has(t, RynthAiHubApiV1.SetPlayerCounterOffset) && t->SetPlayerCounter != null, "the wield counters are served (appended 2026-10-20)"); + RynthCore.Plugin.RynthAi.Loot.T11ItemSupport.Reset(); + Check.Eq(t->SetPlayerCounter(9008, 3100), 1, "item augmentations taken"); + Check.Eq(RynthCore.Plugin.RynthAi.Loot.T11ItemSupport.Player.Get(RynthCore.Loot.T11.T11Counter.ItemAugmentations), 3100L, "and the loot rules see them"); + Check.Eq(t->SetPlayerCounter(42, 1), 0, "not a counter: refused"); + RynthCore.Plugin.RynthAi.Loot.T11ItemSupport.Reset(); SessionStatsV1 ss; Check.Eq(t->SessionStats(&ss), 0, "no session before login"); } diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/NavEngineTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/NavEngineTests.cs index 4d5f09e..d94afa5 100644 --- a/Tools/RynthCore.RynthAiHostTests/Tests/NavEngineTests.cs +++ b/Tools/RynthCore.RynthAiHostTests/Tests/NavEngineTests.cs @@ -32,6 +32,7 @@ internal static class NavEngineTests r.Add("nav engine: a Once route ends, turns nav off, and re-runs from [0]", OnceCompletes); r.Add("nav engine: closest approach counts as arriving; a pause forgets it", SweepPass); r.Add("nav engine: a pause point waits its time on the clock", PausePoint); + r.Add("nav engine: standing still through a pause, the stop is sent once and then once a second (not every tick)", PauseStopsOnce); r.Add("nav engine: a chat point sends its text once and moves on", ChatPoint); r.Add("nav engine: a jump point jumps on arrival (heading and power clamped)", JumpPoint); r.Add("nav engine: a recall that teleports moves on after the settle", RecallTeleports); @@ -263,6 +264,26 @@ internal static class NavEngineTests Check.Eq(nav.Idx, 1, "3.1 s: on to [1]"); } + /// + /// Standing still through a pause, nav sends its stop once and then a reminder a second, not every + /// tick: in portal space the game thread takes none of them and 137 ran 12.7 s late, against the + /// next leg (Dargoth Hera, 2026-10-19). + /// + private static void PauseStopsOnce() + { + FakeHost.Reset(); At(0, 0); + var pause = Pt(0, 0, T.Pause); pause.PauseTimeMs = 5000; + var nav = new Nav(Route(RT.Circular, pause, Pt(20, 0))); + nav.Tick(100); + int before = FakeHost.AutoRunCalls.Count(on => !on); + nav.Run(4.5); + int during = FakeHost.AutoRunCalls.Count(on => !on) - before; + Check.True(nav.E.GetStateSnapshot().InPause, "still pausing"); + Check.True(during <= 5, $"4.5 s of pause: {during} autorun-off sends (a reminder a second at most)"); + Check.True(during >= 3, $"but the reminders keep coming ({during})"); + Check.False(FakeHost.AutoRun, "standing still"); + } + private static void ChatPoint() { FakeHost.Reset(); At(0, 0); diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/RingEvadeTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/RingEvadeTests.cs deleted file mode 100644 index 7a3499d..0000000 --- a/Tools/RynthCore.RynthAiHostTests/Tests/RingEvadeTests.cs +++ /dev/null @@ -1,97 +0,0 @@ -using System; -using RynthCore.Plugin.RynthAi; -using RynthCore.Plugin.RynthAi.LegacyUi; -using RynthCore.RynthAiHostTests.Fakes; -using RynthCore.RynthAiTests.Harness; - -namespace RynthCore.RynthAiHostTests.Tests; - -// Empyrean Handler lethal-ring evade (CombatManager.HandleChatForRingEvade; Silentkelpie's PR 12). The line -// "The handler briefly channels infused Empyrean hatred to release a lethal ring." makes combat back-jump -// away from a Handler inside the ring radius. The base adds a gate: only while the macro is running with -// combat on, and a setting (HandlerRingEvade) turns it off. -internal static class RingEvadeTests -{ - private const uint Player = 0x50000D11; - private const uint Handler = 0x80300110; - private const uint Lb = 0xA9B40000; - private const string RingLine = "The handler briefly channels infused Empyrean hatred to release a lethal ring."; - - public static void Register(Runner r) - { - r.Add("ring evade: the Handler's ring line back-jumps when it is in range and the macro runs with combat on", Jumps); - r.Add("ring evade: not with the setting off, the macro stopped, or combat off", Gated); - r.Add("ring evade: not for a Handler out of range, no Handler, or a player's copy of the line", NotThese); - } - - private sealed class Rig - { - public readonly LegacyUiSettings S = new() { MonsterRange = 40, EnableCombat = true }; - public readonly CombatManager Combat; - public int Jumps; - public float Heading = -1; - - public Rig(float handlerYards, string handlerName = "Empyrean Handler") - { - FakeHost.Reset(); - FakeHost.Names[Player] = "Evader"; - FakeHost.Positions[Player] = (Lb | 0x1C, 96f, 96f, 0f); - FakeHost.PlayerPose = (Lb | 0x1C, 96f, 96f, 0f); - FakeHost.Names[Handler] = handlerName; - FakeHost.Positions[Handler] = (Lb | 0x1C, 96f, 96f + handlerYards, 0f); - FakeHost.ItemTypes[Handler] = 0x10; - var host = FakeHost.Create(Player); - var cache = FakeHost.MakeCache(host, Player, new[] { Handler }); - S.IsMacroRunning = true; - Combat = new CombatManager(host, S, cache); - Combat.SetPlayerId(Player); - Combat.ScanNearbyTargets(); - Combat.RequestBackJump = (h, ms) => { Jumps++; Heading = h; return true; }; - Combat.JumpBusy = () => false; - } - } - - private static void Jumps() - { - var rig = new Rig(handlerYards: 5); - rig.Combat.HandleChatForRingEvade(RingLine, 0x0C); - Check.Eq(rig.Jumps, 1, "a Handler 5 yards away: one back-jump"); - rig.Combat.HandleChatForRingEvade(RingLine, 0x0C); - Check.Eq(rig.Jumps, 1, "a second line inside the cooldown does nothing"); - } - - private static void Gated() - { - var off = new Rig(5); - off.S.HandlerRingEvade = false; - off.Combat.HandleChatForRingEvade(RingLine, 0x0C); - Check.Eq(off.Jumps, 0, "setting off: no jump"); - - var stopped = new Rig(5); - stopped.S.IsMacroRunning = false; - stopped.Combat.HandleChatForRingEvade(RingLine, 0x0C); - Check.Eq(stopped.Jumps, 0, "macro stopped: no jump"); - - var noCombat = new Rig(5); - noCombat.S.EnableCombat = false; - noCombat.Combat.HandleChatForRingEvade(RingLine, 0x0C); - Check.Eq(noCombat.Jumps, 0, "combat off: no jump"); - - Check.True(new LegacyUiSettings().HandlerRingEvade, "on by default (it is gated)"); - } - - private static void NotThese() - { - var far = new Rig(30); - far.Combat.HandleChatForRingEvade(RingLine, 0x0C); - Check.Eq(far.Jumps, 0, "a Handler 30 yards away is outside the ring"); - - var none = new Rig(5, handlerName: "Drudge Skulker"); - none.Combat.HandleChatForRingEvade(RingLine, 0x0C); - Check.Eq(none.Jumps, 0, "no Empyrean Handler nearby"); - - var said = new Rig(5); - said.Combat.HandleChatForRingEvade("Someone says, \"" + RingLine + "\"", 0x03); - Check.Eq(said.Jumps, 0, "a player's copy of the line is ignored"); - } -} diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/SectionsTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/SectionsTests.cs index 270ec76..12cb50c 100644 --- a/Tools/RynthCore.RynthAiHostTests/Tests/SectionsTests.cs +++ b/Tools/RynthCore.RynthAiHostTests/Tests/SectionsTests.cs @@ -9,10 +9,11 @@ namespace RynthCore.RynthAiHostTests.Tests; // Mini Remote sections (RynthCore 2026.10.5.46+): RynthCore sends its server verdicts (V lines) and // section rail (X lines) in the "servermenu" payload, and reads RynthAi's views from -// RynthPluginGetSectionsJson. RynthAi lists its own views (Pets, Crafting, Spells, Fellowship) and -// hosts RynthILT's ILT tabs (RynthILT.Hub: Gear, Charms, Banking, Games); Quests are RynthOracle's, -// and RynthILT's Character tab moved out (RynthOracle's Character tab, Session Stats). The manifest is checked -// against the engine's own parser and catalog (UI/Sections, linked), so the two sides can't drift. +// RynthPluginGetSectionsJson. RynthAi lists only its own views (Session Stats, Pets, Crafting, Spells, +// Fellowship): since 2026-10-20 RynthILT lists its ILT tabs (Gear, Charms, Banking, Games, Vaulted +// Dungeons) in its own manifest (RynthILT.Tests); Quests are RynthOracle's, and the Character tab moved +// out (RynthOracle's Character tab, Session Stats). The manifest is checked against the engine's own +// parser and catalog (UI/Sections, linked), so the two sides can't drift. internal static class SectionsTests { public static void Register(Runner r) @@ -63,22 +64,6 @@ internal static class SectionsTests "S\tilt\tInfinite Leaftide\t1\t/rc server ilt on\n" + "I\tProgression\t/rc progression\tPlanners.\t\n"; - /// - /// RynthILT's tabs as its GetTabs would give them (Gear not reported yet, Games hidden), plus the - /// Character tab an older RynthILT still reports: it moved out of the Mini Remote (2026-10-13) - /// and must not be placed any more. - /// - private static readonly IltTabInfo[] IltTabs = - { - new("character", "Character", 520, 440, Shown: true, Available: true), - new("banking", "Banking", 560, 520, Shown: true, Available: true), - new("gear", "Gear", 560, 520, Shown: true, Available: false), - new("charms", "Charms", 560, 520, Shown: true, Available: true), - new("games", "Games", 520, 440, Shown: false, Available: false), - new("bogus id!", "Nope", 100, 100, Shown: true, Available: true), - new("unknowntab", "Unknown", 100, 100, Shown: true, Available: true), - }; - private static void ParsesVerdicts() { ServerMenuPayload p = ServerMenuModel.ParsePayload(Payload); @@ -117,20 +102,22 @@ internal static class SectionsTests finally { ServerMenuModel.Apply(string.Empty); } } - private static List SomeViews() => SectionsManifest.Views(IltTabs); + private static List SomeViews() => SectionsManifest.Views(); private static void ManifestRoundTrip() { var views = SomeViews(); Check.False(views.Any(v => v.Section == "quests"), "no Quests view: RynthOracle has them"); - Check.False(views.Any(v => v.Surface == "section:games"), "a tab RynthILT doesn't show isn't listed"); - Check.False(views.Any(v => v.Surface.Contains("unknowntab") || v.Surface.Contains("bogus")), "unplaced or unsafe tab ids aren't listed"); + Check.True(views.All(v => v.Server.Length == 0), "every view is every world's: no server's tab is listed by RynthAi"); + foreach (string tab in new[] { "gear", "charms", "banking", "games", "vaulted", "character" }) + Check.False(views.Any(v => v.Surface == SectionsManifest.SurfaceOf(tab)), tab + ": not RynthAi's (RynthILT lists its own tabs)"); + Check.Eq(SectionsManifest.OwnSections.Length, 0, "no section of RynthAi's own (Games went with RynthILT's tabs)"); string json = SectionsManifest.Build(views, SectionsManifest.OwnSections); SectionManifest m = SectionManifestParser.Parse("RynthAi", json, out string error); Check.Eq(error, string.Empty, "no parse error"); - Check.Eq(m.Contributions.Length, views.Count, "every view survives"); - Check.Eq(m.Sections.Length, SectionsManifest.OwnSections.Length, "own sections survive"); + Check.Eq(m.Contributions.Length, 5, "Session stats, Pets, Crafting, Spells, Fellowship"); + Check.Eq(m.Sections.Length, 0, "no own sections"); for (int i = 0; i < views.Count; i++) { SectionsManifest.View v = views[i]; @@ -141,26 +128,12 @@ internal static class SectionsTests Check.Eq(c.Enabled, v.Enabled, "enabled " + v.Surface); Check.Eq(c.Order, v.Order, "order " + v.Surface); } - SectionContribution gear = m.Contributions.Single(c => c.Surface == SectionsManifest.SurfaceOf("gear")); - Check.False(gear.Enabled, "unavailable Gear is disabled"); - Check.True(gear.Note.Length > 0, "with a note"); - Check.False(views.Any(v => v.Surface == SectionsManifest.SurfaceOf("character")), "character moved out: not placed even if RynthILT reports it"); - foreach (string kept in new[] { "charms", "banking" }) - { - SectionsManifest.View v = views.Single(x => x.Surface == SectionsManifest.SurfaceOf(kept)); - Check.True(v.Section == "inventory" && v.Server == SectionsManifest.IltServer && v.Enabled, kept + ": an ILT view in Inventory"); - } Check.True(json.Length < SectionManifestParser.MaxJsonLength / 16, "small"); SectionsManifest.View session = views.Single(v => v.Surface == SectionsManifest.SessionSurface); Check.Eq(session.Section, "char", "session stats in the char (Session Stats) section"); Check.Eq(session.Server, string.Empty, "every world"); Check.True(session.Primary, "a primary view (RynthCore drops its own overview)"); - - string noIlt = SectionsManifest.Build(SectionsManifest.Views(System.Array.Empty()), SectionsManifest.OwnSections); - SectionManifest plain = SectionManifestParser.Parse("RynthAi", noIlt, out string error2); - Check.Eq(error2, string.Empty, "without RynthILT: no parse error"); - Check.Eq(plain.Contributions.Length, 5, "without RynthILT: Session stats, Pets, Crafting, Spells, Fellowship"); } private static void CatalogPlacement() @@ -181,36 +154,27 @@ internal static class SectionsTests Check.True(charOff.Panes.Length == 1 && charOff.Panes[0].Contribution?.Surface == SectionsManifest.SessionSurface, "Session Stats: RynthAi's session view replaces the engine overview"); + // On Infinite Leaftide RynthAi's own manifest still adds no ILT pane: RynthILT's manifest does. List on = SectionCatalog.Build(new[] { m }, _ => false, new[] { iltOn }); SectionView charOn = on.Single(v => v.Id == "char"); Check.True(charOn.Panes.Length == 1 && charOn.Panes[0].Contribution?.Surface == SectionsManifest.SessionSurface, "Session Stats on ILT: session stats only (no ILT Character tab)"); SectionView inventoryOn = on.Single(v => v.Id == "inventory"); - Check.True(inventoryOn.Panes.Any(p => p.Title == "Gear") && inventoryOn.Panes.Any(p => p.Title == "Charms") - && inventoryOn.Panes.Any(p => p.Title == "Banking"), - "Inventory on ILT: RynthILT's Gear, Charms and Banking"); - SectionView inventoryOff = off.Single(v => v.Id == "inventory"); - Check.False(inventoryOff.Panes.Any(p => p.Title is "Gear" or "Charms" or "Banking"), "Inventory off ILT: none of RynthILT's tabs"); + Check.False(inventoryOn.Panes.Any(p => p.Contribution?.Plugin == "RynthAi" && p.Title is "Gear" or "Charms" or "Banking"), + "Inventory on ILT: none of RynthILT's tabs come from RynthAi"); + Check.False(on.Any(v => v.Id == "games" && v.Panes.Any(p => p.Contribution?.Plugin == "RynthAi")), "no Games pane from RynthAi"); Check.True(on.Single(v => v.Id == "spells").Panes.Any(p => p.Contribution?.Surface == SectionsManifest.SpellsSurface), "Spells"); Check.True(on.Single(v => v.Id == "fellowship").Panes.Any(p => p.Contribution?.Surface == SectionsManifest.FellowshipSurface), "Fellowship"); } private static void SurfaceRoundTrip() { - foreach (string id in new[] { "gear", "games", "charms", "banking" }) - { - string surface = SectionsManifest.SurfaceOf(id); - Check.True(SectionsManifest.TryIltTabOf(surface, out string back) && back == id, "round trip " + surface); - Check.Eq(SectionManifestParser.Surface(surface), surface, "the engine accepts " + surface); - } - Check.False(SectionsManifest.TryIltTabOf(SectionsManifest.SurfaceOf("character"), out _), "character isn't a section tab any more"); Check.Eq(SectionManifestParser.Surface(SectionsManifest.SessionSurface), SectionsManifest.SessionSurface, "the engine accepts the session surface"); Check.True(SectionsManifest.TryOwnTabOf(SectionsManifest.PetsSurface, out string pets) && pets == MiniRemoteTabs.Pets, "pets is RynthAi's"); Check.True(SectionsManifest.TryOwnTabOf(SectionsManifest.CraftingSurface, out string craft) && craft == MiniRemoteTabs.Crafting, "crafting is RynthAi's"); - Check.False(SectionsManifest.TryIltTabOf(SectionsManifest.PetsSurface, out _), "pets isn't an ILT tab"); - Check.False(SectionsManifest.TryIltTabOf(SectionsManifest.SpellsSurface, out _), "spells isn't a tab"); - Check.False(SectionsManifest.TryIltTabOf("section:nonsense", out _), "unknown"); - Check.False(SectionsManifest.TryIltTabOf("banking", out _), "no prefix"); - Check.False(SectionsManifest.TryIltTabOf("section:quests", out _), "Quests are RynthOracle's"); + foreach (string tab in new[] { "gear", "charms", "banking", "games", "vaulted" }) + Check.False(SectionsManifest.TryOwnTabOf(SectionsManifest.SurfaceOf(tab), out _), tab + " isn't RynthAi's to draw"); + Check.False(SectionsManifest.TryOwnTabOf(SectionsManifest.SpellsSurface, out _), "spells isn't a tab"); + Check.False(SectionsManifest.TryOwnTabOf("section:nonsense", out _), "unknown"); } } diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/ServerHubClientLookupTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/ServerHubClientLookupTests.cs new file mode 100644 index 0000000..30677e4 --- /dev/null +++ b/Tools/RynthCore.RynthAiHostTests/Tests/ServerHubClientLookupTests.cs @@ -0,0 +1,40 @@ +using RynthCore.Plugin.RynthAi.MiniRemote; +using RynthCore.RynthAiTests.Harness; + +namespace RynthCore.RynthAiHostTests.Tests; + +// RynthAi's lookup of a server plugin's hub table (MiniRemote/ServerHubClient.Tick, IltClient until +// 2026-10-20: the active server's owner under "RynthServer.Hub", else RynthILT's "RynthILT.Hub"). Until +// 0.5.60 the "never looked" sentinel was long.MinValue, "now - long.MinValue" overflowed to a +// negative number, the recheck gate always said "not due", and RynthAi never found RynthILT: +// no ILT tabs, sections or feature bits in the Mini Remote on Infinite Leaftide. +internal static class ServerHubClientLookupTests +{ + public static void Register(Runner r) + { + r.Add("ILT client: the first Tick (and the first after Reset) looks RynthILT up", FirstLook); + r.Add("ILT client: a live table is kept until the recheck interval", LiveTableKept); + r.Add("ILT client: no table retries every interval; a shut-down table at once", RetryRules); + } + + private static void FirstLook() + { + // Any clock value, including the large tick counts of a long-running PC. + foreach (long now in new[] { 0L, 1_000L, 5_000_000L, long.MaxValue / 2 }) + Check.True(ServerHubClient.LookupDue(checkedOnce: false, checkedAt: 0, now, haveTable: false, tableLive: false), + $"never looked: due at now={now}"); + } + + private static void LiveTableKept() + { + Check.False(ServerHubClient.LookupDue(true, checkedAt: 10_000, now: 11_000, haveTable: true, tableLive: true), "live table within the interval"); + Check.True(ServerHubClient.LookupDue(true, checkedAt: 10_000, now: 13_000, haveTable: true, tableLive: true), "live table after the interval"); + } + + private static void RetryRules() + { + Check.False(ServerHubClient.LookupDue(true, checkedAt: 10_000, now: 12_999, haveTable: false, tableLive: false), "no table: waits the interval"); + Check.True(ServerHubClient.LookupDue(true, checkedAt: 10_000, now: 13_000, haveTable: false, tableLive: false), "no table: looks again after it"); + Check.True(ServerHubClient.LookupDue(true, checkedAt: 10_000, now: 10_001, haveTable: true, tableLive: false), "Version 0 (RynthILT shut down): looks again at once"); + } +} diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/ServerPluginForwardTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/ServerPluginForwardTests.cs new file mode 100644 index 0000000..5cb14cf --- /dev/null +++ b/Tools/RynthCore.RynthAiHostTests/Tests/ServerPluginForwardTests.cs @@ -0,0 +1,76 @@ +using System; +using System.Reflection; +using System.Runtime.CompilerServices; +using RynthCore.Plugin.RynthAi; +using RynthCore.Plugin.RynthAi.LegacyUi; +using RynthCore.Plugin.RynthAi.MiniRemote; +using RynthCore.PluginCore; +using RynthCore.RynthAiHostTests.Fakes; +using RynthCore.RynthAiTests.Harness; + +namespace RynthCore.RynthAiHostTests.Tests; + +// "/ra" verbs RynthAi doesn't have go to the active server plugin (2026-10-20): "/ra t11" (moved to +// RynthILT with the T11 counters), "/ra guardian", "/ra bounty". Without a server plugin they are not +// RynthAi's at all: the line is left for the server, as any unknown "/ra", and nothing ILT answers. +internal static class ServerPluginForwardTests +{ + private const uint Player = 0x50000F21; + private const BindingFlags Any = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public; + + public static void Register(Runner r) + { + r.Add("server plugin verbs: /ra t11 and /ra guardian go to the server plugin; RynthAi's own verbs don't", Forwarded); + r.Add("server plugin verbs: without a server plugin /ra t11 is no RynthAi command (left for the server)", NoServerPlugin); + } + + private static RynthAiPlugin NewPlugin(bool serverPlugin) + { + FakeHost.Reset(); + FakeServerHub.Reset(); + FakeHost.Names[Player] = "Tester"; + var host = FakeHost.Create(Player); + var p = new RynthAiPlugin(); + typeof(RynthPluginBase).GetMethod("Attach", Any)!.Invoke(p, new object[] { FakeHost.LastApi }); + var dash = (LegacyDashboardRenderer)RuntimeHelpers.GetUninitializedObject(typeof(LegacyDashboardRenderer)); + typeof(LegacyDashboardRenderer).GetField("_settings", Any)!.SetValue(dash, new LegacyUiSettings()); + typeof(RynthAiPlugin).GetField("_dashboard", Any)!.SetValue(p, dash); + var client = new ServerHubClient(host); + if (serverPlugin) client.UseTableForTests(FakeServerHub.Table); + typeof(RynthAiPlugin).GetField("_serverHub", Any)!.SetValue(p, client); + return p; + } + + /// Runs "/ra ..." through RynthAi's dispatcher; returns its eat flag (1 = RynthAi or a plugin took it). + private static int Ra(RynthAiPlugin p, string line) + { + string[] parts = line.Split(' ', StringSplitOptions.RemoveEmptyEntries); + object[] args = { parts[1].ToLowerInvariant(), parts, 1 }; + typeof(RynthAiPlugin).GetMethod("DispatchRaCommand", Any)!.Invoke(p, args); + return (int)args[2]; + } + + private static void Forwarded() + { + var p = NewPlugin(serverPlugin: true); + FakeServerHub.TakesCommand = line => line.StartsWith("t11", StringComparison.Ordinal) || line.StartsWith("guardian", StringComparison.Ordinal); + Check.Eq(Ra(p, "/ra t11 augs 2500"), 1, "/ra t11 is taken"); + Check.Eq(FakeServerHub.Commands.Count, 1, "by the server plugin"); + Check.Eq(FakeServerHub.Commands[0], "t11 augs 2500", "the words after /ra, as typed"); + Check.Eq(Ra(p, "/ra guardian handin"), 1, "/ra guardian is taken"); + Check.Eq(FakeServerHub.Commands[1], "guardian handin", "by the server plugin too"); + Check.Eq(Ra(p, "/ra nosuchverb"), 0, "a verb nobody has is left for the server"); + Check.Eq(FakeServerHub.Commands.Count, 2, "and the plugin took nothing more"); + Ra(p, "/ra version"); + Check.Eq(FakeServerHub.Commands.Count, 2, "RynthAi's own verbs never reach the server plugin"); + } + + private static void NoServerPlugin() + { + var p = NewPlugin(serverPlugin: false); + FakeHost.Chat.Clear(); + Check.Eq(Ra(p, "/ra t11"), 0, "/ra t11 isn't RynthAi's: left for the server (unknown command there)"); + Check.False(FakeHost.Chat.Exists(l => l.Contains("T11")), "RynthAi says nothing about T11"); + Check.Eq(Ra(p, "/ra guardian"), 0, "/ra guardian likewise"); + } +} diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/T11LootTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/T11LootTests.cs index a830ce9..63f6ff3 100644 --- a/Tools/RynthCore.RynthAiHostTests/Tests/T11LootTests.cs +++ b/Tools/RynthCore.RynthAiHostTests/Tests/T11LootTests.cs @@ -11,7 +11,8 @@ namespace RynthCore.RynthAiHostTests.Tests; // T11 (ACECustom tier 11+) items through the real evaluator: the virtual T11 keys answered by // WorldObject.Values, the wield requirement and ratings the server strips put back from the -// item text, and "Can Wield" fed by the "/aug" reply. +// item text, and "Can Wield" fed by the wield counters the server plugin reports (RynthILT reads the +// "/aug" reply and applies its item-aug override since 2026-10-20; RynthAi.Hub SetPlayerCounter). internal static class T11LootTests { private const string WeaponLongDesc = @@ -35,7 +36,7 @@ internal static class T11LootTests r.Add("loot t11: modifier ratings feed Gear* keys and TotalRatings", ModifierRatings); r.Add("loot t11: a live rating wins over the modifier text", LiveRatingWins); r.Add("loot t11: retail items are untouched", RetailUntouched); - r.Add("loot t11: Can Wield from the /aug reply and the override", CanWield); + r.Add("loot t11: Can Wield from the counters the server plugin reports (unknown without one)", CanWield); r.Add("loot t11: server tier and quality properties", ServerProps); } @@ -112,15 +113,15 @@ internal static class T11LootTests { T11ItemSupport.Reset(); WorldObject w = Weapon(); - Check.Eq(w.Values(T11Keys.CanWield, -5), -1, "unknown before /aug"); - T11ItemSupport.OnChat("Advanced Augmentation Levels:"); - T11ItemSupport.OnChat("Item:2,400"); + Check.Eq(w.Values(T11Keys.CanWield, -5), -1, "unknown until a server plugin reports the counters (retail: never)"); + Check.True(T11ItemSupport.SetCounter((uint)T11Counter.ItemAugmentations, 2400), "RynthILT reports 2,400 item augs"); Check.Eq(w.Values(T11Keys.CanWield, -5), 0, "2,400 < 2,500"); Check.False(M(w, C(N.LongValKeyE, "1", K(T11Keys.CanWield))), "rule: wieldable fails"); - T11ItemSupport.SyncOverride(2500); - Check.Eq(w.Values(T11Keys.CanWield, -5), 1, "override 2,500 meets the gate"); - T11ItemSupport.SyncOverride(-1); - Check.Eq(w.Values(T11Keys.CanWield, -5), 0, "back to the /aug count"); + T11ItemSupport.SetCounter((uint)T11Counter.ItemAugmentations, 2500); // RynthILT's override, applied there + Check.Eq(w.Values(T11Keys.CanWield, -5), 1, "2,500 meets the gate"); + T11ItemSupport.SetCounter((uint)T11Counter.ItemAugmentations, -1); + Check.Eq(w.Values(T11Keys.CanWield, -5), -1, "reported unknown again: unknown"); + Check.False(T11ItemSupport.SetCounter(12345, 7), "an id that is no wield counter is refused"); Check.Eq(new Item("T11 - Robe").Wo.Values(T11Keys.CanWield, -5), -1, "not appraised yet: unknown"); Check.Eq(new Item("T11 - Robe").Str(16, "A robe.").Wo.Values(T11Keys.CanWield, -5), 1, "appraised, no gate: wieldable"); T11ItemSupport.Reset(); diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/TinkerTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/TinkerTests.cs index 495d46e..7d04b17 100644 --- a/Tools/RynthCore.RynthAiHostTests/Tests/TinkerTests.cs +++ b/Tools/RynthCore.RynthAiHostTests/Tests/TinkerTests.cs @@ -244,7 +244,14 @@ internal static class TinkerTests Check.Eq(p2.Count(x => x == TinkerCatalog.Serpentine), 3, "group a: its cap"); Check.Eq(p2.Count(x => x == TinkerCatalog.Steel), 4, "group b: its own cap"); Check.Eq(p2.Count(x => x == TinkerCatalog.Iron), 9, "no group, no slot: all 9"); - Check.True(TinkerCatalog.IsTrinket("Ornate Compass") && !TinkerCatalog.IsTrinket("Yellow Topaz Ring"), "trinkets left to their tab"); + // Which jewelry is a trinket is the server plugin's (its profile's "trinkets"; RynthILT's Leaftide list). + Check.False(TinkerCatalog.IsTrinket("Ornate Compass", null), "no server plugin: no trinkets (retail jewelry is all Jewelry)"); + var leaftide = ServerTrinketRule.Parse("{\"schema\":1,\"trinkets\":{\"names\":[\"compass\",\"top\"],\"except\":[\"topaz\"]}}"); + Check.True(TinkerCatalog.IsTrinket("Ornate Compass", leaftide) && !TinkerCatalog.IsTrinket("Yellow Topaz Ring", leaftide), + "with the server's rule: trinkets left to their tab, a topaz ring is no top"); + Check.True(TinkerCatalog.IsTrinket("Spinning Top", leaftide), "a top is"); + Check.Eq(ServerTrinketRule.Parse("{\"schema\":1,\"salvage\":[]}"), ServerTrinketRule.None, "a profile without trinkets: none"); + Check.Eq(ServerTrinketRule.Parse("not json"), ServerTrinketRule.None, "unusable text: none"); } private static void ItemRows() @@ -345,8 +352,11 @@ internal static class TinkerTests Check.Eq(TinkerPlanner.TierOf("Minor Pyreal Salvage"), 0, "Minor"); Check.Eq(TinkerPlanner.TierOf("Salvage (100)"), -1, "no tier"); - Check.True(TinkerCatalog.IsTrinket("Spinning Top") && TinkerCatalog.IsTrinket("Copper Pocket Watch") - && !TinkerCatalog.IsTrinket("Imperial Topaz Necklace"), "trinket names (topaz isn't a top)"); + // The server plugin's rule (RynthILT's Leaftide list, as its profile sends it). + var rule = new ServerTrinketRule(new[] { "compass", "goggles", "scarab", "watch", "puzzle box", "top" }, new[] { "topaz" }); + Check.True(TinkerCatalog.IsTrinket("Spinning Top", rule) && TinkerCatalog.IsTrinket("Copper Pocket Watch", rule) + && !TinkerCatalog.IsTrinket("Imperial Topaz Necklace", rule), "trinket names (topaz isn't a top)"); + Check.False(TinkerCatalog.IsTrinket("Copper Pocket Watch", ServerTrinketRule.None), "without a server rule nothing is a trinket"); Check.True(TinkerCatalog.Targets(TinkerBench.Trinkets, AcObjectClass.Jewelry), "trinkets are jewelry"); } } diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/UbCompatTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/UbCompatTests.cs new file mode 100644 index 0000000..ec4c2cf --- /dev/null +++ b/Tools/RynthCore.RynthAiHostTests/Tests/UbCompatTests.cs @@ -0,0 +1,158 @@ +using System; +using System.Linq; +using System.Reflection; +using System.Runtime.CompilerServices; +using RynthCore.Plugin.RynthAi; +using RynthCore.Plugin.RynthAi.LegacyUi; +using RynthCore.PluginCore; +using RynthCore.RynthAiHostTests.Fakes; +using RynthCore.RynthAiTests.Harness; + +namespace RynthCore.RynthAiHostTests.Tests; + +// ub-IT's remaining /ub verbs (2026-10-18): metas written for ub-IT send them, so every one is +// handled: mapped where RynthAi, RynthNav, RynthSort or the server has the feature, left to +// ub-Rythai for its verbs, and accepted quietly where nothing here matches (videopatch, ...). +internal static class UbCompatTests +{ + private const uint Player = 0x50000F21; + private const uint Robe = 0x80282101, WornRobe = 0x80282102; + private const BindingFlags Any = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public; + + public static void Register(Runner r) + { + r.Add("ub compat: ub-IT verbs with no RynthAi equivalent are accepted, said once", NoEquivalentAccepted); + r.Add("ub compat: ub-Rythai's verbs get no RynthAi reply, and a meta passes them on", UbRythaiVerbsLeftAlone); + r.Add("ub compat: aliases and features map onto RynthAi, RynthNav, RynthSort and the server", AliasesAndFeatures); + r.Add("ub compat: a meta's /ub line uses the /ub meaning, not /mt's", MetaUsesUbMeaning); + } + + private sealed class World + { + public readonly RynthAiPlugin P = new(); + public readonly LegacyUiSettings S = new(); + + public World() + { + FakeHost.Reset(); + FakeHost.PluginCommandCalls = true; + FakeHost.SalvageCalls = true; // GetObjectWielderInfo: the worn robe reads as worn + FakeHost.Names[Player] = "Kelpie"; + FakeHost.PlayerIdValue = Player; + foreach (var (id, name) in new[] { (Robe, "Faran Robe"), (WornRobe, "Faran Robe") }) + { + FakeHost.Names[id] = name; + FakeHost.Containers[id] = Player; + FakeHost.ItemTypes[id] = 0x2; // clothing + } + FakeHost.Wielded[WornRobe] = 0x0400; + var host = FakeHost.Create(playerId: Player); + typeof(RynthPluginBase).GetMethod("Attach", Any)!.Invoke(P, new object[] { FakeHost.LastApi }); + var dash = (LegacyDashboardRenderer)RuntimeHelpers.GetUninitializedObject(typeof(LegacyDashboardRenderer)); + typeof(LegacyDashboardRenderer).GetField("_settings", Any)!.SetValue(dash, S); + Set("_dashboard", dash); + var cache = new WorldObjectCache(host); + cache.SetPlayerId(Player); + Set("_objectCache", cache); + Set("_playerId", Player); + Set("_initialized", true); + Set("_loginComplete", true); + foreach (uint id in new[] { Robe, WornRobe }) cache.OnCreateObject(id); + cache.Tick(); + } + + public void Set(string f, object? v) => typeof(RynthAiPlugin).GetField(f, Any)!.SetValue(P, v); + public bool Ub(string line) => (bool)typeof(RynthAiPlugin).GetMethod("HandleUbCommand", Any)!.Invoke(P, new object[] { line })!; + public bool Meta(string line) => (bool)typeof(RynthAiPlugin).GetMethod("HandleMetaChatCommand", Any)!.Invoke(P, new object[] { line })!; + public int ChatWith(string text) => FakeHost.Chat.Count(c => c.Contains(text, StringComparison.OrdinalIgnoreCase)); + } + + private static void NoEquivalentAccepted() + { + var w = new World(); + Check.True(w.Ub("/ub soak on"), "/ub soak is handled"); + Check.True(w.Ub("/ub soak off"), "again"); + Check.Eq(w.ChatWith("/ub soak"), 1, "said once per session, not per meta pulse"); + // /ub videopatch is not here: RynthAi already forwards it to the engine's /rc videopatch. + foreach (string line in new[] { "/ub chat max", "/ub playeroption AutoRepeatAttack on", "/ub statushud toggle", "/ub professor war 7", "/ub xp level" }) + Check.True(w.Ub(line), line + " is handled"); + Check.Eq(w.ChatWith("Unrecognized"), 0, "no 'Unrecognized /ub command'"); + Check.False(w.Ub("/ub notaubitcommand"), "a verb ub-IT doesn't have is still unknown"); + } + + private static void UbRythaiVerbsLeftAlone() + { + var w = new World(); + int chat = FakeHost.Chat.Count; + foreach (string line in new[] { "/ub bank status", "/ub periodic add 5 /say hi", "/ub xpmeter", "/ub portal use Aerlinthe", "/ub portal list", "/ub leaftide status" }) + Check.True(w.Ub(line), line + ": not unknown"); + Check.Eq(FakeHost.Chat.Count, chat, "RynthAi says nothing; ub-Rythai answers these"); + // A meta hands them to the chat parser, which every plugin (ub-Rythai too) sees. + Check.False(w.Meta("/ub bank status"), "a meta's /ub bank goes on to the chat parser"); + // "/ub portal " is RynthAi's (the nearest portal), not a portal gem. + Check.False(RynthAiPluginIsUbRythai("portal", "Town Network"), "/ub portal stays RynthAi's"); + } + + private static bool RynthAiPluginIsUbRythai(string cmd, string args) + => (bool)typeof(RynthAiPlugin).GetMethod("IsUbRythaiCommand", BindingFlags.Static | BindingFlags.NonPublic)!.Invoke(null, new object[] { cmd, args })!; + + private static void AliasesAndFeatures() + { + var w = new World(); + + // wear: the carried copy, never the worn one (using a worn item takes it off). + Check.True(w.Ub("/ub wear Faran Robe"), "/ub wear"); + Check.True(FakeHost.Uses.Contains(Robe) && !FakeHost.Uses.Contains(WornRobe), "wears the carried robe only"); + + // Frame limits are RynthAi's FPS settings. + w.Ub("/ub globalframelimit 45"); + Check.Eq(w.S.TargetFPSFocused, 45, "globalframelimit"); + Check.True(w.S.EnableFPSLimit, "and the limit is on"); + w.Ub("/ub bgframelimit 20"); + Check.Eq(w.S.TargetFPSBackground, 20, "bgframelimit"); + w.Ub("/ub globalframelimit 0"); + Check.False(w.S.EnableFPSLimit, "0 turns the limit off"); + + // RynthNav and RynthSort through the plugin broker. + w.Ub("/ub arrow point 42.1N, 33.6E"); + Check.True(FakeHost.PluginCommands.Contains(("RynthNav", "rnav", "arrow 42.1N, 33.6E")), "arrow point -> /rnav arrow"); + w.Ub("/ub navgoto -12.5 40.25 walk"); + Check.True(FakeHost.PluginCommands.Contains(("RynthNav", "rnav", "go 12.5S, 40.25E")), "navgoto signed coords -> /rnav go"); + w.Ub("/ub packsort"); + Check.True(FakeHost.PluginCommands.Contains(("RynthSort", "rsort", "now")), "packsort -> /rsort now"); + + // Server and engine commands go to the chat parser. + w.Ub("/ub qblist"); + w.Ub("/ub augs"); + w.Ub("/ub window save"); + w.Ub("/ub fellow dismiss Storm"); + // qblist / augs are ACECustom's commands: the server plugin's (RynthILT) since 2026-10-20. + Check.False(FakeHost.ChatCommands.Contains("/qb list") || FakeHost.ChatCommands.Contains("/aug"), + "qblist / augs: no server plugin, so nothing is sent to the server"); + Check.True(FakeHost.ChatCommands.Contains("/rc window save"), "window save -> /rc window save"); + Check.True(FakeHost.ChatCommands.Contains("/fellowship dismiss Storm"), "fellow dismiss -> /fellowship dismiss"); + + // With a server plugin they are its verbs ("ub qblist", "ub augs"). + FakeServerHub.Reset(); + FakeServerHub.TakesCommand = line => line.StartsWith("ub ", StringComparison.Ordinal); + var hub = new RynthCore.Plugin.RynthAi.MiniRemote.ServerHubClient(default); + hub.UseTableForTests(FakeServerHub.Table); + w.Set("_serverHub", hub); + w.Ub("/ub qblist"); + w.Ub("/ub augs"); + Check.True(FakeServerHub.Commands.Contains("ub qblist") && FakeServerHub.Commands.Contains("ub augs"), "qblist / augs -> the server plugin"); + + // stfl / getxy are the /mt strafe / cursor commands (no game window here: they say so). + Check.True(w.Ub("/ub stfl 500"), "stfl handled"); + Check.True(w.Ub("/ub getxy"), "getxy handled"); + } + + private static void MetaUsesUbMeaning() + { + var w = new World(); + // A /ub verb /mt doesn't know used to fall to the chat parser and come back round. + Check.True(w.Meta("/ub soak on"), "a meta's /ub line runs the /ub dispatcher"); + Check.Eq(FakeHost.ChatCommands.Count(c => c.StartsWith("/ub", StringComparison.Ordinal)), 0, "not re-sent to the chat parser"); + Check.True(w.Meta("/mt get xy"), "/mt lines still go to /mt"); + } +} diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/UbMtSafetyTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/UbMtSafetyTests.cs new file mode 100644 index 0000000..b60f834 --- /dev/null +++ b/Tools/RynthCore.RynthAiHostTests/Tests/UbMtSafetyTests.cs @@ -0,0 +1,340 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Reflection; +using System.Runtime.CompilerServices; +using RynthCore.Plugin.RynthAi; +using RynthCore.Plugin.RynthAi.LegacyUi; +using RynthCore.Plugin.RynthAi.Meta; +using RynthCore.PluginCore; +using RynthCore.PluginSdk; +using RynthCore.RynthAiHostTests.Fakes; +using RynthCore.RynthAiTests.Harness; + +namespace RynthCore.RynthAiHostTests.Tests; + +// The safety limits on the ub-IT / Mag-Tools meta verbs (SilentKelpie's PR 12, taken 2026-10-19): +// VTank unit conversion only where documented, loot-ownership options, /ub give limits, key +// injection off by default, vendor / trade verbs only from a running meta. +internal static class UbMtSafetyTests +{ + public static void Register(Runner r) + { + r.Add("ub/mt safety: VTank distances convert only for the documented option names", VtConversionOnlyDocumentedNames); + r.Add("ub/mt safety: values above 1 are yards and are never scaled", VtValuesAboveOneUnchanged); + r.Add("ub/mt safety: loot-ownership options change LootOwnership and nothing else", VtLootOwnership); + r.Add("ub/mt safety: keystroke verbs do nothing by default, said once", KeystrokesOffByDefault); + r.Add("ub/mt safety: with the setting on the keystroke verbs reach the game window", KeystrokesWhenAllowed); + r.Add("ub/mt safety: a meta cannot switch the keystroke setting on", MetaCannotEnableKeystrokes); + r.Add("ub/mt safety: /mt trade accept and /mt vendor buy|sell refuse outside a running meta", VendorTradeRefusedOutsideMeta); + r.Add("ub/mt safety: /mt trade accept and /mt vendor sell act for a running meta, one log line each", VendorTradeFromRunningMeta); + r.Add("ub/mt safety: /mt vendor sell never sells equipped gear or RynthAi's own items", VendorSellSkipsProtected); + } + + private const uint Player = 0x50000F41; + private const uint Robe = 0x80282201, Cloak = 0x80282202, Sword = 0x80282203; + private const BindingFlags Any = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public; + + /// A RynthAi plugin wired enough to run its /mt dispatcher: a carried robe, a worn cloak, a carried sword. + private sealed class World + { + public readonly RynthAiPlugin P = new(); + public readonly LegacyUiSettings S = new(); + public readonly List<(uint Msg, uint W, uint L)> Posted = new(); + + public World(bool tradeVendor = false) + { + FakeHost.Reset(); + FakeHost.TradeVendorCalls = tradeVendor; + FakeHost.SalvageCalls = true; // GetObjectWielderInfo: the worn cloak reads as worn + FakeHost.Names[Player] = "Kelpie"; + FakeHost.PlayerIdValue = Player; + foreach (var (id, name) in new[] { (Robe, "Faran Robe"), (Cloak, "Worn Cloak"), (Sword, "Sharp Sword") }) + { + FakeHost.Names[id] = name; + FakeHost.Containers[id] = Player; + FakeHost.ItemTypes[id] = 0x2; + } + FakeHost.Wielded[Cloak] = 0x0400; + var host = FakeHost.Create(playerId: Player); + typeof(RynthPluginBase).GetMethod("Attach", Any)!.Invoke(P, new object[] { FakeHost.LastApi }); + var dash = (LegacyDashboardRenderer)RuntimeHelpers.GetUninitializedObject(typeof(LegacyDashboardRenderer)); + typeof(LegacyDashboardRenderer).GetField("_settings", Any)!.SetValue(dash, S); + Set("_dashboard", dash); + var cache = new WorldObjectCache(host); + cache.SetPlayerId(Player); + Set("_objectCache", cache); + Set("_playerId", Player); + Set("_initialized", true); + Set("_loginComplete", true); + foreach (uint id in new[] { Robe, Cloak, Sword }) cache.OnCreateObject(id); + cache.Tick(); + GameInput.TestSink = (m, w, l) => Posted.Add((m, w, l)); + } + + public void Set(string f, object? v) => typeof(RynthAiPlugin).GetField(f, Any)!.SetValue(P, v); + /// A line typed in the chat bar. + public bool Mt(string line) => (bool)typeof(RynthAiPlugin).GetMethod("HandleMtCommand", Any)!.Invoke(P, new object[] { line })!; + /// A line a meta's chat-command action sends. + public bool Meta(string line) => (bool)typeof(RynthAiPlugin).GetMethod("HandleMetaChatCommand", Any)!.Invoke(P, new object[] { line })!; + public int ChatWith(string text) => FakeHost.Chat.Count(c => c.Contains(text, StringComparison.OrdinalIgnoreCase)); + public int LogWith(string text) => FakeHost.Logs.Count(c => c.Contains(text, StringComparison.OrdinalIgnoreCase)); + public void Dispose() => GameInput.TestSink = null; + } + + private static readonly string[] KeyLines = + { + "/mt send enter", "/mt send msg hello", "/mt send cntrl+a", "/mt click ok", "/mt click 10 20", + "/mt movement w 100", "/mt strafe left 100", "/mt client minimize", "/mt client restore", "/mt jump 100", + }; + + private static void KeystrokesOffByDefault() + { + Check.False(new LegacyUiSettings().AllowMetaKeystrokes, "the setting defaults off"); + var w = new World(); + try + { + int before = GameInput.PostAttempts; + foreach (string line in KeyLines) + { + Check.True(w.Meta(line), line + " is handled (so it is not sent on as an unknown command)"); + w.Meta(line); // a meta pulse again + } + Check.Eq(w.Posted.Count, 0, "nothing reached the game window"); + Check.Eq(GameInput.PostAttempts - before, 0, "and nothing was even attempted"); + Check.Eq(w.ChatWith("'Allow metas to send keystrokes"), 6, "each of the six verbs says so once, however often a meta repeats it"); + Check.Eq(w.LogWith("'Allow metas to send keystrokes"), 6, "and logs it once"); + + // A chat command through /mt send is not a key press: it works either way. + w.Meta("/mt send /say hello"); + Check.True(FakeHost.ChatCommands.Contains("/say hello"), "/mt send /command still goes to the chat parser"); + Check.Eq(w.Posted.Count, 0, "and posted no key"); + + // Reading the cursor posts nothing, so it is not gated. + int chat = w.ChatWith("ignored"); + w.Meta("/mt get xy"); + Check.Eq(w.ChatWith("ignored"), chat, "/mt get xy is not refused"); + } + finally { w.Dispose(); } + } + + private static (LegacyUiSettings S, MetaManager M) Meta() + { + FakeHost.Reset(); + var s = new LegacyUiSettings(); + var m = new MetaManager(s, FakeHost.Create(), new PlayerVitalsCache()); + m.SetRaCommandHandler(_ => { }); + return (s, m); + } + + private static void VtConversionOnlyDocumentedNames() + { + var (s, m) = Meta(); + + // Documented: the VTank distance options (landblock units x240 = yards). + m.Expressions.Evaluate("vtsetsetting[AttackDistance,`0.025`]"); + Check.Eq(s.MonsterRange, 6, "AttackDistance 0.025 = 6 yd"); + m.TryHandleVtCommand("/vt opt set approachdistance 0.0175"); + Check.Eq(s.ApproachRange, 4, "approachdistance 0.0175 = 4 yd"); + + // RynthAi's own names (rasetsetting, or a direct setting name) keep their units: no x240. + s.CorpseApproachRangeMax = 3; + m.Expressions.Evaluate("rasetsetting[CorpseApproachRangeMax,`0.5`]"); + Check.Near(s.CorpseApproachRangeMax, 0.5, 1e-9, "rasetsetting CorpseApproachRangeMax 0.5 stays 0.5 yd"); + m.Expressions.Evaluate("vtsetsetting[CorpseApproachRangeMax,`0.5`]"); + Check.Near(s.CorpseApproachRangeMax, 0.5, 1e-9, "a RynthAi setting named directly is not a VTank distance"); + m.TryHandleVtCommand("/vt opt set follownavmin 0.5"); + Check.Near(s.FollowNavMin, 0.5, 1e-9, "follownavmin is RynthAi's own name, in yards"); + + // Options that are not distances are never scaled, whatever the value. + m.TryHandleVtCommand("/vt opt set minimumringtargets 1"); + Check.Eq(s.MinRingTargets, 1, "minimumringtargets 1 stays 1 (not 240)"); + m.Expressions.Evaluate("vtsetsetting[BlacklistMonsterTimeoutSeconds,`1`]"); + Check.Eq(s.BlacklistTimeoutSec, 1, "a timeout of 1 s stays 1"); + m.TryHandleVtCommand("/vt opt set rebufftimeremainingseconds 1"); + Check.Eq(s.RebuffSecondsRemaining, 1, "a seconds option of 1 stays 1"); + } + + private static void VtValuesAboveOneUnchanged() + { + var (s, m) = Meta(); + foreach (var (name, value, expect) in new[] { ("attackdistance", "25", 25), ("attackdistance", "1.5", 2), ("attackdistance", "50", 50), ("approachdistance", "30", 30), ("ringdistance", "6", 6) }) + { + m.TryHandleVtCommand($"/vt opt set {name} {value}"); + int got = name switch { "attackdistance" => s.MonsterRange, "approachdistance" => s.ApproachRange, _ => s.RingRange }; + Check.Eq(got, expect, $"{name} {value} is yards already -> {expect}"); + } + // And through the expression. + m.Expressions.Evaluate("vtsetsetting[AttackDistance,`40`]"); + Check.Eq(s.MonsterRange, 40, "vtsetsetting AttackDistance 40 stays 40 yd"); + // Zero is not a landblock fraction either. + m.Expressions.Evaluate("vtsetsetting[AttackDistance,`0`]"); + Check.Eq(s.MonsterRange, 0, "0 stays 0"); + // Read back in VTank units. + m.TryHandleVtCommand("/vt opt set attackdistance 24"); + Check.Eq(m.Expressions.Evaluate("vtgetsetting[AttackDistance]"), "0.1", "24 yd reads back as 0.1"); + } + + private static void VtLootOwnership() + { + var (s, m) = Meta(); + s.LootOwnership = 0; + m.TryHandleVtCommand("/vt opt set lootfellowcorpses true"); + Check.Eq(s.LootOwnership, 1, "lootfellowcorpses true: fellowship kills"); + m.TryHandleVtCommand("/vt opt set lootallcorpses true"); + Check.Eq(s.LootOwnership, 2, "lootallcorpses true: all corpses"); + m.TryHandleVtCommand("/vt opt set lootfellowcorpses false"); + Check.Eq(s.LootOwnership, 2, "lootfellowcorpses false leaves 'all corpses' alone"); + m.TryHandleVtCommand("/vt opt set lootallcorpses false"); + Check.Eq(s.LootOwnership, 0, "lootallcorpses false: my kills"); + s.LootOwnership = 1; + m.TryHandleVtCommand("/vt opt set lootallcorpses false"); + Check.Eq(s.LootOwnership, 1, "lootallcorpses false leaves 'fellowship kills' alone"); + m.TryHandleVtCommand("/vt opt set lootfellowcorpses false"); + Check.Eq(s.LootOwnership, 0, "lootfellowcorpses false: my kills"); + + // Other options never touch it, and an unreadable value is ignored. + s.LootOwnership = 2; + m.TryHandleVtCommand("/vt opt set lootonlyrarecorpses 1"); + m.TryHandleVtCommand("/vt opt set usearcs 0"); + m.TryHandleVtCommand("/vt opt set lootallcorpses banana"); + Check.Eq(s.LootOwnership, 2, "other options and junk values leave LootOwnership alone"); + } + + private static void KeystrokesWhenAllowed() + { + var w = new World(); + try + { + w.S.AllowMetaKeystrokes = true; + w.Meta("/mt send enter"); + Check.Eq(w.Posted.Count, 2, "send enter: key down and key up"); + w.Posted.Clear(); + w.Meta("/mt send msg hi"); + Check.Eq(w.Posted.Count, 4, "send msg hi: two keys, down and up"); + w.Posted.Clear(); + w.Meta("/mt click 10 20"); + Check.Eq(w.Posted.Count, 3, "click x y: move, down, up"); + w.Posted.Clear(); + w.Meta("/mt client minimize"); + Check.Eq(w.Posted.Count, 1, "client minimize"); + w.Posted.Clear(); + w.Meta("/mt movement w 0"); + Check.Eq(w.Posted.Count, 2, "movement w 0: pressed and released at once"); + w.Posted.Clear(); + w.Meta("/mt strafe right 0"); + Check.Eq(w.Posted.Count, 2, "strafe right 0"); + w.Posted.Clear(); + w.Meta("/mt jump"); + Check.Eq(w.Posted.Count, 2, "no jump hook: the space key"); + Check.Eq(w.ChatWith("Allow metas to send keystrokes"), 0, "nothing was refused"); + + // A held key is released from the plugin tick, not a timer, and never held for ever. + w.Posted.Clear(); + w.Meta("/mt movement w 99999999"); + Check.Eq(w.Posted.Count, 1, "held: only the key down so far"); + GameInput.Shutdown(); + Check.Eq(w.Posted.Count, 2, "Shutdown releases it at once"); + } + finally { w.Dispose(); } + } + + private static void MetaCannotEnableKeystrokes() + { + var w = new World(); + try + { + var m = new MetaManager(w.S, FakeHost.Create(playerId: Player), new PlayerVitalsCache()); + m.SetRaCommandHandler(_ => { }); + m.Expressions.Evaluate("rasetsetting[AllowMetaKeystrokes,`1`]"); + m.Expressions.Evaluate("vtsetsetting[AllowMetaKeystrokes,`1`]"); + m.TryHandleVtCommand("/vt opt set AllowMetaKeystrokes true"); + w.Mt("/mt opt set AllowMetaKeystrokes true"); + Check.False(w.S.AllowMetaKeystrokes, "no expression, /vt or /mt option can switch it on"); + w.Meta("/mt send enter"); + Check.Eq(w.Posted.Count, 0, "so the keys still go nowhere"); + } + finally { w.Dispose(); } + } + + private static void VendorTradeRefusedOutsideMeta() + { + var w = new World(tradeVendor: true); + try + { + w.S.IsMacroRunning = true; + w.S.EnableMeta = true; + w.Mt("/mt vendor addsell Faran Robe"); + Check.Eq(w.ChatWith("Sell list"), 1, "building the list is allowed from a typed line"); + + // Typed lines (the chat bar, a chat line, anything that is not a running meta). + Check.True(w.Mt("/mt trade accept"), "typed /mt trade accept is handled ..."); + Check.True(w.Mt("/mt vendor sell"), "typed /mt vendor sell ..."); + Check.True(w.Mt("/mt vendor buy"), "typed /mt vendor buy ..."); + Check.Eq(FakeHost.TradeActions.Count, 0, "... but accepted nothing"); + Check.Eq(FakeHost.VendorSells.Count, 0, "... sold nothing"); + Check.Eq(FakeHost.VendorBuys.Count, 0, "... bought nothing"); + Check.Eq(w.ChatWith("only runs from a meta that is running"), 3, "and said why, three times"); + + // A meta line while the macro or the Meta switch is off is not a running meta either. + w.S.IsMacroRunning = false; + w.Meta("/mt trade accept"); + w.Meta("/mt vendor sell"); + w.S.IsMacroRunning = true; + w.S.EnableMeta = false; + w.Meta("/mt trade accept"); + Check.Eq(FakeHost.TradeActions.Count, 0, "macro off or Meta off: no trade accept"); + Check.Eq(FakeHost.VendorSells.Count, 0, "macro off: no sale"); + Check.Eq(w.ChatWith("only runs from a meta that is running"), 6, "all refused with the reason"); + } + finally { w.Dispose(); } + } + + private static void VendorTradeFromRunningMeta() + { + var w = new World(tradeVendor: true); + try + { + w.S.IsMacroRunning = true; + w.S.EnableMeta = true; + Check.True(w.Meta("/mt trade accept"), "a running meta's trade accept"); + Check.Eq(FakeHost.TradeActions.Count(a => a == "accept"), 1, "is sent"); + Check.Eq(w.LogWith("/mt trade accept (from the running meta)"), 1, "with one log line"); + + w.Meta("/mt vendor addsell Faran Robe"); + Check.True(w.Meta("/mt vendor sell"), "a running meta's vendor sell"); + Check.Eq(FakeHost.VendorSells.Count, 1, "is sent once"); + Check.True(FakeHost.VendorSells[0].Items.SequenceEqual(new[] { Robe }), "with the listed item"); + Check.Eq(w.LogWith("/mt vendor sell (from the running meta)"), 1, "with one log line naming it"); + + // The other trade verbs do not need a meta. + int actions = FakeHost.TradeActions.Count; + w.Mt("/mt trade decline"); + Check.Eq(FakeHost.TradeActions.Count, actions + 1, "typed /mt trade decline still works"); + } + finally { w.Dispose(); } + } + + private static void VendorSellSkipsProtected() + { + var w = new World(tradeVendor: true); + try + { + w.S.IsMacroRunning = true; + w.S.EnableMeta = true; + w.Meta("/mt vendor addsell Worn Cloak"); + w.Meta("/mt vendor sell"); + Check.Eq(FakeHost.VendorSells.Count, 0, "an equipped item is never sold"); + Check.True(w.ChatWith("Nothing left to sell") == 1 && w.LogWith("equipped") >= 1, "and the skip is logged"); + + // An item RynthAi uses (the Weapons list) is never sold either; the others still are. + w.S.ItemRules.Add(new ItemRule { Id = unchecked((int)Sword), Name = "Sharp Sword" }); + w.Meta("/mt vendor addsell Sharp Sword"); + w.Meta("/mt vendor addsell Faran Robe"); + w.Meta("/mt vendor sell"); + Check.Eq(FakeHost.VendorSells.Count, 1, "one sale"); + Check.True(FakeHost.VendorSells[0].Items.SequenceEqual(new[] { Robe }), "of the robe only"); + } + finally { w.Dispose(); } + } +} diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/VitalsTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/VitalsTests.cs index 1b38277..b33d9ba 100644 --- a/Tools/RynthCore.RynthAiHostTests/Tests/VitalsTests.cs +++ b/Tools/RynthCore.RynthAiHostTests/Tests/VitalsTests.cs @@ -23,6 +23,8 @@ internal static class VitalsTests r.Add("vitals: Stamina to Health follows its own health line and stamina floor", StaminaToHealthThresholds); r.Add("vitals: profiles without the Stamina to Health keys load today's 30 / 20", StaminaToHealthDefaults); r.Add("vitals: Re-stam To keeps a started recharge going to its line; off = one recharge as before", RestamTo); + r.Add("vitals: a recharge started in a fight finishes to Re-stam To after the fight", RestamRunOutlivesFight); + r.Add("vitals: a Re-stam To run counts casts sent, not the ticks spent waiting for one", RestamRunCountsSentCasts); r.Add("vitals: out of Magic stance a listed stamina potion goes before Revitalize; a caster casts first", StaminaPotionFirst); r.Add("vitals: a listed potion whose stack ran out is drunk from the next stack of that name", ListedPotionNextStack); r.Add("vitals: after a kit, nothing else heals until the kit's result line lands", KitResultWait); @@ -321,6 +323,60 @@ internal static class VitalsTests Check.Eq(FakeHost.Casts.Count, 0, "no Revitalize while a tincture is carried"); } + // A recharge started in a fight finishes to Re-stam To when the fight ends, instead of dropping to + // a lower Top Stam (Drakkon: Re-stam At 35, To 90, Top Stam 60). + private static void RestamRunOutlivesFight() + { + var s = new LegacyUiSettings { RestamAt = 35, RestamTo = 90, TopOffStam = 60 }; + bool run = false; int casts = 0; + Check.Eq(BuffManager.StaminaLine(true, 30, s, ref run, ref casts), 90, "fight, 30%: recharge to 90"); + casts++; + Check.Eq(BuffManager.StaminaLine(false, 58, s, ref run, ref casts), 90, "fight over at 58%: the recharge still goes to 90"); + casts++; + Check.Eq(BuffManager.StaminaLine(false, 91, s, ref run, ref casts), 60, "reached 90: done, the top-off line again"); + Check.False(run, "the recharge ended"); + Check.Eq(BuffManager.StaminaLine(false, 55, s, ref run, ref casts), 60, "no recharge running: idle uses Top Stam"); + } + + // Drakkon, 2026-10-20: every Re-stam To run stopped after one Robustification. The stamina chain also + // answers "handled" while it waits for the last cast to finish, and each such tick counted as a cast: + // the 4-cast cap was reached during the first cast's 2.3 s. Only casts actually sent count now. + private static void RestamRunCountsSentCasts() + { + FakeHost.Reset(); + FakeHost.WeaponCalls = true; + FakeHost.ServerGates = true; + FakeHost.LastUseDoneCalls = true; + FakeHost.CombatModeValue = CombatMode.Magic; + foreach (var row in SpellTable.Rows) FakeHost.Spellbook.Add((uint)row.Id); + FakeHost.Skills[(Player, STypeLife)] = (400, 2); + var host = FakeHost.Create(); + var s = new LegacyUiSettings { IsMacroRunning = true, HealAt = 0, TopOffHP = 0, EmergencyHealAt = 0, StaminaToHealthAt = 0, + GetManaAt = 0, TopOffMana = 0, RestamAt = 35, RestamTo = 90, TopOffStam = 60, UsePotions = false, EnableBuffing = false, + SpellCastIntervalMs = 0 }; + var skills = new CharacterSkills(host); + skills.SetPlayerId(Player); + var sm = new SpellManager(host, s); + sm.InitializeNatively(); + sm.SetCharacterSkills(skills); + var vitals = new PlayerVitalsCache { MaxHealth = 100, CurrentHealth = 100, MaxStamina = 100, CurrentStamina = 30, MaxMana = 100, CurrentMana = 100 }; + var b = new BuffManager(host, s, sm, vitals) { InCombatOverride = () => true }; + b.SetCharacterSkills(skills); + + Check.True(b.CheckVitals(), "30% in a fight: the recharge starts"); + Check.Eq(FakeHost.Casts.Count, 1, "one Revitalize sent"); + for (int i = 0; i < 12; i++) b.CheckVitals(); // its 2.3 s: the server hasn't answered yet + Check.Eq(FakeHost.Casts.Count, 1, "nothing re-cast while the first is out"); + + string castName = SpellTableStub.GetById(FakeHost.Casts[0].SpellId)?.Name ?? "Revitalize Self"; + b.OnChatWindowText($"You cast {castName} and restore 25 points of your stamina.", 7); // the cast lands: +25 + FakeHost.UseDone(0); + vitals.CurrentStamina = 55; + System.Threading.Thread.Sleep(600); // real-time gaps between vital actions + Check.True(b.CheckVitals(), "55%: under Re-stam To, the run goes on"); + Check.Eq(FakeHost.Casts.Count, 2, "a second Revitalize (the waits didn't use up the run)"); + } + // Tom, 2026-10-06: one Revitalize often doesn't recover enough stamina. private static void RestamTo() { diff --git a/Tools/RynthCore.RynthAiTests/Program.cs b/Tools/RynthCore.RynthAiTests/Program.cs index e942b6f..c8c7a71 100644 --- a/Tools/RynthCore.RynthAiTests/Program.cs +++ b/Tools/RynthCore.RynthAiTests/Program.cs @@ -20,7 +20,6 @@ internal static class Program CreatureWeaknessTests.Register(runner); MonsterDamageTierTests.Register(runner); LootBaselineTests.Register(runner); - PetCaptureRulesTests.Register(runner); ChatClassifierTests.Register(runner); return runner.Run("RynthAi tests", args.Length > 0 ? args[0] : null); } diff --git a/Tools/RynthCore.RynthAiTests/RynthCore.RynthAiTests.csproj b/Tools/RynthCore.RynthAiTests/RynthCore.RynthAiTests.csproj index e6e6169..70b4055 100644 --- a/Tools/RynthCore.RynthAiTests/RynthCore.RynthAiTests.csproj +++ b/Tools/RynthCore.RynthAiTests/RynthCore.RynthAiTests.csproj @@ -30,7 +30,6 @@ - diff --git a/Tools/RynthILT.Tests/BreedingTests.cs b/Tools/RynthILT.Tests/BreedingTests.cs index 07b4b7d..5501050 100644 --- a/Tools/RynthILT.Tests/BreedingTests.cs +++ b/Tools/RynthILT.Tests/BreedingTests.cs @@ -12,7 +12,7 @@ namespace RynthILT.Tests; // The pet breeding tracker (IltBreedingRules / IltBreedingEssence / IltBreedingSupplies / IltPetBreeding): // the server's rules and where each value came from, the parsers for ACECustom's appraisal block, // chat and "@breed-debug" (formats copied from PetDevice_Breeding.cs / PetDevice_Maturity.cs), each -// breeding gate, the pair planner's odds, the supply refusals, and the "RynthILT.Data" v2 reader JSON. +// breeding gate, the pair planner's odds, the supply refusals, and the JSON RynthOracle reads. internal static class BreedingTests { public static void Register(Runner r) @@ -26,7 +26,7 @@ internal static class BreedingTests r.Add("breeding: each gate (charges, rest, growth, neutered, shiny, bond, tier, ID)", Gates); r.Add("breeding: pair planner blocks wrong sexes and ranges the inherited mutations", Planner); r.Add("breeding: supplies are refused where the server would refuse them", Supplies); - r.Add("breeding: reader JSON round-trips through the shared reader view", ReaderJson); + r.Add("breeding: reader JSON round-trips through RynthOracle's view", ReaderJson); r.Add("breeding: saved state survives the hub.json source-generated serializer", StateJson); r.Add("breeding: RynthILT.Data v2 keeps v1 readers working", DataApiVersion); } @@ -363,12 +363,15 @@ internal static class BreedingTests private static unsafe void DataApiVersion() { - Check.Eq(RynthIltDataApiV1.InterfaceVersion, 2u, "version 2"); - Check.True(RynthIltDataApiV1.V1Size < (uint)sizeof(RynthIltDataApiV1), "v2 appends to v1"); + // Version 3 (the Temple guardians) appends after the breeding pair; a v2 reader sees the same breeding layout. + Check.Eq(RynthIltDataApiV1.InterfaceVersion, 3u, "version 3"); + Check.True(RynthIltDataApiV1.V1Size < RynthIltDataApiV1.V2Size && RynthIltDataApiV1.V2Size < (uint)sizeof(RynthIltDataApiV1), + "v2 appends to v1, v3 to v2"); Check.Eq(RynthIltDataApiV1.V1Size, (uint)(8 + 4 * sizeof(IntPtr)), "v1 = two uints and four function pointers"); Check.True(DataInterface.Query(RynthIltDataApiV1.InterfaceName, 1) != IntPtr.Zero, "v1 readers still get the table"); Check.True(DataInterface.Query(RynthIltDataApiV1.InterfaceName, 2) != IntPtr.Zero, "v2 readers too"); - Check.True(DataInterface.Query(RynthIltDataApiV1.InterfaceName, 3) == IntPtr.Zero, "a future version isn't claimed"); + Check.True(DataInterface.Query(RynthIltDataApiV1.InterfaceName, 3) != IntPtr.Zero, "v3 readers too"); + Check.True(DataInterface.Query(RynthIltDataApiV1.InterfaceName, 4) == IntPtr.Zero, "a future version isn't claimed"); var t = (RynthIltDataApiV1*)DataInterface.Query(RynthIltDataApiV1.InterfaceName, 1); Check.True(t->GetPetBreedingJson != null && t->PetBreedingCommand != null, "breeding functions filled"); Check.Eq(RynthIltHub.SectionPetBreeding, "pets-breeding", "section id"); diff --git a/Tools/RynthILT.Tests/DataApiTests.cs b/Tools/RynthILT.Tests/DataApiTests.cs index 55d53da..3434c10 100644 --- a/Tools/RynthILT.Tests/DataApiTests.cs +++ b/Tools/RynthILT.Tests/DataApiTests.cs @@ -19,6 +19,7 @@ internal static class DataApiTests r.Add("data: the bank JSON reads back whole: characters (current first), choices, notes, log", BankRoundTrip); r.Add("data: the bank verb lines carry their fields in RunVerb's order", BankVerbs); r.Add("data: bad bank JSON reads as nothing", BankBadJson); + r.Add("data: the Temple guardian JSON reads back whole (switches, answer, hand-in, rows)", GuardianRoundTrip); // Last: Release() switches the table off for the rest of the process. r.Add("data: the RynthILT.Data table: query, functions, release", DataTable); } @@ -82,17 +83,53 @@ internal static class DataApiTests Check.True(empty.Loaded && !empty.Available && empty.Enabled == -1 && empty.Characters.Count == 0, "missing fields read as nothing known"); } + /// + /// Version 3: the guardian JSON RynthILT builds (IltGuardian.BuildJson) read back by the reader + /// RynthOracle's Quests tab uses, quotes and all. + /// + private static void GuardianRoundTrip() + { + var rows = new[] + { + new IltTempleAttrStatus("Strength", "Fiun \"Big\" Strongarm", 3, "Ready", "", true, true), + new IltTempleAttrStatus("Focus", "Fiun Thinker", 1, "Cooldown", "in 5h 2m", false, false), + }; + string json = IltGuardian.BuildJson("InfiniteLeaftide", chat: true, auto: false, buy: true, cooldownHours: 20, + answer: "Pyreal", npc: "Guardian of Attribute Enlightenment", answerAgeSec: 42, heard: "What is \"coin\"?", + running: true, status: "handing Pyreal to Guardian...", syncedUtc: new DateTime(2026, 10, 18, 19, 5, 0, DateTimeKind.Utc), rows); + Check.True(json.All(c => c >= 0x20 && c <= 0x7E), "plain printable ASCII"); + + IltGuardianView v = IltGuardianView.Parse(json); + Check.True(v.Loaded && v.Available && v.World == "InfiniteLeaftide", "loaded, the world"); + Check.True(v.Chat && !v.Auto && v.Buy && v.CooldownHours == 20, "the switches"); + Check.True(v.Answer == "Pyreal" && v.Npc == "Guardian of Attribute Enlightenment" && v.AnswerAgeSec == 42 && v.Heard == "What is \"coin\"?", + "the last answer"); + Check.True(v.Running && v.Status.StartsWith("handing Pyreal"), "the hand-in"); + Check.Eq(v.SyncedUtc, new DateTime(2026, 10, 18, 19, 5, 0, DateTimeKind.Utc), "the /qb read time"); + Check.Eq(v.Rows.Count, 2, "both rows"); + Check.True(v.Rows[0].Npc == "Fiun \"Big\" Strongarm" && v.Rows[0].Count == 3 && v.Rows[0].Ready && v.Rows[0].Exact, "an exact, ready row"); + Check.True(v.Rows[1].Eta == "in 5h 2m" && !v.Rows[1].Ready && !v.Rows[1].Exact, "an estimated row on cooldown"); + + IltGuardianView none = IltGuardianView.Parse(IltGuardian.BuildJson("x", false, false, false, 1, "", "", -1, "", false, "idle", + DateTime.MinValue, Array.Empty())); + Check.True(none.Answer.Length == 0 && none.AnswerAgeSec == -1 && none.SyncedUtc == DateTime.MinValue && none.Rows.Count == 0, + "no answer, no /qb read, no rows"); + } + private static unsafe void DataTable() { Check.Eq(DataInterface.Query("RynthILT.Hub", 1), IntPtr.Zero, "another interface's name: not ours"); - Check.Eq(DataInterface.Query(RynthIltDataApiV1.InterfaceName, 3), IntPtr.Zero, "a newer version than we have: none"); + Check.Eq(DataInterface.Query(RynthIltDataApiV1.InterfaceName, 4), IntPtr.Zero, "a newer version than we have: none"); var t = (RynthIltDataApiV1*)DataInterface.Query(RynthIltDataApiV1.InterfaceName, 1); Check.True(t != null, "v1 is served"); - Check.Eq(t->Version, 2u, "Version 2 (v1 readers take it: it starts with the v1 table)"); + Check.Eq(t->Version, 3u, "Version 3 (v1 and v2 readers take it: it starts with their tables)"); Check.Eq(t->StructSize, (uint)sizeof(RynthIltDataApiV1), "StructSize"); - Check.Eq(sizeof(RynthIltDataApiV1), 8 + 6 * IntPtr.Size, "header + 6 functions (v1's 4, then the breeding pair)"); + Check.Eq(sizeof(RynthIltDataApiV1), 8 + 8 * IntPtr.Size, "header + 8 functions (v1's 4, the breeding pair, the guardian pair)"); + Check.Eq(RynthIltDataApiV1.V1Size, (uint)(8 + 4 * IntPtr.Size), "a v1 table ends before the breeding pair"); + Check.Eq(RynthIltDataApiV1.V2Size, (uint)(8 + 6 * IntPtr.Size), "a v2 table ends before the guardian pair (readers still see breeding on it)"); Check.True(t->GetCharmsJson != null && t->GetBankJson != null && t->ToggleCharm != null && t->BankCommand != null - && t->GetPetBreedingJson != null && t->PetBreedingCommand != null, "every function is filled in"); + && t->GetPetBreedingJson != null && t->PetBreedingCommand != null + && t->GetGuardianJson != null && t->GuardianCommand != null, "every function is filled in"); Check.Eq((IntPtr)t, DataInterface.Query(RynthIltDataApiV1.InterfaceName, 1), "the same table each time"); // No plugin instance here (not logged in): nothing to report, every action refused. @@ -104,6 +141,8 @@ internal static class DataApiTests Check.Eq(t->BankCommand(verb), 0, "no bank command before login"); Check.Eq(t->GetPetBreedingJson(buf, 64), 0, "no breeding JSON before login"); Check.Eq(t->PetBreedingCommand(verb), 0, "no breeding command before login"); + Check.Eq(t->GetGuardianJson(buf, 64), 0, "no guardian JSON before login"); + Check.Eq(t->GuardianCommand(verb), 0, "no guardian command before login"); DataInterface.Release(); Check.Eq(t->Version, 0u, "Release zeroes Version (readers re-query)"); diff --git a/Tools/RynthILT.Tests/FakeAiHub.cs b/Tools/RynthILT.Tests/FakeAiHub.cs new file mode 100644 index 0000000..05092c6 --- /dev/null +++ b/Tools/RynthILT.Tests/FakeAiHub.cs @@ -0,0 +1,76 @@ +using System; +using System.Collections.Generic; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using RynthCore.Plugin.Shared; + +namespace RynthILT.Tests; + +/// +/// A stand-in for RynthAi's "RynthAi.Hub" table (Plugins/Shared/RynthAiHubApi.cs), so the tests can +/// check what RynthILT asks of RynthAi (RynthAiClient.UseTableForTests takes it). Only the functions +/// the moved features use answer anything; the rest are absent (null), as an old RynthAi's would be. +/// Reset() before each test that uses it. +/// +internal static unsafe class FakeAiHub +{ + /// BackAwayFrom calls (object, radius, hold), and what it answers. + public static readonly List<(uint Id, float Radius, int HoldMs)> BackAways = new(); + public static int BackAwayResult = RynthAiHub.BackAwayStarted; + /// SetPlayerCounter: the last value reported per counter id. + public static readonly Dictionary Counters = new(); + /// SessionStats: the shared session's start (0 = no session: SessionStats answers 0). + public static long SessionStartTicks; + + private static RynthAiHubApiV1* _table; + + public static void Reset() + { + BackAways.Clear(); + BackAwayResult = RynthAiHub.BackAwayStarted; + Counters.Clear(); + SessionStartTicks = 0; + } + + public static IntPtr Table + { + get + { + if (_table == null) + { + var t = (RynthAiHubApiV1*)NativeMemory.AllocZeroed((nuint)sizeof(RynthAiHubApiV1)); + t->StructSize = (uint)sizeof(RynthAiHubApiV1); + t->BackAwayFrom = &BackAwayFrom; + t->SetPlayerCounter = &SetPlayerCounter; + t->SessionStats = &SessionStats; + t->Version = RynthAiHubApiV1.InterfaceVersion; + _table = t; + } + return (IntPtr)_table; + } + } + + [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] + private static int SessionStats(SessionStatsV1* s) + { + if (SessionStartTicks == 0 || s == null) return 0; + *s = default; + s->StartUtcTicks = SessionStartTicks; + s->SessionSeconds = 60; + return 1; + } + + [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] + private static int SetPlayerCounter(uint id, long value) + { + Counters[id] = value; + return 1; + } + + [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] + private static int BackAwayFrom(uint id, float radius, int holdMs) + { + BackAways.Add((id, radius, holdMs)); + return BackAwayResult; + } +} diff --git a/Tools/RynthILT.Tests/FeatureCatalogTests.cs b/Tools/RynthILT.Tests/FeatureCatalogTests.cs index 227f2f5..5e73202 100644 --- a/Tools/RynthILT.Tests/FeatureCatalogTests.cs +++ b/Tools/RynthILT.Tests/FeatureCatalogTests.cs @@ -1,7 +1,9 @@ using System; using System.Text; +using System.Text.Json; using RynthCore.Plugin.RynthILT; using RynthCore.Plugin.RynthILT.Hub; +using RynthCore.Plugin.Shared; using RynthCore.RynthAiTests.Harness; namespace RynthILT.Tests; @@ -15,7 +17,10 @@ internal static class FeatureCatalogTests { r.Add("features: banking, guardian, attributes, augs, paragon x3, split arrows, T11 and fellowship are listed", Listed); r.Add("features: state follows the server bit on ILT, built-ins are on, nothing is known off ILT", States); + r.Add("features: profile JSON is valid ASCII with features and the fellowship rules", ProfileJson); r.Add("features: the interface copies the JSON only when it fits, NUL-terminated", InterfaceWrite); + r.Add("features: the /qb list rides the profile JSON on ILT worlds only", QuestBonusJson); + r.Add("features: the RynthILT.Server table: query, filled in, release", ServerTable); r.Add("features: the ILT profile is on with the world; a refusal in chat turns a feature off", ProfileOnWithTheWorld); r.Add("features: probed features read checking; options ILT runs off are off until chat shows them", ProbedAndOffInIlt); r.Add("features: charms are on with the ILT world unless refused; rows describe themselves", Charms); @@ -121,6 +126,75 @@ internal static class FeatureCatalogTests Check.Eq(IltFeatureCatalog.FellowshipMax(false), 9, "retail fellowships hold 9"); } + private static void ProfileJson() + { + string json = IltFeatureCatalog.BuildProfileJson(true, "Infinite \"Leaftide\"", false, "probe", + new DateTime(2026, 10, 13, 21, 25, 37, DateTimeKind.Utc), + key => key == IltFeature.FBlackjack ? IltTri.Off : IltTri.On); + bool ascii = true; + foreach (char c in json) if (c < 0x20 || c > 0x7E) ascii = false; + Check.True(ascii, "plain printable ASCII"); + + using JsonDocument doc = JsonDocument.Parse(json); + JsonElement root = doc.RootElement; + Check.True(root.GetProperty("ilt").GetBoolean(), "ilt"); + Check.Eq(root.GetProperty("world").GetString(), "Infinite \"Leaftide\"", "quotes in the world name survive"); + Check.Eq(root.GetProperty("checked").GetString(), "2026-10-13T21:25:37Z", "checked time in UTC"); + Check.Eq(root.GetProperty("features").GetArrayLength(), IltFeatureCatalog.All.Length, "every feature in the JSON"); + JsonElement fel = root.GetProperty("fellowship"); + Check.Eq(fel.GetProperty("maxMembers").GetInt32(), 29, "fellowship size"); + Check.Eq(fel.GetProperty("zoneShare").GetInt32(), 1, "Zone Share on (built in)"); + Check.Eq(fel.GetProperty("blackjack").GetInt32(), 0, "Fellowship Blackjack off (server bit)"); + + string off = IltFeatureCatalog.BuildProfileJson(false, "", false, "", DateTime.MinValue, _ => IltTri.On); + using JsonDocument d2 = JsonDocument.Parse(off); + Check.Eq(d2.RootElement.GetProperty("fellowship").GetProperty("maxMembers").GetInt32(), 9, "off ILT: retail size"); + Check.Eq(d2.RootElement.GetProperty("checked").GetString(), "", "never checked: empty time"); + } + + private static void QuestBonusJson() + { + var qb = new IltQuestBonusInfo(false, 2, 41, "2 completed, 1 incomplete", + new[] { "flag\"one", "flagTwo" }, new[] { "flagThree" }); + string json = IltFeatureCatalog.BuildProfileJson(true, "Infinite Leaftide", false, "probe", DateTime.MinValue, _ => IltTri.On, qb); + using JsonDocument doc = JsonDocument.Parse(json); + JsonElement q = doc.RootElement.GetProperty("questBonus"); + Check.False(q.GetProperty("disabled").GetBoolean(), "enabled"); + Check.Eq(q.GetProperty("generation").GetInt32(), 2, "generation"); + Check.Eq(q.GetProperty("count").GetInt64(), 41L, "count"); + Check.Eq(q.GetProperty("status").GetString(), "2 completed, 1 incomplete", "status"); + Check.Eq(q.GetProperty("completed").GetArrayLength(), 2, "completed flags"); + Check.Eq(q.GetProperty("completed")[0].GetString(), "flag\"one", "quotes in a flag survive"); + Check.Eq(q.GetProperty("incomplete")[0].GetString(), "flagThree", "incomplete flags"); + Check.True(doc.RootElement.TryGetProperty("fellowship", out _), "the fellowship rules are still there"); + + string off = IltFeatureCatalog.BuildProfileJson(false, "", false, "", DateTime.MinValue, _ => IltTri.On, qb); + using JsonDocument d2 = JsonDocument.Parse(off); + Check.False(d2.RootElement.TryGetProperty("questBonus", out _), "off ILT: no /qb list"); + } + + private static unsafe void ServerTable() + { + Check.Eq(ServerInterface.Query("RynthILT.Hub", 1), IntPtr.Zero, "another interface's name: not ours"); + Check.Eq(ServerInterface.Query(RynthIltServerApiV1.InterfaceName, 2), IntPtr.Zero, "a newer version than we have: none"); + var t = (RynthIltServerApiV1*)ServerInterface.Query(RynthIltServerApiV1.InterfaceName, 1); + Check.True(t != null && t->Version == 1 && t->StructSize == (uint)sizeof(RynthIltServerApiV1) && t->GetProfileJson != null, + "v1 is served and filled in"); + + // Before login the profile is the not-ILT default; the copy is NUL-terminated and valid JSON. + byte* buf = stackalloc byte[262144]; + int n = t->GetProfileJson(buf, 262144); + Check.True(n > 0 && n < 262144 && buf[n] == 0, "the default profile fits and is NUL-terminated"); + using JsonDocument doc = JsonDocument.Parse(Encoding.UTF8.GetString(buf, n)); + Check.False(doc.RootElement.GetProperty("ilt").GetBoolean(), "not an ILT world before login"); + Check.Eq(t->GetProfileJson(buf, 8), n, "too small: the length comes back"); + + ServerInterface.Release(); + Check.Eq(t->Version, 0u, "Release zeroes Version (readers re-query)"); + Check.Eq(t->GetProfileJson(buf, 64), 0, "answers 0 after release"); + Check.Eq(ServerInterface.Query(RynthIltServerApiV1.InterfaceName, 1), IntPtr.Zero, "not served after release"); + } + private static unsafe void InterfaceWrite() { const string json = "{\"ilt\":true}"; diff --git a/Tools/RynthILT.Tests/MoveTests.cs b/Tools/RynthILT.Tests/MoveTests.cs index fe838c5..f4d6c46 100644 --- a/Tools/RynthILT.Tests/MoveTests.cs +++ b/Tools/RynthILT.Tests/MoveTests.cs @@ -34,7 +34,7 @@ internal static class MoveTests r.Add("move: off ILT nothing is sent, no tab or section shows; on ILT the login probe runs", DormantOffIlt); r.Add("move: the charms JSON for RynthILT.Data readers carries the Guardian Hands", CharmsReaderJson); r.Add("move: Character redirects to RynthOracle; Charms and Banking stay RynthILT's tabs", MovedSections); - r.Add("sections: RynthILT's manifest (rates, /fship, /qb) is valid schema-1 JSON with its own surfaces", SectionsManifest); + r.Add("sections: RynthILT's manifest (rates, /fship, /qb, and the ILT tabs it shows) is valid schema-1 JSON the engine places", SectionsManifest); // Last: Release() switches the table off for the rest of the process. r.Add("move: the RynthILT.Hub table: query, functions, release", HubTable); } @@ -364,11 +364,28 @@ internal static class MoveTests { Check.Eq(sizeof(IltTabV1), 24 + 32 + 4 + 4 + 4, "IltTabV1: id, label, width, height, flags"); Check.Eq((int)Marshal.OffsetOf(nameof(IltTabV1.Flags)), 64, "IltTabV1.Flags offset"); - Check.Eq(sizeof(RynthIltHubApiV1), 8 + 9 * IntPtr.Size, "RynthIltHubApiV1: header + 9 functions"); + // RynthILT.Hub grew on 2026-10-20 (append-only): readers accept any table at least BaseStructSize + // long (the first release's 9 functions) and check the appended ones with Has. + Check.Eq((int)RynthIltHubApiV1.BaseStructSize, 8 + 9 * IntPtr.Size, "RynthIltHubApiV1.BaseStructSize: the first release's 9 functions"); + Check.Eq(RynthIltHubApiV1.AllowSummonOnEmptyOffset, 8 + 9 * IntPtr.Size, "AllowSummonOnEmpty right after Command"); + Check.Eq((int)Marshal.OffsetOf(nameof(RynthIltHubApiV1.AllowSummonOnEmpty)), RynthIltHubApiV1.AllowSummonOnEmptyOffset, + "AllowSummonOnEmptyOffset is where the field really is"); + Check.Eq((int)Marshal.OffsetOf(nameof(RynthIltHubApiV1.GetSubTabs)), RynthIltHubApiV1.GetSubTabsOffset, + "GetSubTabsOffset is where the field really is"); + Check.Eq((int)Marshal.OffsetOf(nameof(RynthIltHubApiV1.GetSetting)), RynthIltHubApiV1.GetSettingOffset, + "GetSettingOffset is where the field really is"); + Check.Eq((int)Marshal.OffsetOf(nameof(RynthIltHubApiV1.SetSetting)), RynthIltHubApiV1.SetSettingOffset, + "SetSettingOffset is where the field really is"); // SessionStatsMore was appended (2026-10-13); readers accept any table at least // BaseStructSize long, so an older RynthAi still connects. // VaultedDungeonsEnabled was appended (2026-10-18): the Vaulted Dungeons master switch. - Check.Eq(sizeof(RynthAiHubApiV1), 8 + 12 * IntPtr.Size, "RynthAiHubApiV1: header + 12 functions"); + // BackAwayFrom was appended (2026-10-20): the generic back-away RynthILT's Handler ring evade asks for. + // SetPlayerCounter too (2026-10-20): the T11 wield counters RynthILT reads from /aug. + Check.Eq(sizeof(RynthAiHubApiV1), 8 + 14 * IntPtr.Size, "RynthAiHubApiV1: header + 14 functions"); + Check.Eq((int)Marshal.OffsetOf(nameof(RynthAiHubApiV1.SetPlayerCounter)), RynthAiHubApiV1.SetPlayerCounterOffset, + "SetPlayerCounterOffset is where the field really is"); + Check.Eq((int)Marshal.OffsetOf(nameof(RynthAiHubApiV1.BackAwayFrom)), RynthAiHubApiV1.BackAwayFromOffset, + "BackAwayFromOffset is where the field really is"); Check.Eq((int)RynthAiHubApiV1.BaseStructSize, 8 + 10 * IntPtr.Size, "RynthAiHubApiV1.BaseStructSize: the first release's 10 functions"); Check.Eq(RynthAiHubApiV1.SessionStatsMoreOffset, (int)RynthAiHubApiV1.BaseStructSize, "SessionStatsMore right after the base table"); Check.Eq(RynthAiHubApiV1.VaultedDungeonsEnabledOffset, 8 + 11 * IntPtr.Size, "VaultedDungeonsEnabled right after SessionStatsMore"); @@ -456,12 +473,15 @@ internal static class MoveTests /// private static void SectionsManifest() { - using var doc = System.Text.Json.JsonDocument.Parse(RynthILTPlugin.SectionsJson); + // No Hub (before the character's name is known): the always-there views only. + string bare = IltSectionsManifest.Build(IltSectionsManifest.TabsOf(null)); + using var doc = System.Text.Json.JsonDocument.Parse(bare); var root = doc.RootElement; Check.Eq(root.GetProperty("version").GetInt32(), 1, "schema 1"); var sections = root.GetProperty("sections"); - Check.Eq(sections.GetArrayLength(), 1, "one section of RynthILT's own"); + Check.Eq(sections.GetArrayLength(), 2, "two sections of RynthILT's own"); Check.Eq(sections[0].GetProperty("id").GetString(), "quests", "a Quests section (the /qb list)"); + Check.Eq(sections[1].GetProperty("id").GetString(), "games", "and Games (moved from RynthAi with the tabs)"); var surfaces = new System.Collections.Generic.List(); foreach (var c in root.GetProperty("contributions").EnumerateArray()) { @@ -471,7 +491,38 @@ internal static class MoveTests Check.True(surfaces.SequenceEqual(new[] { RynthILTPlugin.RatesSurface, RynthILTPlugin.FellowshipSurface, RynthILTPlugin.QuestBonusSurface }), "rates, fellowship, quest bonus: " + string.Join(",", surfaces)); Check.True(surfaces.All(s => s.StartsWith("section:ilt-", StringComparison.Ordinal) && s.Length <= 64), "short section:ilt-* surfaces"); - Check.True(RynthILTPlugin.SectionsJson.All(ch => ch < 128), "ASCII only"); + Check.True(bare.All(ch => ch < 128), "ASCII only"); + + // The Mini Remote ILT tabs the Hub shows (RynthAi listed them until 2026-10-20): Gear not reported yet, + // Games hidden, Charms and Banking shown. + var tabs = new[] + { + new IltSectionsManifest.Tab("banking", 560, 520, Shown: true, Available: true), + new IltSectionsManifest.Tab("gear", 560, 520, Shown: true, Available: false), + new IltSectionsManifest.Tab("charms", 560, 520, Shown: true, Available: true), + new IltSectionsManifest.Tab("games", 520, 440, Shown: false, Available: false), + new IltSectionsManifest.Tab("character", 520, 440, Shown: true, Available: true), + }; + string json = IltSectionsManifest.Build(tabs); + var m = RynthCore.Engine.UI.Sections.SectionManifestParser.Parse("RynthILT", json, out string error); + Check.Eq(error, string.Empty, "the engine's parser takes it"); + Check.Eq(m.Contributions.Length, 6, "rates, fellowship, /qb, Banking, Gear, Charms"); + var gear = m.Contributions.Single(c => c.Surface == "section:gear"); + Check.True(gear.Section == "inventory" && !gear.Enabled && gear.Note.Length > 0, "Gear in Inventory, disabled with a note until reported"); + Check.True(m.Contributions.Any(c => c.Surface == "section:charms" && c.Enabled) && m.Contributions.Any(c => c.Surface == "section:banking" && c.Enabled), + "Charms and Banking stay RynthILT's tabs"); + Check.False(m.Contributions.Any(c => c.Surface == "section:games"), "a hidden tab isn't listed"); + Check.False(m.Contributions.Any(c => c.Surface == "section:character"), "Character moved out: never placed"); + var iltOn = new RynthCore.Engine.UI.Sections.ServerState("ilt", "Infinite Leaftide", true, true, RynthCore.Engine.UI.Sections.ServerForce.Auto, true, ""); + var on = RynthCore.Engine.UI.Sections.SectionCatalog.Build(new[] { m }, _ => false, new[] { iltOn }); + Check.True(on.Single(v => v.Id == "inventory").Panes.Any(p => p.Title == "Charms" && p.Contribution?.Plugin == "RynthILT"), + "on ILT the engine shows RynthILT's Charms in Inventory (drawn by RynthILT)"); + var off = RynthCore.Engine.UI.Sections.SectionCatalog.Build(new[] { m }, _ => false, new[] { iltOn with { Active = false } }); + Check.False(off.Single(v => v.Id == "inventory").Panes.Any(p => p.Title == "Charms"), "off ILT: none"); + Check.True(IltSectionsManifest.TryTabOf("section:banking", out IltSection bank) && bank == IltSection.Banking, "section:banking draws Banking"); + Check.False(IltSectionsManifest.TryTabOf("section:bank", out _), "only the tab's own id"); + Check.False(IltSectionsManifest.TryTabOf("section:pets", out _), "pets is RynthAi's"); + Check.False(IltSectionsManifest.TryTabOf("section:ilt-rates", out _), "not a tab"); Check.True(RynthILTPlugin.IsParsedRemoteAction("servermenu") && RynthILTPlugin.IsParsedRemoteAction("ServerMenu") && !RynthILTPlugin.IsParsedRemoteAction("prog"), "RynthCore's servermenu push is answered, never queued as a verb"); } @@ -520,8 +571,13 @@ internal static class MoveTests Check.Eq(t->Version, 1u, "Version 1"); Check.Eq(t->StructSize, (uint)sizeof(RynthIltHubApiV1), "StructSize"); Check.True(t->IsIltWorld != null && t->GetFeature != null && t->GetRates != null && t->GetForceIlt != null && t->SetForceIlt != null - && t->GetTabs != null && t->RenderTab != null && t->RenderSection != null && t->Command != null, "every function is filled in"); + && t->GetTabs != null && t->RenderTab != null && t->RenderSection != null && t->Command != null + && t->AllowSummonOnEmpty != null && t->GetSubTabs != null && t->GetSetting != null && t->SetSetting != null, + "every function is filled in"); + Check.True(RynthIltHubApiV1.Has(t, RynthIltHubApiV1.GetSubTabsOffset), "the appended functions are inside StructSize"); Check.Eq((IntPtr)t, HubInterface.Query(RynthIltHubApiV1.InterfaceName, 1), "the same table each time"); + Check.Eq((IntPtr)t, HubInterface.Query(RynthIltHubApiV1.NeutralInterfaceName, 1), + "and under the server-neutral name RynthAi asks the active server's owner for (RynthServer.Hub)"); // No plugin instance here (not logged in): every function answers "nothing". Check.Eq(t->IsIltWorld(), 0, "not ILT before login"); @@ -529,6 +585,11 @@ internal static class MoveTests Check.Eq(t->GetFeature(key), -1, "feature unknown before login"); Check.Eq(t->GetTabs(null, 0), 0, "no tabs before login"); Check.Eq(t->Command(key), 0, "no command taken before login"); + Check.Eq(t->AllowSummonOnEmpty(), 0, "no summon from empty before login"); + byte* pets = stackalloc byte[] { (byte)'p', (byte)'e', (byte)'t', (byte)'s', 0 }; + Check.Eq(t->GetSubTabs(pets, null, 0), 0, "no Pets sub-tabs before login"); + Check.Eq(t->GetSetting(pets), -1, "no setting offered before login"); + Check.Eq(t->SetSetting(pets, 1), 0, "and none taken"); HubInterface.Release(); Check.Eq(t->Version, 0u, "Release zeroes Version (callers re-query)"); diff --git a/Tools/RynthILT.Tests/PetAutomationTests.cs b/Tools/RynthILT.Tests/PetAutomationTests.cs new file mode 100644 index 0000000..463d274 --- /dev/null +++ b/Tools/RynthILT.Tests/PetAutomationTests.cs @@ -0,0 +1,189 @@ +using System; +using System.IO; +using System.Linq; +using RynthCore.Plugin.RynthILT.Hub; +using RynthCore.Plugin.Shared; +using RynthCore.RynthAiHostTests.Fakes; +using RynthCore.RynthAiTests.Harness; + +namespace RynthILT.Tests; + +// ACECustom's parts of RynthAi's Pets tab moved to RynthILT on 2026-10-20 (Hub/IltPetAutomation.cs): +// the pet charms, the summon-from-empty refill gate RynthAi's PetManager asks through RynthILT.Hub, +// siphon-lens auto-capture and the Breeding sub-tab offer. Their settings are copied once from the +// character's RynthAi miniremote.json (IltMigration.ImportRynthAiSettings). +internal static class PetAutomationTests +{ + private const uint Player = 0x50000A01; + private const uint Lens = 0x80000A02; + private const uint Mob = 0x80000A03; + private const uint Charm = 0x80000A04; + private const uint Lb = 0xA9B40000; + + public static void Register(Runner r) + { + r.Add("pets (RynthILT): summon from empty needs the opt-in, an active refill charm and the server's word; never off ILT", RefillGate); + r.Add("pets (RynthILT): auto-capture uses the lens on a weak creature in range only, and only when switched on", Capture); + r.Add("pets (RynthILT): the Breeding sub-tab is offered on ILT unless the server reports breeding off", BreedingSubTab); + r.Add("pets (RynthILT): off ILT the Pets sections draw nothing and nothing ticks", DormantOffIlt); + r.Add("migration: the Pets tab's ACECustom options come over from RynthAi's miniremote.json once", ImportsPetSettings); + } + + private static IltHubController NewHub(string world, string folder, Action? setup = null) + { + FakeHost.Reset(); + FakeHost.WorldName = world; + FakeHost.ContentsCalls = true; + FakeHost.WeaponCalls = true; // UseObject, RequestId, appraisal state + FakeHost.LiveObjectsCalls = true; + FakeHost.Names[Player] = "Petter"; + FakeHost.Positions[Player] = (Lb | 0x1C, 96f, 96f, 0f); + setup?.Invoke(); + var host = FakeHost.Create(Player); + string dir = Path.Combine(Program.TempRoot, "pets-" + folder); + if (Directory.Exists(dir)) Directory.Delete(dir, recursive: true); + Directory.CreateDirectory(dir); + var hub = new IltHubController(host, dir, new IltSettings(), new RynthAiClient(host)); + hub.OnLoginComplete("Petter", forceFromMigration: false); + return hub; + } + + private static void Carry(uint id, string name, uint wcid) + { + FakeHost.Names[id] = name; + FakeHost.ItemTypes[id] = 0x80; // misc + FakeHost.Containers[id] = Player; + FakeHost.Wcids[id] = wcid; + } + + private static void RefillGate() + { + var hub = NewHub("InfiniteLeaftide", "refill", () => FakeHost.Bools[(Player, IltInventory.BoolPyrealRefillActive)] = true); + var pets = hub.PetAutomation; + Check.False(pets.ComputeAllowSummonOnEmpty(), "not opted in: no summon from empty"); + hub.State.Pet.RefillFromEmpty = true; + Check.True(pets.ComputeAllowSummonOnEmpty(), "opted in, and the server stamped the refill bool (active and confirmed)"); + + var charmOnly = NewHub("InfiniteLeaftide", "refill-charm", () => + { + Carry(Charm, "Summon Essence Refill Charm", IltInventory.WcidSummonRefillCharm); + FakeHost.Strings[(Charm, IltInventory.StrUse)] = "Toggles the refill. Status: ON"; + }); + charmOnly.State.Pet.RefillFromEmpty = true; + Check.True(charmOnly.PetAutomation.RefillCharmActive(), "the carried charm reads ON"); + Check.False(charmOnly.PetAutomation.ComputeAllowSummonOnEmpty(), "but the server hasn't confirmed pet_refill: never spend"); + charmOnly.Options.Set(IltFeature.PetRefill, IltTri.On); + Check.True(charmOnly.PetAutomation.ComputeAllowSummonOnEmpty(), "confirmed: summon from empty"); + charmOnly.Tick(); + Check.True(charmOnly.PetAutomation.AllowSummonOnEmpty, "the tick caches it for RynthAi (RynthILT.Hub AllowSummonOnEmpty)"); + + var off = NewHub("Aeshnidae", "refill-off", () => FakeHost.Bools[(Player, IltInventory.BoolPyrealRefillActive)] = true); + off.State.Pet.RefillFromEmpty = true; + Check.False(off.PetAutomation.ComputeAllowSummonOnEmpty(), "off ILT: never"); + off.Tick(); + Check.False(off.PetAutomation.AllowSummonOnEmpty, "and nothing cached for RynthAi"); + } + + private static void Capture() + { + var hub = NewHub("InfiniteLeaftide", "capture", () => + { + Carry(Lens, "Flawed Siphon Lens", PetCaptureRules.Lenses[0].Wcid); + FakeHost.Names[Mob] = "Drudge Skulker"; + FakeHost.ItemTypes[Mob] = 0x10; // creature + FakeHost.Positions[Mob] = (Lb | 0x1C, 96f, 99f, 0f); // 3 m + FakeHost.TargetVitals[Mob] = (100, 100); + }); + var pets = hub.PetAutomation; + long now = Environment.TickCount64; // the chat replies time their back-off on the real clock + pets.TickCapture(now); + Check.Eq(FakeHost.Uses.Count, 0, "switched off: no lens used"); + Check.Eq(pets.CaptureStatus, "off", "status off"); + + hub.State.Pet.AutoCapture = true; + pets.TickCapture(now); + Check.Eq(FakeHost.Uses.Count, 0, "a full-health creature: no lens"); + Check.True(pets.CaptureStatus.Contains("Drudge Skulker") && pets.CaptureStatus.Contains("need"), "it says what it waits for"); + + FakeHost.TargetVitals[Mob] = (15, 100); + pets.TickCapture(now + 1000); + Check.Eq(FakeHost.Uses.Count, 1, "15%: the lens is used"); + Check.Eq(FakeHost.Uses[0], Lens, "the chosen lens"); + pets.TickCapture(now + 1500); + Check.Eq(FakeHost.Uses.Count, 1, "the cooldown holds the next use back"); + pets.OnChat("The creature is too strong to be siphoned."); + Check.True(pets.CaptureStatus.StartsWith("refused"), "a refusal is noted"); + + FakeHost.Positions[Mob] = (Lb | 0x1C, 96f, 110f, 0f); // 14 m + pets.TickCapture(now + 60_000); + Check.Eq(FakeHost.Uses.Count, 1, "out of range: no lens"); + + hub.Options.Set(RynthIltHub.FeatureMonsterCapture, IltTri.Off); + FakeHost.Positions[Mob] = (Lb | 0x1C, 96f, 99f, 0f); + pets.TickCapture(now + 120_000); + Check.Eq(FakeHost.Uses.Count, 1, "the server reports monster capture off: no lens"); + Check.True(pets.CaptureStatus.Contains("disabled"), "and says so"); + } + + private static void BreedingSubTab() + { + var on = NewHub("InfiniteLeaftide", "breed-on"); + var tabs = on.SubTabs(RynthIltHub.TabParentPets); + Check.Eq(tabs.Length, 1, "one Pets sub-tab on ILT"); + Check.Eq(tabs[0].Id, RynthIltHub.SectionPetBreeding, "Breeding, drawn as the pets-breeding section"); + Check.Eq(on.SubTabs("crafting").Length, 0, "nothing for another tab"); + on.Options.Set(RynthIltHub.FeaturePetBreeding, IltTri.Off); + Check.Eq(on.SubTabs(RynthIltHub.TabParentPets).Length, 0, "the server reports breeding off: none"); + + var off = NewHub("Aeshnidae", "breed-off"); + Check.Eq(off.SubTabs(RynthIltHub.TabParentPets).Length, 0, "off ILT: none"); + } + + private static void DormantOffIlt() + { + var off = NewHub("Aeshnidae", "dormant", () => + { + Carry(Lens, "Flawed Siphon Lens", PetCaptureRules.Lenses[0].Wcid); + FakeHost.Names[Mob] = "Drudge Skulker"; + FakeHost.ItemTypes[Mob] = 0x10; + FakeHost.Positions[Mob] = (Lb | 0x1C, 96f, 99f, 0f); + FakeHost.TargetVitals[Mob] = (1, 100); + }); + off.State.Pet.AutoCapture = true; + for (int i = 0; i < 5; i++) { off.Tick(); System.Threading.Thread.Sleep(60); } + Check.Eq(FakeHost.Uses.Count, 0, "off ILT the capture never ticks (no lens used)"); + Check.False(off.RenderSection(RynthIltHub.SectionPetCharms) || off.RenderSection(RynthIltHub.SectionPetCapture), + "the Pets sections draw nothing (checked before any ImGui call)"); + } + + private static void ImportsPetSettings() + { + string legacy = Path.Combine(IltMigration.LegacyProfilesBase, "InfiniteLeaftide", "Petter"); + Directory.CreateDirectory(legacy); + File.WriteAllText(Path.Combine(legacy, "Default.json"), "{}"); + File.WriteAllText(Path.Combine(legacy, IltMigration.LegacyMiniRemoteFile), + "{ \"Pet\": { \"HealingEnabled\": true, \"UsePyrealRefillPath\": true, \"AutoCaptureEnabled\": true, \"CaptureLensIndex\": 3 } }"); + var state = new IltHubState(); + Check.False(state.Pet.RefillFromEmpty || state.Pet.AutoCapture, "RynthILT's defaults: both off"); + var lines = IltMigration.ImportRynthAiSettings(state, "InfiniteLeaftide", "Petter"); + Check.True(state.RynthAiSettingsImported, "marked done"); + Check.True(state.Pet.RefillFromEmpty, "summon from empty came over"); + Check.True(state.Pet.AutoCapture, "auto-capture came over"); + Check.Eq(state.Pet.CaptureLens, 3, "the lens came over"); + Check.True(lines.Any(l => l.Contains("auto-capture on")), "and the log line says so"); + + state.Pet.AutoCapture = false; // changed in RynthILT afterwards + Check.Eq(IltMigration.ImportRynthAiSettings(state, "InfiniteLeaftide", "Petter").Count, 0, "the second login does nothing"); + Check.False(state.Pet.AutoCapture, "RynthILT's own change stays"); + + var fresh = new IltHubState(); + IltMigration.ImportRynthAiSettings(fresh, "InfiniteLeaftide", "Nobody"); + Check.True(fresh.RynthAiSettingsImported && !fresh.Pet.AutoCapture && !fresh.Pet.RefillFromEmpty, + "a character without RynthAi files keeps the defaults (and is marked done)"); + + File.WriteAllText(Path.Combine(legacy, IltMigration.LegacyMiniRemoteFile), "{ broken"); + var broken = new IltHubState(); + IltMigration.ImportRynthAiSettings(broken, "InfiniteLeaftide", "Petter"); + Check.True(broken.RynthAiSettingsImported && !broken.Pet.AutoCapture, "an unreadable miniremote.json: defaults, no exception"); + } +} diff --git a/Tools/RynthCore.RynthAiTests/Tests/PetCaptureRulesTests.cs b/Tools/RynthILT.Tests/PetCaptureRulesTests.cs similarity index 96% rename from Tools/RynthCore.RynthAiTests/Tests/PetCaptureRulesTests.cs rename to Tools/RynthILT.Tests/PetCaptureRulesTests.cs index efc9eab..3e523ce 100644 --- a/Tools/RynthCore.RynthAiTests/Tests/PetCaptureRulesTests.cs +++ b/Tools/RynthILT.Tests/PetCaptureRulesTests.cs @@ -1,8 +1,9 @@ // ACECustom MonsterCapture health / range / lens table — matches Source/ACE.Server/Entity/MonsterCapture.cs. -using RynthCore.Plugin.RynthAi.MiniRemote; +// Moved from RynthCore.RynthAiTests with the rules (RynthILT's IltPetCaptureRules since 2026-10-20). +using RynthCore.Plugin.RynthILT.Hub; using RynthCore.RynthAiTests.Harness; -namespace RynthCore.RynthAiTests.Tests; +namespace RynthILT.Tests; internal static class PetCaptureRulesTests { diff --git a/Tools/RynthILT.Tests/ProfileTests.cs b/Tools/RynthILT.Tests/ProfileTests.cs index 0f23642..c6237e0 100644 --- a/Tools/RynthILT.Tests/ProfileTests.cs +++ b/Tools/RynthILT.Tests/ProfileTests.cs @@ -18,6 +18,7 @@ internal static unsafe class ProfileTests { r.Add("profile: RynthILT serves RynthServer.Profile for ilt", Interface); r.Add("profile: ILT's salvage reaches the Crafting tab's reader (Leather after the cap, jewelry stack)", Salvage); + r.Add("profile: ILT's trinkets reach the Crafting tab's reader (RynthAi's TinkerCatalog rule until 2026-10-20)", Trinkets); } private static void Interface() @@ -45,6 +46,16 @@ internal static unsafe class ProfileTests "before the Hub is up: not active"); } + private static void Trinkets() + { + var rule = ServerTrinketRule.Parse(ProfileInterface.CurrentJson(true, "InfiniteLeaftide")); + Check.True(rule != ServerTrinketRule.None, "the profile carries a trinket rule"); + foreach (string t in new[] { "Ornate Compass", "Tinker's Goggles", "Jade Scarab", "Pocket Watch", "Puzzle Box", "Spinning Top" }) + Check.True(rule.IsTrinket(t), t + " is a trinket"); + foreach (string j in new[] { "Yellow Topaz Ring", "Gold Necklace", "Silver Bracelet" }) + Check.False(rule.IsTrinket(j), j + " is Jewelry"); + } + private static void Salvage() { var rows = ServerSalvageView.ParseList(ProfileInterface.CurrentJson(true, "InfiniteLeaftide")); diff --git a/Tools/RynthILT.Tests/Program.cs b/Tools/RynthILT.Tests/Program.cs index d0ffb62..bc3f213 100644 --- a/Tools/RynthILT.Tests/Program.cs +++ b/Tools/RynthILT.Tests/Program.cs @@ -48,6 +48,12 @@ internal static class Program ChunkTargetTests.Register(runner); RingChainTests.Register(runner); VaultedDungeonsTests.Register(runner); + PetCaptureRulesTests.Register(runner); + PetAutomationTests.Register(runner); + RingEvadeTests.Register(runner); + VaultedSwitchTests.Register(runner); + T11Tests.Register(runner); + RemoteTabTests.Register(runner); // Before DataApiTests: its last test releases the RynthILT.Data table, which the breeding version test queries. BreedingTests.Register(runner); DataApiTests.Register(runner); diff --git a/Tools/RynthILT.Tests/RemoteTabTests.cs b/Tools/RynthILT.Tests/RemoteTabTests.cs new file mode 100644 index 0000000..10a976f --- /dev/null +++ b/Tools/RynthILT.Tests/RemoteTabTests.cs @@ -0,0 +1,94 @@ +using System; +using System.IO; +using RynthCore.Plugin.RynthILT.Hub; +using RynthCore.Plugin.Shared; +using RynthCore.RynthAiHostTests.Fakes; +using RynthCore.RynthAiTests.Harness; + +namespace RynthILT.Tests; + +// The ILT parts of RynthAi's Remote tab moved to RynthILT on 2026-10-20: the coin / pyreal lines under +// RynthAi's Stats ("remote-stats"), the session report's tail (GetText "session-report"), the Bank and +// Guardian sections' switches (RynthILT's own now, drawn in RynthAi's Options popup, "remote-options"), +// and the coin session restarting with RynthAi's shared session instead of RynthAi sending "rates reset". +internal static class RemoteTabTests +{ + public static void Register(Runner r) + { + r.Add("remote tab (RynthILT): its texts for RynthAi (server id, the session report's coins) and none off ILT", Texts); + r.Add("remote tab (RynthILT): Bank / Guardian follow RynthILT's own switches; the stats and options draw nothing off ILT", Switches); + r.Add("remote tab (RynthILT): the coins start over when RynthAi's shared session restarts", FollowsSession); + r.Add("migration: RynthAi's huds.json Bank / Guardian switches come over once", ImportsSwitches); + } + + private static IltHubController NewHub(string world, string folder) + { + FakeHost.Reset(); + FakeAiHub.Reset(); + FakeHost.WorldName = world; + var host = FakeHost.Create(0x50000D21); + var ai = new RynthAiClient(host); + ai.UseTableForTests(FakeAiHub.Table); + string dir = Path.Combine(Program.TempRoot, "remote-" + folder); + if (Directory.Exists(dir)) Directory.Delete(dir, recursive: true); + Directory.CreateDirectory(dir); + var hub = new IltHubController(host, dir, new IltSettings(), ai); + hub.OnLoginComplete("Remoter", forceFromMigration: false); + return hub; + } + + private static void Texts() + { + var on = NewHub("InfiniteLeaftide", "texts-on"); + Check.Eq(on.GetText(RynthIltHub.TextServerId), "ilt", "its tabs belong to RynthCore's 'ilt'"); + string tail = on.GetText(RynthIltHub.TextSessionReport); + Check.True(tail.StartsWith(", Coins ") && tail.Contains("/h, Pyr "), "the session report's tail: coins and pyreals per hour"); + Check.Eq(on.GetText("no-such-text"), string.Empty, "an unknown id: nothing"); + + var off = NewHub("Aeshnidae", "texts-off"); + Check.Eq(off.GetText(RynthIltHub.TextSessionReport), string.Empty, "off ILT: no coins in RynthAi's report"); + } + + private static void Switches() + { + var on = NewHub("InfiniteLeaftide", "switches"); + Check.True(on.State.Remote.ShowBank && on.State.Remote.ShowGuardian, "both on by default"); + on.State.Remote.ShowBank = false; + on.State.Remote.ShowGuardian = false; + Check.False(on.RenderSection(RynthIltHub.SectionRemoteBank), "Bank switched off: nothing drawn"); + Check.False(on.RenderSection(RynthIltHub.SectionRemoteGuardian), "Guardian switched off: nothing drawn"); + + var off = NewHub("Aeshnidae", "switches-off"); + Check.False(off.RenderSection(RynthIltHub.SectionRemoteStats) || off.RenderSection(RynthIltHub.SectionRemoteOptions) + || off.RenderSection(RynthIltHub.SectionRemoteBank) || off.RenderSection(RynthIltHub.SectionRemoteGuardian), + "off ILT: none of the Remote tab's ILT parts draws (checked before any ImGui call)"); + } + + private static void FollowsSession() + { + var hub = NewHub("InfiniteLeaftide", "session"); + long t1 = DateTime.UtcNow.AddMinutes(-10).Ticks; + FakeAiHub.SessionStartTicks = t1; + long now = Environment.TickCount64; + hub.Rates.Tick(now); + DateTime first = hub.Rates.SessionStartUtc; + System.Threading.Thread.Sleep(30); + hub.Rates.Tick(now + 100); + Check.Eq(hub.Rates.SessionStartUtc, first, "the same shared session: no restart"); + FakeAiHub.SessionStartTicks = DateTime.UtcNow.Ticks; // RynthAi's Reset XP + hub.Rates.Tick(now + 200); + Check.True(hub.Rates.SessionStartUtc > first, "RynthAi's session restarted: the coins start over too"); + } + + private static void ImportsSwitches() + { + string legacy = Path.Combine(IltMigration.LegacyProfilesBase, "InfiniteLeaftide", "Remoter"); + Directory.CreateDirectory(legacy); + File.WriteAllText(Path.Combine(legacy, "Default.json"), "{}"); + File.WriteAllText(Path.Combine(legacy, IltMigration.LegacyHudsFile), "{ \"ShowMiniRemote\": true, \"MiniShowBank\": false }"); + var state = new IltHubState(); + IltMigration.ImportRynthAiSettings(state, "InfiniteLeaftide", "Remoter"); + Check.False(state.Remote.ShowBank, "Bank was hidden in RynthAi: hidden here"); + Check.True(state.Remote.ShowGuardian, "Guardian wasn't in the file: the default (shown)"); + } +} diff --git a/Tools/RynthILT.Tests/RingEvadeTests.cs b/Tools/RynthILT.Tests/RingEvadeTests.cs new file mode 100644 index 0000000..df992a7 --- /dev/null +++ b/Tools/RynthILT.Tests/RingEvadeTests.cs @@ -0,0 +1,134 @@ +using System; +using System.IO; +using System.Linq; +using RynthCore.Plugin.RynthILT.Hub; +using RynthCore.Plugin.Shared; +using RynthCore.RynthAiHostTests.Fakes; +using RynthCore.RynthAiTests.Harness; + +namespace RynthILT.Tests; + +// The Empyrean Handler's lethal ring (Hub/IltRingEvade.cs), RynthAi's CombatManager's until 2026-10-20 +// (Silentkelpie's PR 12). The line "The handler briefly channels infused Empyrean hatred to release a +// lethal ring." on an ILT world, with a Handler near, makes RynthILT ask RynthAi to back away from it +// (RynthAi.Hub BackAwayFrom, 12 yards, a 750 ms jump). The setting (on by default) is RynthILT's now, +// copied once from the RynthAi profile. +internal static class RingEvadeTests +{ + private const uint Player = 0x50000B01; + private const uint Handler = 0x80000B02; + private const uint Lb = 0xA9B40000; + private const string RingLine = "The handler briefly channels infused Empyrean hatred to release a lethal ring."; + + public static void Register(Runner r) + { + r.Add("ring evade (RynthILT): the Handler's line, and not a player's copy of it", ChannelLine); + r.Add("ring evade (RynthILT): on ILT with a Handler near, RynthAi is asked to back away (once per cooldown)", AsksRynthAi); + r.Add("ring evade (RynthILT): not with the setting off, no Handler near, off ILT, or without RynthAi", NotThese); + r.Add("migration: the RynthAi profile's Handler ring evade comes over once (on by default)", ImportsSetting); + } + + private static IltHubController NewHub(string world, string folder, bool handler = true, bool withAi = true, string handlerName = "Empyrean Handler") + { + FakeHost.Reset(); + FakeAiHub.Reset(); + FakeHost.WorldName = world; + FakeHost.ContentsCalls = true; + FakeHost.LiveObjectsCalls = true; + FakeHost.Names[Player] = "Evader"; + FakeHost.Positions[Player] = (Lb | 0x1C, 96f, 96f, 0f); + if (handler) + { + FakeHost.Names[Handler] = handlerName; + FakeHost.ItemTypes[Handler] = 0x10; + FakeHost.Positions[Handler] = (Lb | 0x1C, 96f, 101f, 0f); + } + var host = FakeHost.Create(Player); + var ai = new RynthAiClient(host); + if (withAi) ai.UseTableForTests(FakeAiHub.Table); + string dir = Path.Combine(Program.TempRoot, "ring-" + folder); + if (Directory.Exists(dir)) Directory.Delete(dir, recursive: true); + Directory.CreateDirectory(dir); + var hub = new IltHubController(host, dir, new IltSettings(), ai); + hub.OnLoginComplete("Evader", forceFromMigration: false); + return hub; + } + + private static void ChannelLine() + { + Check.True(IltRingEvade.IsChannelLine(RingLine, ChatSource.Emote), "the Handler's emote"); + Check.True(IltRingEvade.IsChannelLine("handler briefly channels infused Empyrean hatred to release a lethal ring.", 0x00), + "mid-line on a system line (a client that strips 'The ')"); + Check.False(IltRingEvade.IsChannelLine("Someone says, \"" + RingLine + "\"", ChatSource.Speech), "a player saying it"); + Check.False(IltRingEvade.IsChannelLine("Bob tells you, \"" + RingLine + "\"", 0x00), "a tell repeating it"); + Check.False(IltRingEvade.IsChannelLine("The handler waves.", ChatSource.Emote), "another Handler emote"); + } + + private static void AsksRynthAi() + { + var hub = NewHub("InfiniteLeaftide", "asks"); + hub.OnChat(RingLine, ChatSource.Emote); + Check.Eq(FakeAiHub.BackAways.Count, 1, "one back-away request"); + var (id, radius, hold) = FakeAiHub.BackAways[0]; + Check.Eq(id, Handler, "away from the Handler"); + Check.Eq(radius, IltRingEvade.DangerYards, "12 yards (RynthAi widens it to Ring Range)"); + Check.Eq(hold, IltRingEvade.JumpHoldMs, "a 750 ms jump"); + Check.True(hub.RingEvade.LastOutcome.Contains("backs away"), "logged"); + hub.OnChat(RingLine, ChatSource.Emote); + Check.Eq(FakeAiHub.BackAways.Count, 1, "a second line inside the cooldown asks nothing"); + + var outside = NewHub("InfiniteLeaftide", "outside"); + FakeAiHub.BackAwayResult = RynthAiHub.BackAwayOutside; + outside.OnChat(RingLine, ChatSource.Emote); + Check.Eq(FakeAiHub.BackAways.Count, 1, "RynthAi decides the radius"); + Check.True(outside.RingEvade.LastOutcome.Contains("outside"), "and its answer is logged"); + + var notFighting = NewHub("InfiniteLeaftide", "notnow"); + FakeAiHub.BackAwayResult = RynthAiHub.BackAwayNotNow; + notFighting.OnChat(RingLine, ChatSource.Emote); + Check.True(notFighting.RingEvade.LastOutcome.Contains("isn't fighting"), "RynthAi not fighting: it says so"); + } + + private static void NotThese() + { + var off = NewHub("InfiniteLeaftide", "setting-off"); + off.State.Combat.HandlerRingEvade = false; + off.OnChat(RingLine, ChatSource.Emote); + Check.Eq(FakeAiHub.BackAways.Count, 0, "setting off: nothing asked"); + + var none = NewHub("InfiniteLeaftide", "none", handlerName: "Drudge Skulker"); + none.OnChat(RingLine, ChatSource.Emote); + Check.Eq(FakeAiHub.BackAways.Count, 0, "no Empyrean Handler near: nothing asked"); + + var said = NewHub("InfiniteLeaftide", "said"); + said.OnChat("Someone says, \"" + RingLine + "\"", ChatSource.Speech); + Check.Eq(FakeAiHub.BackAways.Count, 0, "a player's copy: nothing asked"); + + var retail = NewHub("Aeshnidae", "retail"); + retail.OnChat(RingLine, ChatSource.Emote); + Check.Eq(FakeAiHub.BackAways.Count, 0, "off ILT: nothing asked"); + + var noAi = NewHub("InfiniteLeaftide", "noai", withAi: false); + noAi.OnChat(RingLine, ChatSource.Emote); + Check.True(noAi.RingEvade.LastOutcome.Contains("RynthAi"), "without RynthAi: said in the log, no crash"); + } + + private static void ImportsSetting() + { + Check.True(new IltHubState().Combat.HandlerRingEvade, "on by default"); + string legacy = Path.Combine(IltMigration.LegacyProfilesBase, "InfiniteLeaftide", "Evader"); + Directory.CreateDirectory(legacy); + File.WriteAllText(Path.Combine(legacy, "active_profile.txt"), "Farm"); + File.WriteAllText(Path.Combine(legacy, "Farm.json"), "{ \"HandlerRingEvade\": false, \"MonsterRange\": 30 }"); + var state = new IltHubState(); + IltMigration.ImportRynthAiSettings(state, "InfiniteLeaftide", "Evader"); + Check.False(state.Combat.HandlerRingEvade, "the active profile had it off: off here too"); + + string legacy2 = Path.Combine(IltMigration.LegacyProfilesBase, "InfiniteLeaftide", "Oldie"); + Directory.CreateDirectory(legacy2); + File.WriteAllText(Path.Combine(legacy2, "Default.json"), "{ \"MonsterRange\": 30 }"); + var old = new IltHubState(); + IltMigration.ImportRynthAiSettings(old, "InfiniteLeaftide", "Oldie"); + Check.True(old.Combat.HandlerRingEvade, "a profile from before the setting: on (the default)"); + } +} diff --git a/Tools/RynthILT.Tests/RynthILT.Tests.csproj b/Tools/RynthILT.Tests/RynthILT.Tests.csproj index f6c2e02..47e875b 100644 --- a/Tools/RynthILT.Tests/RynthILT.Tests.csproj +++ b/Tools/RynthILT.Tests/RynthILT.Tests.csproj @@ -53,6 +53,16 @@ + + + + + + + + + diff --git a/Tools/RynthILT.Tests/T11Tests.cs b/Tools/RynthILT.Tests/T11Tests.cs new file mode 100644 index 0000000..686edda --- /dev/null +++ b/Tools/RynthILT.Tests/T11Tests.cs @@ -0,0 +1,113 @@ +using System; +using System.IO; +using System.Linq; +using RynthCore.Loot.T11; +using RynthCore.Plugin.RynthILT; +using RynthCore.Plugin.RynthILT.Hub; +using RynthCore.RynthAiHostTests.Fakes; +using RynthCore.RynthAiTests.Harness; + +namespace RynthILT.Tests; + +// T11 (ACECustom tier 11+ gear) moved from RynthAi on 2026-10-20 (Hub/IltT11.cs): RynthILT reads the +// "/aug" reply's wield counters, applies its item-aug override and reports them to RynthAi's loot rules +// (RynthAi.Hub SetPlayerCounter); "/ilt t11" (and RynthAi's "/ra t11", passed on) shows and sets them. +internal static class T11Tests +{ + private const uint Player = 0x50000E01; + + public static void Register(Runner r) + { + r.Add("t11 (RynthILT): the /aug reply's counters go to RynthAi, with the item-aug override applied", ReportsCounters); + r.Add("t11 (RynthILT): /ilt t11 and /ra t11 are RynthILT's verbs; augs sets the override", Commands); + r.Add("t11 (RynthILT): off ILT nothing is read or reported", DormantOffIlt); + r.Add("migration: the RynthAi profile's T11 item-aug override comes over once", ImportsOverride); + } + + private static IltHubController NewHub(string world, string folder) + { + FakeHost.Reset(); + FakeAiHub.Reset(); + FakeHost.WorldName = world; + var host = FakeHost.Create(Player); + var ai = new RynthAiClient(host); + ai.UseTableForTests(FakeAiHub.Table); + string dir = Path.Combine(Program.TempRoot, "t11-" + folder); + if (Directory.Exists(dir)) Directory.Delete(dir, recursive: true); + Directory.CreateDirectory(dir); + var hub = new IltHubController(host, dir, new IltSettings(), ai); + hub.OnLoginComplete("Augger", forceFromMigration: false); + return hub; + } + + private static void ReportsCounters() + { + var hub = NewHub("InfiniteLeaftide", "report"); + hub.T11.Tick(Environment.TickCount64); + Check.Eq(FakeAiHub.Counters[(uint)T11Counter.ItemAugmentations], -1L, "unknown before /aug (reported as -1)"); + Check.Eq(hub.T11.LastReported, T11Catalog.CounterNames.Length, "every counter is reported"); + + hub.OnChat("Advanced Augmentation Levels:"); + hub.OnChat("Item:2,400"); + hub.OnChat("Triune Weave: 5 (adds 5 to your aug counts)"); + hub.T11.Tick(Environment.TickCount64); + Check.Eq(FakeAiHub.Counters[(uint)T11Counter.ItemAugmentations], 2400L, "Item: 2,400 reported"); + Check.Eq(FakeAiHub.Counters[(uint)T11Counter.TriuneWeave], 5L, "Triune Weave: 5 reported"); + + hub.State.T11.ItemAugsOverride = 2500; + hub.T11.Tick(Environment.TickCount64); + Check.Eq(FakeAiHub.Counters[(uint)T11Counter.ItemAugmentations], 2500L, "the override replaces /aug's item count"); + hub.State.T11.ItemAugsOverride = -1; + hub.T11.Tick(Environment.TickCount64); + Check.Eq(FakeAiHub.Counters[(uint)T11Counter.ItemAugmentations], 2400L, "auto again: /aug's count"); + + hub.OnLogout(); + hub.T11.Tick(Environment.TickCount64); + Check.Eq(FakeAiHub.Counters[(uint)T11Counter.ItemAugmentations], -1L, "after logout: unknown again"); + } + + private static void Commands() + { + Check.True(RynthILTPlugin.IsIltVerb(new[] { "t11" }), "/ra t11 is RynthILT's (RynthAi passes it on)"); + Check.True(RynthILTPlugin.IsIltVerb(new[] { "t11", "augs", "5" }), "with its arguments"); + Check.True(RynthILTPlugin.IsIltVerb(new[] { "ub", "qblist" }) && RynthILTPlugin.IsIltVerb(new[] { "ub", "augs" }), + "ub-IT's /ub qblist and /ub augs (ACECustom commands RynthAi passes on) are RynthILT's"); + Check.False(RynthILTPlugin.IsIltVerb(new[] { "ub", "wear" }) || RynthILTPlugin.IsIltVerb(new[] { "ub" }), "no other /ub verb"); + + var hub = NewHub("InfiniteLeaftide", "cmd"); + FakeHost.Chat.Clear(); + hub.T11.HandleCommand(new[] { "augs", "3,000" }); + Check.Eq(hub.State.T11.ItemAugsOverride, 3000, "augs 3,000 fixes the override"); + Check.Eq(FakeAiHub.Counters[(uint)T11Counter.ItemAugmentations], 3000L, "and reports it at once"); + hub.T11.HandleCommand(new[] { "augs", "auto" }); + Check.Eq(hub.State.T11.ItemAugsOverride, -1, "augs auto clears it"); + FakeHost.Chat.Clear(); + hub.T11.HandleCommand(Array.Empty()); + Check.True(FakeHost.Chat.Any(l => l.Contains("=== T11 loot")), "no argument: the status"); + Check.True(FakeHost.Chat.Any(l => l.Contains("Item Augmentations") || l.Contains("unknown")), "lists the counters"); + FakeHost.Chat.Clear(); + hub.T11.HandleCommand(new[] { "augs", "-5" }); + Check.True(FakeHost.Chat.Any(l => l.Contains("Usage")), "a bad count: usage"); + } + + private static void DormantOffIlt() + { + var off = NewHub("Aeshnidae", "off"); + off.OnChat("Advanced Augmentation Levels:"); + off.OnChat("Item:2,400"); + for (int i = 0; i < 3; i++) off.Tick(); + Check.Eq(FakeAiHub.Counters.Count, 0, "off ILT: no counter is reported to RynthAi"); + Check.True(off.T11.Player.Get(T11Counter.ItemAugmentations) == null, "nor read"); + } + + private static void ImportsOverride() + { + string legacy = Path.Combine(IltMigration.LegacyProfilesBase, "InfiniteLeaftide", "Augger"); + Directory.CreateDirectory(legacy); + File.WriteAllText(Path.Combine(legacy, "Default.json"), "{ \"T11ItemAugsOverride\": 2750 }"); + var state = new IltHubState(); + Check.Eq(state.T11.ItemAugsOverride, -1, "automatic by default"); + IltMigration.ImportRynthAiSettings(state, "InfiniteLeaftide", "Augger"); + Check.Eq(state.T11.ItemAugsOverride, 2750, "the RynthAi profile's override came over"); + } +} diff --git a/Tools/RynthILT.Tests/VaultedSwitchTests.cs b/Tools/RynthILT.Tests/VaultedSwitchTests.cs new file mode 100644 index 0000000..bf19e76 --- /dev/null +++ b/Tools/RynthILT.Tests/VaultedSwitchTests.cs @@ -0,0 +1,64 @@ +using System; +using System.IO; +using RynthCore.Plugin.RynthILT.Hub; +using RynthCore.Plugin.Shared; +using RynthCore.RynthAiHostTests.Fakes; +using RynthCore.RynthAiTests.Harness; + +namespace RynthILT.Tests; + +// The Vaulted Dungeons keeper's master switch moved from RynthAi's profile to RynthILT on 2026-10-20 +// (IltHubState.VaultedDungeonsEnabled, the ILT settings view). RynthAi mirrors it into the engine's +// Settings > Navigation row through RynthILT.Hub GetSetting / SetSetting, which offer it on ILT only. +internal static class VaultedSwitchTests +{ + public static void Register(Runner r) + { + r.Add("vaulted switch: RynthILT's own (off by default), what the keeper reads, offered to the engine row on ILT only", OwnSwitch); + r.Add("migration: the RynthAi profile's Vaulted Dungeons switch comes over once", ImportsSwitch); + } + + private static IltHubController NewHub(string world, string folder) + { + FakeHost.Reset(); + FakeHost.WorldName = world; + var host = FakeHost.Create(0x50000C01); + string dir = Path.Combine(Program.TempRoot, "vswitch-" + folder); + if (Directory.Exists(dir)) Directory.Delete(dir, recursive: true); + Directory.CreateDirectory(dir); + var hub = new IltHubController(host, dir, new IltSettings(), new RynthAiClient(host)); + hub.OnLoginComplete("Vaulter", forceFromMigration: false); + return hub; + } + + private static void OwnSwitch() + { + var hub = NewHub("InfiniteLeaftide", "own"); + Check.False(hub.State.VaultedDungeonsEnabled, "off by default"); + Check.False(hub.VaultedDungeons.MasterEnabled(), "the keeper reads RynthILT's own switch (no RynthAi needed)"); + Check.False(hub.SectionAvailable(IltSection.VaultedDungeons), "no tab while off"); + Check.Eq(hub.GetSetting(RynthIltHub.SettingVaultedDungeons), 0, "offered to the engine row: off"); + Check.True(hub.SetSetting(RynthIltHub.SettingVaultedDungeons, 1), "the engine row (through RynthAi) sets it"); + Check.True(hub.State.VaultedDungeonsEnabled && hub.VaultedDungeons.MasterEnabled(), "on"); + Check.True(hub.SectionAvailable(IltSection.VaultedDungeons), "the tab shows on ILT"); + Check.Eq(hub.GetSetting("no-such-setting"), -1, "an unknown key isn't offered"); + Check.False(hub.SetSetting("no-such-setting", 1), "nor taken"); + + var off = NewHub("Aeshnidae", "off"); + Check.Eq(off.GetSetting(RynthIltHub.SettingVaultedDungeons), -1, "off ILT: not offered (the engine row hides)"); + } + + private static void ImportsSwitch() + { + string legacy = Path.Combine(IltMigration.LegacyProfilesBase, "InfiniteLeaftide", "Vaulter"); + Directory.CreateDirectory(legacy); + File.WriteAllText(Path.Combine(legacy, "Default.json"), "{ \"EnableVaultedDungeons\": true }"); + var state = new IltHubState(); + var lines = IltMigration.ImportRynthAiSettings(state, "InfiniteLeaftide", "Vaulter"); + Check.True(state.VaultedDungeonsEnabled, "on in the RynthAi profile: on here"); + Check.True(lines.Exists(l => l.Contains("Vaulted Dungeons master switch on")), "logged"); + state.VaultedDungeonsEnabled = false; + IltMigration.ImportRynthAiSettings(state, "InfiniteLeaftide", "Vaulter"); + Check.False(state.VaultedDungeonsEnabled, "copied once: RynthILT's later change stays"); + } +} diff --git a/Tools/RynthInventory.Tests/Program.cs b/Tools/RynthInventory.Tests/Program.cs index 026e083..0f9496f 100644 --- a/Tools/RynthInventory.Tests/Program.cs +++ b/Tools/RynthInventory.Tests/Program.cs @@ -64,7 +64,9 @@ namespace RynthInventory.Tests Run("scheduler: unchanged content is not rewritten", SchedulerUnchanged); Run("window display lists parse in the engine", Pages); Run("window events", Events); - Run("vault feed (/mule-data)", VaultTests); + Run("banking: roster, totals and amounts", BankRosterTests); + Run("banking: the tab draws and sends RynthILT's verbs", BankingTab); + Run("storage from other plugins (StorageFeed)", StorageFeedTests); } finally { @@ -633,6 +635,103 @@ namespace RynthInventory.Tests ParseAll(host, "after forget", out _); } + // ── Banking (the Mini Remote's Banking tab moved here 2026-10-13) ─── + + /// RynthILT's bank JSON for the sample index: Buffy (here) and Ghost (another account, no inventory file). + private const string BankJson = "{\"available\":true,\"enabled\":1,\"world\":\"Aelrynth\",\"character\":\"Buffy\"," + + "\"characters\":[{\"name\":\"Buffy\",\"current\":true,\"pyreals\":100,\"luminance\":2000,\"legendaryKeys\":1,\"mythicalKeys\":0," + + "\"enlightenedCoins\":3,\"weaklyEnlightenedCoins\":0,\"prestigeCoins\":0,\"updated\":\"2026-10-03T11:00:00Z\"}," + + "{\"name\":\"Ghost\",\"current\":false,\"pyreals\":50,\"luminance\":0,\"legendaryKeys\":2,\"mythicalKeys\":1," + + "\"enlightenedCoins\":0,\"weaklyEnlightenedCoins\":4,\"prestigeCoins\":5,\"updated\":\"2026-10-01T11:00:00Z\"}]," + + "\"deposits\":[\"Everything\",\"Pyreals\"],\"withdrawals\":[{\"label\":\"Pyreals\",\"notes\":false},{\"label\":\"Trade notes\",\"notes\":true}]," + + "\"transfers\":[{\"label\":\"Pyreals\",\"notes\":false}],\"notes\":[{\"label\":\"MMD\",\"value\":250000}]," + + "\"result\":\"Deposited everything.\",\"transactions\":[{\"when\":\"2026-10-03 11:30\",\"type\":\"Sent\",\"amount\":10,\"currency\":\"Pyreals\",\"player\":\"Willow\"}]}"; + + private static void BankRosterTests() + { + InventoryIndex index = SampleIndex(out _); + var bank = RynthCore.Plugin.Shared.IltBankView.Parse(BankJson); + List roster = BankRoster.Build(bank, index); + Eq(string.Join(",", roster.Select(e => e.Name)), "Buffy,Ghost,Willow", "you first, then by name; Conquest's characters left out"); + Check(roster[0].Current && roster[0].Bank != null && roster[0].Account == "tom", "Buffy: RynthILT's balance and the inventory's account"); + Check(roster[1].Bank != null && roster[1].Account == "", "Ghost: only RynthILT knows it (another account on this PC)"); + Check(roster[2].Bank == null && roster[2].Account == "tom", "Willow: in the inventory, no bank read yet"); + var total = BankRoster.Totals(roster); + Check(total.Pyreals == 150 && total.Luminance == 2000 && total.LegendaryKeys == 3 && total.PrestigeCoins == 5, "totals add every balance"); + + Eq(BankRoster.Build(RynthCore.Plugin.Shared.IltBankView.None, null).Count, 0, "nothing without RynthILT or the index"); + var noWorld = RynthCore.Plugin.Shared.IltBankView.Parse("{\"available\":true,\"characters\":[]}"); + Eq(string.Join(",", BankRoster.Build(noWorld, index).Select(e => e.Name)), "Buffy,Willow", "no world named: the server you're on"); + + Eq(BankRoster.ParseAmount("1,000"), 1000L, "commas allowed"); + Eq(BankRoster.ParseAmount(" 25 "), 25L, "spaces trimmed"); + foreach (string bad in new[] { "", "0", "-5", "1.5", "abc", "1e6" }) + Eq(BankRoster.ParseAmount(bad), 0L, $"'{bad}' isn't an amount"); + } + + private static void BankingTab() + { + InventoryContext c = Context(false); + var sent = new List(); + c.BankCommand = v => { sent.Add(v); return true; }; + var view = new InventoryView(c); + var host = new UiHost(); + UiWindow w = host.Add(new UiWindow("RynthInventory/Main", "Global Inventory") { Visible = true }); + + // Without RynthILT the tab button stays hidden; /ginv bank still opens it and says why. + Draw(w, view); + Check(!BodyText(w).Contains("###tab.bank"), "no Banking button without RynthILT"); + view.ShowBanking(); + Draw(w, view); + Check(BodyText(w).Contains("Load RynthILT"), "asked for: says RynthILT is needed"); + w.MarkSubmitted(true); + + c.Bank = RynthCore.Plugin.Shared.IltBankView.Parse(BankJson); + view.Tab = InventoryView.TabSearch; + Draw(w, view); + Check(BodyText(w).Contains("###tab.bank"), "the Banking button shows on an ILT world"); + Apply(host, Event(1, 1, w.Hash, w.KeyOf("tab.bank"), new byte[] { 1, 0 })); + Check(view.Tab == InventoryView.TabBanking, "a click opens it"); + Draw(w, view); + ParseAll(host, "banking tab", out int ops); + string body = BodyText(w); + Check(ops > 5 && ops <= 1500, $"banking tab: {ops} ops"); + Check(body.Contains("Buffy (you)") && body.Contains("Ghost") && body.Contains("Willow") && !body.Contains("Spike"), + "every character on this server, none from another"); + Check(body.Contains("not read yet"), "a character without a balance says so"); + Check(body.Contains("150") && body.Contains("Deposited everything."), "the total and RynthILT's last reply"); + + Apply(host, Event(1, 2, w.Hash, w.KeyOf("b.dep.go"), new byte[] { 1, 0 })); + Eq(sent.LastOrDefault(), "deposit 0", "Deposit sends the chosen deposit"); + + Apply(host, Event(5, 3, w.Hash, w.KeyOf("b.wd.amt"), TextPayload("5"))); + Draw(w, view); + Apply(host, Event(1, 4, w.Hash, w.KeyOf("b.wd.go"), new byte[] { 1, 0 })); + Eq(sent.LastOrDefault(), "withdraw 0 5 0", "Withdraw sends currency, amount and note"); + + // A transfer asks first; only "Yes, send" sends it. + Apply(host, Event(5, 5, w.Hash, w.KeyOf("b.tx.amt"), TextPayload("1,000"))); + Apply(host, Event(5, 6, w.Hash, w.KeyOf("b.tx.to"), TextPayload("Willow"))); + Draw(w, view); + int before = sent.Count; + Apply(host, Event(1, 7, w.Hash, w.KeyOf("b.tx.go"), new byte[] { 1, 0 })); + Check(sent.Count == before, "one click doesn't transfer"); + Draw(w, view); + Check(BodyText(w).Contains("Send 1,000 Pyreals to Willow?"), "it asks, naming amount and recipient"); + Apply(host, Event(1, 8, w.Hash, w.KeyOf("b.tx.yes"), new byte[] { 1, 0 })); + Eq(sent.LastOrDefault(), "transfer 0 1000 0 Willow", "confirmed: the transfer verb"); + + // A bad amount is refused here, nothing sent. + Apply(host, Event(5, 9, w.Hash, w.KeyOf("b.wd.amt"), TextPayload("lots"))); + Draw(w, view); + before = sent.Count; + Apply(host, Event(1, 10, w.Hash, w.KeyOf("b.wd.go"), new byte[] { 1, 0 })); + Check(sent.Count == before, "a bad amount isn't sent"); + Draw(w, view); + Check(BodyText(w).Contains("Type a whole number"), "and it says why"); + ParseAll(host, "banking after actions", out _); + } + // ── Helpers ───────────────────────────────────────────────────────── private static void Draw(UiWindow w, InventoryView view) diff --git a/Tools/RynthInventory.Tests/RynthInventory.Tests.csproj b/Tools/RynthInventory.Tests/RynthInventory.Tests.csproj index 8066d73..f97d7eb 100644 --- a/Tools/RynthInventory.Tests/RynthInventory.Tests.csproj +++ b/Tools/RynthInventory.Tests/RynthInventory.Tests.csproj @@ -30,7 +30,9 @@ - + + + diff --git a/Tools/RynthInventory.Tests/StorageFeedTests.cs b/Tools/RynthInventory.Tests/StorageFeedTests.cs new file mode 100644 index 0000000..fd5f96e --- /dev/null +++ b/Tools/RynthInventory.Tests/StorageFeedTests.cs @@ -0,0 +1,79 @@ +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.Linq; +using System.Runtime.CompilerServices; +using RynthCore.Plugin.RynthInventory; +using RynthCore.Plugin.RynthInventory.Data; +using RynthCore.Plugin.Shared; + +namespace RynthInventory.Tests +{ + // Storage another plugin reads for RynthInventory (Plugins/Shared/StorageFeed.cs): since 2026-10-20 + // Aelrynth's account vault comes from RynthAelrynth (which reads /mule-data) instead of RynthInventory + // asking every server for it. RynthInventory only takes "storage" records and files them. + internal static partial class Program + { + [UnsafeAccessor(UnsafeAccessorKind.Field, Name = "_storagePushes")] + private static extern ref ConcurrentQueue StoragePushes(RynthInventoryPlugin p); + + private static StorageFeedRecord Feed(uint id, string name, params StorageFeedItem[] items) => new(id, name, "Account vault", items); + + private static void StorageFeedTests() + { + var vaultItem = new StorageFeedItem(2147483649u, 100, "Acid Assagai", 100667000, 100667001, 100667002, 3, 100, 1); + var coin = new StorageFeedItem(2147483650u, 101, "Pyreal", 100667003, 0, 0, 0, 0, 8192); + + // The payload round-trips and becomes an ordinary storage record. + StorageFeedRecord? feed = StorageFeed.Parse(StorageFeed.ToJson(Feed(0xFF123456u, "Aelrynth vault", vaultItem, coin)), out string error); + Check(feed != null && error == "", "a sender's payload parses: " + error); + StorageRecord rec = ExternalStorage.ToRecord(feed!, Now); + Eq(rec.Id, 0xFF123456u, "id kept"); + Eq(rec.Name, "Aelrynth vault", "name"); Eq(rec.Label, "Account vault", "label"); Eq(rec.Cell, 0u, "no cell (not a place in the world)"); + Eq(rec.SeenUtc, Now, "seen now"); + Eq(rec.Items.Count, 2, "items"); + ItemRecord a = rec.Items[0]; + Eq(a.Name, "Acid Assagai", "name"); Eq(a.Icon, 100667000u, "icon"); Eq(a.Underlay, 100667001u, "underlay"); + Eq(a.Overlay, 100667002u, "overlay"); Eq(a.Stack, 3, "stack"); Eq(a.MaxStack, 100, "max stack"); + Eq(a.Place, ItemPlace.Storage, "place"); + Eq(a.Category, ItemCategory.FromItemType(1), "category from the item type"); + Eq(rec.Items[1].Stack, 1, "a stack of 0 is a stack of 1"); + + // Filed with the character's storage: the same id replaces, a new one adds. + var storage = new List { new() { Id = 77, Name = "Chest", Label = "Chest", Items = { Item(1, "Sword") } } }; + List once = ExternalStorage.FileInto(storage, rec); + Eq(once.Count, 2, "added beside the opened chest"); + StorageRecord newer = ExternalStorage.ToRecord(Feed(0xFF123456u, "Aelrynth vault", coin), Now.AddMinutes(10)); + List twice = ExternalStorage.FileInto(once, newer); + Eq(twice.Count, 2, "the newer copy replaces the older"); + Eq(twice.Single(s => s.Id == 0xFF123456u).Items.Count, 1, "with its own contents"); + Eq(storage.Count, 1, "the old list is left alone (snapshots are never changed)"); + + // Anything unusable is refused, never filed. + Check(StorageFeed.Parse(null, out _) == null && StorageFeed.Parse("", out _) == null, "empty"); + Check(StorageFeed.Parse("{not json", out string bad) == null && bad.StartsWith("bad JSON", StringComparison.Ordinal), "broken JSON"); + Check(StorageFeed.Parse("{\"v\":1,\"id\":77,\"name\":\"Chest\",\"items\":[]}", out string real) == null && real.Contains("stand-in"), + "a real object's id can't be overwritten"); + Check(StorageFeed.Parse("{\"v\":2,\"id\":4278190081,\"name\":\"X\",\"items\":[]}", out _) == null, "a newer format is refused"); + Check(StorageFeed.Parse("{\"v\":1,\"id\":4278190081,\"name\":\" \",\"items\":[]}", out _) == null, "a store needs a name"); + string many = "{\"v\":1,\"id\":4278190081,\"name\":\"X\",\"items\":[" + string.Join(",", Enumerable.Repeat("{\"o\":1}", StorageFeed.MaxItems + 1)) + "]}"; + Check(StorageFeed.Parse(many, out _) == null, "too many items"); + + // The receiver: only "storage" is taken, and only the newest few are kept until the tick files them. + var plugin = new RynthInventoryPlugin(); + string json = StorageFeed.ToJson(Feed(0xFF000001u, "Aelrynth vault", coin)); + plugin.ApplyRemoteCommand("something-else", json); + Eq(StoragePushes(plugin).Count, 0, "other commands are ignored"); + plugin.ApplyRemoteCommand("storage", ""); + Eq(StoragePushes(plugin).Count, 0, "an empty payload is ignored"); + for (int i = 0; i < 20; i++) plugin.ApplyRemoteCommand("storage", json); + Check(StoragePushes(plugin).Count is > 0 and <= 8, $"queued, capped ({StoragePushes(plugin).Count})"); + + // Nothing of any one server's store is left in RynthInventory itself. + var asm = typeof(RynthInventoryPlugin).Assembly; + Check(asm.GetType("RynthCore.Plugin.RynthInventory.Scanning.VaultFeed") == null, "no vault reader (/mule-data) in RynthInventory"); + Check(typeof(RynthInventoryPlugin).GetMethod(nameof(RynthInventoryPlugin.OnChatWindowText))!.DeclaringType != typeof(RynthInventoryPlugin), + "RynthInventory doesn't read chat (nothing to ask a server for, nothing to hide)"); + } + } +} diff --git a/Tools/RynthInventory.Tests/VaultFeedTests.cs b/Tools/RynthInventory.Tests/VaultFeedTests.cs deleted file mode 100644 index 742d5dc..0000000 --- a/Tools/RynthInventory.Tests/VaultFeedTests.cs +++ /dev/null @@ -1,157 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using RynthCore.Plugin.RynthInventory.Data; -using RynthCore.Plugin.RynthInventory.Scanning; - -namespace RynthInventory.Tests -{ - // The Aelrynth account vault: /mule-data answers, one "~ael1" line a page (Aeshnidae.Mule MuleData.cs). - internal static partial class Program - { - private static string VaultPage(int page, int pages, int count, string items, bool ready = true, string why = "") => - ready - ? "~ael1 {\"t\":\"mule\",\"ready\":true,\"page\":" + page + ",\"pages\":" + pages + ",\"count\":" + count + ",\"max\":1000,\"items\":[" + items + "]}" - : "~ael1 {\"t\":\"mule\",\"ready\":false,\"why\":\"" + why + "\"}"; - - private static (VaultFeed Feed, List Sent) NewVault() - { - var sent = new List(); - return (new VaultFeed(t => { sent.Add(t); return true; }), sent); - } - - private static void VaultTests() - { - const string A = "{\"o\":2147483649,\"w\":100,\"n\":\"Acid Assagai\",\"i\":100667000,\"u\":100667001,\"v\":100667002,\"s\":3,\"m\":100,\"y\":1,\"e\":1}"; - const string B = "{\"o\":2147483650,\"w\":101,\"n\":\"Pyreal\",\"i\":100667003,\"y\":8192}"; - - // Two pages, asked one after the other, filed as one record. - { - (VaultFeed v, List sent) = NewVault(); - Check(v.Ask(1000), "ask starts"); - Eq(sent.Count == 1 ? sent[0] : "?", "/mule-data", "page 1 asked first"); - Check(v.ShouldEat(VaultPage(1, 2, 2, A)), "page 1 is eaten"); - v.Tick(1100, "Tom"); - Eq(sent.Count == 2 ? sent[1] : "?", "/mule-data 2", "page 2 asked when page 1 came"); - Check(v.Record == null, "nothing filed before the last page"); - Check(v.ShouldEat(VaultPage(2, 2, 2, B)), "page 2 is eaten"); - v.Tick(1200, "Tom"); - StorageRecord? r = v.Record; - Check(r != null && v.TakeChanged() && !v.TakeChanged(), "filed once"); - Eq(r?.Items.Count ?? -1, 2, "both pages' items"); - Eq(r?.Id ?? 0, VaultFeed.VaultId("tom"), "id follows the account, case-blind"); - Check((r?.Id ?? 0) >> 24 == 0xFF, "id is a stand-in, far from real objects"); - Eq(r?.Label ?? "", "Account vault", "label"); - ItemRecord a = r!.Items[0]; - Eq(a.Name, "Acid Assagai", "name"); Eq(a.Icon, 100667000u, "icon"); Eq(a.Underlay, 100667001u, "underlay"); - Eq(a.Overlay, 100667002u, "overlay"); Eq(a.Stack, 3, "stack"); Eq(a.MaxStack, 100, "max stack"); - Eq(a.Place, ItemPlace.Storage, "place"); - Eq(r.Items[1].Stack, 1, "no stack field is a stack of 1"); - Eq(v.Status, VaultFeed.State.Idle, "idle again"); - } - - // Other plugins' lines are left alone. - { - (VaultFeed v, _) = NewVault(); - v.Ask(0); - Check(!v.ShouldEat("~ael1 {\"t\":\"inspect\",\"ok\":true}"), "the Companion's line stays visible"); - Check(!v.ShouldEat("Welcome to Aelrynth"), "ordinary chat stays visible"); - Check(!v.ShouldEat(null), "null is fine"); - } - - // A player imitating the server: their name is in front, or the chat type is theirs. - { - (VaultFeed v, _) = NewVault(); - v.Ask(0); - Check(!v.ShouldEat("Bob says, \"" + VaultPage(1, 1, 1, A) + "\"", 2), "spoken data line is not ours"); - Check(!v.ShouldEat("Bob " + VaultPage(1, 1, 1, A), 12), "an emoted data line is not ours"); - Check(!v.ShouldEat("Bob " + VaultPage(1, 1, 1, A)), "a data line not at the start is not ours, type unknown"); - Check(!v.ShouldEat(VaultPage(1, 1, 1, A), 3), "a data line in a tell is not ours"); - Check(!v.ShouldEat("Bob tells you, \"Unknown command: mule-data\"", 3), "a told unknown-command line is not ours"); - Check(!v.ShouldEat("Unknown command: mule-data", 2), "unknown-command in speech is not ours"); - Check(!v.ShouldEat("Unknown command: mule-data-ish"), "another command's refusal is not ours"); - Check(v.ShouldEat("Unknown command: mule-data", 15), "ACE's real reply (Help) is ours"); - } - { - (VaultFeed v, _) = NewVault(); - v.Ask(0); - Check(v.ShouldEat(" " + VaultPage(1, 1, 1, A), 0), "the server's line (Broadcast), leading space allowed"); - } - - // A server without the command. - { - (VaultFeed v, List sent) = NewVault(); - v.Ask(0); - Check(v.ShouldEat("Unknown command: /mule-data"), "the unknown-command reply is eaten while we wait"); - v.Tick(100, "tom"); - Eq(v.Status, VaultFeed.State.Unsupported, "unsupported"); - Check(!v.Ask(200), "not asked again"); - Eq(sent.Count, 1, "one probe, no more"); - Check(v.Ask(300, force: true), "/ginv vault asks anyway"); - } - { - (VaultFeed v, _) = NewVault(); - Check(!v.ShouldEat("Unknown command: /mule-data"), "an unknown-command line we did not provoke is left alone"); - } - - // A vault the server is still loading is asked again, and never recorded as empty. - { - (VaultFeed v, List sent) = NewVault(); - v.Ask(0); - v.ShouldEat(VaultPage(1, 1, 0, "", ready: false, why: "loading")); - v.Tick(10, "tom"); - Eq(v.Status, VaultFeed.State.Waiting, "waiting"); - v.Tick(2000, "tom"); - Eq(sent.Count, 1, "not before the retry delay"); - v.Tick(3500, "tom"); - Eq(sent.Count, 2, "asked again after it"); - Check(v.Record == null, "never recorded"); - for (int i = 0; i < 10; i++) - { - v.ShouldEat(VaultPage(1, 1, 0, "", ready: false, why: "loading")); - v.Tick(4000 + i * 4000, "tom"); - } - Check(v.Status != VaultFeed.State.Asking || sent.Count < 12, "it gives up after a few tries"); - Check(v.Record == null, "still never recorded"); - } - - // A vault that changed between pages is read again, not filed half and half. - { - (VaultFeed v, _) = NewVault(); - v.Ask(0); - v.ShouldEat(VaultPage(1, 2, 3, A)); - v.Tick(10, "tom"); - v.ShouldEat(VaultPage(2, 2, 3, B)); // 2 read, the server says 3 - v.Tick(20, "tom"); - Check(v.Record == null, "a mismatched read is not filed"); - Eq(v.Status, VaultFeed.State.Waiting, "and is retried"); - } - - // Silence is an idle feed, not a stuck one. - { - (VaultFeed v, _) = NewVault(); - v.Ask(0); - v.Tick(20_000, "tom"); - Eq(v.Status, VaultFeed.State.Idle, "no answer in time"); - Check(v.Ask(21_000), "can ask again"); - } - - // A line typed by hand while we are not asking is eaten (it is ours) but changes nothing. - { - (VaultFeed v, _) = NewVault(); - Check(v.ShouldEat(VaultPage(1, 1, 1, A)), "eaten"); - v.Tick(0, "tom"); - Check(v.Record == null, "ignored when we did not ask"); - } - - // Garbage inside a mule line does not throw. - { - (VaultFeed v, _) = NewVault(); - v.Ask(0); - v.ShouldEat("~ael1 {\"t\":\"mule\",\"ready\":tru"); - v.Tick(5, "tom"); - Check(v.Record == null && v.Status == VaultFeed.State.Idle, "bad JSON drops the read"); - } - } - } -} diff --git a/Tools/RynthNav.RouteTests/AutoRunGateTests.cs b/Tools/RynthNav.RouteTests/AutoRunGateTests.cs new file mode 100644 index 0000000..a31daf8 --- /dev/null +++ b/Tools/RynthNav.RouteTests/AutoRunGateTests.cs @@ -0,0 +1,177 @@ +using System; +using System.Collections.Generic; +using RynthCore.Plugin.RynthNav; + +namespace RynthNav.RouteTests; + +// The goto's autorun (AutoRunGate): on 10-19 a /rnav go "Matron Hive East" sent SetAutoRun about +// 55 times a second (settling after the recall, turning at the portal, walking the Town Network) +// and filled the engine's action ring in portal space. Now sent when it changes. +internal static partial class Program +{ + private static void RunAutoRunGate() + { + Run(nameof(TurnInPlaceSendsOffOnce), TurnInPlaceSendsOffOnce); + Run(nameof(RunningReassertsTwiceASecond), RunningReassertsTwiceASecond); + Run(nameof(SettleAfterATeleportSendsNothingMore), SettleAfterATeleportSendsNothingMore); + Run(nameof(HoldHaltsOnce), HoldHaltsOnce); + Run(nameof(TurnGateFlipsSendEachChange), TurnGateFlipsSendEachChange); + Run(nameof(RefusedCallIsRetriedNotEveryTick), RefusedCallIsRetriedNotEveryTick); + Run(nameof(NewGotoSendsAgain), NewGotoSendsAgain); + Run(nameof(MatronHiveTripReplay), MatronHiveTripReplay); + } + + private const long GateTickMs = 18; // the plugin tick on 10-19: ~55 a second + + /// The host's SetAutoRun/StopCompletely, counted; Accept = false refuses them (a full action ring). + private sealed class FakeMover + { + public long Now = 1_000_000; + public bool Accept = true; + public int On, Off, Stops, Tries; + public readonly AutoRunGate Gate; + + public FakeMover() + { + Gate = new AutoRunGate( + on => { Tries++; if (!Accept) return false; if (on) On++; else Off++; return true; }, + () => { Tries++; if (!Accept) return false; Stops++; return true; }, + () => Now); + } + + public int Sent => On + Off + Stops; + + /// once a tick for . + public void For(long ms, Action each) + { + for (long end = Now + ms; Now < end; Now += GateTickMs) each(); + } + } + + private static void TurnInPlaceSendsOffOnce() + { + // At the Town Network portal (16:38:46): turning in place, SetAutoRun(False) every tick. + var m = new FakeMover(); + m.For(4000, () => m.Gate.Run(false)); + Check(m.Off == 1 && m.On == 0 && m.Stops == 0, $"4 s turning in place: one SetAutoRun(False) (sent {m.Off}/{m.On}/{m.Stops})"); + } + + private static void RunningReassertsTwiceASecond() + { + // Running: "on" goes out once, then again every ReassertMs (a cast or a server stop can + // turn autorun off without telling the goto). + var m = new FakeMover(); + m.For(3000, () => m.Gate.Run(true)); + long ticks = 3000 / GateTickMs + 1; + Check(m.On >= 3000 / AutoRunGate.ReassertMs && m.On <= 3000 / AutoRunGate.ReassertMs + 1, + $"3 s running: {m.On} SetAutoRun(True), one every {AutoRunGate.ReassertMs} ms (was {ticks}, one a tick)"); + Check(m.Off == 0 && m.Stops == 0, "nothing else sent while running"); + } + + private static void SettleAfterATeleportSendsNothingMore() + { + // The recall lands (Stop), then portal space and the settle: SetAutoRun(False) every tick + // for 7.5 s (16:38:38-16:38:46). + var m = new FakeMover(); + m.Gate.Stop(); + m.For(7500, () => m.Gate.Run(false)); + Check(m.Off == 1 && m.Stops == 1 && m.On == 0, $"teleport + 7.5 s settle: just the Stop (sent {m.Off}/{m.Stops}/{m.On})"); + } + + private static void HoldHaltsOnce() + { + // The Town Network landing wait and the exit hold: SetAutoRun(False) + StopCompletely every tick. + var m = new FakeMover(); + m.For(2000, () => m.Gate.Halt()); + Check(m.Off == 1 && m.Stops == 1, $"2 s holding: one halt (sent {m.Off}/{m.Stops})"); + m.Gate.Run(true); + Check(m.On == 1, "running after the hold goes out"); + m.Gate.Halt(); + Check(m.Off == 2 && m.Stops == 2, "a hold after running halts again"); + m.Gate.Run(false); + Check(m.Off == 2, "autorun is already off after a halt"); + m.Gate.Stop(); + Check(m.Off == 3 && m.Stops == 3, "Stop always sends (a goto's end, a teleport)"); + } + + private static void TurnGateFlipsSendEachChange() + { + // DriveTo's stop-to-turn hysteresis: every flip is a change and goes out at once. + var m = new FakeMover(); + foreach (bool on in new[] { true, true, false, false, false, true, false }) + { + m.Gate.Run(on); + m.Now += GateTickMs; + } + Check(m.On == 2 && m.Off == 2, $"run, turn, run, turn: four sends (sent {m.On} on, {m.Off} off)"); + } + + private static void RefusedCallIsRetriedNotEveryTick() + { + // The engine refuses a call (its action ring full): not taken as sent, tried again after + // RetryMs instead of every tick. + var m = new FakeMover { Accept = false }; + m.For(1000, () => m.Gate.Run(false)); + Check(m.Off == 0, "nothing went through"); + Check(m.Tries >= 2 && m.Tries <= 1000 / AutoRunGate.RetryMs + 1, $"1 s refused: {m.Tries} tries, not one a tick"); + m.Accept = true; + m.For(1000, () => m.Gate.Run(false)); + Check(m.Off == 1, $"once it's accepted it goes out once (sent {m.Off})"); + + var h = new FakeMover { Accept = false }; + h.For(1000, () => h.Gate.Halt()); + Check(h.Tries >= 2 && h.Tries <= 2 * (1000 / AutoRunGate.RetryMs + 1), $"refused halt: {h.Tries} tries in 1 s"); + h.Accept = true; + h.For(1000, () => h.Gate.Halt()); + Check(h.Off == 1 && h.Stops == 1, "the halt goes out once accepted"); + } + + private static void NewGotoSendsAgain() + { + // Between gotos the d-pad or another plugin may have moved the character: Forget, and the + // first call of the new goto goes out even if it's the same as the last one sent. + var m = new FakeMover(); + m.Gate.Run(false); + m.Gate.Forget(); + m.Gate.Run(false); + Check(m.Off == 2, "after Forget the same state is sent again"); + m.Gate.Halt(); + m.Gate.Forget(); + m.Gate.Halt(); + Check(m.Stops == 2, "after Forget a halt is sent again"); + } + + private static void MatronHiveTripReplay() + { + // The 10-19 trip's movement calls in order (RynthNav's tick, ~55 a second), from the + // goto's start to the Baishi landing. Each phase is what the code asks for every tick. + var m = new FakeMover(); + int asks = 0; + var phases = new List<(long ms, Action tick)> + { + (0, () => m.Gate.Stop()), // recall step: stop before the cast + (2300, () => { }), // casting (no movement calls) + (0, () => m.Gate.Stop()), // the recall's teleport + (7900, () => m.Gate.Run(false)), // settle: portal space and the quiet second + (4000, () => m.Gate.Run(false)), // turning to the Town Network portal + (600, () => m.Gate.Run(true)), // running at it + (1800, () => m.Gate.Run(false)), // within reach: standing, using it + (0, () => m.Gate.Stop()), // its teleport + (8000, () => m.Gate.Halt()), // landing in the Town Network (portal space, settle) + (5000, () => m.Gate.Run(true)), // the walk to the Baishi portal + (300, () => m.Gate.Run(false)), // a turn in place on the way + (5000, () => m.Gate.Run(true)), + (300, () => m.Gate.Halt()), // at the exit + (0, () => m.Gate.Stop()), // Baishi's teleport + (6000, () => m.Gate.Run(false)), // its portal space + }; + foreach (var (ms, tick) in phases) + { + if (ms == 0) { tick(); asks++; continue; } + for (long end = m.Now + ms; m.Now < end; m.Now += GateTickMs) { tick(); asks++; } + } + Check(asks > 2000, $"the replay asks every tick ({asks} asks)"); + Check(m.Sent < 60, $"the trip sent {m.Sent} movement calls for {asks} asks (10-19: ~4,460 SetAutoRun and 97 StopCompletely)"); + Check(m.On <= 2 + 2 * (10000 / AutoRunGate.ReassertMs + 1), $"running sent {m.On} SetAutoRun(True)"); + } +} diff --git a/Tools/RynthNav.RouteTests/Program.cs b/Tools/RynthNav.RouteTests/Program.cs index 3d1e7fa..7a17d33 100644 --- a/Tools/RynthNav.RouteTests/Program.cs +++ b/Tools/RynthNav.RouteTests/Program.cs @@ -58,6 +58,7 @@ internal static partial class Program RunAvoid(); RunTravelPlan(); RunTripExport(); + RunAutoRunGate(); Console.WriteLine(); Console.WriteLine(_fails == 0 && _asserts > 0 diff --git a/Tools/RynthNav.RouteTests/RynthNav.RouteTests.csproj b/Tools/RynthNav.RouteTests/RynthNav.RouteTests.csproj index cf9ea22..5b2f4f7 100644 --- a/Tools/RynthNav.RouteTests/RynthNav.RouteTests.csproj +++ b/Tools/RynthNav.RouteTests/RynthNav.RouteTests.csproj @@ -28,6 +28,8 @@ + + diff --git a/Tools/RynthOracle.Tests/MergedQuestsTests.cs b/Tools/RynthOracle.Tests/MergedQuestsTests.cs new file mode 100644 index 0000000..215aff0 --- /dev/null +++ b/Tools/RynthOracle.Tests/MergedQuestsTests.cs @@ -0,0 +1,872 @@ +using System; +using System.Buffers.Binary; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; +using RynthCore.Plugin.RynthOracle; +using RynthCore.Plugin.RynthOracle.Data; +using RynthCore.Plugin.RynthOracle.Ui; +using RynthCore.Plugin.RynthOracle.Views; +using IltBreedingView = RynthCore.Plugin.Shared.IltBreedingView; +using IltGuardianView = RynthCore.Plugin.Shared.IltGuardianView; + +namespace RynthOracle.Tests +{ + // The 0.3.0 port of SilentKelpie's RynthOracle 0.6.0 (RynthSuite PR 12): the merged Quests list + // (Legendary, Markers, Dynamic Stamps and Temple guardians), Go to, the Give Parchment gate, the two + // CSV loaders, the RynthILT profile and the Charms / Pet Breeding pieces. Ported from his tests where + // they fit, adapted where our tree differs (the Refresh row, the Mini Remote keeping its tabs), and + // added for what the merge must keep (favourites, click-to-print, the Markers tab's content). + internal static partial class Program + { + // ── Helpers ────────────────────────────────────────────────────────── + + private static uint _seq = 5000; + + private static string Body(UiWindow w) => Encoding.UTF8.GetString(w.Body); + + /// One draw of the main window, parsed by the engine's own parser (ops under the limit), body returned. + private static string Frame(UiHost host, UiWindow main, OracleView view, string what, out int ops) + { + main.Begin(); view.Draw(main); main.End(); + ParseAll(host, what, out ops); + string body = Body(main); + main.MarkSubmitted(true); + return body; + } + + private static string Frame(UiHost host, UiWindow main, OracleView view, string what) => Frame(host, main, view, what, out _); + + private static void Click(UiHost host, UiWindow w, string id) => Apply(host, Event(1, ++_seq, w.Hash, w.KeyOf(id), new byte[] { 1, 0, 0 })); + + private static void Tick(UiHost host, UiWindow w, string id, bool on) => Apply(host, Event(2, ++_seq, w.Hash, w.KeyOf(id), new byte[] { (byte)(on ? 1 : 0) })); + + private static void Type(UiHost host, UiWindow w, string id, string text) + { + byte[] t = Encoding.UTF8.GetBytes(text); + var payload = new byte[3 + t.Length]; + BinaryPrimitives.WriteUInt16LittleEndian(payload.AsSpan(1), (ushort)t.Length); + t.CopyTo(payload, 3); + Apply(host, Event(5, ++_seq, w.Hash, w.KeyOf(id), payload)); + } + + /// A context on a given server (a tag, or "" for retail) with the retail catalog loaded. + private static OracleContext On(string tag) + { + OracleContext c = Context(); + c.Server.Force(tag, tag.Length > 0 ? tag : "Coldeve"); + c.Catalog.Load(tag, null); + c.Catalog.SyncDiscoveries(c.Flags); + return c; + } + + // ── The CSV lists ──────────────────────────────────────────────────── + + /// The Legendary list (legendary.csv) and its have / missing / timer rules. + private static void Legendary() + { + Check(LegendaryList.All.Count == 40, $"legendary quests: {LegendaryList.All.Count} (40 expected)"); + Check(LegendaryList.Groups.SequenceEqual(new[] { "Graveyard", "Rynthid", "Hoshino", "Frozen Valley", "Neftet", "Random Locations" }), + "legendary groups: " + string.Join(",", LegendaryList.Groups)); + Check(LegendaryList.All.All(q => q.Flags.Length > 0 && q.Luminance > 0), "every legendary quest has a flag and luminance"); + var catalog = new QuestCatalog(); + catalog.Load("", _ => { }); + var unknown = LegendaryList.All.SelectMany(q => q.Flags).Where(f => !catalog.TryGet(f, out _)).ToList(); + Check(unknown.Count == 0, "every legendary flag is a known quest flag: " + string.Join(",", unknown)); + LegendaryQuest rtw = LegendaryList.All.First(q => q.CommonName == "RTW"); + Check(rtw.Flags[0] == "rtwcompleted_1013" && rtw.Label == "Defeating the Curator of Torment (RTW)", "RTW row: " + rtw.Label); + + var lf = new QuestFlagStore(); + long t = 900_000; + long done = DateTimeOffset.UtcNow.AddHours(-2).ToUnixTimeSeconds(); + long old = DateTimeOffset.UtcNow.AddDays(-3).ToUnixTimeSeconds(); + // RTW done 2 h ago on a 20 h timer; End of Days done 3 days ago (ready); Lugian Assault never. + lf.OnChatLine($"rtwcompleted_1013 - 4 solves ({done})\"RTW\" -1 72000", t); + lf.OnChatLine($"eodcompleted_1013 - 1 solves ({old})\"EoD\" -1 72000", t + 1); + lf.OnChatLine($"legendaryquestcounter_0913 - 12 solves ({old})\"John\" -1 0", t + 2); + lf.Tick(t + 5_000); + DateTime now = DateTime.UtcNow; + TimeSpan? rtwLeft = rtw.TimeLeft(lf, now); + Check(rtw.Have(lf) && rtwLeft is { } l && l.TotalHours > 17.9 && l.TotalHours < 18.1, $"RTW: done, ~18 h left ({rtwLeft})"); + LegendaryQuest eod = LegendaryList.All.First(q => q.CommonName == "EoD"); + Check(eod.Have(lf) && eod.Status(lf, now) == "ready", "EoD: done, timer up -> ready: " + eod.Status(lf, now)); + LegendaryQuest la = LegendaryList.All.First(q => q.CommonName == "LA"); + Check(!la.Have(lf) && la.TimeLeft(lf, now) == null && la.Status(lf, now) == "missing", "Lugian Assault: missing"); + Check(LegendaryList.JohnCount(lf) == 12, "John's counter read: " + LegendaryList.JohnCount(lf)); + Check(LegendaryList.JohnCount(new QuestFlagStore()) == null, "no counter on a fresh character"); + + // A quest with a second timer flag: the longest wait of the two counts. + LegendaryQuest erq = LegendaryList.All.First(q => q.Name == "Empyrean Rescue Quest"); + var ef = new QuestFlagStore(); + ef.OnChatLine($"empyreanrescuecompleted_1010 - 1 solves ({old})\"ERQ\" -1 0", t); + ef.OnChatLine($"erqlegkeypickuptimer - 1 solves ({done})\"key\" -1 36000", t + 1); + ef.Tick(t + 5_000); + TimeSpan? erqLeft = erq.TimeLeft(ef, now); + Check(erqLeft is { } e && e.TotalHours > 7.9 && e.TotalHours < 8.1, $"ERQ: key pickup timer decides (~8 h): {erqLeft}"); + } + + /// The Dynamic Stamps list (dynstamps.csv), its have / missing rules, RynthNav targets and the Go to parser. + private static void DynamicStamps() + { + var all = DynamicStampList.All; + Check(all.Count == 243, $"dynamic stamps: {all.Count} (243 expected from the ExtraDyn sheet)"); + Check(DynamicStampList.Areas.Count == 17 && DynamicStampList.Areas[0] == "Facility Hub" && DynamicStampList.Areas[^1] == "Candeth Keep", + "dynamic areas: " + string.Join(",", DynamicStampList.Areas)); + Check(all.All(s => s.Stamp.StartsWith("dynamic_") && s.Stamp == s.Stamp.ToLowerInvariant()), "every stamp is a lower-case dynamic_ flag"); + Check(all.Select(s => s.Stamp).Distinct().Count() == all.Count, "no stamp listed twice"); + Check(all.All(s => s.Label.Length > 0), "every row names an NPC or a place"); + + DynamicStamp felscuda = all.First(s => s.Npc == "Felscuda"); + Check(felscuda.Stamp == "dynamic_1_&9jiytb!" && felscuda.Place == "Folthid Cellar" && felscuda.Reward == "Healing Rabbit Pie" + && felscuda.Note == "8.8S, 53.1E", $"Felscuda row: {felscuda.Place} / {felscuda.Reward} / {felscuda.Note}"); + + // /myquests keys flags as \S+ lower case, so the stamps' ! & # ^ $ survive. + var f = new QuestFlagStore(); + long t = 900_000, at = DateTimeOffset.UtcNow.AddDays(-1).ToUnixTimeSeconds(); + f.OnChatLine($"Dynamic_1_&9jiyTB! - 1 solves ({at})\"Dynamic\" 1 0", t); + f.OnChatLine($"Dynamic_1_ANND! - 1 solves ({at})\"Dynamic\" 1 0", t + 1); // the sheet lost the closing ! + f.OnChatLine($"Dynamic_1_ZZZnewNPC! - 1 solves ({at})\"Dynamic\" 1 0", t + 2); // not on the sheet + f.OnChatLine($"rtwcompleted_1013 - 1 solves ({at})\"RTW\" -1 72000", t + 3); + f.Tick(t + 5_000); + Check(felscuda.Have(f), "Felscuda's stamp read from /myquests"); + DynamicStamp annd = all.First(s => s.Stamp == "dynamic_1_annd"); + Check(annd.Have(f) && annd.MatchedFlag(f) == "dynamic_1_annd!", "a stamp the sheet lost its ! on still matches"); + Check(!all.First(s => s.Npc == "Raxanza Folthid").Have(f), "an NPC not done is missing"); + List extra = DynamicStampList.Unlisted(f); + Check(extra.Count == 1 && extra[0] == "dynamic_1_zzznewnpc!", "unlisted: only the stamp the sheet doesn't have: " + string.Join(",", extra)); + DynamicStamp shortStamp = all.First(s => s.Stamp == "dynamic_1_s"); + var sf = new QuestFlagStore(); + sf.OnChatLine($"Dynamic_1_SomethingElse! - 1 solves ({at})\"Dynamic\" 1 0", t); + sf.Tick(t + 5_000); + Check(!shortStamp.Have(sf), "a cut-short stem under 14 characters isn't matched by prefix"); + + // RynthNav targets, best first (RynthNav takes the first on its map). + Check(string.Join(" | ", felscuda.NavCandidates()) == "8.8S, 53.1E | Folthid Cellar | Felscuda | Facility Hub", + "Felscuda nav: " + string.Join(" | ", felscuda.NavCandidates())); + var gerent = new DynamicStamp { Area = "Graveyard", Place = "Gerent's Compound at 87.2S, 17.5W", Npc = "Gerent" }; + Check(string.Join(" | ", gerent.NavCandidates()) == "87.2S, 17.5W | Gerent's Compound | Gerent | Graveyard", + "coordinates inside the place, 'at' dropped: " + string.Join(" | ", gerent.NavCandidates())); + var lost = new DynamicStamp { Area = "Odd Stamps", Place = "Lost Wish Cottages (Arwic) 42.6n 62.4e", Npc = "Bob" }; + Check(string.Join(" | ", lost.NavCandidates()) == "42.6N, 62.4E | Lost Wish Cottages (Arwic) | Lost Wish Cottages | Arwic", + "lower-case n/e, a bracketed town, no grouping area, a 3-letter NPC left out: " + string.Join(" | ", lost.NavCandidates())); + var mhoire = new DynamicStamp { Area = "Looking Around", Place = "Mhoire Castle - Great Hall" }; + Check(string.Join(" | ", mhoire.NavCandidates()) == "Mhoire Castle - Great Hall | Mhoire Castle | Great Hall", + "a place's parts: " + string.Join(" | ", mhoire.NavCandidates())); + Check(all.Count(s => s.NavCandidates().Count > 0) >= 200, "most stamps have somewhere to go: " + all.Count(s => s.NavCandidates().Count > 0)); + } + + /// Coordinates in a quest's notes become RynthNav targets (Go to). + private static void GoToParsing() + { + var grael = NavTargets.Stops("Give Progenitor's Ichor to Hoshar. - Speak with Hoshar ibn Jalaq 59.6S 88.0W - Kill Mukkir Progenitor 86.5N 57.3E" + + " - Speak with Hoshar ibn Jalaq - Abyssal Totem Gateway 86.5N 57.3E - Abyssal Totem Temple 86.5N 57.3E"); + Check(string.Join(" | ", grael.ConvertAll(s => s.Display)) == "Speak with Hoshar ibn Jalaq - 59.6S, 88.0W | Kill Mukkir Progenitor - 86.5N, 57.3E", + "Splitting Grael stops: " + string.Join(" | ", grael.ConvertAll(s => s.Display))); + Check(grael[0].Target == "59.6S, 88.0W Speak with Hoshar ibn Jalaq", "a stop's RynthNav target is the coordinates, then its label"); + var shadow = NavTargets.Stops("Xarabydun 41.8S 15.8E - Speak with Ciandra Arcanum Alchemist - Empyrean Workshop 66.9N 15.9E - Cragstone 26.0N 47.0E Speak with Bretself the Translator - Xarabydun - Shade of Farelaith 74.3N 58.6E"); + Check(string.Join(" | ", shadow.ConvertAll(s => s.Label)) == "Xarabydun | Empyrean Workshop | Cragstone | Shade of Farelaith", + "Shadowfire Stone labels: " + string.Join(" | ", shadow.ConvertAll(s => s.Label))); + Check(NavTargets.Stops("Kill 20 drudges near Holtburg.").Count == 0, "no coordinates: no stops"); + Check(NavTargets.Stops(null).Count == 0 && NavTargets.Stops("").Count == 0, "no text: no stops"); + Check(NavTargets.Stops("Meet at 42.6n 62.4e").Count == 1 && NavTargets.Stops("Meet at 42.6n 62.4e")[0].Display == "Meet - 42.6N, 62.4E", + "lower-case letters; 'at' dropped from the label"); + Check(NavTargets.FirstCoords("go to 8.8S, 53.1E now") == "8.8S, 53.1E" && NavTargets.FirstCoords("nowhere") == null, "the first coordinates in a text"); + Check(NavTargets.WithoutCoords("Hall 8.8S, 53.1E door").Contains("Hall") && !NavTargets.WithoutCoords("Hall 8.8S, 53.1E door").Contains("53.1"), + "the text without its coordinates"); + Check(NavTargets.Place(" Holtburg ").Target == "Holtburg", "a named place is its own target"); + } + + /// Both CSV loaders: counts from the shipped files, and a malformed file doesn't cost the good rows. + private static void Loaders() + { + // The shipped files: counts, and they are embedded resources (the way the other lists are). + Check(LegendaryList.All.Count == 40 && DynamicStampList.All.Count == 243, "the shipped lists load: 40 Legendary quests, 243 stamps"); + Check(MarkerList.All.Count == 100, "the shipped marker list still has its 100 markers"); + + var rows = LegendaryList.Parse(new StringReader( + "Group,Quest,CommonName,Luminance,Flags,Url,Note,Video\n" + + "\"G\",\"Good\",\"GD\",5000,\"a_flag;B_Flag\",\"https://x\",\"a note, with a comma\",\"\"\n" + + "\"G\",\"\",\"\",1,\"x\",\"\",\"\",\"\"\n" // no quest name: skipped + + "\"G\",\"ShortRow\",\"\",abc\n" // short row, luminance isn't a number + + "\n" + + "just one field\n" + + "\"G\",\"After\",\"\",7,\"c_flag\"\n")); + Check(rows.Count == 3 && rows[0].Name == "Good" && rows[1].Name == "ShortRow" && rows[2].Name == "After", + "legendary: bad rows skipped, the rest kept: " + string.Join(",", rows.Select(r => r.Name))); + Check(rows[0].Flags.SequenceEqual(new[] { "a_flag", "b_flag" }) && rows[0].Luminance == 5000 && rows[0].Note == "a note, with a comma" + && rows[0].Label == "Good (GD)", "legendary: flags lower-cased and split, quoted commas kept, the short name in the label"); + Check(rows[1].Luminance == 0 && rows[1].Flags.Length == 0 && rows[1].Url == "", "legendary: a short row reads as empty, luminance 0"); + Check(LegendaryList.Parse(new StringReader("")).Count == 0 && LegendaryList.Parse(new StringReader("Group,Quest\n")).Count == 0, + "legendary: an empty file is an empty list"); + Check(LegendaryList.Parse(new StringReader("Quest\r\nCRLF Quest\r\n")).Single().Name == "CRLF Quest", "legendary: CRLF lines"); + + var stamps = DynamicStampList.Parse(new StringReader( + "Area,Place,Npc,Reward,Stamp,Note\n" + + "\"A\",\"P\",\"Npc1\",\"R\",\"Dynamic_1_Abc!\",\"8.8S, 53.1E\"\n" + + "\"A\",\"P\",\"Dup\",\"R\",\"dynamic_1_abc!\",\"\"\n" // the same stamp again: skipped + + "\"A\",\"P\",\"NotDyn\",\"R\",\"something_else\",\"\"\n" // not a dynamic_ flag: skipped + + "\"A\",\"P\",\"Short\"\n" // no stamp column: skipped + + "\n" + + "\"B\",\"\",\"\",\"\",\"Dynamic_2_x\",\"\"\n")); + Check(stamps.Count == 2 && stamps[0].Stamp == "dynamic_1_abc!" && stamps[1].Stamp == "dynamic_2_x", + "dynamic: bad and repeated rows skipped, the rest kept: " + string.Join(",", stamps.Select(s => s.Stamp))); + Check(stamps[0].Npc == "Npc1" && stamps[0].Note == "8.8S, 53.1E" && stamps[1].Label == "", "dynamic: fields read, a missing NPC and place leave an empty label"); + Check(DynamicStampList.Parse(new StringReader("")).Count == 0, "dynamic: an empty file is an empty list"); + + // The markers file is the existing loader; a marker row still parses to its flag bit. + Marker m = MarkerList.All[0]; + Check(m.Number == 1 && m.Flag.StartsWith("explorationmarkersfoundingroup") && m.BitMask == 1, "marker 1 keeps its quest flag bit"); + } + + // ── RynthILT's profile, charms and pet breeding ────────────────────── + + private const string QbProfileJson = "{\"ilt\":true,\"world\":\"InfiniteLeaftide\",\"fellowship\":{\"maxMembers\":29}," + + "\"questBonus\":{\"disabled\":false,\"generation\":3,\"count\":41,\"status\":\"2 completed, 1 incomplete\"," + + "\"completed\":[\"qbflagone\",\"qbflagtwo\"],\"incomplete\":[\"qbflagthree\"]}}"; + + /// RynthILT's "RynthILT.Server" profile JSON as the Quests, About and Pet Breeding pages read it. + private static void IltProfile() + { + const string json = "{\"ilt\":true,\"world\":\"InfiniteLeaftide\",\"forced\":false,\"source\":\"probe\",\"checked\":\"2026-10-13T21:25:37Z\"," + + "\"features\":[{\"key\":\"bank\",\"label\":\"Banking\",\"group\":\"Character\",\"state\":1,\"where\":\"Mini Remote > Banking tab\"}," + + "{\"key\":\"zone_share\",\"label\":\"Zone Share\",\"group\":\"Fellowship\",\"state\":1,\"where\":\"server\"}," + + "{\"key\":\"fellowship_blackjack\",\"label\":\"Fellowship Blackjack\",\"group\":\"Fellowship\",\"state\":0,\"where\":\"/fblackjack\"}]," + + "\"fellowship\":{\"maxMembers\":29,\"zoneShare\":1,\"blackjack\":0,\"luminanceShare\":-1},\"later\":{\"x\":1}}"; + IltServerProfile p = IltServerProfile.Parse(json); + Check(p.Available && p.Ilt && p.World == "InfiniteLeaftide" && p.Source == "probe", "ILT profile header"); + Check(p.FellowshipMax == 29 && p.ZoneShare == 1 && p.Blackjack == 0 && p.LuminanceShare == -1, "ILT fellowship rules"); + Check(p.Features.Count == 3 && p.InGroup("Fellowship").Count() == 2, $"ILT features: {p.Features.Count}"); + Check(p.CheckedUtc == new DateTime(2026, 10, 13, 21, 25, 37, DateTimeKind.Utc), "checked time is UTC: " + p.CheckedUtc.ToString("o")); + + IltServerProfile none = IltServerProfile.Parse(""); + Check(!none.Available && none.FellowshipMax == 9, "no RynthILT: a retail fellowship"); + Check(!IltServerProfile.Parse("not json").Available, "garbage is ignored"); + Check(IltServerProfile.Parse("{\"ilt\":false}").FellowshipMax == 9, "an older profile without fellowship rules: retail size"); + Check(IltServerProfile.Parse("{\"fellowship\":{\"maxMembers\":5000}}").FellowshipMax == 9, "an absurd size is not believed"); + Check(IltServerProfile.StateText(1) == "on" && IltServerProfile.StateText(0) == "off" && IltServerProfile.StateText(-1) == "checking", "state words"); + + Check(p.QuestBonus == null, "no questBonus object: no /qb list"); + IltServerProfile qb = IltServerProfile.Parse(QbProfileJson); + Check(qb.QuestBonus is { Disabled: false, Generation: 3, Count: 41 } b && b.Completed.Count == 2 && b.Incomplete.Count == 1 + && b.Incomplete[0] == "qbflagthree" && b.Status == "2 completed, 1 incomplete", "quest bonus list parsed"); + + // The identity: a Leaftide world name, RynthILT's own verdict, and RynthCore's "ilt" server all give the ILT tag. + Check(ServerIdentity.TagForWorld("InfiniteLeaftide") == ServerTags.InfiniteLeaftide, "InfiniteLeaftide"); + Check(ServerIdentity.TagForWorld("Infinite Leaftide Staging") == ServerTags.InfiniteLeaftide, "a Leaftide staging world is ILT"); + Check(ServerIdentity.TagForEngineId("ilt") == ServerTags.InfiniteLeaftide && ServerIdentity.EngineIdForTag(ServerTags.InfiniteLeaftide) == "ilt", + "RynthCore's ilt server <-> the ILT tag"); + } + + /// The About page's "Server features" list comes from RynthILT's profile. + private static void ServerFeatures() + { + OracleContext c = On(ServerTags.InfiniteLeaftide); + c.Settings.TabName = OracleView.TabAbout; + var view = new OracleView(c); + var host = new UiHost(); + UiWindow main = host.Add(new UiWindow("RynthOracle/Oracle", "Oracle") { Visible = true }); + string body = Frame(host, main, view, "About, no RynthILT"); + Check(body.Contains("Load RynthILT to list the Infinite Leaftide features here."), "ILT without RynthILT: says to load it"); + c.Ilt.SetJson("{\"ilt\":true,\"world\":\"InfiniteLeaftide\",\"checked\":\"2026-10-13T21:25:37Z\"," + + "\"features\":[{\"key\":\"bank\",\"label\":\"Banking\",\"group\":\"Character\",\"state\":1,\"where\":\"Mini Remote > Banking tab\"}," + + "{\"key\":\"pet_breeding\",\"label\":\"Pet breeding\",\"group\":\"Pets\",\"state\":0,\"where\":\"Pets\"}]}"); + body = Frame(host, main, view, "About, with RynthILT"); + Check(body.Contains("Server features") && body.Contains("1 of 2 on.") && body.Contains("Character") && body.Contains("###o.feat.h.Pets"), + "the features RynthILT lists, grouped, with a count on"); + Check(body.Contains("o.alert") && body.Contains("o.alertall") && body.Contains("o.readlogin"), "the About settings (quest alerts too) are all still there"); + Check(body.Contains("/ro trackers") && body.Contains("/ro legendary") && body.Contains("/ro markers") && body.Contains("/ro guardians") && body.Contains("/ro breeding"), + "the About page lists the new commands on ILT"); + } + + private static string BreedingJson(int essences) + { + var sb = new StringBuilder("{\"available\":true,\"world\":\"InfiniteLeaftide\",\"enabled\":\"on\",\"maturity\":\"on\",\"bond\":\"on\"," + + "\"room\":\"landblock 0x0106 variant 2\",\"freeSlots\":12,\"message\":\"\",\"essences\":["); + for (int i = 0; i < essences; i++) + { + if (i > 0) sb.Append(','); + bool male = i % 2 == 0, ready = i < 2; + sb.Append("{\"id\":").Append(1000 + i).Append(",\"name\":\"Essence ").Append(i).Append("\",\"sex\":\"").Append(male ? 'M' : 'F') + .Append("\",\"tier\":125,\"bond\":100,\"ready\":").Append(ready ? "true" : "false") + .Append(",\"status\":\"").Append(ready ? "Ready" : "Rest 1h 05m").Append("\",\"readyIn\":").Append(ready ? 0 : 3900) + .Append(",\"charges\":7,\"chargesMax\":10,\"juvenile\":false,\"stage\":\"\",\"kills\":0,\"killsRequired\":300,") + .Append("\"mutations\":1,\"potencyMutations\":0,\"problems\":").Append(ready ? "[]" : "[\"resting after a breed\"]") + .Append(",\"boosters\":").Append(i == 0 ? "[\"Incense +10%\"]" : "[]").Append('}'); + } + sb.Append("],\"pairs\":[{\"stud\":\"Essence 0\",\"dam\":\"Essence 1\",\"chanceBest\":0.13636,\"chanceWorst\":0.05,\"inheritMin\":1,\"inheritMax\":2}],") + .Append("\"supplies\":[{\"key\":\"incense1\",\"name\":\"Breeding Incense\",\"effect\":\"+10% mutation chance\",\"count\":2,\"price\":250000,\"apply\":true,\"targets\":[1000,1001]},") + .Append("{\"key\":\"neuter\",\"name\":\"Neutering Kit\",\"effect\":\"Permanent\",\"count\":1,\"price\":0,\"apply\":false,\"targets\":[]}],") + .Append("\"rules\":[{\"label\":\"Stud charges\",\"value\":\"10/day\",\"source\":\"seen on server\",\"help\":\"Breeds per refill.\"},") + .Append("{\"label\":\"Mutation decay\",\"value\":\"0.1\",\"source\":\"ILT profile\",\"help\":\"\"}],") + .Append("\"events\":[{\"when\":\"10-15 12:00\",\"kind\":\"birth\",\"text\":\"Congratulations! A baby pet has been born: Pup\"}],") + .Append("\"debug\":{\"when\":\"10-15 12:01\",\"enabled\":\"on\",\"location\":\"0x0106 variant 2\",\"match\":\"valid\",\"pet\":\"Essence 0\",\"sex\":\"M\",\"partners\":1}}"); + return sb.ToString(); + } + + /// + /// The Pet Breeding tab: Infinite Leaftide only and only where the server has pet breeding; RynthILT's + /// breeding JSON drawn within the op budget; Dance and supply uses asked first, then sent as RynthILT's verbs. + /// + private static void Breeding() + { + OracleContext c = Context(); + var view = new OracleView(c); + Check(!view.VisibleTabs().Contains(OracleView.TabBreeding), "Aelrynth: no Pet Breeding tab"); + c.Server.Force("", "Coldeve"); + Check(!view.VisibleTabs().Contains(OracleView.TabBreeding), "other servers: no Pet Breeding tab"); + c.Server.Force(ServerTags.InfiniteLeaftide, "InfiniteLeaftide"); + Check(view.VisibleTabs().Contains(OracleView.TabBreeding), "Infinite Leaftide: the Pet Breeding tab"); + c.Ilt.SetJson("{\"ilt\":true,\"features\":[{\"key\":\"pet_breeding\",\"label\":\"Pet breeding\",\"group\":\"Pets\",\"state\":0,\"where\":\"\"}]}"); + Check(!view.VisibleTabs().Contains(OracleView.TabBreeding), "ILT with pet breeding off on the server: no Pet Breeding tab"); + c.Ilt.SetJson("{\"ilt\":true,\"features\":[{\"key\":\"pet_breeding\",\"label\":\"Pet breeding\",\"group\":\"Pets\",\"state\":1,\"where\":\"\"}]}"); + Check(view.VisibleTabs().Contains(OracleView.TabBreeding), "ILT with pet breeding on: the tab"); + c.Ilt.SetJson("{\"ilt\":true,\"features\":[{\"key\":\"pet_breeding\",\"label\":\"Pet breeding\",\"group\":\"Pets\",\"state\":-1,\"where\":\"\"}]}"); + Check(view.VisibleTabs().Contains(OracleView.TabBreeding), "ILT with pet breeding not known yet: the tab (it says what it is waiting for)"); + c.Ilt.SetJson(""); + + IltBreedingView v = IltBreedingView.Parse(BreedingJson(2)); + Check(v.Loaded && v.Available && v.Enabled == "on" && v.Room == "landblock 0x0106 variant 2" && v.FreeSlots == 12, "breeding JSON header"); + Check(v.Essences.Count == 2 && v.Essences[0].Male && !v.Essences[1].Male && v.Essences[0].Ready && v.Essences[0].Boosters.Count == 1, + "breeding essences with sex, readiness and boosters"); + Check(v.Pairs.Count == 1 && Math.Abs(v.Pairs[0].ChanceBest - 0.13636) < 1e-9 && v.Pairs[0].InheritMax == 2, "breeding pair odds"); + Check(v.Supplies.Count == 2 && v.Supplies[0].Targets.Count == 2 && !v.Supplies[1].Apply, "breeding supplies and their targets"); + Check(v.Debug is { Match: "valid", Partners: 1 }, "breeding diagnostics"); + Check(!IltBreedingView.Parse("not json").Loaded && !IltBreedingView.Parse("").Loaded && !IltBreedingView.Parse("[1]").Loaded, + "bad breeding JSON is not loaded"); + Check(IltBreedingView.ApplyVerb(" incense1 ", 1000) == "apply incense1 1000" && IltBreedingView.DanceVerb() == "dance", "breeding verbs"); + + // Nothing from RynthILT yet: the tab says to load it. + var host = new UiHost(); + UiWindow main = host.Add(new UiWindow("RynthOracle/Oracle", "Oracle") { Visible = true }); + c.Settings.TabName = OracleView.TabBreeding; + Check(Frame(host, main, view, "Pet Breeding empty").Contains("Load RynthILT (0.3.1 or later)"), "without RynthILT: says to load it"); + + // 50 essences with every section open: rows cut at 40, the page still fits. + var sent = new List(); + string ran = ""; + c.BreedingCommand = verb => { sent.Add(verb); return true; }; + c.RunCommand = cmd => { ran = cmd; return true; }; + c.Breeding = IltBreedingView.Parse(BreedingJson(50)); + Frame(host, main, view, "Pet Breeding opening"); + foreach (string header in new[] { "br.sup", "br.rules", "br.events" }) + Apply(host, Event(6, ++_seq, main.Hash, main.KeyOf(header), new byte[] { 1 })); + string body = Frame(host, main, view, "Pet Breeding with 50 essences", out int ops); + Check(ops > 5 && ops < 1400, $"Pet Breeding with 50 essences: {ops} ops"); + Console.WriteLine($" InfiniteLeaftide/Pet Breeding (50 essences, all open): {ops} ops, {body.Length} bytes"); + Check(body.Contains("Essences (2 ready of 50)") && body.Contains("... and 10 more"), "essence rows cut at 40 with a count"); + Check(body.Contains("Essence 0 x Essence 1") && body.Contains("5%-13.6%"), "the ready pair with its odds"); + Check(body.Contains("Supplies (3 carried)") && body.Contains("250,000 pyreals"), "supplies with Ivo's price"); + Check(body.Contains("Stud charges") && body.Contains("seen on server") && body.Contains("In the breeding room"), "rules and diagnostics"); + Check(body.Contains("A baby pet has been born"), "recent events"); + Check(body.Contains("###refresh.Pet Breeding"), "the page has the Refresh row every page has"); + + // Dance asks first; No drops it, Yes sends it. + Click(host, main, "br.dance"); + Check(sent.Count == 0, "Dance asks before sending"); + body = Frame(host, main, view, "Pet Breeding asking"); + Check(body.Contains("Dance now?") && body.Contains("###br.yes") && body.Contains("###br.no"), "the question with Yes / No"); + Click(host, main, "br.no"); + body = Frame(host, main, view, "Pet Breeding no"); + Check(sent.Count == 0 && !body.Contains("###br.yes"), "No drops the question"); + Click(host, main, "br.dance"); + Frame(host, main, view, "Pet Breeding asking again"); + Click(host, main, "br.yes"); + Check(sent.Count == 1 && sent[0] == "dance", "Yes sends the dance verb"); + + // A supply use on the selected essence (the first) asks first as well. + body = Frame(host, main, view, "Pet Breeding supplies"); + Check(body.Contains("###br.use.0") && !body.Contains("###br.use.1"), "only a usable, carried supply has Use"); + Click(host, main, "br.use.0"); + Check(sent.Count == 1, "a supply use asks before sending"); + Frame(host, main, view, "Pet Breeding supply question"); + Click(host, main, "br.yes"); + Check(sent.Count == 2 && sent[1] == "apply incense1 1000", "Use then Yes sends apply with the essence id: " + string.Join("|", sent)); + + Click(host, main, "br.debug"); + Check(sent.Count == 3 && sent[2] == "debug", "Diagnostics is sent straight away (it only reads)"); + Click(host, main, "br.remote"); + Check(ran == "/ra hub open breeding", "Mini Remote opens Pets > Breeding: " + ran); + + // The page's Refresh row asks RynthILT to appraise again. + Click(host, main, "refresh.Pet Breeding"); + Check(sent.Count == 4 && sent[3] == "refresh", "Refresh sends refresh: " + string.Join("|", sent)); + + // Breeding switched off on the server: said in red, page still drawn. + c.Breeding = IltBreedingView.Parse("{\"available\":true,\"enabled\":\"off\",\"essences\":[]}"); + Check(Frame(host, main, view, "Pet Breeding off").Contains("Pet breeding is off on this server."), "breeding off is shown"); + } + + /// The Character tab's Charms section (RynthILT's list, Toggle routed back to it). + private static void Charms() + { + const string charmsJson = "{\"available\":true,\"world\":\"InfiniteLeaftide\",\"acquiredCount\":2,\"activeCount\":1," + + "\"charms\":[{\"name\":\"Mana Barrier\",\"effect\":\"Absorbs damage\",\"acquired\":\"carried\",\"count\":1,\"tier\":3,\"maxTier\":5," + + "\"active\":\"on\",\"server\":\"on\",\"toggleId\":5001}," + + "{\"name\":\"Swift Feet\",\"acquired\":\"seen\",\"lastSeen\":\"2026-10-12\",\"active\":\"unknown\",\"server\":\"off\"}]," + + "\"hands\":[{\"id\":7001,\"name\":\"Guardian Hand\",\"active\":\"off\",\"server\":\"on\"}]}"; + + OracleContext c = Context(); + c.Server.Force(ServerTags.InfiniteLeaftide, "InfiniteLeaftide"); + c.Settings.TabName = OracleView.TabCharacter; + var view = new OracleView(c); + var host = new UiHost(); + UiWindow main = host.Add(new UiWindow("RynthOracle/Oracle", "Oracle") { Visible = true }); + + string empty = Frame(host, main, view, "Character, no RynthILT"); + Check(empty.Contains("Load RynthILT to list your Infinite Leaftide charms"), "ILT without RynthILT: says to load it"); + + uint toggled = 0; + c.ToggleCharm = id => { toggled = id; return true; }; + c.Charms = RynthCore.Plugin.Shared.IltCharmsView.Parse(charmsJson); + string body = Frame(host, main, view, "Character with charms", out int ops); + Check(ops > 5 && ops < 1400, $"Character with charms: {ops} ops"); + Check(body.Contains("Charms (2)") && body.Contains("Mana Barrier") && body.Contains("T3/5") && body.Contains("seen 2026-10-12"), + "the charms RynthILT listed, with tier and acquired state"); + Check(body.Contains("server off"), "a charm the server switched off is marked"); + Check(body.Contains("Guardian Hands (1)"), "the Guardian Hands are listed"); + Check(body.Contains("###c.charm.0") && !body.Contains("###c.charm.1"), "an uncarried charm has no Toggle"); + Click(host, main, "c.charm.0"); + Check(toggled == 5001, "the carried charm's Toggle goes to RynthILT with its id"); + Click(host, main, "c.hand.0"); + Check(toggled == 7001, "the Guardian Hand's Toggle goes to RynthILT with its id"); + + // Another world: RynthILT answers "not available", so no charms section at all. + c.Server.Force("", ""); + c.Charms = RynthCore.Plugin.Shared.IltCharmsView.Parse("{\"available\":false,\"charms\":[]}"); + Check(!Frame(host, main, view, "Character off ILT").Contains("Charms ("), "off ILT: no charms section"); + } + + // ── The merged Quests list ─────────────────────────────────────────── + + private const string GuardianJson = "{\"available\":true,\"world\":\"InfiniteLeaftide\",\"chat\":true,\"auto\":false,\"buy\":true," + + "\"cooldownHours\":20,\"answer\":\"Pyreal\",\"npc\":\"Guardian of Attribute Enlightenment\",\"answerAgeSec\":30," + + "\"heard\":\"What is the coin of the realm?\",\"running\":false,\"status\":\"idle\",\"synced\":\"2026-10-18T19:05:00Z\"," + + "\"rows\":[{\"attribute\":\"Strength\",\"npc\":\"Fiun Strongarm\",\"count\":3,\"status\":\"Ready\",\"eta\":\"\",\"ready\":true,\"exact\":true}," + + "{\"attribute\":\"Focus\",\"npc\":\"Fiun Thinker\",\"count\":1,\"status\":\"Cooldown\",\"eta\":\"in 5h 2m\",\"ready\":false,\"exact\":false}]}"; + + /// The "N shown" count in a page body. + private static int Shown(string body) + { + int at = body.IndexOf(" shown", StringComparison.Ordinal); + if (at < 0) return -1; + int s = at; + while (s > 0 && char.IsDigit(body[s - 1])) s--; + return int.TryParse(body.AsSpan(s, at - s), out int n) ? n : -1; + } + + /// Each source appears in the one list, per server, with its filters; Trackers only and Show narrow it. + private static void MergedList() + { + // Retail: quests, Legendary quests and markers; no stamps or guardians. + OracleContext c = On(""); + var view = new OracleView(c); + var host = new UiHost(); + UiWindow main = host.Add(new UiWindow("RynthOracle/Oracle", "Oracle") { Visible = true }); + c.Settings.TabName = OracleView.TabQuests; + int quests = c.Catalog.Quests.Count; + int leg = LegendaryList.All.Count, mrk = MarkerList.All.Count, dyn = DynamicStampList.All.Count; + + Check(view.AvailableKinds().SequenceEqual(new[] { QuestKind.Quest, QuestKind.Legendary, QuestKind.Marker }), "retail kinds: quests, Legendary, markers"); + string body = Frame(host, main, view, "Quests, retail, everything"); + Check(Shown(body) == quests + leg + mrk, $"retail: quests + Legendary + markers in one list ({Shown(body)} shown, {quests + leg + mrk} expected)"); + Check(body.Contains("###q.trackers") && body.Contains("###q.kind") && body.Contains("###q.sort") && body.Contains("###q.timers"), + "Trackers only, Show, Sort and the Quest Timers button are on the page"); + Check(body.Contains("###refresh.Quests"), "the Refresh row every page has is still on the Quests page"); + + // Trackers only: the quests drop out, the trackers' status shows above. + Tick(host, main, "q.trackers", true); + body = Frame(host, main, view, "Quests, trackers only"); + Check(Shown(body) == leg + mrk, $"Trackers only: Legendary + markers ({Shown(body)})"); + Check(body.Contains("toward John") && body.Contains("markers found") && body.Contains("LEG") && !body.Contains("###q.r.30minattributes"), + "Trackers only: John's counter and the markers' progress above, no quests"); + Check(!body.Contains("###dy.area") && !body.Contains("Dynamic stamps"), "retail: no stamp status or area picker"); + Tick(host, main, "q.trackers", false); + + // Show: one kind per source. + foreach ((QuestKind kind, int want) in new[] { (QuestKind.Quest, quests), (QuestKind.Legendary, leg), (QuestKind.Marker, mrk) }) + { + view.ShowTrackers(kind); + body = Frame(host, main, view, "Quests, " + kind); + Check(Shown(body) == want, $"Show {kind}: {Shown(body)} shown ({want} expected)"); + } + + // Done / Not done on markers: the Markers tab's "only the ones still to find". + long at = DateTimeOffset.UtcNow.AddDays(-1).ToUnixTimeSeconds(); + c.Flags.OnChatLine($"explorationmarkersfoundingroupa - 3 solves ({at})\"Markers\" 1023 0", c.NowMs); + c.Flags.Tick(c.NowMs + 5_000); + view.ShowTrackers(QuestKind.Marker); + body = Frame(host, main, view, "Markers, none filtered"); + Check(Shown(body) == 100 && body.Contains("2 / 100 markers found"), "markers: bits 1 and 2 of group A found: " + (body.Contains("markers found") ? "status shown" : "no status")); + Tick(host, main, "q.notdone", true); + body = Frame(host, main, view, "Markers, not done"); + Check(Shown(body) == 98, $"markers, Not done: the ones still to find ({Shown(body)})"); + Tick(host, main, "q.notdone", false); + Tick(host, main, "q.done", true); + body = Frame(host, main, view, "Markers, done"); + Check(Shown(body) == 2, $"markers, Done: the two found ({Shown(body)})"); + Tick(host, main, "q.done", false); + + // Repeatable / One-time: Legendary rows repeat, markers don't. + view.ShowTrackers(null); + Tick(host, main, "q.rep", true); + body = Frame(host, main, view, "Trackers, repeatable"); + Check(Shown(body) == leg, $"Repeatable: the Legendary quests ({Shown(body)})"); + Tick(host, main, "q.rep", false); + Tick(host, main, "q.one", true); + body = Frame(host, main, view, "Trackers, one-time"); + Check(Shown(body) == mrk, $"One-time: the markers ({Shown(body)})"); + Tick(host, main, "q.one", false); + + // The quest-only filters leave the trackers out. + Tick(host, main, "q.new", true); + body = Frame(host, main, view, "Trackers, Not in list"); + Check(Shown(body) == 0, "Not in list is a quests-only filter: no tracker rows"); + Tick(host, main, "q.new", false); + + // Search reaches the trackers' text (the notes, places, flags). + Type(host, main, "q.search", "mhoire"); + body = Frame(host, main, view, "Trackers, search"); + int wantSearch = LegendaryList.All.Count(l => $"{l.Label} {l.Group} {l.Note} {string.Join(" ", l.Flags)}".Contains("mhoire", StringComparison.OrdinalIgnoreCase)) + + MarkerList.All.Count(m => $"#{m.Number} {m.Name} {m.Location} {m.Hint}".Contains("mhoire", StringComparison.OrdinalIgnoreCase)); + Check(Shown(body) == wantSearch && wantSearch > 0, $"Search \"mhoire\" over the trackers: {Shown(body)} shown ({wantSearch} expected)"); + Type(host, main, "q.search", ""); + + // Favourites: tracking a quest (the * list) also marks the Legendary row of the same flag. + LegendaryQuest rtw = LegendaryList.All.First(q => q.CommonName == "RTW"); + c.Book.SetTracked(rtw.Flags[0], true); + Tick(host, main, "q.tracked", true); + body = Frame(host, main, view, "Trackers, tracked"); + Check(Shown(body) == 1 && body.Contains("###q.r.lg:" + rtw.Name), $"Tracked: the tracked quest's Legendary row ({Shown(body)})"); + view.ShowTrackers(QuestKind.Quest); + body = Frame(host, main, view, "Quests, tracked"); + Check(Shown(body) == 3 && body.Contains("###q.t.30minattributes"), $"Tracked quests are still the favourites (the * list): {Shown(body)} shown"); + Tick(host, main, "q.tracked", false); + c.Book.SetTracked(rtw.Flags[0], false); + + // Sorts do not throw and keep every row. + view.ShowTrackers(null); + foreach (int sort in new[] { 1, 2, 3, 4, 5, 0 }) + { + Apply(host, Event(3, ++_seq, main.Hash, main.KeyOf("q.sort"), BitConverter.GetBytes(sort))); + body = Frame(host, main, view, "Trackers, sort " + sort); + Check(Shown(body) == leg + mrk, $"sort {sort} keeps every row ({Shown(body)})"); + } + + // Infinite Leaftide: stamps and guardians join; the area picker narrows the stamps. + OracleContext ic = On(ServerTags.InfiniteLeaftide); + var iv = new OracleView(ic); + var ihost = new UiHost(); + UiWindow imain = ihost.Add(new UiWindow("RynthOracle/Oracle", "Oracle") { Visible = true }); + ic.Settings.TabName = OracleView.TabQuests; + ic.Guardian = IltGuardianView.Parse(GuardianJson); + ic.GuardianRevision++; + int iq = ic.Catalog.Quests.Count; + body = Frame(ihost, imain, iv, "Quests, ILT, everything"); + Check(Shown(body) == iq + leg + mrk + dyn + 2, $"ILT: quests + Legendary + markers + {dyn} stamps + 2 guardians ({Shown(body)}, {iq + leg + mrk + dyn + 2} expected)"); + foreach ((QuestKind kind, int want, string tag) in new[] { (QuestKind.Dynamic, dyn, "DYN"), (QuestKind.Guardian, 2, "GRD") }) + { + iv.ShowTrackers(kind); + body = Frame(ihost, imain, iv, "Quests, ILT, " + kind); + Check(Shown(body) == want && body.Contains(tag), $"ILT Show {kind}: {Shown(body)} shown ({want} expected)"); + } + iv.ShowTrackers(QuestKind.Dynamic); + Frame(ihost, imain, iv, "Quests, ILT, stamps"); + Apply(ihost, Event(3, ++_seq, imain.Hash, imain.KeyOf("dy.area"), BitConverter.GetBytes(1))); + body = Frame(ihost, imain, iv, "Quests, ILT, one area"); + int areaCount = DynamicStampList.All.Count(s => s.Area == DynamicStampList.Areas[0]); + Check(Shown(body) == areaCount, $"the area picker narrows the stamps to {DynamicStampList.Areas[0]}: {Shown(body)} ({areaCount} expected)"); + + // A saved tab name of an old tab opens Quests; the Markers / Legendary / Dynamic Stamps tabs are gone. + ic.Settings.TabName = "Markers"; + Check(iv.Tab == OracleView.TabQuests, "a saved \"Markers\" tab opens Quests"); + ic.Settings.TabName = "Dynamic Stamps"; + Check(iv.Tab == OracleView.TabQuests, "a saved \"Dynamic Stamps\" tab opens Quests"); + string[] tabs = iv.VisibleTabs(); + Check(!tabs.Contains("Markers") && !tabs.Contains("Legendary") && !tabs.Contains("Dynamic Stamps"), "no separate tracker tabs: " + string.Join(",", tabs)); + } + + /// Everything the old Markers tab showed is reachable from the Quests list. + private static void MarkersReachable() + { + OracleContext c = On(""); + var printed = new List(); + c.PrintSink = printed.Add; + var navs = new List(); + c.SendNav = line => { navs.Add(line); return true; }; + var view = new OracleView(c); + var host = new UiHost(); + UiWindow main = host.Add(new UiWindow("RynthOracle/Oracle", "Oracle") { Visible = true }); + c.Settings.TabName = OracleView.TabQuests; + long at = DateTimeOffset.UtcNow.AddDays(-1).ToUnixTimeSeconds(); + c.Flags.OnChatLine($"explorationmarkersfoundingroupa - 1 solves ({at})\"Markers\" 1023 0", c.NowMs); + c.Flags.Tick(c.NowMs + 5_000); + + view.ShowTrackers(QuestKind.Marker); // /ro markers + string body = Frame(host, main, view, "Markers"); + Check(body.Contains("1 / 100 markers found"), "the progress bar: markers found of 100"); + Marker next = MarkerList.All[1]; + Check(body.Contains("Next marker:") && body.Contains($"#{next.Number} {next.Name} ({next.Location})"), "the next marker to run to"); + Check(body.Contains("###q.r.mk:1") && body.Contains("###q.r.mk:2"), "a row per marker"); + + // "Next marker" opens that marker, and a click prints the directions in chat (the old tab did). + Click(host, main, "m.next"); + Check(printed.Count >= 2 && printed[0].StartsWith($"Marker {next.Number}: {next.Name}") && printed.Contains(next.Hint), "a click prints the marker and its directions: " + string.Join(" | ", printed.Take(3))); + body = Frame(host, main, view, "Marker opened"); + Check(body.Contains("Marker 2") && body.Contains("not found yet") && body.Contains("###q.nav.go") && body.Contains("###m.sel.print") && body.Contains("###m.sel.close"), + "the marker opens below the list: status, Go to, Print, Close"); + Click(host, main, "q.nav.go"); + Check(navs.Count == 1 && navs[0].StartsWith("go "), "Go to sends RynthNav a go: " + string.Join("|", navs)); + Click(host, main, "q.nav.route"); + Click(host, main, "q.nav.arrow"); + Check(navs.Count == 3 && navs[1].StartsWith("route ") && navs[2].StartsWith("arrow "), "Route and Arrow likewise"); + + // Print in chat from the panel; a second click on the row closes it (and prints again). + printed.Clear(); + Click(host, main, "m.sel.print"); + Check(printed.Count >= 2, "Print in chat from the opened marker"); + printed.Clear(); + Click(host, main, "q.r.mk:2"); + body = Frame(host, main, view, "Marker closed"); + Check(printed.Count >= 2 && !body.Contains("###m.sel.close"), "a second click on the row prints again and closes it"); + } + + /// Opening a Legendary quest, a marker or a quest with coordinates in its notes offers RynthNav's Go to. + private static void GoToButtons() + { + OracleContext c = On(""); + var navs = new List(); + c.SendNav = line => { navs.Add(line); return true; }; + var printed = new List(); + c.PrintSink = printed.Add; + var view = new OracleView(c); + var host = new UiHost(); + UiWindow main = host.Add(new UiWindow("RynthOracle/Oracle", "Oracle") { Visible = true }); + c.Settings.TabName = OracleView.TabQuests; + + // The shipped Legendary notes carry no coordinates, so a row with them is added for the test + // (first in the list, taken out again): several places give a picker first, picking plans the route. + var fake = new LegendaryQuest + { + Group = "Testing", Name = "Test Route Quest", Luminance = 1, Flags = new[] { "testroutequest" }, + Note = "Speak with Hoshar 59.6S 88.0W - Kill Mukkir 86.5N 57.3E", + }; + var one = new LegendaryQuest + { + Group = "Testing", Name = "Test One Place", Luminance = 1, Flags = new[] { "testoneplace" }, + Note = "Speak with Hoshar 59.6S 88.0W", + }; + LegendaryList.All.Insert(0, fake); + try + { + view.ShowTrackers(QuestKind.Legendary); + Frame(host, main, view, "Legendary"); + Click(host, main, "q.r.lg:" + fake.Name); + string body = Frame(host, main, view, "Legendary opened"); + Check(body.Contains("Go to (2 places in these notes)") && body.Contains("###q.nav.pick") && body.Contains("###q.nav.go"), + "a Legendary quest with 2 places in its notes: a picker and Go"); + Check(body.Contains("###lg.sel.print") && body.Contains("###lg.sel.close") && body.Contains("Testing"), "its area, Print and Close buttons"); + Apply(host, Event(3, ++_seq, main.Hash, main.KeyOf("q.nav.pick"), BitConverter.GetBytes(1))); + Check(navs.Count == 1 && navs[0] == "route 86.5N, 57.3E Kill Mukkir", "picking the second place plans its route: " + string.Join("|", navs)); + Frame(host, main, view, "Legendary, second place picked"); + Click(host, main, "q.nav.go"); + Check(navs.Count == 2 && navs[1] == "go 86.5N, 57.3E Kill Mukkir", "Go walks the picked place: " + string.Join("|", navs)); + Click(host, main, "lg.sel.print"); + Check(printed.Count >= 1 && printed[0].Contains("Test Route Quest") && printed.Any(p => p.Contains("Speak with Hoshar")), + "Print in chat prints the quest and its notes: " + string.Join(" | ", printed.Take(3))); + + // One place: no picker. + Click(host, main, "q.r.lg:" + fake.Name); // close + LegendaryList.All.Insert(0, one); + Type(host, main, "q.search", "Test One"); // the row list is cached per filter: a new search rebuilds it + Frame(host, main, view, "Legendary, with the one-place row"); + Click(host, main, "q.r.lg:" + one.Name); + body = Frame(host, main, view, "Legendary, one place"); + Check(body.Contains("Go to") && !body.Contains("###q.nav.pick") && body.Contains("###q.nav.go"), "one place: Go / Route / Arrow, no picker"); + + // A real Legendary quest (no coordinates in its notes): opens, no Go to. + LegendaryQuest real = LegendaryList.All.First(q => q != fake && q != one); + Click(host, main, "q.r.lg:" + one.Name); // close + Type(host, main, "q.search", ""); + Frame(host, main, view, "Legendary, all rows again"); + Click(host, main, "q.r.lg:" + real.Name); + body = Frame(host, main, view, "Legendary, no place"); + Check(!body.Contains("###q.nav.go") && body.Contains("###lg.sel.close") && body.Contains("Area"), "no coordinates in the notes: no Go to"); + } + finally + { + LegendaryList.All.Remove(fake); + LegendaryList.All.Remove(one); + } + + // A plain quest whose notes have coordinates: Go to under its texts, and the click still prints. + Quest? withCoords = c.Catalog.Quests.FirstOrDefault(q => NavTargets.Stops(q.Info + " - " + q.Hint).Count > 0); + Check(withCoords != null, "some quest in the list has coordinates in its notes"); + if (withCoords != null) + { + view.ShowTrackers(QuestKind.Quest); + Type(host, main, "q.search", withCoords.Flag); + Frame(host, main, view, "Quests, searched"); + printed.Clear(); + Click(host, main, "q.r." + withCoords.Flag); + string body = Frame(host, main, view, "Quest with coordinates"); + Check(printed.Count >= 4, "a click on a quest still prints its texts in chat"); + Check(body.Contains("###q.nav.go") && body.Contains("Save rewards") && body.Contains("###q.sel.track"), + "the quest opens with Go to, Track and the rewards editor"); + Type(host, main, "q.search", ""); + } + } + + /// The guardians as rows, their controls sending RynthILT's verbs, and the stamps' opened box. + private static void Trackers() + { + var g = IltGuardianView.Parse(GuardianJson); + Check(g.Loaded && g.Chat && !g.Auto && g.Buy && g.Answer == "Pyreal" && g.AnswerAgeSec == 30 && g.SyncedUtc.Year == 2026, "guardian JSON header"); + Check(g.Rows.Count == 2 && g.Rows[0].Ready && g.Rows[0].Exact && g.Rows[1].Eta == "in 5h 2m" && !g.Rows[1].Exact, "guardian rows"); + Check(!IltGuardianView.Parse("nope").Loaded && !IltGuardianView.Parse("").Loaded, "bad guardian JSON is not loaded"); + Check(IltGuardianView.SwitchVerb(" Auto ", true) == "auto on" && IltGuardianView.SwitchVerb("buy", false) == "buy off" + && IltGuardianView.HandInVerb() == "handin", "guardian verbs"); + + OracleContext c = On(ServerTags.InfiniteLeaftide); + var view = new OracleView(c); + var host = new UiHost(); + UiWindow main = host.Add(new UiWindow("RynthOracle/Oracle", "Oracle") { Visible = true }); + c.Settings.TabName = OracleView.TabQuests; + + view.ShowTrackers(QuestKind.Guardian); + string body = Frame(host, main, view, "Guardians without RynthILT"); + Check(body.Contains("RynthILT isn't loaded"), "guardians without RynthILT: says to load it"); + + var sent = new List(); + c.GuardianCommand = verb => { sent.Add(verb); return true; }; + c.Guardian = g; + c.GuardianRevision++; + body = Frame(host, main, view, "Guardians"); + Check(body.Contains("Temple guardians") && body.Contains("1 of 2 attribute turn-ins ready") && body.Contains("Pyreal") + && body.Contains("###gd.handin") && body.Contains("GRD") && body.Contains("Strength (Fiun Strongarm)") && body.Contains("in 5h 2m"), + "guardian controls, answer and rows"); + Click(host, main, "gd.handin"); + Tick(host, main, "gd.auto", true); + Tick(host, main, "gd.buy", false); + Click(host, main, "gd.refresh"); + Check(string.Join("|", sent) == "handin|auto on|buy off|refresh", "guardian controls send their verbs: " + string.Join("|", sent)); + + // Open a guardian row, then every kind at once under the engine's ops limit. + Click(host, main, "q.r.gd:Strength"); + view.ShowTrackers(null); + body = Frame(host, main, view, "ILT trackers, a guardian opened", out int ops); + int rows = LegendaryList.All.Count + MarkerList.All.Count + DynamicStampList.All.Count + 2; + Check(Shown(body) == rows && body.Contains("Temple guardian: Strength") && body.Contains("###gd.sel.close"), $"every ILT tracker listed ({Shown(body)}), a guardian opened below"); + Check(ops > 40 && ops < 1400, $"ILT Quests with every tracker and a guardian opened: {ops} ops"); + Console.WriteLine($" InfiniteLeaftide/Quests, trackers only ({rows} rows, guardian opened): {ops} ops, {body.Length} bytes"); + + // A stamp: the nav box with Go / Arrow / Chat, RynthNav asked for the route at once. + var navs = new List(); + c.SendNav = line => { navs.Add(line); return true; }; + var printed = new List(); + c.PrintSink = printed.Add; + view.ShowTrackers(QuestKind.Dynamic); + DynamicStamp felscuda = DynamicStampList.All.First(s => s.Npc == "Felscuda"); + Frame(host, main, view, "Stamps"); + Click(host, main, "q.r.dy:" + felscuda.Stamp); + Check(navs.Count == 1 && navs[0] == "route 8.8S, 53.1E || Folthid Cellar || Felscuda || Facility Hub", "clicking a stamp asks RynthNav for its route: " + string.Join("|", navs)); + body = Frame(host, main, view, "Stamp opened"); + Check(body.Contains("Navigate to Felscuda") && body.Contains("###dy.nav.go") && body.Contains("###dy.nav.arrow") && body.Contains("###dy.nav.chat"), "the stamp's box"); + Click(host, main, "dy.nav.go"); + Check(navs.Count == 2 && navs[1].StartsWith("go 8.8S, 53.1E || "), "Go sends a go with every candidate"); + Click(host, main, "dy.nav.chat"); + Check(printed.Count >= 1 && printed[0].Contains("Felscuda") && printed[0].Contains("missing"), "Chat prints the stamp: " + string.Join(" | ", printed.Take(2))); + } + + /// Give Parchment sends /ub give, and is disabled with a tooltip when RynthAi can't take it. + private static void GiveParchment() + { + OracleContext c = On(ServerTags.InfiniteLeaftide); + c.ParchmentFinder = () => "Parchment of Learning"; + var ran = new List(); + c.RunCommand = cmd => { ran.Add(cmd); return true; }; + c.SendNav = _ => true; + var view = new OracleView(c); + var host = new UiHost(); + UiWindow main = host.Add(new UiWindow("RynthOracle/Oracle", "Oracle") { Visible = true }); + c.Settings.TabName = OracleView.TabQuests; + DynamicStamp felscuda = DynamicStampList.All.First(s => s.Npc == "Felscuda"); + view.ShowTrackers(QuestKind.Dynamic); + Frame(host, main, view, "Stamps"); + Click(host, main, "q.r.dy:" + felscuda.Stamp); + + // RynthAi isn't there: no button, a greyed line and the reason. + c.UbGiveAvailable = () => false; + string body = Frame(host, main, view, "Give, no RynthAi"); + Check(!body.Contains("###dy.nav.give") && body.Contains("[Give Parchment of Learning]") && body.Contains("Needs RynthAi"), + "no RynthAi: Give Parchment is disabled with a tooltip"); + Check(ran.Count == 0, "nothing was sent"); + + // RynthAi there: the button sends /ub give 1. + c.UbGiveAvailable = () => true; + body = Frame(host, main, view, "Give, RynthAi"); + Check(body.Contains("###dy.nav.give") && body.Contains("Hands one Parchment of Learning to Felscuda"), "RynthAi loaded: the Give button and its tooltip"); + c.NowMs = 50_000; + Click(host, main, "dy.nav.give"); + Check(ran.Count == 0, "one click doesn't give anything away"); + body = Frame(host, main, view, "Give, asking"); + Check(body.Contains("Give one Parchment of Learning to Felscuda?") && body.Contains("###dy.nav.give.yes") && body.Contains("###dy.nav.give.no"), + "it asks, naming the item and the NPC"); + Click(host, main, "dy.nav.give.no"); + body = Frame(host, main, view, "Give, cancelled"); + Check(ran.Count == 0 && body.Contains("###dy.nav.give") && !body.Contains("###dy.nav.give.yes"), "Cancel drops the question, nothing sent"); + Click(host, main, "dy.nav.give"); + Frame(host, main, view, "Give, asking again"); + Click(host, main, "dy.nav.give.yes"); + Check(ran.Count == 1 && ran[0] == "/ub give 1 Parchment of Learning to Felscuda", "Yes sends /ub give 1: " + string.Join("|", ran)); + Check(c.UbGiveSentMs == 50_000, "the send is stamped, so a rejection can be tied to it"); + + // The loaded RynthAi answers "Unrecognized /ub command": the button turns itself off. + Check(!c.NoteChatLineForGive("[RynthAi] some other line", 52_000) && !c.UbGiveMissing, "an unrelated line changes nothing"); + Check(!c.NoteChatLineForGive("[RynthAi] Unrecognized /ub command.", 60_000) && !c.UbGiveMissing, "a rejection long after the send is not tied to it"); + Check(c.NoteChatLineForGive("[RynthAi] Unrecognized /ub command.", 52_000) && c.UbGiveMissing, "a rejection right after the send disables Give"); + body = Frame(host, main, view, "Give, rejected"); + Check(!body.Contains("###dy.nav.give") && body.Contains("[Give Parchment of Learning]") && body.Contains("Unrecognized /ub command"), + "rejected: disabled, the tooltip says why"); + Click(host, main, "q.r.dy:" + felscuda.Stamp); // close + Click(host, main, "q.r.dy:" + felscuda.Stamp); // open again + ran.Clear(); + Frame(host, main, view, "Give, rejected again"); + Check(ran.Count == 0, "no further /ub give goes out"); + + // No Parchment carried: said, no button either way. + c.UbGiveMissing = false; + c.ParchmentFinder = () => null; + body = Frame(host, main, view, "Give, none carried"); + Check(body.Contains("No Parchment in your packs") && !body.Contains("###dy.nav.give"), "no Parchment: no button, says so"); + + // A name with a control character can't smuggle a second command. + c.ParchmentFinder = () => "Parchment\nof /quit"; + c.UbGiveAvailable = () => true; + Frame(host, main, view, "Give, odd name"); + ran.Clear(); + Click(host, main, "dy.nav.give"); + Frame(host, main, view, "Give, odd name asking"); + Click(host, main, "dy.nav.give.yes"); + Check(ran.Count == 1 && !ran[0].Contains('\n') && ran[0].StartsWith("/ub give 1 "), "control characters are stripped from the command: " + (ran.Count > 0 ? ran[0].Replace("\n", "\\n") : "")); + } + + /// The throttle line, and the Refresh bar on the Quests page. + private static void Throttle() + { + OracleContext c = On(""); + var view = new OracleView(c); + var host = new UiHost(); + UiWindow main = host.Add(new UiWindow("RynthOracle/Oracle", "Oracle") { Visible = true }); + c.Settings.TabName = OracleView.TabQuests; + c.Flags.Request(_ => true, c.NowMs); + c.Flags.OnChatLine("[MyQuests] This command may only be run once every 60 seconds.", c.NowMs + 100); + string body = Frame(host, main, view, "Quests, throttled"); + Check(body.Contains("The server answers one /myquests a minute: Refresh works again in 6"), "the throttle line says when Refresh works again"); + Click(host, main, "refresh.Quests"); + Check(Frame(host, main, view, "Quests, Refresh while throttled").Contains("try again in 6"), "Refresh while the server's minute runs says to wait, and sends nothing"); + c.NowMs += 61_000; + Check(!Frame(host, main, view, "Quests, throttle over").Contains("Refresh works again in"), "the countdown line goes once the minute is up"); + } + } +} diff --git a/Tools/RynthOracle.Tests/Program.cs b/Tools/RynthOracle.Tests/Program.cs index 01c116a..b76bc1a 100644 --- a/Tools/RynthOracle.Tests/Program.cs +++ b/Tools/RynthOracle.Tests/Program.cs @@ -24,7 +24,7 @@ namespace RynthCore.Engine.UI.ScriptWindows namespace RynthOracle.Tests { - internal static class Program + internal static partial class Program { private static int _pass, _fail; @@ -39,22 +39,37 @@ namespace RynthOracle.Tests private static int Main() { + // Tab clicks save the settings: into a scratch file, never the player's %APPDATA% copy. + OracleSettings.PathOverride = System.IO.Path.Combine(System.IO.Path.GetTempPath(), "RynthOracleTests-" + Guid.NewGuid().ToString("N") + "-settings.json"); Lists(); QuestLines(); Catalog(); Servers(); EngineServers(); + IltProfile(); + ServerFeatures(); QuestNotes(); - ConquestReplies(); - AelrynthReplies(); Void(); TimerAlerts(); Pages(); CharacterExtras(); + Charms(); + Breeding(); + Legendary(); + DynamicStamps(); + GoToParsing(); + Loaders(); + MergedList(); + MarkersReachable(); + GoToButtons(); + Trackers(); + GiveParchment(); + Throttle(); Events(); QuestTexts(); Refreshes(); SkillsTabs(); + ServerMove(); Console.WriteLine($"{_pass} passed, {_fail} failed"); return _fail == 0 ? 0 : 1; } @@ -156,6 +171,37 @@ namespace RynthOracle.Tests s2.NoteTypedCommand(); // the player typing it s2.Tick(51_200); Check(!s2.AwaitingOurs, "a typed /myquests shows its reply"); + + // A second reply that lost most of its lines on the way (the engine's chat queue dropped + // the head of the burst) updates the flags instead of blanking them. + var s3 = new QuestFlagStore(); + long t3 = 200_000; + for (int i = 0; i < 100; i++) + s3.OnChatLine($"flag{i:D3} - 1 solves (1719432000)\"Q{i}\" -1 0", t3 + i); + s3.Tick(t3 + 5_000); + Check(s3.Flags.Count == 100, "first full reply: 100 flags"); + long t4 = t3 + 120_000; + for (int i = 90; i < 100; i++) + s3.OnChatLine($"flag{i:D3} - 2 solves (1719500000)\"Q{i}\" -1 0", t4 + i); + s3.Tick(t4 + 5_000); + Check(s3.Flags.Count == 100 && s3.LastPartialReply is { Got: 10, Had: 100 }, + "a cut-short reply (10 of 100) is merged, not a replacement"); + Check(s3.TryGet("flag095", out QuestFlag f95) && f95.Solves == 2 && s3.TryGet("flag001", out _), + "merged reply updates the lines it had and keeps the rest"); + long t5 = t4 + 120_000; + for (int i = 0; i < 95; i++) + s3.OnChatLine($"flag{i:D3} - 3 solves (1719600000)\"Q{i}\" -1 0", t5 + i); + s3.Tick(t5 + 5_000); + Check(s3.Flags.Count == 95 && !s3.TryGet("flag099", out _), "a near-full reply still replaces (a dropped flag goes away)"); + + // ACECustom's once-a-minute limit: the throttle line ends "Reading..." and keeps the flags. + int had = s3.Flags.Count; + long t6 = t5 + 30_000; + Check(s3.Request(_ => true, t6) && s3.AwaitingOurs, "refresh sent"); + Check(s3.OnChatLine("[MyQuests] This command may only be run once every 60 seconds.", t6 + 200) == MyQuestsLine.Throttled + && !s3.AwaitingOurs && s3.Flags.Count == had, "throttle reply: not loading, flags kept"); + Check(s3.ThrottleSecondsLeft(t6 + 1_000) > 50 && !s3.Request(_ => true, t6 + 10_000), "no resend while the server's minute runs"); + Check(s3.ThrottleSecondsLeft(t6 + 61_000) == 0 && s3.Request(_ => true, t6 + 61_000), "refresh allowed again after the minute"); } private static void Catalog() @@ -224,7 +270,7 @@ namespace RynthOracle.Tests // Identity from it. ServerIdentity.FromEngine(st, "Launcher Profile", out string tag, out string world, out string source); - Check(tag == "" && world == "InfiniteLeaftide" && source.Contains("no RynthOracle pages"), "engine: ILT active has no Oracle tag (its screens are RynthILT's): " + source); + Check(tag == ServerTags.InfiniteLeaftide && world == "InfiniteLeaftide", "engine: ILT active is the ILT tag: " + source); Check(source.Contains("host matches"), "engine: the reason is shown: " + source); var picked = RynthCore.Plugin.Shared.EngineServerState.Parse(EngineJson("conquest", "ConquestAC", "RynthConquest", "conquest", "", @@ -273,7 +319,7 @@ namespace RynthOracle.Tests Check(ServerIdentity.TagForWorld("Conquest") == ServerTags.Conquest, "Conquest"); Check(ServerIdentity.TagForWorld("Levistras") == ServerTags.Levistras, "Levistras"); Check(ServerIdentity.TagForWorld("Coldeve") == "" && ServerIdentity.TagForWorld("") == "", "other servers have no tag"); - Check(ServerIdentity.TagForWorld("InfiniteLeaftide") == "", "Infinite Leaftide has no Oracle tag (RynthILT draws its screens)"); + Check(ServerIdentity.TagForWorld("InfiniteLeaftide") == ServerTags.InfiniteLeaftide, "Infinite Leaftide is the ILT tag (the Quests tab's stamps and guardians, Pet Breeding)"); var id = new ServerIdentity(); id.Force("", "Coldeve"); Check(id.Allows(null) && id.Allows("") && !id.Allows(ServerTags.Conquest) && !id.Allows(ServerTags.Aelrynth), "untagged everywhere, tagged nowhere else"); @@ -285,16 +331,19 @@ namespace RynthOracle.Tests var view = new OracleView(c); c.Server.Force("", "Coldeve"); string[] none = view.VisibleTabs(); - Check(!none.Contains(OracleView.TabBoards) && !none.Contains(OracleView.TabConquest), "no server tabs on other servers: " + string.Join(",", none)); + Check(!none.Contains("Leaderboards") && !none.Contains("Conquest"), "no server tabs on other servers: " + string.Join(",", none)); + // A server's own pages are its server plugin's since 2026-10-20 (RynthConquest, RynthAelrynth). c.Server.Force(ServerTags.Aelrynth, "Aeshnidae"); string[] ael = view.VisibleTabs(); - Check(ael.Contains(OracleView.TabBoards) && !ael.Contains(OracleView.TabConquest), "Aelrynth: leaderboards, no Conquest tab"); + Check(!ael.Contains("Leaderboards") && !ael.Contains("Conquest"), "Aelrynth: no leaderboards in RynthOracle: " + string.Join(",", ael)); c.Server.Force(ServerTags.Conquest, "Conquest"); string[] cq = view.VisibleTabs(); - Check(cq.Contains(OracleView.TabBoards) && cq.Contains(OracleView.TabConquest), "ConquestAC: leaderboards and the Conquest tab"); - c.Settings.TabName = OracleView.TabConquest; - c.Server.Force(ServerTags.Aelrynth, "Aeshnidae"); - Check(view.Tab == OracleView.TabQuests, "a Conquest tab left selected falls back to Quests elsewhere"); + Check(!cq.Contains("Leaderboards") && !cq.Contains("Conquest"), "Conquest: no Conquest tab and no leaderboards in RynthOracle: " + string.Join(",", cq)); + foreach (string old in new[] { "Conquest", "Leaderboards" }) + { + c.Settings.TabName = old; + Check(view.Tab == OracleView.TabQuests, $"a {old} tab saved by an older version falls back to Quests"); + } } // Quest notes: tracking and rewards saved per character, UB's reward format and import, kill-task timers. @@ -369,101 +418,6 @@ namespace RynthOracle.Tests } } - private static void ConquestReplies() - { - var d = new ConquestData(); - long now = 1_000_000; - d.RequestBank(now); - Check(d.OnChatLine("[BANK] Your balances:", now, out bool ours) && ours, "bank heading (ours)"); - d.OnChatLine("[BANK] Pyreals: 1,039,678,533", now, out _); - d.OnChatLine("[BANK] Event Tokens [Dragon Coins] (x): 12", now, out _); - Check(d.Bank.Any(b => b.Name == "Pyreals" && b.Value.Contains("4,158 MMDs")), "pyreals with MMDs"); - Check(d.Bank.Any(b => b.Name == "Dragon Coins (x)"), "event token name"); - Check(!d.OnChatLine("Bob says, \"[BANK] Pyreals: 999\"", now, out _), "a pasted balance is ignored"); - d.OnChatLine("[BANK] Pyreals: 5", now + 60_000, out bool late); - Check(!late, "a reply long after the request isn't ours (shows in chat)"); - - d.RequestAugs(now); - d.OnChatLine("Creature: 25", now, out _); - d.OnChatLine("Duration: 3", now, out _); - ConquestAug creature = d.Augs.First(a => a.Name == "Creature"); - Check(creature.Count == 25 && creature.NextLuminanceCost() == 6_229_500, $"Creature 25 next costs 6,229,500 ({creature.NextLuminanceCost()})"); - Check(d.DurationAugs == 3 && Math.Abs(d.VoidDurationMultiplier(5) - 2.15) < 1e-9, "void duration x(1 + 5*0.2 + 3*0.05)"); - - d.RequestEnl(now); - d.OnChatLine("Enlightenment Augmentations:", now, out _); - d.OnChatLine("Skill Credits: 2 (10 max)", now, out _); - d.OnChatLine("Damage: 5 (25 max)", now, out _); - Check(d.EnlAugs.Count == 2 && d.EnlAugs[0].Name == "Damage", "enlightenment augs in display order"); - - d.RequestBonus(now); - d.OnChatLine("=== XP Bonuses ===", now, out _); - d.OnChatLine("Quest Bonus: 14.18% (1,418 quests)", now, out _); - d.OnChatLine("Total Bonus (Kills): 0.16%", now, out _); - Check(d.Bonuses.First(b => b.Name == "Quest").Value == "14.18% (1,418 quests)" && d.Bonuses.First(b => b.Name == "Total (Kills)").Value == "0.16%", "bonuses"); - - d.RequestFships(now); - d.OnChatLine("Fellowships looking for members:", now, out _); - d.OnChatLine("- Heroes (Leader: Bob) [3/14] @ Bur", now, out _); - d.OnChatLine("- Quiet (Leader: Ann) [1/14]", now, out _); - Check(d.Fellowships.Count == 2 && d.Fellowships[0].Location == "Bur" && d.Fellowships[1].MemberCount == 1, "fellowship list"); - - ConquestBoard lvl = d.Boards.First(b => b.Key == "level"); - d.RequestBoard(lvl, now); - d.OnChatLine("Top 2 Players by Level:", now, out _); - d.OnChatLine("1: 300 - Alpha", now, out _); - d.OnChatLine("2: 299 - Beta", now, out _); - d.OnChatLine("57: 250 - Me (You)", now, out _); - Check(lvl.Rows.Count == 2 && lvl.You != null && lvl.You.Rank == 57 && lvl.You.Name == "Me", "ConquestAC /top board"); - - Check(ConquestData.WithdrawCommand(ConquestData.Withdrawable[ConquestData.DefaultWithdraw], "10") == "/bank withdraw n 10", "withdraw MMDs"); - Check(ConquestData.WithdrawCommand(ConquestData.Withdrawable[0], "-3") == null, "withdraw refuses a bad amount"); - Check(ConquestData.TransferCommand(ConquestData.Transferable[2], "4", "Some One") == "/bank transfer p 1000000 \"Some One\"", "transfer MMD notes as pyreals"); - Check(ConquestData.TransferCommand(ConquestData.Transferable[2], "1001", "X") == null, "transfer cap"); - } - - private static void AelrynthReplies() - { - var a = new AelrynthBoards(); - long now = 2_000_000; - a.RequestTop("", now); - Check(a.OnChatLine("Leaderboards - 37 characters, refreshed 4 min ago. /top for the top ten, /top me for yourself.", now, out bool ours) && ours, "overview header"); - a.OnChatLine(" kills Creature kills: Buffy, 1,234,567", now, out _); - a.OnChatLine(" pk PK kills: nobody yet", now, out _); - Check(a.Overview.Count == 2 && a.Overview[0].Key == "kills" && a.Overview[0].Leader == "Buffy" && a.Overview[0].Value == "1,234,567" - && a.Overview[1].Leader == "nobody yet", "overview rows"); - - a.RequestTop("kills", now); - a.OnChatLine("Creature kills - top 10 of 37:", now, out _); - a.OnChatLine(" 1. Buffy 1,234,567 <- you", now, out _); - a.OnChatLine(" 2. Dargoth 987,654", now, out _); - a.OnChatLine(" 3. Sal 500 12 kills per death", now, out _); - Check(a.BoardTitle == "Creature kills" && a.BoardRows.Count == 3 && a.BoardRows[0].IsYou && a.BoardRows[1].Value == "987,654" - && a.BoardRows[2].Extra == "12 kills per death", "board rows: " + string.Join(" | ", a.BoardRows.Select(r => $"{r.Rank} {r.Name} {r.Value} [{r.Extra}] {r.IsYou}"))); - - a.RequestTop("me", now); - a.OnChatLine("Buffy on the boards:", now, out _); - a.OnChatLine(" Creature kills #1 of 37, 1,234,567", now, out _); - a.OnChatLine(" PK kills -", now, out _); - Check(a.Standings.Count == 2 && a.Standings[0].Rank == 1 && a.Standings[1].Rank == 0, "/top me"); - - Check(!a.OnChatLine(" 9. Nobody 12", now + 30_000, out _), "an entry long after its header is ignored"); - - a.RequestTrial("", now); - a.OnChatLine("Trials - a fresh personal copy of a listed dungeon, entered through its portal, is a timed course: ...", now, out _); - a.OnChatLine(" The Citadel Below - Trial (02F0): tier 0 12:34 by Buffy | you: tier 0 12:34 | this week: Buffy 12:34 (tier 0)", now, out _); - a.OnChatLine(" your next attempt here: in 12 min", now, out _); - a.OnChatLine("Trophy: the week's fastest clear of each dungeon, any tier - a trophy and 1,000 experience, Sunday 20:00 (2026-W40). /trial for the top 10 of one dungeon.", now, out _); - Check(a.Trials.Count == 1 && a.Trials[0].Landblock == "02F0" && a.TrialLines.Count == 3, $"/trial overview ({a.Trials.Count} dungeons, {a.TrialLines.Count} lines)"); - - a.RequestTrial("citadel", now); - a.OnChatLine("The Citadel Below - Trial (02F0) - top 10, best per character, any tier:", now, out _); - a.OnChatLine(" 1. 12:34 Buffy (tier 0, 105 kills, 3 Oct)", now, out _); - a.OnChatLine(" you: tier 0 12:34 (105 kills)", now, out _); - Check(a.TrialRows.Count == 1 && a.TrialRows[0].Name == "Buffy" && a.TrialRows[0].Value == "12:34" && a.TrialNotes.Count == 1, "/trial dungeon top 10"); - Check(!a.OnChatLine("Bob tells you, \"hello\"", now, out _), "ordinary chat is never taken"); - } - private static void Void() { var v = new VoidTracker(); @@ -526,13 +480,9 @@ namespace RynthOracle.Tests Check(timersBody.Contains("Attribute and Skill Redistribution") && timersBody.Contains("ready"), "the Quest Timers window lists tracked quests with their timers"); // Every tab on each server, including the server-specific ones (with data in them). - c.Conquest.RequestBank(c.NowMs); - c.Conquest.OnChatLine("[BANK] Pyreals: 1,000", c.NowMs, out _); - c.Boards.OnChatLine("Leaderboards - 3 characters, refreshed just now. /top ...", c.NowMs, out _); - c.Boards.OnChatLine(" kills Creature kills: Buffy, 12", c.NowMs, out _); c.EarnedTitles.Add(1); c.TitlesKnown = true; - foreach (string server in new[] { ServerTags.Aelrynth, ServerTags.Conquest, "" }) + foreach (string server in new[] { ServerTags.Aelrynth, ServerTags.Conquest, ServerTags.InfiniteLeaftide, "" }) { c.Server.Force(server, server); foreach (string tab in view.VisibleTabs()) @@ -543,7 +493,7 @@ namespace RynthOracle.Tests main.End(); ParseAll(host, $"{server}/{tab}", out int ops); Check(ops > 5 && ops < 1400, $"{server}/{tab}: {ops} ops"); - if (server == ServerTags.Aelrynth || tab is OracleView.TabConquest) Console.WriteLine($" {(server.Length > 0 ? server : "other")}/{tab}: {ops} ops, {main.Body.Length} bytes"); + if (server == ServerTags.Aelrynth) Console.WriteLine($" {(server.Length > 0 ? server : "other")}/{tab}: {ops} ops, {main.Body.Length} bytes"); main.MarkSubmitted(true); } } @@ -565,18 +515,6 @@ namespace RynthOracle.Tests Console.WriteLine($" Quests (opened): {openOps} ops, {main.Body.Length} bytes"); main.MarkSubmitted(true); - // The Conquest tab's sub-pages and the Aelrynth board views. - c.Server.Force(ServerTags.Conquest, "Conquest"); - c.Settings.TabName = OracleView.TabConquest; - for (int v = 0; v < 6; v++) - { - main.Begin(); view.Draw(main); main.End(); - Apply(host, Event(1, (uint)(100 + v), main.Hash, main.KeyOf("cq.v." + ((v + 1) % 6)), new byte[] { 1, 0, 0 })); - main.Begin(); view.Draw(main); main.End(); - ParseAll(host, $"conquest view {v}", out int ops); - Check(ops > 5 && ops < 1400, $"conquest view {v}: {ops} ops"); - } - // A page that can't fit: everything in the catalog on one page is cut short, still valid. var big = new UiWindow("RynthOracle/Big", "Big") { Visible = true }; var bigHost = new UiHost(); @@ -727,10 +665,10 @@ namespace RynthOracle.Tests { // The tabs: after Character, on every server; every earlier tab is still there. string[] earlier = { OracleView.TabQuests, OracleView.TabCharacter, OracleView.TabAugs, OracleView.TabSociety, - OracleView.TabMarkers, OracleView.TabTitles, OracleView.TabVoid, OracleView.TabFellowship, OracleView.TabAbout }; + OracleView.TabTitles, OracleView.TabVoid, OracleView.TabFellowship, OracleView.TabAbout }; OracleContext c = Context(); var view = new OracleView(c); - foreach (string server in new[] { ServerTags.Aelrynth, ServerTags.Conquest, "" }) + foreach (string server in new[] { ServerTags.Aelrynth, ServerTags.Conquest, ServerTags.InfiniteLeaftide, "" }) { c.Server.Force(server, server); string[] tabs = view.VisibleTabs(); @@ -876,7 +814,7 @@ namespace RynthOracle.Tests void Press(string scope) => Click("refresh." + scope); // A Refresh button on every tab, on every server. - foreach (string server in new[] { ServerTags.Aelrynth, ServerTags.Conquest, "" }) + foreach (string server in new[] { ServerTags.Aelrynth, ServerTags.Conquest, ServerTags.InfiniteLeaftide, "" }) { c.Server.Force(server, server); foreach (string tab in view.VisibleTabs()) @@ -908,7 +846,7 @@ namespace RynthOracle.Tests foreach ((string tab, int wantChars, int wantQuests) in new[] { (OracleView.TabCharacter, 1, 0), (OracleView.TabAugs, 1, 1), (OracleView.TabSociety, 1, 1), - (OracleView.TabMarkers, 0, 1), (OracleView.TabVoid, 1, 0), + (OracleView.TabVoid, 1, 0), }) { chars = quests = 0; @@ -936,45 +874,6 @@ namespace RynthOracle.Tests c.NowMs += 4000; Press("About"); Check(lists == 2, "About: allowed again after the pause"); - - // ConquestAC: the sub-page's own command, once per pause; the line follows the reply. - c.Server.Force(ServerTags.Conquest, "Conquest"); - c.Settings.TabName = OracleView.TabConquest; - string[] want = { "/b", "/augs", "/enl augs", "/bonus", "/fship list" }; - for (int v = 0; v < 6; v++) - { - Click("cq.v." + v); - sent.Clear(); - quests = 0; - c.NowMs += 4000; - Press("Conquest" + v); - if (v < 5) Check(sent.Count == 1 && sent[0] == want[v], $"Conquest view {v}: Refresh sends {want[v]} (sent {string.Join(",", sent)})"); - else Check(sent.Count == 0 && quests == 1, "Conquest custom quests: Refresh asks for the quest flags"); - Press("Conquest" + v); - Check(sent.Count == (v < 5 ? 1 : 0), $"Conquest view {v}: a second press at once sends nothing more"); - } - Click("cq.v.0"); - c.NowMs += 4000; - Press("Conquest0"); - System.Threading.Thread.Sleep(5); - c.Conquest.OnChatLine("[BANK] Pyreals: 2,000", c.NowMs, out _); - Check(Draw().Contains("Updated "), "Conquest bank: the line says Updated when the balances arrive"); - - // Boards: ConquestAC's board, then Aelrynth's three views. - c.Settings.TabName = OracleView.TabBoards; - sent.Clear(); - c.NowMs += 4000; - Press(OracleView.TabBoards + "00"); - Check(sent.Count == 1 && sent[0].StartsWith("/top "), "ConquestAC boards: Refresh sends /top : " + string.Join(",", sent)); - c.Server.Force(ServerTags.Aelrynth, "Aeshnidae"); - sent.Clear(); - foreach ((int viewNo, string cmd) in new[] { (0, "/top"), (1, "/top me"), (2, "/trial") }) - { - Click("ab.v" + viewNo); - c.NowMs += 4000; - Press($"{OracleView.TabBoards}{viewNo}0"); - Check(sent.Count > 0 && sent[^1].TrimEnd() == cmd, $"Aelrynth boards view {viewNo}: Refresh sends {cmd} (sent {sent.LastOrDefault()})"); - } } private static byte[] Event(ushort type, uint seq, uint window, uint key, byte[] payload) diff --git a/Tools/RynthOracle.Tests/RynthOracle.Tests.csproj b/Tools/RynthOracle.Tests/RynthOracle.Tests.csproj index 9bd8011..a2284a4 100644 --- a/Tools/RynthOracle.Tests/RynthOracle.Tests.csproj +++ b/Tools/RynthOracle.Tests/RynthOracle.Tests.csproj @@ -28,6 +28,8 @@ + + @@ -47,7 +49,8 @@ - + + diff --git a/Tools/RynthOracle.Tests/ServerMoveTests.cs b/Tools/RynthOracle.Tests/ServerMoveTests.cs new file mode 100644 index 0000000..7eec22e --- /dev/null +++ b/Tools/RynthOracle.Tests/ServerMoveTests.cs @@ -0,0 +1,112 @@ +using System; +using System.IO; +using System.Text.Json; +using RynthCore.Plugin.RynthOracle; +using RynthCore.Plugin.RynthOracle.Data; +using RynthCore.Plugin.RynthOracle.Views; + +namespace RynthOracle.Tests +{ + // RynthOracle without one server's features (2026-10-20: Conquest's went to RynthConquest, + // Aelrynth's to RynthAelrynth): the settings file keeps what moved, so the server plugin can + // take it over once, and nothing of those servers is left in RynthOracle itself. + internal static partial class Program + { + private static void ServerMove() + { + SettingsKeepUnknown(); + ConquestGone(); + AelrynthGone(); + } + + /// Aelrynth without RynthAelrynth: no leaderboards or Trials in RynthOracle (the quest pack stays, as data). + private static void AelrynthGone() + { + Check(typeof(RynthOraclePlugin).Assembly.GetType("RynthCore.Plugin.RynthOracle.Data.AelrynthBoards") == null, + "aelrynth: the /top and /trial parser is not in RynthOracle"); + Check(typeof(OracleContext).GetField("Boards") == null, "aelrynth: RynthOracle keeps no leaderboard data"); + var c = new OracleContext { InWorld = true }; + var view = new OracleView(c); + c.Server.Force(ServerTags.Aelrynth, "Aeshnidae"); + string[] tabs = view.VisibleTabs(); + Check(Array.IndexOf(tabs, "Leaderboards") < 0, "aelrynth: no Leaderboards tab in RynthOracle on Aelrynth: " + string.Join(",", tabs)); + c.Catalog.Load(ServerTags.Aelrynth, null); + Check(c.Catalog.PackServer == ServerTags.Aelrynth && c.Catalog.ServerCount > 0, "aelrynth: the quest pack is still RynthOracle's (data)"); + } + + /// + /// Conquest without RynthConquest: no Conquest data, setting, auto-deposit or tab in RynthOracle, + /// and the Void DoT rule comes only from the server plugin's profile. + /// + private static void ConquestGone() + { + const System.Reflection.BindingFlags All = System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Static + | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic; + Check(typeof(OracleSettings).GetField("ConquestAutoDeposit", All) == null, "conquest: RynthOracle has no auto-deposit setting"); + Check(typeof(OracleContext).GetField("Conquest", All) == null, "conquest: RynthOracle keeps no Conquest data"); + Check(typeof(RynthOraclePlugin).GetMethod("TickConquest", All) == null, "conquest: RynthOracle's tick has no Conquest part (no auto-deposit, no /augs)"); + Check(typeof(RynthOraclePlugin).Assembly.GetType("RynthCore.Plugin.RynthOracle.Data.ConquestData") == null + && typeof(RynthOraclePlugin).Assembly.GetType("RynthCore.Plugin.RynthOracle.Data.CustomQuestList") == null, + "conquest: the Conquest reply parser and custom quest list are not in RynthOracle"); + + // Conquest tagged by its world name (RynthConquest not installed): retail tabs only. + var c = new OracleContext { InWorld = true }; + var view = new OracleView(c); + c.Server.Force(ServerTags.Conquest, "Conquest"); + string[] tabs = view.VisibleTabs(); + Check(Array.IndexOf(tabs, "Conquest") < 0 && Array.IndexOf(tabs, "Leaderboards") < 0, + "conquest: no Conquest pages in RynthOracle on Conquest: " + string.Join(",", tabs)); + + // The Void DoT rule: whatever the server plugin publishes (1 to 10), 1 without one. + Check(RynthOraclePlugin.VoidScaleFrom(null) == 1.0 && RynthOraclePlugin.VoidScaleFrom("") == 1.0, "void scale: 1 without a profile"); + Check(RynthOraclePlugin.VoidScaleFrom("{\"id\":\"coldeve\",\"values\":{}}") == 1.0, "void scale: 1 for a server without the rule"); + Check(Math.Abs(RynthOraclePlugin.VoidScaleFrom("{\"id\":\"conquest\",\"values\":{\"voidDotDurationScale\":2.15}}") - 2.15) < 1e-12, + "void scale: RynthConquest's value is applied"); + Check(RynthOraclePlugin.VoidScaleFrom("{\"values\":{\"voidDotDurationScale\":0.5}}") == 1.0 + && RynthOraclePlugin.VoidScaleFrom("{\"values\":{\"voidDotDurationScale\":50}}") == 1.0, + "void scale: a value out of 1..10 is ignored"); + var v = new VoidTracker(); + v.OnChatLine("You cast Corrosion VII on Drudge Slinker", 1_000_000, _ => 0x50000001u, () => false, 2.0); + Check(v.Remaining(0x50000001u, "Drudge Slinker", VoidFamily.Corrosion, 1_001_000, out _) == 31, + "void scale: a scaled Corrosion lasts 30 s (+2 s before the first tick)"); + } + + /// A value this version doesn't use survives a load and a save, unchanged. + private static void SettingsKeepUnknown() + { + string? saved = OracleSettings.PathOverride; + string path = Path.Combine(Path.GetTempPath(), "RynthOracleTests-" + Guid.NewGuid().ToString("N") + "-keep.json"); + OracleSettings.PathOverride = path; + try + { + File.WriteAllText(path, "{ \"hideOwnQuestReplies\": false, \"conquestAutoDeposit\": true, \"fromTheFuture\": {\"x\": [1, \"two\"]}, \"tabName\": \"Void\" }"); + var s = new OracleSettings(); + s.Load(); + Check(!s.HideOwnQuestReplies && s.TabName == "Void", "settings: known values read as before"); + s.MainWindowOpen = true; + s.Save(); + using (JsonDocument doc = JsonDocument.Parse(File.ReadAllText(path))) + { + JsonElement r = doc.RootElement; + Check(r.TryGetProperty("conquestAutoDeposit", out JsonElement cq) && cq.ValueKind == JsonValueKind.True, + "settings: a moved setting (conquestAutoDeposit) is still in the file after a save"); + Check(r.TryGetProperty("fromTheFuture", out JsonElement f) && f.GetProperty("x").GetArrayLength() == 2, + "settings: an unknown value is written back unchanged"); + Check(r.GetProperty("mainWindowOpen").GetBoolean(), "settings: the change was saved"); + } + var again = new OracleSettings(); + again.Load(); + again.Save(); + again.Save(); + string text = File.ReadAllText(path); + Check(text.IndexOf("fromTheFuture", StringComparison.Ordinal) == text.LastIndexOf("fromTheFuture", StringComparison.Ordinal), + "settings: kept values aren't duplicated by repeated saves"); + } + finally + { + try { File.Delete(path); } catch { } + OracleSettings.PathOverride = saved; + } + } + } +} diff --git a/Tools/RynthServerPack.Tests/AelrynthTests.cs b/Tools/RynthServerPack.Tests/AelrynthTests.cs new file mode 100644 index 0000000..c305988 --- /dev/null +++ b/Tools/RynthServerPack.Tests/AelrynthTests.cs @@ -0,0 +1,119 @@ +using System; +using System.IO; +using System.Linq; +using RynthCore.Engine.UI.Sections; +using RynthCore.Plugin.RynthAelrynth; +using RynthCore.Plugin.ServerPack; +using RynthCore.RynthAiTests.Harness; + +namespace RynthServerPack.Tests; + +// RynthAelrynth's own features (Plugins\RynthCore.Plugin.RynthAelrynth\Aelrynth), moved out of +// RynthOracle on 2026-10-20: the /top and /trial reply parser (RynthOracle.Tests' old +// AelrynthReplies), the own-reply hiding, the setting taken over from rynthoracle.json and its page. +internal static class AelrynthTests +{ + public static void Register(Runner r) + { + r.Add("aelrynth: the replies of /top, /top me and /trial parse", Replies); + r.Add("aelrynth: replies to RynthAelrynth's own requests are hidden, typed ones show", HideOwnReplies); + r.Add("aelrynth: RynthOracle's reply-hiding choice is taken over once", Migration); + r.Add("aelrynth: its Leaderboards page is an Aelrynth-only view of the Server section", Pages); + } + + private static void Replies() + { + var a = new AelrynthBoards(); + long now = 2_000_000; + a.RequestTop("", now); + Check.True(a.OnChatLine("Leaderboards - 37 characters, refreshed 4 min ago. /top for the top ten, /top me for yourself.", now, out bool ours) && ours, "overview header"); + a.OnChatLine(" kills Creature kills: Buffy, 1,234,567", now, out _); + a.OnChatLine(" pk PK kills: nobody yet", now, out _); + Check.True(a.Overview.Count == 2 && a.Overview[0].Key == "kills" && a.Overview[0].Leader == "Buffy" && a.Overview[0].Value == "1,234,567" + && a.Overview[1].Leader == "nobody yet", "overview rows"); + + a.RequestTop("kills", now); + a.OnChatLine("Creature kills - top 10 of 37:", now, out _); + a.OnChatLine(" 1. Buffy 1,234,567 <- you", now, out _); + a.OnChatLine(" 2. Dargoth 987,654", now, out _); + a.OnChatLine(" 3. Sal 500 12 kills per death", now, out _); + Check.True(a.BoardTitle == "Creature kills" && a.BoardRows.Count == 3 && a.BoardRows[0].IsYou && a.BoardRows[1].Value == "987,654" + && a.BoardRows[2].Extra == "12 kills per death", "board rows: " + string.Join(" | ", a.BoardRows.Select(r => $"{r.Rank} {r.Name} {r.Value} [{r.Extra}] {r.IsYou}"))); + + a.RequestTop("me", now); + a.OnChatLine("Buffy on the boards:", now, out _); + a.OnChatLine(" Creature kills #1 of 37, 1,234,567", now, out _); + a.OnChatLine(" PK kills -", now, out _); + Check.True(a.Standings.Count == 2 && a.Standings[0].Rank == 1 && a.Standings[1].Rank == 0, "/top me"); + + Check.False(a.OnChatLine(" 9. Nobody 12", now + 30_000, out _), "an entry long after its header is ignored"); + + a.RequestTrial("", now); + a.OnChatLine("Trials - a fresh personal copy of a listed dungeon, entered through its portal, is a timed course: ...", now, out _); + a.OnChatLine(" The Citadel Below - Trial (02F0): tier 0 12:34 by Buffy | you: tier 0 12:34 | this week: Buffy 12:34 (tier 0)", now, out _); + a.OnChatLine(" your next attempt here: in 12 min", now, out _); + a.OnChatLine("Trophy: the week's fastest clear of each dungeon, any tier - a trophy and 1,000 experience, Sunday 20:00 (2026-W40). /trial for the top 10 of one dungeon.", now, out _); + Check.True(a.Trials.Count == 1 && a.Trials[0].Landblock == "02F0" && a.TrialLines.Count == 3, $"/trial overview ({a.Trials.Count} dungeons, {a.TrialLines.Count} lines)"); + + a.RequestTrial("citadel", now); + a.OnChatLine("The Citadel Below - Trial (02F0) - top 10, best per character, any tier:", now, out _); + a.OnChatLine(" 1. 12:34 Buffy (tier 0, 105 kills, 3 Oct)", now, out _); + a.OnChatLine(" you: tier 0 12:34 (105 kills)", now, out _); + Check.True(a.TrialRows.Count == 1 && a.TrialRows[0].Name == "Buffy" && a.TrialRows[0].Value == "12:34" && a.TrialNotes.Count == 1, "/trial dungeon top 10"); + Check.False(a.OnChatLine("Bob tells you, \"hello\"", now, out _), "ordinary chat is never taken"); + } + + private static void HideOwnReplies() + { + var f = new AelrynthFeature(); + long now = 3_000_000; + f.Boards.RequestTop("", now); + Check.True(f.OnChatLine("Leaderboards - 3 characters, refreshed just now. /top ...", 0, now), "a reply to RynthAelrynth's /top is hidden"); + Check.True(f.OnChatLine(" kills Creature kills: Buffy, 12", 0, now), "and its rows"); + Check.False(f.OnChatLine("Leaderboards - 3 characters, refreshed just now. /top ...", 0, now + 60_000), "a typed /top's reply shows"); + Check.False(f.OnChatLine(" kills Creature kills: Ann, 14", 0, now + 60_000), "and its rows"); + Check.True(f.Boards.Overview.Count == 1 && f.Boards.Overview[0].Leader == "Ann", "read either way"); + f.HideOwnReplies = false; + f.Boards.RequestTrial("", now); + Check.False(f.OnChatLine("Trials - a fresh personal copy of a listed dungeon ...", 0, now), "with hiding off, own replies show too"); + Check.False(f.OnChatLine("Bob says, \"hi\"", 0, now), "ordinary chat shows"); + f.Reset(); + Check.True(f.Boards.Overview.Count == 0 && f.Boards.Trials.Count == 0, "login/logout clears the boards"); + } + + private static void Migration() + { + string dir = ServerPackHooksTests.TempDir(); + try + { + string oracle = Path.Combine(dir, "rynthoracle.json"), mine = Path.Combine(dir, "rynthaelrynth.json"); + File.WriteAllText(oracle, "{ \"hideOwnQuestReplies\": false }"); + var s = new ServerPackSettings(mine); + s.Load(); + Check.True(AelrynthFeature.Migrate(s, oracle), "taken over the first time"); + var f = new AelrynthFeature(); + f.LoadSettings(s); + Check.False(f.HideOwnReplies, "the player's choice (shown) came over"); + Check.False(AelrynthFeature.Migrate(s, oracle), "never twice"); + var fresh = new ServerPackSettings(Path.Combine(dir, "fresh.json")); + fresh.Load(); + AelrynthFeature.Migrate(fresh, Path.Combine(dir, "none.json")); + var g = new AelrynthFeature(); + g.LoadSettings(fresh); + Check.True(g.HideOwnReplies, "default: hidden"); + } + finally { try { Directory.Delete(dir, true); } catch { } } + } + + private static void Pages() + { + var pages = ServerPackPages.Validate(AelrynthFeature.PageList.Select(p => new ServerPage(p.Id, p.Label, p.Tooltip, () => { }))); + Check.Eq(pages.Count, 1, "one page"); + ServerPackInfo info = new("aelrynth", "Aelrynth", new[] { "aelrynth.com" }, new[] { "Aelrynth*", "Aeshnidae*" }); + SectionManifest m = SectionManifestParser.Parse("RynthAelrynth", ServerPackModel.BuildSectionsJson(info, "RynthAelrynth", pages), out string error); + Check.Eq(error, "", "RynthCore parses the manifest"); + SectionContribution view = m.Contributions.Single(c => c.Primary); + Check.True(view.Server == "aelrynth" && view.Label == "Leaderboards" && view.Surface == "section:server-aelrynth.boards", + "Leaderboards, only while Aelrynth is active"); + } +} diff --git a/Tools/RynthServerPack.Tests/ConquestTests.cs b/Tools/RynthServerPack.Tests/ConquestTests.cs new file mode 100644 index 0000000..3c08bc8 --- /dev/null +++ b/Tools/RynthServerPack.Tests/ConquestTests.cs @@ -0,0 +1,216 @@ +using System; +using System.IO; +using System.Linq; +using RynthCore.Engine.UI.Sections; +using RynthCore.Plugin.RynthConquest; +using RynthCore.Plugin.RynthOracle.Data; +using RynthCore.Plugin.ServerPack; +using RynthCore.RynthAiTests.Harness; + +namespace RynthServerPack.Tests; + +// RynthConquest's own features (Plugins\RynthCore.Plugin.RynthConquest\Conquest), moved out of +// RynthOracle on 2026-10-20: the reply parser (RynthOracle.Tests' old ConquestReplies), the +// own-reply hiding, the login /augs, the auto-deposit, the settings taken over from rynthoracle.json, +// the Void DoT rule it publishes, the custom quest list and its pages. +internal static class ConquestTests +{ + public static void Register(Runner r) + { + r.Add("conquest: the replies of /b, /augs, /enl augs, /bonus, /fship list and /top parse", Replies); + r.Add("conquest: replies to RynthConquest's own requests are hidden, typed ones show", HideOwnReplies); + r.Add("conquest: /augs once after login, then never again", LoginAugs); + r.Add("conquest: the auto-deposit is off unless turned on, then once per ten-minute mark", AutoDeposit); + r.Add("conquest: RynthOracle's settings are taken over once (defaults kept without them)", Migration); + r.Add("conquest: the Void DoT rule for RynthOracle's timers", VoidRule); + r.Add("conquest: the custom quest worklist and its status", CustomQuests); + r.Add("conquest: its pages are Conquest-only views of the Server section", Pages); + } + + private static void Replies() + { + var d = new ConquestData(); + long now = 1_000_000; + d.RequestBank(now); + Check.True(d.OnChatLine("[BANK] Your balances:", now, out bool ours) && ours, "bank heading (ours)"); + d.OnChatLine("[BANK] Pyreals: 1,039,678,533", now, out _); + d.OnChatLine("[BANK] Event Tokens [Dragon Coins] (x): 12", now, out _); + Check.True(d.Bank.Any(b => b.Name == "Pyreals" && b.Value.Contains("4,158 MMDs")), "pyreals with MMDs"); + Check.True(d.Bank.Any(b => b.Name == "Dragon Coins (x)"), "event token name"); + Check.False(d.OnChatLine("Bob says, \"[BANK] Pyreals: 999\"", now, out _), "a pasted balance is ignored"); + d.OnChatLine("[BANK] Pyreals: 5", now + 60_000, out bool late); + Check.False(late, "a reply long after the request isn't ours (shows in chat)"); + + d.RequestAugs(now); + d.OnChatLine("Creature: 25", now, out _); + d.OnChatLine("Duration: 3", now, out _); + ConquestAug creature = d.Augs.First(a => a.Name == "Creature"); + Check.True(creature.Count == 25 && creature.NextLuminanceCost() == 6_229_500, $"Creature 25 next costs 6,229,500 ({creature.NextLuminanceCost()})"); + Check.True(d.DurationAugs == 3 && Math.Abs(d.VoidDurationMultiplier(5) - 2.15) < 1e-9, "void duration x(1 + 5*0.2 + 3*0.05)"); + + d.RequestEnl(now); + d.OnChatLine("Enlightenment Augmentations:", now, out _); + d.OnChatLine("Skill Credits: 2 (10 max)", now, out _); + d.OnChatLine("Damage: 5 (25 max)", now, out _); + Check.True(d.EnlAugs.Count == 2 && d.EnlAugs[0].Name == "Damage", "enlightenment augs in display order"); + + d.RequestBonus(now); + d.OnChatLine("=== XP Bonuses ===", now, out _); + d.OnChatLine("Quest Bonus: 14.18% (1,418 quests)", now, out _); + d.OnChatLine("Total Bonus (Kills): 0.16%", now, out _); + Check.True(d.Bonuses.First(b => b.Name == "Quest").Value == "14.18% (1,418 quests)" && d.Bonuses.First(b => b.Name == "Total (Kills)").Value == "0.16%", "bonuses"); + + d.RequestFships(now); + d.OnChatLine("Fellowships looking for members:", now, out _); + d.OnChatLine("- Heroes (Leader: Bob) [3/14] @ Bur", now, out _); + d.OnChatLine("- Quiet (Leader: Ann) [1/14]", now, out _); + Check.True(d.Fellowships.Count == 2 && d.Fellowships[0].Location == "Bur" && d.Fellowships[1].MemberCount == 1, "fellowship list"); + + ConquestBoard lvl = d.Boards.First(b => b.Key == "level"); + d.RequestBoard(lvl, now); + d.OnChatLine("Top 2 Players by Level:", now, out _); + d.OnChatLine("1: 300 - Alpha", now, out _); + d.OnChatLine("2: 299 - Beta", now, out _); + d.OnChatLine("57: 250 - Me (You)", now, out _); + Check.True(lvl.Rows.Count == 2 && lvl.You != null && lvl.You.Rank == 57 && lvl.You.Name == "Me", "Conquest /top board"); + + Check.Eq(ConquestData.WithdrawCommand(ConquestData.Withdrawable[ConquestData.DefaultWithdraw], "10"), "/bank withdraw n 10", "withdraw MMDs"); + Check.Null(ConquestData.WithdrawCommand(ConquestData.Withdrawable[0], "-3"), "withdraw refuses a bad amount"); + Check.Eq(ConquestData.TransferCommand(ConquestData.Transferable[2], "4", "Some One"), "/bank transfer p 1000000 \"Some One\"", "transfer MMD notes as pyreals"); + Check.Null(ConquestData.TransferCommand(ConquestData.Transferable[2], "1001", "X"), "transfer cap"); + } + + private static void HideOwnReplies() + { + var f = new ConquestFeature(); + f.Login(0); + long now = 100_000; + f.Data.RequestBank(now); + Check.True(f.OnChatLine("[BANK] Pyreals: 1,000", now), "a reply to RynthConquest's /b is hidden"); + Check.False(f.OnChatLine("[BANK] Pyreals: 1,000", now + 60_000), "the same reply long after (typed /b) shows"); + Check.False(f.OnChatLine("Bob says, \"hello\"", now), "ordinary chat shows"); + f.HideOwnReplies = false; + f.Data.RequestBank(now); + Check.False(f.OnChatLine("[BANK] Pyreals: 1,000", now), "with hiding off, own replies show too"); + f.HideOwnReplies = true; + + // /myquests: only RynthConquest's own request's reply is hidden; the flags are read either way. + Check.True(f.Flags.Request(_ => true, now), "own /myquests sent"); + Check.True(f.OnChatLine("assaultonaimaru - 1 solves (1719432000)\"x\" -1 0", now), "its reply is hidden"); + f.Flags.Tick(now + 2000); + Check.True(f.Flags.TryGet("assaultonaimaru", out _), "and read"); + Check.False(f.OnChatLine("ghostdencompleted - 1 solves (1719432000)\"x\" -1 0", now + 3000), "a reply nobody here asked for shows"); + Check.True(f.Data.AutoDeposit(now).Length > 0 && f.OnChatLine("Deposited 12 items.", now), "the auto-deposit's reply is hidden"); + } + + private static void LoginAugs() + { + var f = new ConquestFeature(); + f.Login(1000); + Check.Null(f.LoginAugsDue(1000 + ConquestFeature.AugsReadDelayMs), "not before the delay"); + Check.Eq(f.LoginAugsDue(1001 + ConquestFeature.AugsReadDelayMs), "/augs", "/augs after it"); + Check.Null(f.LoginAugsDue(5_000_000), "only once"); + f.Login(9_000_000); + Check.Eq(f.LoginAugsDue(9_000_001 + ConquestFeature.AugsReadDelayMs), "/augs", "again for the next login"); + } + + private static void AutoDeposit() + { + var f = new ConquestFeature(); + f.Login(0); + var at = new DateTime(2026, 10, 20, 14, 0, 5, DateTimeKind.Local); + Check.False(f.AutoDeposit, "off by default (as it was in RynthOracle)"); + Check.Null(f.AutoDepositDue(at, 0), "off: no deposit at :00"); + f.AutoDeposit = true; + Check.Eq(f.AutoDepositDue(at, 0), "/bank deposit", "on: /bank deposit at :00"); + Check.Null(f.AutoDepositDue(at.AddSeconds(30), 0), "once per mark"); + Check.Null(f.AutoDepositDue(at.AddMinutes(5), 0), "not at :05"); + Check.Eq(f.AutoDepositDue(at.AddMinutes(10), 0), "/bank deposit", "again at :10"); + long block = -1; + Check.True(ConquestFeature.DepositDue(new DateTime(2026, 1, 1, 0, 20, 0), ref block), "the schedule: :20"); + Check.False(ConquestFeature.DepositDue(new DateTime(2026, 1, 1, 0, 21, 0), ref block), "the schedule: not :21"); + } + + private static void Migration() + { + string dir = ServerPackHooksTests.TempDir(); + try + { + string oracle = Path.Combine(dir, "rynthoracle.json"), mine = Path.Combine(dir, "rynthconquest.json"); + File.WriteAllText(oracle, "{ \"hideOwnQuestReplies\": false, \"conquestAutoDeposit\": true, \"tabName\": \"Conquest\" }"); + var s = new ServerPackSettings(mine); + s.Load(); + Check.True(ConquestFeature.Migrate(s, oracle), "taken over the first time"); + var f = new ConquestFeature(); + f.LoadSettings(s); + Check.True(f.AutoDeposit, "auto-deposit came over (on)"); + Check.False(f.HideOwnReplies, "hiding came over (off)"); + + // Turned off here later: a newer rynthoracle.json never turns it back on. + f.AutoDeposit = false; + f.SaveSettings(s); + var again = new ServerPackSettings(mine); + again.Load(); + Check.False(ConquestFeature.Migrate(again, oracle), "never taken over twice"); + var g = new ConquestFeature(); + g.LoadSettings(again); + Check.False(g.AutoDeposit, "the player's choice here stands"); + + // A new player (no RynthOracle settings): the defaults. + string fresh = Path.Combine(dir, "fresh.json"); + var n = new ServerPackSettings(fresh); + n.Load(); + Check.True(ConquestFeature.Migrate(n, Path.Combine(dir, "missing.json")), "runs (nothing to take)"); + var h = new ConquestFeature(); + h.LoadSettings(n); + Check.True(!h.AutoDeposit && h.HideOwnReplies, "defaults: auto-deposit off, own replies hidden"); + Check.True(new ServerPackSettings(fresh) is var reread && Reload(reread) && reread.GetBool(ConquestFeature.MigrationMarker, false), + "the marker is saved"); + } + finally { try { Directory.Delete(dir, true); } catch { } } + } + + private static bool Reload(ServerPackSettings s) { s.Load(); return true; } + + private static void VoidRule() + { + var f = new ConquestFeature(); + f.Login(0); + Check.Eq(f.VoidScale, 1.0, "no augs, no Archmage's Endurance: x1"); + f.ArchmagesEndurance = 5; + f.Data.RequestAugs(0); + f.Data.OnChatLine("Duration: 3", 0, out _); + Check.Near(f.VoidScale, 2.15, 1e-9, "x(1 + 5*0.2 + 3*0.05)"); + Check.Eq(ConquestFeature.VoidScaleKey, "voidDotDurationScale", "the profile value RynthOracle reads"); + } + + private static void CustomQuests() + { + Check.Eq(CustomQuestList.All.Count, 6, "six custom quests (customquests.csv, embedded)"); + Check.True(CustomQuestList.All.All(q => q.Server == "Conquest" && q.Flag.Length > 0 && q.Flag == q.Flag.ToLowerInvariant()), "Conquest rows, flags in lower case"); + var flags = new QuestFlagStore(); + CustomQuest darsh = CustomQuestList.All.First(q => q.Flag == "assaultonaimaru"); + DateTime now = DateTime.UtcNow; + Check.False(darsh.IsComplete(flags, now), "not done without the flag"); + Check.Eq(darsh.Status(flags, now), "ready", "ready without the flag"); + long done = DateTimeOffset.UtcNow.ToUnixTimeSeconds() - 60; + flags.OnChatLine($"assaultonaimaru - 1 solves ({done})\"x\" -1 3600", 0); + flags.Tick(5000); + Check.True(darsh.IsComplete(flags, now), "a repeatable on cooldown counts as done"); + Check.True(darsh.Status(flags, now) is not ("ready" or "completed") && darsh.Status(flags, now).Contains('m'), "its status is the time left: " + darsh.Status(flags, now)); + } + + private static void Pages() + { + var pages = ServerPackPages.Validate(ConquestFeature.PageList.Select(p => new ServerPage(p.Id, p.Label, p.Tooltip, () => { }))); + Check.Eq(pages.Count, ConquestFeature.PageList.Length, "every page is valid"); + Check.True(pages.Select(p => p.Label).SequenceEqual(new[] { "Conquest", "Leaderboards" }), "the Conquest and Leaderboards pages"); + ServerPackInfo info = new("conquest", "Conquest", new[] { "acconquest.ddns.net" }, new[] { "Conquest", "ConquestAC" }); + SectionManifest m = SectionManifestParser.Parse("RynthConquest", ServerPackModel.BuildSectionsJson(info, "RynthConquest", pages), out string error); + Check.Eq(error, "", "RynthCore parses the manifest"); + SectionContribution[] views = m.Contributions.Where(c => c.Primary).ToArray(); + Check.Eq(views.Length, 2, "two pages in the Mini Remote"); + Check.True(views.All(c => c.Server == "conquest"), "shown only while Conquest is active"); + Check.True(views.Select(c => c.Surface).SequenceEqual(new[] { "section:server-conquest.main", "section:server-conquest.boards" }), "their surfaces"); + } +} diff --git a/Tools/RynthServerPack.Tests/Program.cs b/Tools/RynthServerPack.Tests/Program.cs index 603fa97..2ed1d0f 100644 --- a/Tools/RynthServerPack.Tests/Program.cs +++ b/Tools/RynthServerPack.Tests/Program.cs @@ -13,6 +13,10 @@ internal static class Program var runner = new Runner(); ServerPackModelTests.Register(runner); ServerProjectsTests.Register(runner); + ServerPackHooksTests.Register(runner); + ConquestTests.Register(runner); + AelrynthTests.Register(runner); + VaultTests.Register(runner); return runner.Run("RynthServerPack tests", args.Length > 0 ? args[0] : null); } } diff --git a/Tools/RynthServerPack.Tests/RynthServerPack.Tests.csproj b/Tools/RynthServerPack.Tests/RynthServerPack.Tests.csproj index 6184827..27e541c 100644 --- a/Tools/RynthServerPack.Tests/RynthServerPack.Tests.csproj +++ b/Tools/RynthServerPack.Tests/RynthServerPack.Tests.csproj @@ -23,6 +23,26 @@ + + + + + + + + + + + + + + + + + + + + diff --git a/Tools/RynthServerPack.Tests/ServerPackHooksTests.cs b/Tools/RynthServerPack.Tests/ServerPackHooksTests.cs new file mode 100644 index 0000000..f6d75e2 --- /dev/null +++ b/Tools/RynthServerPack.Tests/ServerPackHooksTests.cs @@ -0,0 +1,210 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text.Json; +using RynthCore.Engine.UI.Sections; +using RynthCore.Plugin.ServerPack; +using RynthCore.RynthAiTests.Harness; + +namespace RynthServerPack.Tests; + +// The shared hooks a server plugin's own features use (2026-10-20, when RynthOracle's and +// RynthInventory's Conquest and Aelrynth features moved into RynthConquest and RynthAelrynth): +// pages beside the server card, the plugin's own settings file (with a one-time migration), live +// numbers in the "RynthServer.Profile" JSON, and the own-reply window. +internal static class ServerPackHooksTests +{ + public static void Register(Runner r) + { + r.Add("hooks: page ids, surfaces and the surface a page is drawn under", PageNames); + r.Add("hooks: bad, duplicate and surplus pages are left out", PageValidation); + r.Add("hooks: pages are server-only primary views of the Server section, accepted by RynthCore's parser", PagesInManifest); + r.Add("hooks: settings round-trip and keep values the plugin doesn't know", SettingsRoundTrip); + r.Add("hooks: settings migration runs once, and a broken file means defaults", SettingsMigration); + r.Add("hooks: profile values are published, validated and read back", ProfileValues); + r.Add("hooks: the own-reply window opens, stretches and closes", ReplyWindow); + } + + internal static string TempDir() + { + string dir = Path.Combine(Path.GetTempPath(), "RynthServerPack.Tests", Guid.NewGuid().ToString("N")); + Directory.CreateDirectory(dir); + return dir; + } + + private static void PageNames() + { + Check.True(ServerPackPages.IsValidId("bank") && ServerPackPages.IsValidId("top-10"), "plain ids"); + Check.False(ServerPackPages.IsValidId("") || ServerPackPages.IsValidId("Bank") || ServerPackPages.IsValidId("a.b") + || ServerPackPages.IsValidId(new string('a', 17)), "empty, capitals, dots and long ids are refused"); + Check.Eq(ServerPackPages.SurfaceFor("conquest", "bank"), "section:server-conquest.bank", "surface"); + Check.Eq(ServerPackPages.PageIdOf("section:server-conquest.bank", "conquest"), "bank", "page from its surface"); + Check.Eq(ServerPackPages.PageIdOf("section:server-conquest.bank:popout", "conquest"), "bank", "popped out"); + Check.Null(ServerPackPages.PageIdOf("section:server-conquest", "conquest"), "the card is not a page"); + Check.Null(ServerPackPages.PageIdOf("section:server-aelrynth.top", "conquest"), "another server's page"); + Check.Null(ServerPackPages.PageIdOf("section:server-conquest.Bad!", "conquest"), "a malformed page id"); + Check.Null(ServerPackPages.PageIdOf(null, "conquest"), "null"); + string longest = ServerPackPages.SurfaceFor(new string('a', 32), new string('b', ServerPackPages.MaxIdLength)); + Check.True(longest.Length <= SectionManifestParser.MaxSurfaceLength, "the longest surface fits RynthCore's cap: " + longest.Length); + } + + private static void PageValidation() + { + Action draw = () => { }; + var notes = new List(); + var pages = new List + { + new("one", "One", "", draw), new("one", "Again", "", draw), new("Two", "Two", "", draw), + new("three", " ", "", draw), new("four", "Four", "tip", null!), + }; + for (int i = 0; i < 8; i++) pages.Add(new ServerPage("p" + i, "Page " + i, "", draw)); + List kept = ServerPackPages.Validate(pages, notes.Add); + Check.Eq(kept.Count, ServerPackPages.MaxPages, "capped"); + Check.Eq(kept[0].Id, "one", "first kept"); + Check.Eq(kept.Count(p => p.Id == "one"), 1, "a duplicate id is dropped"); + Check.False(kept.Any(p => p.Id is "Two" or "three" or "four"), "bad id, no label, nothing to draw"); + Check.True(notes.Count == pages.Count - kept.Count, "every dropped page is reported: " + string.Join(" | ", notes)); + Check.Eq(ServerPackPages.Validate(null).Count, 0, "no pages"); + string label = new string('x', 60); + Check.Eq(ServerPackPages.Validate(new[] { new ServerPage("x", label, "", draw) })[0].Label.Length, ServerPackPages.MaxLabelLength, "label capped"); + } + + private static void PagesInManifest() + { + ServerPackInfo info = new("conquest", "Conquest", new[] { "acconquest.ddns.net" }, new[] { "Conquest" }); + var pages = ServerPackPages.Validate(new[] + { + new ServerPage("main", "Conquest", "Bank, augs and more", () => { }), + new ServerPage("boards", "Leaderboards", "", () => { }), + }); + string json = ServerPackModel.BuildSectionsJson(info, "RynthConquest", pages); + SectionManifest m = SectionManifestParser.Parse("RynthConquest", json, out string error); + Check.Eq(error, "", "RynthCore parses it"); + Check.Eq(m.Contributions.Length, 3, "the card and two pages"); + SectionContribution card = m.Contributions.Single(c => !c.Primary); + Check.Eq(card.Surface, "section:server-conquest", "the card keeps its surface"); + SectionContribution[] views = m.Contributions.Where(c => c.Primary).ToArray(); + Check.True(views.All(c => c.Section == ServerPackModel.SectionId && c.Server == "conquest" && c.IsSurface), + "pages: primary views of the Server section, only on Conquest"); + Check.Eq(views[0].Surface, "section:server-conquest.main", "page surface"); + Check.Eq(views[0].Label, "Conquest", "page label"); + Check.Eq(views[0].Tooltip, "Bank, augs and more", "page tooltip"); + Check.Eq(views[1].Tooltip, "Leaderboards (RynthConquest)", "a default tooltip"); + Check.True(views[0].Order < views[1].Order, "pages keep their order"); + Check.True(views[0].Width > 0 && views[0].Height > 0, "pages say their size"); + + // Without pages the manifest is byte for byte what it was. + Check.Eq(ServerPackModel.BuildSectionsJson(info, "RynthConquest", null), ServerPackModel.BuildSectionsJson(info, "RynthConquest"), + "no pages: the old manifest"); + Check.Eq(SectionManifestParser.Parse("x", ServerPackModel.BuildSectionsJson(info, "RynthConquest"), out _).Contributions.Length, 1, + "no pages: only the card"); + } + + private static void SettingsRoundTrip() + { + string dir = TempDir(); + try + { + string path = Path.Combine(dir, "rynthtest.json"); + File.WriteAllText(path, "{ \"future\": {\"a\":[1,2]}, \"flag\": false, \"name\": \"x\" }"); + var s = new ServerPackSettings(path); + s.Load(); + Check.Eq(s.LastError, "", "read"); + Check.False(s.GetBool("flag", true), "a stored false"); + Check.True(s.GetBool("missing", true), "a missing value falls back"); + Check.True(s.GetBool("name", true), "a value of another type falls back"); + Check.Eq(s.GetString("name", "?"), "x", "text"); + Check.True(s.SetBool("flag", true), "a change says so"); + Check.False(s.SetBool("flag", true), "the same value is no change"); + s.SetString("quote", "a \"b\" \\ c"); + Check.True(s.Save(), "saved"); + + var again = new ServerPackSettings(path); + again.Load(); + Check.True(again.GetBool("flag", false), "the change was kept"); + Check.Eq(again.GetString("quote", ""), "a \"b\" \\ c", "text escaped and read back"); + using JsonDocument doc = JsonDocument.Parse(File.ReadAllText(path)); + Check.Eq(doc.RootElement.GetProperty("future").GetProperty("a").GetArrayLength(), 2, "an unknown value is written back as it was"); + Check.False(File.Exists(path + ".tmp"), "no temporary file left"); + Check.True(ServerPackSettings.DefaultPath("RynthConquest").EndsWith(Path.Combine("RynthCore", "rynthconquest.json"), StringComparison.Ordinal), + "%APPDATA%\\RynthCore\\.json"); + } + finally { try { Directory.Delete(dir, true); } catch { } } + } + + private static void SettingsMigration() + { + string dir = TempDir(); + try + { + string old = Path.Combine(dir, "old.json"), mine = Path.Combine(dir, "mine.json"); + File.WriteAllText(old, "{ \"moved\": true, \"text\": \"t\" }"); + Check.Eq(ServerPackSettings.ReadBoolFrom(old, "moved"), (bool?)true, "the old home's value"); + Check.Null(ServerPackSettings.ReadBoolFrom(old, "text"), "not a true/false value"); + Check.Null(ServerPackSettings.ReadBoolFrom(old, "absent"), "missing value"); + Check.Null(ServerPackSettings.ReadBoolFrom(Path.Combine(dir, "nope.json"), "moved"), "missing file"); + + var s = new ServerPackSettings(mine); + s.Load(); + int runs = 0; + Action migrate = t => { runs++; if (ServerPackSettings.ReadBoolFrom(old, "moved") is bool b) t.SetBool("moved", b); }; + Check.True(s.MigrateOnce("migratedFromOld", migrate), "runs the first time"); + Check.True(s.GetBool("moved", false), "imported"); + File.WriteAllText(old, "{ \"moved\": false }"); + var later = new ServerPackSettings(mine); + later.Load(); + Check.False(later.MigrateOnce("migratedFromOld", migrate), "never again (the marker was saved)"); + Check.True(later.GetBool("moved", false), "later changes to the old home don't come over"); + Check.Eq(runs, 1, "ran once"); + + File.WriteAllText(mine, "{ not json"); + var broken = new ServerPackSettings(mine); + broken.Load(); + Check.True(broken.LastError.Length > 0 && broken.GetBool("moved", true), "a broken file reads as defaults"); + } + finally { try { Directory.Delete(dir, true); } catch { } } + } + + private static void ProfileValues() + { + var v = new ServerProfileValues(); + int r0 = v.Revision; + Check.True(v.Set("voidDotDurationScale", 1.35), "set"); + Check.True(v.Revision > r0, "a change bumps the revision"); + int r1 = v.Revision; + Check.True(v.Set("voidDotDurationScale", 1.35) && v.Revision == r1, "the same value is no change"); + Check.False(v.Set("bad key", 1) || v.Set("", 1) || v.Set("x", double.NaN) || v.Set("y", double.PositiveInfinity), "bad keys and numbers"); + + ServerPackInfo info = new("conquest", "Conquest", new[] { "h" }, new[] { "Conquest" }); + string json = ServerPackProfile.BuildJson(info, "RynthConquest", "0.2.0", true, "Conquest", v.Snapshot(out int rev)); + Check.Eq(rev, v.Revision, "the snapshot's revision"); + Check.Near(RynthCore.Plugin.Shared.ServerProfileView.Value(json, "voidDotDurationScale", 1), 1.35, 1e-12, "a reader gets the value"); + Check.Eq(RynthCore.Plugin.Shared.ServerProfileView.Value(json, "other", 7), 7.0, "a missing value falls back"); + Check.Eq(RynthCore.Plugin.Shared.ServerProfileView.Value("", "voidDotDurationScale", 1), 1.0, "no profile falls back"); + Check.Eq(RynthCore.Plugin.Shared.ServerProfileView.Value("{\"values\":{\"k\":\"2\"}}", "k", 1), 1.0, "text is not a number"); + Check.Eq(RynthCore.Plugin.Shared.ServerProfileView.Value("{broken", "k", 3), 3.0, "broken JSON falls back"); + using (JsonDocument doc = JsonDocument.Parse(ServerPackProfile.BuildJson(info, "RynthConquest", "0.2.0", true, "Conquest"))) + Check.Eq(doc.RootElement.GetProperty("values").EnumerateObject().Count(), 0, "no values: an empty object"); + + Check.True(v.Remove("voidDotDurationScale") && !v.Remove("voidDotDurationScale"), "remove"); + v.Set("a", 1); + int r2 = v.Revision; + v.Clear(); + Check.True(v.Revision > r2 && v.Snapshot(out _).Length == 0, "clear (logout)"); + } + + private static void ReplyWindow() + { + var req = new ServerChatRequest(); + Check.False(req.Awaiting(0), "nothing asked"); + req.Sent(1000); + Check.True(req.Awaiting(1000 + ServerChatRequest.WindowMs - 1), "inside the window"); + Check.False(req.Awaiting(1000 + ServerChatRequest.WindowMs), "the window closes"); + req.Sent(1000); + req.Extend(5500); + Check.True(req.Awaiting(7000), "a reply line stretches it"); + req.Clear(); + Check.False(req.Awaiting(1001), "cleared"); + } +} diff --git a/Tools/RynthServerPack.Tests/ServerProjectsTests.cs b/Tools/RynthServerPack.Tests/ServerProjectsTests.cs index 66c8434..def802b 100644 --- a/Tools/RynthServerPack.Tests/ServerProjectsTests.cs +++ b/Tools/RynthServerPack.Tests/ServerProjectsTests.cs @@ -19,6 +19,36 @@ internal static class ServerProjectsTests r.Add("server projects: ids, plugin names and hosts are unique", Unique); r.Add("server projects: no server's host is claimed by another server's list", NoHostOverlap); r.Add("server projects: each new server plugin has ServerData.cs and imports the shared props", Layout); + r.Add("server projects: RynthOracle and RynthInventory send no server's own commands (they live in its plugin)", SharedPluginsServerFree); + } + + /// + /// Since 2026-10-20 a server's own features live in its server plugin (RynthConquest, RynthAelrynth): + /// the shared plugins' sources hold none of those servers' commands or chat markers, and use the + /// server tags only to pick a quest pack (data, RynthOracle's ServerIdentity.cs). + /// + private static void SharedPluginsServerFree() + { + string[] commands = { "\"/bank", "\"/b\"", "\"/augs", "\"/enl augs", "\"/bonus", "\"/fship list", "\"/top", "\"/trial", "\"/mule-data", "\"~ael1" }; + foreach (string plugin in new[] { "RynthCore.Plugin.RynthOracle", "RynthCore.Plugin.RynthInventory" }) + { + string dir = Path.Combine(PluginsDir(), plugin); + var files = Directory.GetFiles(dir, "*.cs", SearchOption.AllDirectories) + .Where(f => !f.Contains(Path.DirectorySeparatorChar + "obj" + Path.DirectorySeparatorChar) + && !f.Contains(Path.DirectorySeparatorChar + "bin" + Path.DirectorySeparatorChar)) + .ToList(); + Check.True(files.Count > 10, plugin + ": its sources were found (" + files.Count + ")"); + foreach (string file in files) + { + string text = File.ReadAllText(file); + string name = plugin + "/" + Path.GetRelativePath(dir, file); + foreach (string c in commands) + Check.False(text.Contains(c, StringComparison.Ordinal), $"{name} sends no server command {c.TrimStart('"')}"); + if (!file.EndsWith("ServerIdentity.cs", StringComparison.Ordinal)) + Check.False(text.Contains("ServerTags.Conquest", StringComparison.Ordinal) || text.Contains("ServerTags.Aelrynth", StringComparison.Ordinal), + $"{name} has no Conquest or Aelrynth feature"); + } + } } private sealed record Project(string Dir, string PluginName, string Id, string Name, string[] Hosts, string[] Worlds, bool Shared); diff --git a/Tools/RynthServerPack.Tests/VaultTests.cs b/Tools/RynthServerPack.Tests/VaultTests.cs new file mode 100644 index 0000000..59ad0e8 --- /dev/null +++ b/Tools/RynthServerPack.Tests/VaultTests.cs @@ -0,0 +1,229 @@ +using System.Collections.Generic; +using RynthCore.Plugin.RynthAelrynth; +using RynthCore.Plugin.Shared; +using RynthCore.RynthAiTests.Harness; + +namespace RynthServerPack.Tests; + +// The Aelrynth account vault: /mule-data answers, one "~ael1" line a page (Aeshnidae.Mule MuleData.cs). +// Moved with the feed from RynthInventory.Tests on 2026-10-20: RynthAelrynth reads the vault now and +// hands it to RynthInventory through the storage feed (Plugins/Shared/StorageFeed.cs). +internal static class VaultTests +{ + public static void Register(Runner r) + { + r.Add("vault: pages are asked one after the other and filed as one record", Pages); + r.Add("vault: other plugins' lines and players' imitations are left alone", Imitations); + r.Add("vault: a server without the command is asked once", Unsupported); + r.Add("vault: loading, changed and silent vaults are never filed half or empty", Retries); + r.Add("vault: RynthAelrynth asks after login, every ten minutes and on /rserver vault", Schedule); + r.Add("vault: the record reaches RynthInventory's format intact (plain ASCII)", HandOff); + } + + private const string A = "{\"o\":2147483649,\"w\":100,\"n\":\"Acid Assagai\",\"i\":100667000,\"u\":100667001,\"v\":100667002,\"s\":3,\"m\":100,\"y\":1,\"e\":1}"; + private const string B = "{\"o\":2147483650,\"w\":101,\"n\":\"Pyreal\",\"i\":100667003,\"y\":8192}"; + + private static string VaultPage(int page, int pages, int count, string items, bool ready = true, string why = "") => + ready + ? "~ael1 {\"t\":\"mule\",\"ready\":true,\"page\":" + page + ",\"pages\":" + pages + ",\"count\":" + count + ",\"max\":1000,\"items\":[" + items + "]}" + : "~ael1 {\"t\":\"mule\",\"ready\":false,\"why\":\"" + why + "\"}"; + + private static (VaultFeed Feed, List Sent) NewVault() + { + var sent = new List(); + return (new VaultFeed(t => { sent.Add(t); return true; }), sent); + } + + private static void Pages() + { + (VaultFeed v, List sent) = NewVault(); + Check.True(v.Ask(1000), "ask starts"); + Check.Eq(sent.Count == 1 ? sent[0] : "?", "/mule-data", "page 1 asked first"); + Check.True(v.ShouldEat(VaultPage(1, 2, 2, A)), "page 1 is eaten"); + v.Tick(1100, "Tom"); + Check.Eq(sent.Count == 2 ? sent[1] : "?", "/mule-data 2", "page 2 asked when page 1 came"); + Check.Null(v.Record, "nothing filed before the last page"); + Check.True(v.ShouldEat(VaultPage(2, 2, 2, B)), "page 2 is eaten"); + v.Tick(1200, "Tom"); + StorageFeedRecord? r = v.Record; + Check.True(r != null && v.TakeChanged() && !v.TakeChanged(), "filed once"); + Check.Eq(r?.Items.Count ?? -1, 2, "both pages' items"); + Check.Eq(r?.Id ?? 0, VaultFeed.VaultId("tom"), "id follows the account, case-blind"); + Check.True(StorageFeed.IsStandInId(r?.Id ?? 0), "id is a stand-in, far from real objects"); + Check.Eq(r?.Label ?? "", "Account vault", "label"); + Check.Eq(r?.Name ?? "", "Aelrynth vault", "name"); + StorageFeedItem a = r!.Items[0]; + Check.Eq(a.Name, "Acid Assagai", "name"); Check.Eq(a.Icon, 100667000u, "icon"); Check.Eq(a.Underlay, 100667001u, "underlay"); + Check.Eq(a.Overlay, 100667002u, "overlay"); Check.Eq(a.Stack, 3, "stack"); Check.Eq(a.MaxStack, 100, "max stack"); + Check.Eq(a.ItemType, 1u, "item type"); + Check.Eq(r.Items[1].Stack, 1, "no stack field is a stack of 1"); + Check.Eq(v.Status, VaultFeed.State.Idle, "idle again"); + Check.Eq(VaultFeed.VaultId("Tom"), 0xFF000000u | (FnvOf("tom") & 0x00FFFFFFu), "the id RynthInventory used before the move (no second vault)"); + } + + private static uint FnvOf(string s) + { + uint h = 2166136261u; + foreach (char c in s) { h ^= c; h *= 16777619u; } + return h; + } + + private static void Imitations() + { + { + (VaultFeed v, _) = NewVault(); + v.Ask(0); + Check.False(v.ShouldEat("~ael1 {\"t\":\"inspect\",\"ok\":true}"), "the Companion's line stays visible"); + Check.False(v.ShouldEat("Welcome to Aelrynth"), "ordinary chat stays visible"); + Check.False(v.ShouldEat(null), "null is fine"); + } + { + (VaultFeed v, _) = NewVault(); + v.Ask(0); + Check.False(v.ShouldEat("Bob says, \"" + VaultPage(1, 1, 1, A) + "\"", 2), "spoken data line is not ours"); + Check.False(v.ShouldEat("Bob " + VaultPage(1, 1, 1, A), 12), "an emoted data line is not ours"); + Check.False(v.ShouldEat("Bob " + VaultPage(1, 1, 1, A)), "a data line not at the start is not ours, type unknown"); + Check.False(v.ShouldEat(VaultPage(1, 1, 1, A), 3), "a data line in a tell is not ours"); + Check.False(v.ShouldEat("Bob tells you, \"Unknown command: mule-data\"", 3), "a told unknown-command line is not ours"); + Check.False(v.ShouldEat("Unknown command: mule-data", 2), "unknown-command in speech is not ours"); + Check.False(v.ShouldEat("Unknown command: mule-data-ish"), "another command's refusal is not ours"); + Check.True(v.ShouldEat("Unknown command: mule-data", 15), "ACE's real reply (Help) is ours"); + } + { + (VaultFeed v, _) = NewVault(); + v.Ask(0); + Check.True(v.ShouldEat(" " + VaultPage(1, 1, 1, A), 0), "the server's line (Broadcast), leading space allowed"); + } + { + (VaultFeed v, _) = NewVault(); + Check.True(v.ShouldEat(VaultPage(1, 1, 1, A)), "a line typed by hand while we are not asking is eaten"); + v.Tick(0, "tom"); + Check.Null(v.Record, "but ignored when we did not ask"); + } + } + + private static void Unsupported() + { + { + (VaultFeed v, List sent) = NewVault(); + v.Ask(0); + Check.True(v.ShouldEat("Unknown command: /mule-data"), "the unknown-command reply is eaten while we wait"); + v.Tick(100, "tom"); + Check.Eq(v.Status, VaultFeed.State.Unsupported, "unsupported"); + Check.False(v.Ask(200), "not asked again"); + Check.Eq(sent.Count, 1, "one probe, no more"); + Check.True(v.Ask(300, force: true), "/rserver vault asks anyway"); + } + { + (VaultFeed v, _) = NewVault(); + Check.False(v.ShouldEat("Unknown command: /mule-data"), "an unknown-command line we did not provoke is left alone"); + } + } + + private static void Retries() + { + // A vault the server is still loading is asked again, and never recorded as empty. + { + (VaultFeed v, List sent) = NewVault(); + v.Ask(0); + v.ShouldEat(VaultPage(1, 1, 0, "", ready: false, why: "loading")); + v.Tick(10, "tom"); + Check.Eq(v.Status, VaultFeed.State.Waiting, "waiting"); + v.Tick(2000, "tom"); + Check.Eq(sent.Count, 1, "not before the retry delay"); + v.Tick(3500, "tom"); + Check.Eq(sent.Count, 2, "asked again after it"); + Check.Null(v.Record, "never recorded"); + for (int i = 0; i < 10; i++) + { + v.ShouldEat(VaultPage(1, 1, 0, "", ready: false, why: "loading")); + v.Tick(4000 + i * 4000, "tom"); + } + Check.True(v.Status != VaultFeed.State.Asking || sent.Count < 12, "it gives up after a few tries"); + Check.Null(v.Record, "still never recorded"); + } + // A vault that changed between pages is read again, not filed half and half. + { + (VaultFeed v, _) = NewVault(); + v.Ask(0); + v.ShouldEat(VaultPage(1, 2, 3, A)); + v.Tick(10, "tom"); + v.ShouldEat(VaultPage(2, 2, 3, B)); // 2 read, the server says 3 + v.Tick(20, "tom"); + Check.Null(v.Record, "a mismatched read is not filed"); + Check.Eq(v.Status, VaultFeed.State.Waiting, "and is retried"); + } + // Silence is an idle feed, not a stuck one. + { + (VaultFeed v, _) = NewVault(); + v.Ask(0); + v.Tick(20_000, "tom"); + Check.Eq(v.Status, VaultFeed.State.Idle, "no answer in time"); + Check.True(v.Ask(21_000), "can ask again"); + } + // Garbage inside a mule line does not throw. + { + (VaultFeed v, _) = NewVault(); + v.Ask(0); + v.ShouldEat("~ael1 {\"t\":\"mule\",\"ready\":tru"); + v.Tick(5, "tom"); + Check.True(v.Record == null && v.Status == VaultFeed.State.Idle, "bad JSON drops the read"); + } + } + + private static void Schedule() + { + var sent = new List(); + var f = new AelrynthFeature { SendCommand = t => { sent.Add(t); return true; } }; + f.Reset(); + long login = 50_000; + Check.Null(f.VaultTick(login, "tom"), "nothing at login"); + Check.Eq(sent.Count, 0, "not asked at once"); + f.VaultTick(login + VaultFeed.FirstAskMs - 1, "tom"); + Check.Eq(sent.Count, 0, "not before the first delay"); + f.VaultTick(login + VaultFeed.FirstAskMs, "tom"); + Check.Eq(sent.Count == 1 ? sent[0] : "?", "/mule-data", "asked after the first delay"); + Check.True(f.OnChatLine(VaultPage(1, 1, 1, A), 0, login + VaultFeed.FirstAskMs + 10), "its reply is always hidden"); + StorageFeedRecord? read = f.VaultTick(login + VaultFeed.FirstAskMs + 20, "tom"); + Check.True(read != null && read.Items.Count == 1, "the finished read is handed back once"); + Check.Null(f.VaultTick(login + VaultFeed.FirstAskMs + 30, "tom"), "and only once"); + f.VaultTick(login + VaultFeed.FirstAskMs + VaultFeed.RefreshMs, "tom"); + Check.Eq(sent.Count, 2, "read again ten minutes later"); + f.OnChatLine(VaultPage(1, 1, 1, A), 0, login + VaultFeed.FirstAskMs + VaultFeed.RefreshMs + 1); + f.VaultTick(login + VaultFeed.FirstAskMs + VaultFeed.RefreshMs + 2, "tom"); + Check.True(f.VaultAskNow(login + 700_000) && sent.Count == 3, "/rserver vault reads it now"); + + // A server without the command: one probe per login, then quiet. + var g = new AelrynthFeature { SendCommand = t => { sent.Add(t); return true; } }; + g.Reset(); + int before = sent.Count; + g.VaultTick(0, "tom"); + g.VaultTick(VaultFeed.FirstAskMs, "tom"); + g.OnChatLine("Unknown command: mule-data", 0, VaultFeed.FirstAskMs + 1); + g.VaultTick(VaultFeed.FirstAskMs + 2, "tom"); + g.VaultTick(VaultFeed.FirstAskMs + 3 * VaultFeed.RefreshMs, "tom"); + Check.Eq(sent.Count - before, 1, "no vault on the server: asked once, then never on a timer"); + g.Reset(); + Check.Eq(g.Vault.Status, VaultFeed.State.Idle, "the next login asks again"); + } + + private static void HandOff() + { + var items = new List + { + new(2147483649u, 100, "Acid \"Assagai\" \\ é", 100667000, 100667001, 100667002, 3, 100, 1), + new(2147483650u, 101, "Pyreal", 100667003, 0, 0, 1, 0, 8192), + }; + var rec = new StorageFeedRecord(VaultFeed.VaultId("tom"), VaultFeed.VaultName, VaultFeed.Label, items); + string json = StorageFeed.ToJson(rec); + bool ascii = true; + foreach (char c in json) if (c > 0x7e || c < 0x20) ascii = false; + Check.True(ascii, "plain ASCII (the broker carries ANSI)"); + StorageFeedRecord? back = StorageFeed.Parse(json, out string error); + Check.Eq(error, "", "parsed"); + Check.True(back != null && back.Id == rec.Id && back.Name == rec.Name && back.Label == rec.Label && back.Items.Count == 2, "the record"); + Check.Eq(back!.Items[0], items[0], "an item, name escapes included"); + Check.Eq(back.Items[1], items[1], "another"); + Check.Eq(StorageFeed.TargetPlugin + "/" + StorageFeed.Action, "RynthInventory/storage", "sent to RynthInventory's \"storage\" command"); + } +}